context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
/*
* 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 QuantConnect.Data;
using QuantConnect.Data.Auxiliary;
using QuantConnect.Data.Market;
using QuantConnect.Securities;
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Lean.Engine.DataFeeds.Enumerators;
using QuantConnect.Logging;
namespace QuantConnect.ToolBox.RandomDataGenerator
{
/// <summary>
/// Generates random data according to the specified parameters
/// </summary>
public class RandomDataGenerator
{
private RandomDataGeneratorSettings _settings;
private SecurityManager _securityManager;
/// <summary>
/// Initializes <see cref="RandomDataGenerator"/> instance fields
/// </summary>
/// <param name="settings">random data generation settings</param>
/// <param name="securityManager">security management</param>
public void Init(RandomDataGeneratorSettings settings, SecurityManager securityManager)
{
_settings = settings;
_securityManager = securityManager;
}
/// <summary>
/// Starts data generation
/// </summary>
public void Run()
{
var tickTypesPerSecurityType = SubscriptionManager.DefaultDataTypes();
// can specify a seed value in this ctor if determinism is desired
var random = new Random();
var randomValueGenerator = new RandomValueGenerator();
if (_settings.RandomSeedSet)
{
random = new Random(_settings.RandomSeed);
randomValueGenerator = new RandomValueGenerator(_settings.RandomSeed);
}
var symbolGenerator = BaseSymbolGenerator.Create(_settings, randomValueGenerator);
var maxSymbolCount = symbolGenerator.GetAvailableSymbolCount();
if (_settings.SymbolCount > maxSymbolCount)
{
Log.Error($"RandomDataGenerator.Run(): Limiting Symbol count to {maxSymbolCount}, we don't have more {_settings.SecurityType} tickers for {_settings.Market}");
_settings.SymbolCount = maxSymbolCount;
}
Log.Trace($"RandomDataGenerator.Run(): Begin data generation of {_settings.SymbolCount} randomly generated {_settings.SecurityType} assets...");
// iterate over our randomly generated symbols
var count = 0;
var progress = 0d;
var previousMonth = -1;
foreach (var (symbolRef, currentSymbolGroup) in symbolGenerator.GenerateRandomSymbols()
.GroupBy(s => s.HasUnderlying ? s.Underlying : s)
.Select(g => (g.Key, g.OrderBy(s => s.HasUnderlying).ToList())))
{
Log.Trace($"RandomDataGenerator.Run(): Symbol[{++count}]: {symbolRef} Progress: {progress:0.0}% - Generating data...");
var tickGenerators = new List<IEnumerator<Tick>>();
var tickHistories = new Dictionary<Symbol, List<Tick>>();
Security underlyingSecurity = null;
foreach (var currentSymbol in currentSymbolGroup)
{
if (!_securityManager.TryGetValue(currentSymbol, out var security))
{
security = _securityManager.CreateSecurity(
currentSymbol,
new List<SubscriptionDataConfig>(),
underlying: underlyingSecurity);
_securityManager.Add(security);
}
underlyingSecurity ??= security;
tickGenerators.Add(
new TickGenerator(_settings, tickTypesPerSecurityType[currentSymbol.SecurityType].ToArray(), security, randomValueGenerator)
.GenerateTicks()
.GetEnumerator());
tickHistories.Add(
currentSymbol,
new List<Tick>());
}
using var sync = new SynchronizingBaseDataEnumerator(tickGenerators);
while (sync.MoveNext())
{
var dataPoint = sync.Current;
if (!_securityManager.TryGetValue(dataPoint.Symbol, out var security))
{
Log.Error($"RandomDataGenerator.Run(): Could not find security for symbol {sync.Current.Symbol}");
continue;
}
tickHistories[security.Symbol].Add(dataPoint as Tick);
security.Update(new List<BaseData> { dataPoint }, dataPoint.GetType(), false);
}
foreach (var (currentSymbol, tickHistory) in tickHistories)
{
var symbol = currentSymbol;
// This is done so that we can update the Symbol in the case of a rename event
var delistDate = GetDelistingDate(_settings.Start, _settings.End, randomValueGenerator);
var willBeDelisted = randomValueGenerator.NextBool(1.0);
// Companies rarely IPO then disappear within 6 months
if (willBeDelisted && tickHistory.Select(tick => tick.Time.Month).Distinct().Count() <= 6)
{
willBeDelisted = false;
}
var dividendsSplitsMaps = new DividendSplitMapGenerator(
symbol,
_settings,
randomValueGenerator,
symbolGenerator,
random,
delistDate,
willBeDelisted);
// Keep track of renamed symbols and the time they were renamed.
var renamedSymbols = new Dictionary<Symbol, DateTime>();
if (_settings.SecurityType == SecurityType.Equity)
{
dividendsSplitsMaps.GenerateSplitsDividends(tickHistory);
if (!willBeDelisted)
{
dividendsSplitsMaps.DividendsSplits.Add(new CorporateFactorRow(new DateTime(2050, 12, 31), 1m, 1m));
if (dividendsSplitsMaps.MapRows.Count > 1)
{
// Remove the last element if we're going to have a 20501231 entry
dividendsSplitsMaps.MapRows.RemoveAt(dividendsSplitsMaps.MapRows.Count - 1);
}
dividendsSplitsMaps.MapRows.Add(new MapFileRow(new DateTime(2050, 12, 31), dividendsSplitsMaps.CurrentSymbol.Value));
}
// If the Symbol value has changed, update the current Symbol
if (symbol != dividendsSplitsMaps.CurrentSymbol)
{
// Add all Symbol rename events to dictionary
// We skip the first row as it contains the listing event instead of a rename event
foreach (var renameEvent in dividendsSplitsMaps.MapRows.Skip(1))
{
// Symbol.UpdateMappedSymbol does not update the underlying security ID Symbol, which
// is used to create the hash code. Create a new equity Symbol from scratch instead.
symbol = Symbol.Create(renameEvent.MappedSymbol, SecurityType.Equity, _settings.Market);
renamedSymbols.Add(symbol, renameEvent.Date);
Log.Trace($"RandomDataGenerator.Run(): Symbol[{count}]: {symbol} will be renamed on {renameEvent.Date}");
}
}
else
{
// This ensures that ticks will be written for the current Symbol up until 9999-12-31
renamedSymbols.Add(symbol, new DateTime(9999, 12, 31));
}
symbol = dividendsSplitsMaps.CurrentSymbol;
// Write Splits and Dividend events to directory factor_files
var factorFile = new CorporateFactorProvider(symbol.Value, dividendsSplitsMaps.DividendsSplits, _settings.Start);
var mapFile = new MapFile(symbol.Value, dividendsSplitsMaps.MapRows);
factorFile.WriteToFile(symbol);
mapFile.WriteToCsv(_settings.Market, symbol.SecurityType);
Log.Trace($"RandomDataGenerator.Run(): Symbol[{count}]: {symbol} Dividends, splits, and map files have been written to disk.");
}
else
{
// This ensures that ticks will be written for the current Symbol up until 9999-12-31
renamedSymbols.Add(symbol, new DateTime(9999, 12, 31));
}
// define aggregators via settings
var aggregators = CreateAggregators(_settings, tickTypesPerSecurityType[currentSymbol.SecurityType].ToArray()).ToList();
Symbol previousSymbol = null;
var currentCount = 0;
var monthsTrading = 0;
foreach (var renamed in renamedSymbols)
{
var previousRenameDate = previousSymbol == null ? new DateTime(1, 1, 1) : renamedSymbols[previousSymbol];
var previousRenameDateDay = new DateTime(previousRenameDate.Year, previousRenameDate.Month, previousRenameDate.Day);
var renameDate = renamed.Value;
var renameDateDay = new DateTime(renameDate.Year, renameDate.Month, renameDate.Day);
foreach (var tick in tickHistory.Where(tick => tick.Time >= previousRenameDate && previousRenameDateDay != TickDay(tick)))
{
// Prevents the aggregator from being updated with ticks after the rename event
if (TickDay(tick) > renameDateDay)
{
break;
}
if (tick.Time.Month != previousMonth)
{
Log.Trace($"RandomDataGenerator.Run(): Symbol[{count}]: Month: {tick.Time:MMMM}");
previousMonth = tick.Time.Month;
monthsTrading++;
}
foreach (var item in aggregators)
{
tick.Value = tick.Value / dividendsSplitsMaps.FinalSplitFactor;
item.Consolidator.Update(tick);
}
if (monthsTrading >= 6 && willBeDelisted && tick.Time > delistDate)
{
Log.Trace($"RandomDataGenerator.Run(): Symbol[{count}]: {renamed.Key} delisted at {tick.Time:MMMM yyyy}");
break;
}
}
// count each stage as a point, so total points is 2*Symbol-count
// and the current progress is twice the current, but less one because we haven't finished writing data yet
progress = 100 * (2 * count - 1) / (2.0 * _settings.SymbolCount);
Log.Trace($"RandomDataGenerator.Run(): Symbol[{count}]: {renamed.Key} Progress: {progress:0.0}% - Saving data in LEAN format");
// persist consolidated data to disk
foreach (var item in aggregators)
{
var writer = new LeanDataWriter(item.Resolution, renamed.Key, Globals.DataFolder, item.TickType);
// send the flushed data into the writer. pulling the flushed list is very important,
// lest we likely wouldn't get the last piece of data stuck in the consolidator
// Filter out the data we're going to write here because filtering them in the consolidator update phase
// makes it write all dates for some unknown reason
writer.Write(item.Flush().Where(data => data.Time > previousRenameDate && previousRenameDateDay != DataDay(data)));
}
// update progress
progress = 100 * (2 * count) / (2.0 * _settings.SymbolCount);
Log.Trace($"RandomDataGenerator.Run(): Symbol[{count}]: {symbol} Progress: {progress:0.0}% - Symbol data generation and output completed");
previousSymbol = renamed.Key;
currentCount++;
}
}
}
Log.Trace("RandomDataGenerator.Run(): Random data generation has completed.");
DateTime TickDay(Tick tick) => new(tick.Time.Year, tick.Time.Month, tick.Time.Day);
DateTime DataDay(BaseData data) => new(data.Time.Year, data.Time.Month, data.Time.Day);
}
public static DateTime GetDateMidpoint(DateTime start, DateTime end)
{
TimeSpan span = end.Subtract(start);
int span_time = (int)span.TotalMinutes;
double diff_span = -(span_time / 2.0);
DateTime start_time = end.AddMinutes(Math.Round(diff_span, 2, MidpointRounding.ToEven));
//Returns a DateTime object that is halfway between start and end
return start_time;
}
public static DateTime GetDelistingDate(DateTime start, DateTime end, RandomValueGenerator randomValueGenerator)
{
var mid_point = GetDateMidpoint(start, end);
var delist_Date = randomValueGenerator.NextDate(mid_point, end, null);
//Returns a DateTime object that is a random value between the mid_point and end
return delist_Date;
}
public static IEnumerable<TickAggregator> CreateAggregators(RandomDataGeneratorSettings settings, TickType[] tickTypes)
{
// create default aggregators for tick type/resolution
foreach (var tickAggregator in TickAggregator.ForTickTypes(settings.Resolution, tickTypes))
{
yield return tickAggregator;
}
// ensure we have a daily consolidator when coarse is enabled
if (settings.IncludeCoarse && settings.Resolution != Resolution.Daily)
{
// prefer trades for coarse - in practice equity only does trades, but leaving this as configurable
if (tickTypes.Contains(TickType.Trade))
{
yield return TickAggregator.ForTickTypes(Resolution.Daily, TickType.Trade).Single();
}
else
{
yield return TickAggregator.ForTickTypes(Resolution.Daily, TickType.Quote).Single();
}
}
}
}
}
| |
// Copyright ?2004, 2013, Oracle and/or its affiliates. All rights reserved.
//
// MySQL Connector/NET is licensed under the terms of the GPLv2
// <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
// MySQL Connectors. There are special exceptions to the terms and
// conditions of the GPLv2 as it is applied to this software, see the
// FLOSS License Exception
// <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
//
// 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; version 2 of the License.
//
// 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.,
// 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
using System;
using System.ComponentModel;
using System.Data.Common;
using System.Data;
using System.Text;
using MySql.Data.Common;
using System.Collections;
using MySql.Data.Types;
using System.Globalization;
using MySql.Data.MySqlClient.Properties;
using System.Collections.Generic;
namespace MySql.Data.MySqlClient
{
/// <include file='docs/MySqlCommandBuilder.xml' path='docs/class/*'/>
#if !RT
[ToolboxItem(false)]
[System.ComponentModel.DesignerCategory("Code")]
#endif
public sealed class MySqlCommandBuilder : DbCommandBuilder
{
/// <include file='docs/MySqlCommandBuilder.xml' path='docs/Ctor/*'/>
public MySqlCommandBuilder()
{
QuotePrefix = QuoteSuffix = "`";
}
/// <include file='docs/MySqlCommandBuilder.xml' path='docs/Ctor2/*'/>
public MySqlCommandBuilder(MySqlDataAdapter adapter)
: this()
{
DataAdapter = adapter;
}
/// <include file='docs/mysqlcommandBuilder.xml' path='docs/DataAdapter/*'/>
public new MySqlDataAdapter DataAdapter
{
get { return (MySqlDataAdapter)base.DataAdapter; }
set { base.DataAdapter = value; }
}
#region Public Methods
/// <summary>
/// Retrieves parameter information from the stored procedure specified
/// in the MySqlCommand and populates the Parameters collection of the
/// specified MySqlCommand object.
/// This method is not currently supported since stored procedures are
/// not available in MySql.
/// </summary>
/// <param name="command">The MySqlCommand referencing the stored
/// procedure from which the parameter information is to be derived.
/// The derived parameters are added to the Parameters collection of the
/// MySqlCommand.</param>
/// <exception cref="InvalidOperationException">The command text is not
/// a valid stored procedure name.</exception>
public static void DeriveParameters(MySqlCommand command)
{
if (command.CommandType != CommandType.StoredProcedure)
throw new InvalidOperationException(Resources.CanNotDeriveParametersForTextCommands);
// retrieve the proc definition from the cache.
string spName = command.CommandText;
if (spName.IndexOf(".") == -1)
spName = command.Connection.Database + "." + spName;
try
{
ProcedureCacheEntry entry = command.Connection.ProcedureCache.GetProcedure(command.Connection, spName, null);
command.Parameters.Clear();
foreach (MySqlSchemaRow row in entry.parameters.Rows)
{
MySqlParameter p = new MySqlParameter();
p.ParameterName = String.Format("@{0}", row["PARAMETER_NAME"]);
if (row["ORDINAL_POSITION"].Equals(0) && p.ParameterName == "@")
p.ParameterName = "@RETURN_VALUE";
p.Direction = GetDirection(row);
bool unsigned = StoredProcedure.GetFlags(row["DTD_IDENTIFIER"].ToString()).IndexOf("UNSIGNED") != -1;
bool real_as_float = entry.procedure.Rows[0]["SQL_MODE"].ToString().IndexOf("REAL_AS_FLOAT") != -1;
p.MySqlDbType = MetaData.NameToType(row["DATA_TYPE"].ToString(),
unsigned, real_as_float, command.Connection);
if (row["CHARACTER_MAXIMUM_LENGTH"] != null )
p.Size = (int)row["CHARACTER_MAXIMUM_LENGTH"];
if (row["NUMERIC_PRECISION"] != null)
p.Precision = Convert.ToByte(row["NUMERIC_PRECISION"]);
if (row["NUMERIC_SCALE"] != null )
p.Scale = Convert.ToByte(row["NUMERIC_SCALE"]);
if (p.MySqlDbType == MySqlDbType.Set || p.MySqlDbType == MySqlDbType.Enum)
p.PossibleValues = GetPossibleValues(row);
command.Parameters.Add(p);
}
}
catch (InvalidOperationException ioe)
{
throw new MySqlException(Resources.UnableToDeriveParameters, ioe);
}
}
private static List<string> GetPossibleValues(MySqlSchemaRow row)
{
string[] types = new string[] { "ENUM", "SET" };
string dtdIdentifier = row["DTD_IDENTIFIER"].ToString().Trim();
int index = 0;
for (; index < 2; index++)
if (dtdIdentifier.StartsWith(types[index], StringComparison.OrdinalIgnoreCase ))
break;
if (index == 2) return null;
dtdIdentifier = dtdIdentifier.Substring(types[index].Length).Trim();
dtdIdentifier = dtdIdentifier.Trim('(', ')').Trim();
List<string> values = new List<string>();
MySqlTokenizer tokenzier = new MySqlTokenizer(dtdIdentifier);
string token = tokenzier.NextToken();
int start = tokenzier.StartIndex;
while (true)
{
if (token == null || token == ",")
{
int end = dtdIdentifier.Length - 1;
if (token == ",")
end = tokenzier.StartIndex;
string value = dtdIdentifier.Substring(start, end - start).Trim('\'', '\"').Trim();
values.Add(value);
start = tokenzier.StopIndex;
}
if (token == null) break;
token = tokenzier.NextToken();
}
return values;
}
private static ParameterDirection GetDirection(MySqlSchemaRow row)
{
string mode = row["PARAMETER_MODE"].ToString();
int ordinal = Convert.ToInt32(row["ORDINAL_POSITION"]);
if (0 == ordinal)
return ParameterDirection.ReturnValue;
else if (mode == "IN")
return ParameterDirection.Input;
else if (mode == "OUT")
return ParameterDirection.Output;
return ParameterDirection.InputOutput;
}
/// <summary>
/// Gets the delete command.
/// </summary>
/// <returns></returns>
public new MySqlCommand GetDeleteCommand()
{
return (MySqlCommand)base.GetDeleteCommand();
}
/// <summary>
/// Gets the update command.
/// </summary>
/// <returns></returns>
public new MySqlCommand GetUpdateCommand()
{
return (MySqlCommand)base.GetUpdateCommand();
}
/// <summary>
/// Gets the insert command.
/// </summary>
/// <returns></returns>
public new MySqlCommand GetInsertCommand()
{
return (MySqlCommand)GetInsertCommand(false);
}
public override string QuoteIdentifier(string unquotedIdentifier)
{
if (unquotedIdentifier == null) throw new
ArgumentNullException("unquotedIdentifier");
// don't quote again if it is already quoted
if (unquotedIdentifier.StartsWith(QuotePrefix) &&
unquotedIdentifier.EndsWith(QuoteSuffix))
return unquotedIdentifier;
unquotedIdentifier = unquotedIdentifier.Replace(QuotePrefix, QuotePrefix + QuotePrefix);
return String.Format("{0}{1}{2}", QuotePrefix, unquotedIdentifier, QuoteSuffix);
}
public override string UnquoteIdentifier(string quotedIdentifier)
{
if (quotedIdentifier == null) throw new
ArgumentNullException("quotedIdentifier");
// don't unquote again if it is already unquoted
if (!quotedIdentifier.StartsWith(QuotePrefix) ||
!quotedIdentifier.EndsWith(QuoteSuffix))
return quotedIdentifier;
if (quotedIdentifier.StartsWith(QuotePrefix))
quotedIdentifier = quotedIdentifier.Substring(1);
if (quotedIdentifier.EndsWith(QuoteSuffix))
quotedIdentifier = quotedIdentifier.Substring(0, quotedIdentifier.Length - 1);
quotedIdentifier = quotedIdentifier.Replace(QuotePrefix + QuotePrefix, QuotePrefix);
return quotedIdentifier;
}
#endregion
protected override DataTable GetSchemaTable(DbCommand sourceCommand)
{
DataTable schemaTable = base.GetSchemaTable(sourceCommand);
foreach (DataRow row in schemaTable.Rows)
if (row["BaseSchemaName"].Equals(sourceCommand.Connection.Database))
row["BaseSchemaName"] = null;
return schemaTable;
}
/// <summary>
///
/// </summary>
/// <param name="parameterName"></param>
/// <returns></returns>
protected override string GetParameterName(string parameterName)
{
StringBuilder sb = new StringBuilder(parameterName);
sb.Replace(" ", "");
sb.Replace("/", "_per_");
sb.Replace("-", "_");
sb.Replace(")", "_cb_");
sb.Replace("(", "_ob_");
sb.Replace("%", "_pct_");
sb.Replace("<", "_lt_");
sb.Replace(">", "_gt_");
sb.Replace(".", "_pt_");
return String.Format("@{0}", sb.ToString());
}
protected override void ApplyParameterInfo(DbParameter parameter, DataRow row,
StatementType statementType, bool whereClause)
{
((MySqlParameter)parameter).MySqlDbType = (MySqlDbType)row["ProviderType"];
}
protected override string GetParameterName(int parameterOrdinal)
{
return String.Format("@p{0}", parameterOrdinal.ToString(CultureInfo.InvariantCulture));
}
protected override string GetParameterPlaceholder(int parameterOrdinal)
{
return String.Format("@p{0}", parameterOrdinal.ToString(CultureInfo.InvariantCulture));
}
protected override void SetRowUpdatingHandler(DbDataAdapter adapter)
{
MySqlDataAdapter myAdapter = (adapter as MySqlDataAdapter);
if (adapter != base.DataAdapter)
myAdapter.RowUpdating += new MySqlRowUpdatingEventHandler(RowUpdating);
else
myAdapter.RowUpdating -= new MySqlRowUpdatingEventHandler(RowUpdating);
}
private void RowUpdating(object sender, MySqlRowUpdatingEventArgs args)
{
base.RowUpdatingHandler(args);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using VkNet.Enums.Filters;
using VkNet.Enums.SafetyEnums;
using VkNet.Model;
using VkNet.Model.RequestParams;
using VkNet.Model.RequestParams.Messages;
using VkNet.Model.Results.Messages;
using VkNet.Utils;
namespace VkNet.Categories
{
public partial class MessagesCategory
{
/// <inheritdoc/>
public Task<bool> UnpinAsync(long peerId, ulong? groupId = null)
{
return TypeHelper.TryInvokeMethodAsync(() => Unpin(peerId, groupId));
}
/// <inheritdoc />
public Task<GetImportantMessagesResult> GetImportantMessagesAsync(GetImportantMessagesParams getImportantMessagesParams)
{
return TypeHelper.TryInvokeMethodAsync(() => GetImportantMessages(getImportantMessagesParams));
}
/// <inheritdoc />
public Task<GetRecentCallsResult> GetRecentCallsAsync(IEnumerable<string> fields, ulong? count = null, ulong? startMessageId = null,
bool? extended = null)
{
return TypeHelper.TryInvokeMethodAsync(() => GetRecentCalls(fields, count, startMessageId, extended));
}
/// <inheritdoc />
public Task<bool> AddChatUserAsync(long chatId, long userId)
{
return TypeHelper.TryInvokeMethodAsync(() => AddChatUser(chatId, userId));
}
/// <inheritdoc />
public Task<bool> AllowMessagesFromGroupAsync(long groupId, string key)
{
return TypeHelper.TryInvokeMethodAsync(() => AllowMessagesFromGroup(groupId, key));
}
/// <inheritdoc />
public Task<long> CreateChatAsync(IEnumerable<ulong> userIds, string title)
{
return TypeHelper.TryInvokeMethodAsync(() => CreateChat(userIds, title));
}
/// <inheritdoc />
public Task<IDictionary<ulong, bool>> DeleteAsync(IEnumerable<ulong> messageIds, bool? spam = null, ulong? groupId = null,
bool? deleteForAll = null)
{
return TypeHelper.TryInvokeMethodAsync(() =>
Delete(messageIds, spam, groupId, deleteForAll));
}
/// <inheritdoc />
public Task<IDictionary<ulong, bool>> DeleteAsync(IEnumerable<ulong> conversationMessageIds, ulong peerId, bool? spam = null,
ulong? groupId = null, bool? deleteForAll = null)
{
return TypeHelper.TryInvokeMethodAsync(() =>
Delete(conversationMessageIds, peerId, spam, groupId, deleteForAll));
}
/// <inheritdoc />
public Task<IDictionary<ulong, bool>> DeleteAsync(IEnumerable<ulong> conversationMessageIds, ulong? peerId, bool? spam = null,
ulong? groupId = null,
bool? deleteForAll = null)
{
return TypeHelper.TryInvokeMethodAsync(() =>
Delete(null,
conversationMessageIds,
peerId,
spam,
groupId,
deleteForAll));
}
/// <inheritdoc />
public Task<Chat> DeleteChatPhotoAsync(ulong chatId, ulong? groupId = null)
{
return TypeHelper.TryInvokeMethodAsync(() => DeleteChatPhoto(out var _, chatId, groupId));
}
/// <inheritdoc />
public Task<ulong> DeleteConversationAsync(long? userId, long? peerId = null, ulong? groupId = null)
{
return TypeHelper.TryInvokeMethodAsync(() => DeleteConversation(userId, peerId, groupId));
}
/// <inheritdoc />
public Task<ConversationResult> GetConversationsByIdAsync(IEnumerable<long> peerIds, IEnumerable<string> fields = null,
bool? extended = null, ulong? groupId = null)
{
return TypeHelper.TryInvokeMethodAsync(() => GetConversationsById(peerIds, fields, extended, groupId));
}
/// <inheritdoc />
public Task<GetConversationsResult> GetConversationsAsync(GetConversationsParams getConversationsParams)
{
return TypeHelper.TryInvokeMethodAsync(() => GetConversations(getConversationsParams));
}
/// <inheritdoc />
public Task<GetConversationMembersResult> GetConversationMembersAsync(long peerId, IEnumerable<string> fields = null,
ulong? groupId = null)
{
return TypeHelper.TryInvokeMethodAsync(() => GetConversationMembers(peerId, fields, groupId));
}
/// <inheritdoc />
public Task<GetByConversationMessageIdResult> GetByConversationMessageIdAsync(long peerId,
IEnumerable<ulong> conversationMessageIds,
IEnumerable<string> fields,
bool? extended = null,
ulong? groupId = null)
{
return TypeHelper.TryInvokeMethodAsync(() =>
GetByConversationMessageId(peerId, conversationMessageIds, fields, extended, groupId));
}
/// <inheritdoc />
public Task<SearchConversationsResult> SearchConversationsAsync(string q, IEnumerable<string> fields, ulong? count = null,
bool? extended = null, ulong? groupId = null)
{
return TypeHelper.TryInvokeMethodAsync(() => SearchConversations(q, fields, count, extended, groupId));
}
/// <inheritdoc />
public Task<PinnedMessage> PinAsync(long peerId, ulong? messageId = null, ulong? conversationMessageId = null)
{
return TypeHelper.TryInvokeMethodAsync(() => Pin(peerId, messageId, conversationMessageId));
}
/// <inheritdoc />
public Task<ulong> DeleteDialogAsync(long? userId, long? peerId = null, uint? offset = null, uint? count = null)
{
return TypeHelper.TryInvokeMethodAsync(() =>
DeleteDialog(userId, peerId, offset, count));
}
/// <inheritdoc />
public Task<bool> DenyMessagesFromGroupAsync(long groupId)
{
return TypeHelper.TryInvokeMethodAsync(() => DenyMessagesFromGroup(groupId));
}
/// <inheritdoc />
public Task<bool> EditChatAsync(long chatId, string title)
{
return TypeHelper.TryInvokeMethodAsync(() => EditChat(chatId, title));
}
/// <inheritdoc />
public Task<MessagesGetObject> GetAsync(MessagesGetParams @params)
{
return TypeHelper.TryInvokeMethodAsync(() => Get(@params));
}
/// <inheritdoc />
public Task<VkCollection<Message>> GetByIdAsync(IEnumerable<ulong> messageIds, IEnumerable<string> fields,
ulong? previewLength = null, bool? extended = null, ulong? groupId = null)
{
return TypeHelper.TryInvokeMethodAsync(() => GetById(messageIds, fields, previewLength, extended, groupId));
}
/// <inheritdoc />
public Task<GetIntentUsersResult> GetIntentUsersAsync(MessagesGetIntentUsersParams getIntentUsersParams, CancellationToken token)
{
return TypeHelper.TryInvokeMethodAsync(() => GetIntentUsers(getIntentUsersParams));
}
/// <inheritdoc />
public Task<SearchDialogsResponse> SearchDialogsAsync(string query, ProfileFields fields = null, uint? limit = null)
{
return TypeHelper.TryInvokeMethodAsync(() =>
SearchDialogs(query, fields, limit));
}
/// <inheritdoc />
public Task<MessageSearchResult> SearchAsync(MessagesSearchParams @params)
{
return TypeHelper.TryInvokeMethodAsync(() => Search(@params));
}
/// <inheritdoc />
public Task<long> SendAsync(MessagesSendParams @params)
{
return TypeHelper.TryInvokeMethodAsync(() => Send(@params));
}
/// <inheritdoc />
public Task<ReadOnlyCollection<MessagesSendResult>> SendToUserIdsAsync(MessagesSendParams @params)
{
return TypeHelper.TryInvokeMethodAsync(() => SendToUserIds(@params));
}
/// <inheritdoc />
public Task<bool> RestoreAsync(ulong messageId, ulong? groupId = null)
{
return TypeHelper.TryInvokeMethodAsync(() => Restore(messageId, groupId));
}
/// <inheritdoc />
public Task<bool> MarkAsReadAsync(string peerId, long? startMessageId = null, long? groupId = null,
bool? markConversationAsRead = null)
{
return TypeHelper.TryInvokeMethodAsync(() =>
MarkAsRead(peerId, startMessageId, groupId, markConversationAsRead));
}
/// <inheritdoc />
public Task<bool> SetActivityAsync(string userId, MessageActivityType type, long? peerId = null, ulong? groupId = null)
{
return TypeHelper.TryInvokeMethodAsync(() => SetActivity(userId, type, peerId, groupId));
}
/// <inheritdoc />
public Task<LastActivity> GetLastActivityAsync(long userId)
{
return TypeHelper.TryInvokeMethodAsync(() => GetLastActivity(userId));
}
/// <inheritdoc />
public Task<Chat> GetChatAsync(long chatId, ProfileFields fields = null, NameCase nameCase = null)
{
return TypeHelper.TryInvokeMethodAsync(() =>
GetChat(chatId, fields, nameCase));
}
/// <inheritdoc />
public Task<ReadOnlyCollection<Chat>> GetChatAsync(IEnumerable<long> chatIds
, ProfileFields fields = null
, NameCase nameCase = null)
{
return TypeHelper.TryInvokeMethodAsync(() =>
GetChat(chatIds, fields, nameCase));
}
/// <inheritdoc />
public Task<ChatPreview> GetChatPreviewAsync(string link, ProfileFields fields)
{
return TypeHelper.TryInvokeMethodAsync(() => GetChatPreview(link, fields));
}
/// <inheritdoc />
public Task<ReadOnlyCollection<User>> GetChatUsersAsync(IEnumerable<long> chatIds, UsersFields fields, NameCase nameCase)
{
return TypeHelper.TryInvokeMethodAsync(() =>
GetChatUsers(chatIds, fields, nameCase));
}
/// <inheritdoc />
public Task<MessagesGetObject> GetDialogsAsync(MessagesDialogsGetParams @params)
{
return TypeHelper.TryInvokeMethodAsync(() => GetDialogs(@params));
}
/// <inheritdoc />
public Task<MessageGetHistoryObject> GetHistoryAsync(MessagesGetHistoryParams @params)
{
return TypeHelper.TryInvokeMethodAsync(() => GetHistory(@params));
}
/// <inheritdoc/>
public Task<bool> RemoveChatUserAsync(ulong chatId, long? userId = null, long? memberId = null)
{
return TypeHelper.TryInvokeMethodAsync(() => RemoveChatUser(chatId, userId, memberId));
}
/// <inheritdoc />
public Task<LongPollServerResponse> GetLongPollServerAsync(bool needPts = false, uint lpVersion = 2, ulong? groupId = null)
{
return TypeHelper.TryInvokeMethodAsync(() =>
GetLongPollServer(needPts, lpVersion, groupId));
}
/// <inheritdoc />
public Task<LongPollHistoryResponse> GetLongPollHistoryAsync(MessagesGetLongPollHistoryParams @params)
{
return TypeHelper.TryInvokeMethodAsync(() => GetLongPollHistory(@params));
}
/// <inheritdoc />
public Task<long> SetChatPhotoAsync(string file)
{
return TypeHelper.TryInvokeMethodAsync(() => SetChatPhoto(out var _, file));
}
/// <inheritdoc />
public Task<ReadOnlyCollection<long>> MarkAsImportantAsync(IEnumerable<long> messageIds, bool important = true)
{
return TypeHelper.TryInvokeMethodAsync(() =>
MarkAsImportant(messageIds, important));
}
/// <inheritdoc />
public Task<long> SendStickerAsync(MessagesSendStickerParams parameters)
{
return TypeHelper.TryInvokeMethodAsync(() => SendSticker(parameters));
}
/// <inheritdoc />
public Task<ReadOnlyCollection<HistoryAttachment>> GetHistoryAttachmentsAsync(MessagesGetHistoryAttachmentsParams @params)
{
return TypeHelper.TryInvokeMethodAsync(() =>
GetHistoryAttachments(@params, out var _));
}
/// <inheritdoc />
public Task<string> GetInviteLinkAsync(ulong peerId, bool reset)
{
return TypeHelper.TryInvokeMethodAsync(() => GetInviteLink(peerId, reset));
}
/// <inheritdoc />
public Task<bool> IsMessagesFromGroupAllowedAsync(ulong groupId, ulong userId)
{
return TypeHelper.TryInvokeMethodAsync(() =>
IsMessagesFromGroupAllowed(groupId, userId));
}
/// <inheritdoc />
public Task<long> JoinChatByInviteLinkAsync(string link)
{
return TypeHelper.TryInvokeMethodAsync(() => JoinChatByInviteLink(link));
}
/// <inheritdoc />
public Task<bool> MarkAsAnsweredConversationAsync(long peerId, bool? answered = null, ulong? groupId = null)
{
return TypeHelper.TryInvokeMethodAsync(() => MarkAsAnsweredConversation(peerId, answered, groupId));
}
/// <inheritdoc />
public Task<bool> MarkAsAnsweredDialogAsync(long peerId, bool answered = true)
{
return TypeHelper.TryInvokeMethodAsync(() => MarkAsAnsweredDialog(peerId, answered));
}
/// <inheritdoc />
public Task<bool> MarkAsImportantConversationAsync(long peerId, bool? important = null, ulong? groupId = null)
{
return TypeHelper.TryInvokeMethodAsync(() =>
MarkAsImportantConversation(peerId, important, groupId));
}
/// <inheritdoc />
public Task<bool> MarkAsImportantDialogAsync(long peerId, bool important = true)
{
return TypeHelper.TryInvokeMethodAsync(() =>
MarkAsImportantDialog(peerId, important));
}
/// <inheritdoc />
public Task<bool> EditAsync(MessageEditParams @params)
{
return TypeHelper.TryInvokeMethodAsync(() => Edit(@params));
}
/// <inheritdoc />
public Task<bool> SendMessageEventAnswerAsync(string eventId, long userId, long peerId, EventData eventData = null)
{
return TypeHelper.TryInvokeMethodAsync(() => SendMessageEventAnswer(eventId, userId, peerId, eventData));
}
/// <inheritdoc />
public Task<bool> MarkAsUnreadConversationAsync(long peerId)
{
return TypeHelper.TryInvokeMethodAsync(() => MarkAsUnreadConversation(peerId));
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.IpMessaging.V2
{
/// <summary>
/// ReadCredentialOptions
/// </summary>
public class ReadCredentialOptions : ReadOptions<CredentialResource>
{
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
/// <summary>
/// CreateCredentialOptions
/// </summary>
public class CreateCredentialOptions : IOptions<CredentialResource>
{
/// <summary>
/// The type
/// </summary>
public CredentialResource.PushServiceEnum Type { get; }
/// <summary>
/// The friendly_name
/// </summary>
public string FriendlyName { get; set; }
/// <summary>
/// The certificate
/// </summary>
public string Certificate { get; set; }
/// <summary>
/// The private_key
/// </summary>
public string PrivateKey { get; set; }
/// <summary>
/// The sandbox
/// </summary>
public bool? Sandbox { get; set; }
/// <summary>
/// The api_key
/// </summary>
public string ApiKey { get; set; }
/// <summary>
/// The secret
/// </summary>
public string Secret { get; set; }
/// <summary>
/// Construct a new CreateCredentialOptions
/// </summary>
/// <param name="type"> The type </param>
public CreateCredentialOptions(CredentialResource.PushServiceEnum type)
{
Type = type;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Type != null)
{
p.Add(new KeyValuePair<string, string>("Type", Type.ToString()));
}
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (Certificate != null)
{
p.Add(new KeyValuePair<string, string>("Certificate", Certificate));
}
if (PrivateKey != null)
{
p.Add(new KeyValuePair<string, string>("PrivateKey", PrivateKey));
}
if (Sandbox != null)
{
p.Add(new KeyValuePair<string, string>("Sandbox", Sandbox.Value.ToString().ToLower()));
}
if (ApiKey != null)
{
p.Add(new KeyValuePair<string, string>("ApiKey", ApiKey));
}
if (Secret != null)
{
p.Add(new KeyValuePair<string, string>("Secret", Secret));
}
return p;
}
}
/// <summary>
/// FetchCredentialOptions
/// </summary>
public class FetchCredentialOptions : IOptions<CredentialResource>
{
/// <summary>
/// The sid
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchCredentialOptions
/// </summary>
/// <param name="pathSid"> The sid </param>
public FetchCredentialOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// UpdateCredentialOptions
/// </summary>
public class UpdateCredentialOptions : IOptions<CredentialResource>
{
/// <summary>
/// The sid
/// </summary>
public string PathSid { get; }
/// <summary>
/// The friendly_name
/// </summary>
public string FriendlyName { get; set; }
/// <summary>
/// The certificate
/// </summary>
public string Certificate { get; set; }
/// <summary>
/// The private_key
/// </summary>
public string PrivateKey { get; set; }
/// <summary>
/// The sandbox
/// </summary>
public bool? Sandbox { get; set; }
/// <summary>
/// The api_key
/// </summary>
public string ApiKey { get; set; }
/// <summary>
/// The secret
/// </summary>
public string Secret { get; set; }
/// <summary>
/// Construct a new UpdateCredentialOptions
/// </summary>
/// <param name="pathSid"> The sid </param>
public UpdateCredentialOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (Certificate != null)
{
p.Add(new KeyValuePair<string, string>("Certificate", Certificate));
}
if (PrivateKey != null)
{
p.Add(new KeyValuePair<string, string>("PrivateKey", PrivateKey));
}
if (Sandbox != null)
{
p.Add(new KeyValuePair<string, string>("Sandbox", Sandbox.Value.ToString().ToLower()));
}
if (ApiKey != null)
{
p.Add(new KeyValuePair<string, string>("ApiKey", ApiKey));
}
if (Secret != null)
{
p.Add(new KeyValuePair<string, string>("Secret", Secret));
}
return p;
}
}
/// <summary>
/// DeleteCredentialOptions
/// </summary>
public class DeleteCredentialOptions : IOptions<CredentialResource>
{
/// <summary>
/// The sid
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new DeleteCredentialOptions
/// </summary>
/// <param name="pathSid"> The sid </param>
public DeleteCredentialOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
}
| |
using System;
using System.IO;
namespace Raksha.Asn1
{
public class Asn1StreamParser
{
private readonly Stream _in;
private readonly int _limit;
public Asn1StreamParser(
Stream inStream)
: this(inStream, Asn1InputStream.FindLimit(inStream))
{
}
public Asn1StreamParser(
Stream inStream,
int limit)
{
if (!inStream.CanRead)
throw new ArgumentException("Expected stream to be readable", "inStream");
this._in = inStream;
this._limit = limit;
}
public Asn1StreamParser(
byte[] encoding)
: this(new MemoryStream(encoding, false), encoding.Length)
{
}
internal IAsn1Convertible ReadIndef(int tagValue)
{
// Note: INDEF => CONSTRUCTED
// TODO There are other tags that may be constructed (e.g. BIT_STRING)
switch (tagValue)
{
case Asn1Tags.External:
return new DerExternalParser(this);
case Asn1Tags.OctetString:
return new BerOctetStringParser(this);
case Asn1Tags.Sequence:
return new BerSequenceParser(this);
case Asn1Tags.Set:
return new BerSetParser(this);
default:
throw new Asn1Exception("unknown BER object encountered: 0x" + tagValue.ToString("X"));
}
}
internal IAsn1Convertible ReadImplicit(bool constructed, int tag)
{
if (_in is IndefiniteLengthInputStream)
{
if (!constructed)
throw new IOException("indefinite length primitive encoding encountered");
return ReadIndef(tag);
}
if (constructed)
{
switch (tag)
{
case Asn1Tags.Set:
return new DerSetParser(this);
case Asn1Tags.Sequence:
return new DerSequenceParser(this);
case Asn1Tags.OctetString:
return new BerOctetStringParser(this);
}
}
else
{
switch (tag)
{
case Asn1Tags.Set:
throw new Asn1Exception("sequences must use constructed encoding (see X.690 8.9.1/8.10.1)");
case Asn1Tags.Sequence:
throw new Asn1Exception("sets must use constructed encoding (see X.690 8.11.1/8.12.1)");
case Asn1Tags.OctetString:
return new DerOctetStringParser((DefiniteLengthInputStream)_in);
}
}
throw new Asn1Exception("implicit tagging not implemented");
}
internal Asn1Object ReadTaggedObject(bool constructed, int tag)
{
if (!constructed)
{
// Note: !CONSTRUCTED => IMPLICIT
DefiniteLengthInputStream defIn = (DefiniteLengthInputStream)_in;
return new DerTaggedObject(false, tag, new DerOctetString(defIn.ToArray()));
}
Asn1EncodableVector v = ReadVector();
if (_in is IndefiniteLengthInputStream)
{
return v.Count == 1
? new BerTaggedObject(true, tag, v[0])
: new BerTaggedObject(false, tag, BerSequence.FromVector(v));
}
return v.Count == 1
? new DerTaggedObject(true, tag, v[0])
: new DerTaggedObject(false, tag, DerSequence.FromVector(v));
}
public virtual IAsn1Convertible ReadObject()
{
int tag = _in.ReadByte();
if (tag == -1)
return null;
// turn of looking for "00" while we resolve the tag
Set00Check(false);
//
// calculate tag number
//
int tagNo = Asn1InputStream.ReadTagNumber(_in, tag);
bool isConstructed = (tag & Asn1Tags.Constructed) != 0;
//
// calculate length
//
int length = Asn1InputStream.ReadLength(_in, _limit);
if (length < 0) // indefinite length method
{
if (!isConstructed)
throw new IOException("indefinite length primitive encoding encountered");
IndefiniteLengthInputStream indIn = new IndefiniteLengthInputStream(_in, _limit);
Asn1StreamParser sp = new Asn1StreamParser(indIn, _limit);
if ((tag & Asn1Tags.Application) != 0)
{
return new BerApplicationSpecificParser(tagNo, sp);
}
if ((tag & Asn1Tags.Tagged) != 0)
{
return new BerTaggedObjectParser(true, tagNo, sp);
}
return sp.ReadIndef(tagNo);
}
else
{
DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(_in, length);
if ((tag & Asn1Tags.Application) != 0)
{
return new DerApplicationSpecific(isConstructed, tagNo, defIn.ToArray());
}
if ((tag & Asn1Tags.Tagged) != 0)
{
return new BerTaggedObjectParser(isConstructed, tagNo, new Asn1StreamParser(defIn));
}
if (isConstructed)
{
// TODO There are other tags that may be constructed (e.g. BitString)
switch (tagNo)
{
case Asn1Tags.OctetString:
//
// yes, people actually do this...
//
return new BerOctetStringParser(new Asn1StreamParser(defIn));
case Asn1Tags.Sequence:
return new DerSequenceParser(new Asn1StreamParser(defIn));
case Asn1Tags.Set:
return new DerSetParser(new Asn1StreamParser(defIn));
case Asn1Tags.External:
return new DerExternalParser(new Asn1StreamParser(defIn));
default:
// TODO Add DerUnknownTagParser class?
return new DerUnknownTag(true, tagNo, defIn.ToArray());
}
}
// Some primitive encodings can be handled by parsers too...
switch (tagNo)
{
case Asn1Tags.OctetString:
return new DerOctetStringParser(defIn);
}
try
{
return Asn1InputStream.CreatePrimitiveDerObject(tagNo, defIn.ToArray());
}
catch (ArgumentException e)
{
throw new Asn1Exception("corrupted stream detected", e);
}
}
}
private void Set00Check(
bool enabled)
{
if (_in is IndefiniteLengthInputStream)
{
((IndefiniteLengthInputStream) _in).SetEofOn00(enabled);
}
}
internal Asn1EncodableVector ReadVector()
{
Asn1EncodableVector v = new Asn1EncodableVector();
IAsn1Convertible obj;
while ((obj = ReadObject()) != null)
{
v.Add(obj.ToAsn1Object());
}
return v;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using Common.Logging;
using Spring.Globalization;
using Spring.Validation;
namespace Spring.DataBinding
{
/// <summary>
/// Abstract base class for simple, one-to-one <see cref="IBinding"/> implementations.
/// </summary>
/// <author>Aleksandar Seovic</author>
public abstract class AbstractSimpleBinding : AbstractBinding
{
#region Fields
private readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IFormatter formatter;
#endregion
#region Constructor(s)
/// <summary>
/// Initialize a new instance of <see cref="AbstractSimpleBinding"/> without any <see cref="IFormatter"/>
/// </summary>
protected AbstractSimpleBinding()
{
}
/// <summary>
/// Initialize a new instance of <see cref="AbstractSimpleBinding"/> with the
/// specified <see cref="IFormatter"/>.
/// </summary>
protected AbstractSimpleBinding(IFormatter formatter)
{
this.formatter = formatter;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the <see cref="IFormatter"/> to use.
/// </summary>
/// <value>The formatter to use.</value>
public IFormatter Formatter
{
get { return formatter; }
set { formatter = value; }
}
#endregion
#region IBinding Implementation
/// <summary>
/// Binds source object to target object.
/// </summary>
/// <param name="source">
/// The source object.
/// </param>
/// <param name="target">
/// The target object.
/// </param>
/// <param name="validationErrors">
/// Validation errors collection that type conversion errors should be added to.
/// </param>
/// <param name="variables">
/// Variables that should be used during expression evaluation.
/// </param>
public override void BindSourceToTarget(object source, object target, IValidationErrors validationErrors, IDictionary<string, object> variables)
{
if (this.IsValid(validationErrors)
&& (this.Direction == BindingDirection.Bidirectional || this.Direction == BindingDirection.SourceToTarget))
{
try
{
DoBindSourceToTarget(source, target, variables);
}
catch (Exception)
{
if (!SetInvalid(validationErrors)) throw;
}
}
}
/// <summary>
/// Concrete implementation if source to target binding.
/// </summary>
/// <param name="source">
/// The source object.
/// </param>
/// <param name="target">
/// The target object.
/// </param>
/// <param name="variables">
/// Variables that should be used during expression evaluation.
/// </param>
protected virtual void DoBindSourceToTarget(object source, object target, IDictionary<string, object> variables)
{
object value = this.GetSourceValue(source, variables);
if (this.Formatter != null && value is string)
{
value = this.Formatter.Parse((string)value);
}
this.SetTargetValue(target, value, variables);
}
/// <summary>
/// Binds target object to source object.
/// </summary>
/// <param name="source">
/// The source object.
/// </param>
/// <param name="target">
/// The target object.
/// </param>
/// <param name="validationErrors">
/// Validation errors collection that type conversion errors should be added to.
/// </param>
/// <param name="variables">
/// Variables that should be used during expression evaluation.
/// </param>
public override void BindTargetToSource(object source, object target, IValidationErrors validationErrors, IDictionary<string, object> variables)
{
if (this.IsValid(validationErrors)
&& (this.Direction == BindingDirection.Bidirectional || this.Direction == BindingDirection.TargetToSource))
{
try
{
DoBindTargetToSource(source, target, variables);
}
catch (Exception ex)
{
log.Warn(string.Format("Failed binding[{0}]:{1}", this.Id, ex));
if (!SetInvalid(validationErrors)) throw;
}
}
}
/// <summary>
/// Concrete implementation of target to source binding.
/// </summary>
/// <param name="source">
/// The source object.
/// </param>
/// <param name="target">
/// The target object.
/// </param>
/// <param name="variables">
/// Variables that should be used during expression evaluation.
/// </param>
protected virtual void DoBindTargetToSource(object source, object target, IDictionary<string, object> variables)
{
object value = this.GetTargetValue(target, variables);
if (this.Formatter != null)
{
value = this.Formatter.Format(value);
}
this.SetSourceValue(source, value, variables);
}
#endregion
#region Abstract Methods
/// <summary>
/// Gets the source value for the binding.
/// </summary>
/// <param name="source">
/// Source object to extract value from.
/// </param>
/// <param name="variables">
/// Variables for expression evaluation.
/// </param>
/// <returns>
/// The source value for the binding.
/// </returns>
protected abstract object GetSourceValue(object source, IDictionary<string, object> variables);
/// <summary>
/// Sets the source value for the binding.
/// </summary>
/// <param name="source">
/// The source object to set the value on.
/// </param>
/// <param name="value">
/// The value to set.
/// </param>
/// <param name="variables">
/// Variables for expression evaluation.
/// </param>
protected abstract void SetSourceValue(object source, object value, IDictionary<string, object> variables);
/// <summary>
/// Gets the target value for the binding.
/// </summary>
/// <param name="target">
/// Source object to extract value from.
/// </param>
/// <param name="variables">
/// Variables for expression evaluation.
/// </param>
/// <returns>
/// The target value for the binding.
/// </returns>
protected abstract object GetTargetValue(object target, IDictionary<string, object> variables);
/// <summary>
/// Sets the target value for the binding.
/// </summary>
/// <param name="target">
/// The target object to set the value on.
/// </param>
/// <param name="value">
/// The value to set.
/// </param>
/// <param name="variables">
/// Variables for expression evaluation.
/// </param>
protected abstract void SetTargetValue(object target, object value, IDictionary<string, object> variables);
#endregion
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Build.Evaluation;
using NuGet.Frameworks;
using NuGet.ProjectModel;
namespace Microsoft.DotNet.Cli.Utils
{
internal class MSBuildProject : IProject
{
private static readonly NuGetFramework s_toolPackageFramework = FrameworkConstants.CommonFrameworks.NetCoreApp10;
private Project _project;
private string _projectRoot;
private string _msBuildExePath;
public string DepsJsonPath
{
get
{
return _project
.AllEvaluatedProperties
.FirstOrDefault(p => p.Name.Equals("ProjectDepsFilePath"))
.EvaluatedValue;
}
}
public string RuntimeConfigJsonPath
{
get
{
return _project
.AllEvaluatedProperties
.FirstOrDefault(p => p.Name.Equals("ProjectRuntimeConfigFilePath"))
.EvaluatedValue;
}
}
public string FullOutputPath
{
get
{
return _project
.AllEvaluatedProperties
.FirstOrDefault(p => p.Name.Equals("TargetDir"))
.EvaluatedValue;
}
}
public string ProjectRoot
{
get
{
return _projectRoot;
}
}
public NuGetFramework DotnetCliToolTargetFramework
{
get
{
var frameworkString = _project
.AllEvaluatedProperties
.FirstOrDefault(p => p.Name.Equals("DotnetCliToolTargetFramework"))
?.EvaluatedValue;
if (string.IsNullOrEmpty(frameworkString))
{
return s_toolPackageFramework;
}
return NuGetFramework.Parse(frameworkString);
}
}
public Dictionary<string, string> EnvironmentVariables
{
get
{
return new Dictionary<string, string>
{
{ Constants.MSBUILD_EXE_PATH, _msBuildExePath }
};
}
}
public string ToolDepsJsonGeneratorProject
{
get
{
var generatorProject = _project
.AllEvaluatedProperties
.FirstOrDefault(p => p.Name.Equals("ToolDepsJsonGeneratorProject"))
?.EvaluatedValue;
return generatorProject;
}
}
public MSBuildProject(
string msBuildProjectPath,
NuGetFramework framework,
string configuration,
string outputPath,
string msBuildExePath)
{
_projectRoot = msBuildExePath;
var globalProperties = new Dictionary<string, string>()
{
{ "MSBuildExtensionsPath", Path.GetDirectoryName(msBuildExePath) }
};
if(framework != null)
{
globalProperties.Add("TargetFramework", framework.GetShortFolderName());
}
if(outputPath != null)
{
globalProperties.Add("OutputPath", outputPath);
}
if(configuration != null)
{
globalProperties.Add("Configuration", configuration);
}
_project = ProjectCollection.GlobalProjectCollection.LoadProject(
msBuildProjectPath,
globalProperties,
null);
_msBuildExePath = msBuildExePath;
}
public IEnumerable<SingleProjectInfo> GetTools()
{
var toolsReferences = _project.AllEvaluatedItems.Where(i => i.ItemType.Equals("DotNetCliToolReference"));
var tools = toolsReferences.Select(t => new SingleProjectInfo(
t.EvaluatedInclude,
t.GetMetadataValue("Version"),
Enumerable.Empty<ResourceAssemblyInfo>()));
return tools;
}
public LockFile GetLockFile()
{
var lockFilePath = GetLockFilePathFromProjectLockFileProperty() ??
GetLockFilePathFromIntermediateBaseOutputPath();
return new LockFileFormat()
.ReadWithLock(lockFilePath)
.Result;
}
public bool TryGetLockFile(out LockFile lockFile)
{
lockFile = null;
var lockFilePath = GetLockFilePathFromProjectLockFileProperty() ??
GetLockFilePathFromIntermediateBaseOutputPath();
if (lockFilePath == null)
{
return false;
}
if (!File.Exists(lockFilePath))
{
return false;
}
lockFile = new LockFileFormat()
.ReadWithLock(lockFilePath)
.Result;
return true;
}
private string GetLockFilePathFromProjectLockFileProperty()
{
return _project
.AllEvaluatedProperties
.Where(p => p.Name.Equals("ProjectAssetsFile"))
.Select(p => p.EvaluatedValue)
.FirstOrDefault(p => Path.IsPathRooted(p) && File.Exists(p));
}
private string GetLockFilePathFromIntermediateBaseOutputPath()
{
var intermediateOutputPath = _project
.AllEvaluatedProperties
.FirstOrDefault(p => p.Name.Equals("BaseIntermediateOutputPath"))
.EvaluatedValue;
return Path.Combine(intermediateOutputPath, "project.assets.json");
}
}
}
| |
//#define COSMOSDEBUG
using global::System;
using global::System.IO;
using Cosmos.System;
using IL2CPU.API.Attribs;
using Cosmos.System.FileSystem.VFS;
using Cosmos.System.FileSystem.Listing;
namespace Cosmos.System_Plugs.System.IO
{
[Plug(Target = typeof(FileStream))]
[PlugField(FieldId = InnerStreamFieldId, FieldType = typeof(Stream))]
public class FileStreamImpl
{
private const string InnerStreamFieldId = "$$InnerStream$$";
// This plug basically forwards all calls to the $$InnerStream$$ stream, which is supplied by the file system.
private static void Init(string aPathname, FileMode aMode, ref Stream innerStream)
{
Global.mFileSystemDebugger.SendInternal("FileStream.Init:");
innerStream = InitializeStream(aPathname, aMode);
}
public static void Ctor(FileStream aThis, string aPathname, FileMode aMode,
[FieldAccess(Name = InnerStreamFieldId)] ref Stream innerStream)
{
Init(aPathname, aMode, ref innerStream);
}
public static void CCtor()
{
// plug cctor as it (indirectly) uses Thread.MemoryBarrier()
}
public static void Ctor(FileStream aThis, string aPathname, FileMode aMode, FileAccess access,
FileShare share, int bufferSize, FileOptions options,
[FieldAccess(Name = InnerStreamFieldId)] ref Stream innerStream)
{
Init(aPathname, aMode, ref innerStream);
}
public static int Read(FileStream aThis, byte[] aBuffer, int aOffset, int aCount,
[FieldAccess(Name = InnerStreamFieldId)] ref Stream innerStream)
{
Global.mFileSystemDebugger.SendInternal("FileStream.Read:");
return innerStream.Read(aBuffer, aOffset, aCount);
}
public static int ReadByte(FileStream aThis, [FieldAccess(Name = InnerStreamFieldId)] ref Stream innerStream)
{
return innerStream.ReadByte();
}
public static void Write(FileStream aThis, byte[] aBuffer, int aOffset, int aCount,
[FieldAccess(Name = InnerStreamFieldId)] ref Stream innerStream)
{
Global.mFileSystemDebugger.SendInternal($"FileStream.Write: aOffset {aOffset} aCount {aCount}");
innerStream.Write(aBuffer, aOffset, aCount);
}
public static long get_Length(FileStream aThis,
[FieldAccess(Name = InnerStreamFieldId)] ref Stream innerStream)
{
return innerStream.Length;
}
public static void SetLength(FileStream aThis, long aLength,
[FieldAccess(Name = InnerStreamFieldId)] ref Stream innerStream)
{
innerStream.SetLength(aLength);
}
public static void Dispose(FileStream aThis, bool disposing,
[FieldAccess(Name = InnerStreamFieldId)] ref Stream innerStream)
{
if (disposing)
{
innerStream.Dispose();
}
}
public static long Seek(FileStream aThis,
[FieldAccess(Name = InnerStreamFieldId)] ref Stream innerStream, long offset, SeekOrigin origin)
{
return innerStream.Seek(offset, origin);
}
public static void Flush(FileStream aThis,
[FieldAccess(Name = InnerStreamFieldId)] ref Stream innerStream)
{
/*
* It gives NRE and kills the OS, commented it for now... we will "de-plug" FileStream soon
*/
Global.mFileSystemDebugger.SendInternal($"In FileStream.InitializeStream Flush()");
//innerStream.Flush();
}
public static long get_Position(FileStream aThis,
[FieldAccess(Name = InnerStreamFieldId)] ref Stream innerStream)
{
return innerStream.Position;
}
public static void set_Position(FileStream aThis,
[FieldAccess(Name = InnerStreamFieldId)] ref Stream innerStream, long value)
{
innerStream.Position = value;
}
private static Stream CreateNewFile(string aPath, bool aPathExists)
{
Global.mFileSystemDebugger.SendInternal($"In FileStream.CreateNewFile aPath {aPath} existing? {aPathExists}");
if (aPathExists)
{
Global.mFileSystemDebugger.SendInternal("CreateNew Mode with aPath already existing");
throw new IOException("File already existing but CreateNew Requested");
}
DirectoryEntry xEntry;
xEntry = VFSManager.CreateFile(aPath);
if (xEntry == null)
{
return null;
}
return VFSManager.GetFileStream(aPath);
}
private static Stream TruncateFile(string aPath, bool aPathExists)
{
Global.mFileSystemDebugger.SendInternal($"In FileStream.TruncateFile aPath {aPath} existing? {aPathExists}");
if (!aPathExists)
{
Global.mFileSystemDebugger.SendInternal("Truncate Mode with aPath not existing");
throw new IOException("File not existing but Truncate Requested");
}
Global.mFileSystemDebugger.SendInternal("Truncate Mode: change file lenght to 0 bytes");
var aStream = VFSManager.GetFileStream(aPath);
aStream.SetLength(0);
return aStream;
}
private static Stream CreateFile(string aPath, bool aPathExists)
{
Global.mFileSystemDebugger.SendInternal($"In FileStream.CreateFile aPath {aPath} existing? {aPathExists}");
if (aPathExists == false)
{
Global.mFileSystemDebugger.SendInternal($"File does not exist let's call CreateNew() to create it");
return CreateNewFile(aPath, aPathExists);
}
else
{
Global.mFileSystemDebugger.SendInternal($"File does exist let's call TruncateFile() to truncate it");
return TruncateFile(aPath, aPathExists);
}
}
private static Stream AppendToFile(string aPath, bool aPathExists)
{
Global.mFileSystemDebugger.SendInternal($"In FileStream.AppendToFile aPath {aPath} existing? {aPathExists}");
if (aPathExists)
{
Global.mFileSystemDebugger.SendInternal("Append mode with aPath already existing let's seek to end of the file");
var aStream = VFSManager.GetFileStream(aPath);
Global.mFileSystemDebugger.SendInternal("Actual aStream Lenght: " + aStream.Length);
aStream.Seek(0, SeekOrigin.End);
return aStream;
}
else
{
Global.mFileSystemDebugger.SendInternal("Append mode with aPath not existing let's create a new the file");
return CreateNewFile(aPath, aPathExists);
}
}
private static Stream OpenFile(string aPath, bool aPathExists)
{
Global.mFileSystemDebugger.SendInternal($"In FileStream.OpenFile aPath {aPath} existing? {aPathExists}");
if (!aPathExists)
{
Global.mFileSystemDebugger.SendInternal("Open Mode with aPath not existing");
//throw new FileNotFoundException("File not existing but Open Requested");
throw new IOException("File not existing but Open Requested");
}
Global.mFileSystemDebugger.SendInternal("Open Mode with aPath already existing opening file");
var aStream = VFSManager.GetFileStream(aPath);
aStream.Position = 0;
return aStream;
}
private static Stream OpenOrCreateFile(string aPath, bool aPathExists)
{
Global.mFileSystemDebugger.SendInternal($"In FileStream.OpenOrCreateFile aPath {aPath} existing? {aPathExists}");
if (aPathExists)
{
Global.mFileSystemDebugger.SendInternal("OpenOrCreateFile Mode with aPath already existing, let's Open it!");
return OpenFile(aPath, aPathExists);
}
else
{
Global.mFileSystemDebugger.SendInternal("OpenOrCreateFile Mode with aPath not existing, let's Create it!");
return CreateNewFile(aPath, aPathExists);
}
}
private static Stream InitializeStream(string aPath, FileMode aMode)
{
Global.mFileSystemDebugger.SendInternal($"In FileStream.InitializeStream aPath {aPath}");
if (aPath == null)
{
Global.mFileSystemDebugger.SendInternal("In FileStream.Ctor: Path == null is true");
throw new ArgumentNullException("The file path cannot be null.");
}
if (aPath.Length == 0)
{
Global.mFileSystemDebugger.SendInternal("In FileStream.Ctor: Path.Length == 0 is true");
throw new ArgumentException("The file path cannot be empty.");
}
// Before let's see if aPath already exists
bool aPathExists = VFSManager.FileExists(aPath);
switch (aMode)
{
case FileMode.Append:
return AppendToFile(aPath, aPathExists);
case FileMode.Create:
return CreateFile(aPath, aPathExists);
case FileMode.CreateNew:
return CreateNewFile(aPath, aPathExists);
case FileMode.Open:
return OpenFile(aPath, aPathExists);
case FileMode.OpenOrCreate:
return OpenOrCreateFile(aPath, aPathExists);
case FileMode.Truncate:
return TruncateFile(aPath, aPathExists);
default:
Global.mFileSystemDebugger.SendInternal("The mode " + aMode + "is out of range");
throw new ArgumentOutOfRangeException("The file mode is invalid");
}
}
public static bool get_CanWrite(FileStream aThis, [FieldAccess(Name = InnerStreamFieldId)] ref Stream innerStream)
{
return innerStream.CanWrite;
}
public static bool get_CanRead(FileStream aThis, [FieldAccess(Name = InnerStreamFieldId)] ref Stream innerStream)
{
return innerStream.CanRead;
}
public static void WriteByte(FileStream aThis, byte aByte)
{
throw new NotImplementedException();
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BamActivityStep.cs" company="Solidsoft Reply Ltd.">
// Copyright (c) 2015 Solidsoft Reply Limited. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace SolidsoftReply.Esb.Libraries.Facts
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using Microsoft.BizTalk.Bam.EventObservation;
/// <summary>
/// Represents an activity as a fact. The policy for the named activity
/// will register BAM tracking points to pass back to the resolver.
/// </summary>
/// <remarks>
/// This class subclasses the ActivityInterceptorConfiguration and surfaces
/// the activity name in order to support simple rules that test for the activity name.
/// </remarks>
[Serializable]
[XmlInclude(typeof(TrackPoint))]
public class BamActivityStep : ActivityInterceptorConfiguration
{
/// <summary>
/// The BAM activity step validator.
/// </summary>
private readonly BamActivityStepValidator bamActivityStepValidator;
/// <summary>
/// Dictionary of the number of times a given property has been set in this directive.
/// </summary>
private readonly Dictionary<string, int> actionCounts = new Dictionary<string, int>();
/// <summary>
/// Indicates whether the BAM activity step is valid;
/// </summary>
private bool isValid = true;
/// <summary>
/// Initializes a new instance of the <see cref="BamActivityStep"/> class.
/// </summary>
public BamActivityStep()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BamActivityStep"/> class.
/// Constructor.
/// </summary>
/// <param name="activityName">
/// Name of activity.
/// </param>
/// <param name="stepName">
/// Name of activity step.
/// </param>
public BamActivityStep(string activityName, string stepName)
: base(activityName)
{
this.ActivityName = activityName;
this.StepName = stepName;
this.bamActivityStepValidator = new BamActivityStepValidator(this);
}
/// <summary>
/// Gets or sets the activity name.
/// </summary>
public string ActivityName { get; set; }
/// <summary>
/// Gets or sets the BAM step name.
/// </summary>
public string StepName { get; set; }
/// <summary>
/// Gets or sets the extended step name (extensions only).
/// </summary>
public string ExtendedStepName { get; set; }
/// <summary>
/// Gets the TrackPoints.
/// </summary>
[XmlElement("TrackPoint", typeof(TrackPoint))]
public new ArrayList TrackPoints
{
get
{
return base.TrackPoints;
}
}
/// <summary>
/// Gets a value indicating whether the BAM step is valid;
/// </summary>
public bool IsValid
{
get
{
return this.isValid;
}
}
/// <summary>
/// Gets the current validity errors as text;
/// </summary>
public string ValidErrors
{
get
{
return this.isValid ? string.Empty : this.bamActivityStepValidator.ValidErrors;
}
}
/// <summary>
/// Registers point in the application where the activity begins.
/// </summary>
/// <param name="location">The identifier of a location (step) in the application code.</param>
/// <param name="activityIdExtractionInfo">The callback argument used to extract the activity identifier.</param>
public new void RegisterStartNew(object location, object activityIdExtractionInfo)
{
if (location != null && (location.ToString() != this.StepName))
{
return;
}
this.SetValidity(this.bamActivityStepValidator.ValidateStart(location, activityIdExtractionInfo));
this.IncrementActionCount("Start");
base.RegisterStartNew(location, activityIdExtractionInfo);
}
/// <summary>
/// Registers the track point in the application where the activity events cease.
/// </summary>
/// <param name="location">The identifier of a location (step) in the application code.</param>
public new void RegisterEnd(object location)
{
if (location != null && (location.ToString() != this.StepName))
{
return;
}
this.SetValidity(this.bamActivityStepValidator.ValidateEnd(location));
this.IncrementActionCount("End");
base.RegisterEnd(location);
}
/// <summary>
/// Registers step in the application where the activity continues, using a continuation token.
/// </summary>
/// <param name="location">The identifier of a location (step) in the application code.</param>
/// <param name="continuationTokenExtractionInfo">The callback argument to extract the Correlation token.</param>
public new void RegisterContinue(object location, object continuationTokenExtractionInfo)
{
if (location != null && (location.ToString() != this.StepName))
{
return;
}
this.SetValidity(this.bamActivityStepValidator.ValidateContinue(location, continuationTokenExtractionInfo));
this.IncrementActionCount("Start");
base.RegisterContinue(location, continuationTokenExtractionInfo);
}
/// <summary>
/// Registers step in the application where the activity continues, using a continuation token.
/// </summary>
/// <param name="location">The identifier of a location (step) in the application code.</param>
/// <param name="continuationTokenExtractionInfo">The callback argument to extract the Correlation token.</param>
/// <param name="prefix">
/// The prefix that makes the ID used as the activity ID and continuation ID unique among
/// components of the application that process the same activity instances.
/// </param>
public new void RegisterContinue(object location, object continuationTokenExtractionInfo, string prefix)
{
if (location != null && (location.ToString() != this.StepName))
{
return;
}
this.SetValidity(this.bamActivityStepValidator.ValidateContinue(location, continuationTokenExtractionInfo, prefix));
this.IncrementActionCount("Start");
base.RegisterContinue(location, continuationTokenExtractionInfo, prefix);
}
/// <summary>
/// Registers the extraction of the continuation token.
/// </summary>
/// <param name="location">The identifier of a location (step) in the application code.</param>
/// <param name="continuationTokenExtractionInfo">The callback argument to extract the Correlation token.</param>
public new void RegisterEnableContinuation(object location, object continuationTokenExtractionInfo)
{
if (location != null && (location.ToString() != this.StepName))
{
return;
}
this.SetValidity(this.bamActivityStepValidator.ValidateEnableContinuation(location, continuationTokenExtractionInfo));
base.RegisterEnableContinuation(location, continuationTokenExtractionInfo);
}
/// <summary>
/// Registers the extraction of the continuation token.
/// </summary>
/// <param name="location">The identifier of a location (step) in the application code.</param>
/// <param name="continuationTokenExtractionInfo">The callback argument to extract the Correlation token.</param>
/// <param name="prefix">
/// The prefix that makes the ID used as the activity ID and continuation ID unique among
/// components of the application that process the same activity instances.
/// </param>
public new void RegisterEnableContinuation(object location, object continuationTokenExtractionInfo, string prefix)
{
if (location != null && (location.ToString() != this.StepName))
{
return;
}
this.SetValidity(this.bamActivityStepValidator.ValidateEnableContinuation(location, continuationTokenExtractionInfo, prefix));
base.RegisterEnableContinuation(location, continuationTokenExtractionInfo, prefix);
}
/// <summary>
/// Registers extraction of a Business Activity Monitoring (BAM) activity item, such as a milestone or data.
/// </summary>
/// <param name="itemName">The BAM activity item name. This is the database column name.</param>
/// <param name="location">Identifier of a location (step) in the application code.</param>
/// <param name="extractionInfo">The callback argument indicating how to extract the data item.</param>
public new void RegisterDataExtraction(string itemName, object location, object extractionInfo)
{
if (location != null && (location.ToString() != this.StepName))
{
return;
}
this.SetValidity(this.bamActivityStepValidator.ValidateDataExtraction(itemName, location, extractionInfo));
base.RegisterDataExtraction(itemName, location, extractionInfo);
}
/// <summary>
/// Registers extraction of activity relationship.
/// </summary>
/// <param name="otherActivityName">The name of the other activity item.</param>
/// <param name="location">The identifier of a location (step) in the application code.</param>
/// <param name="otherIdExtractionInfo">The callback argument to extract the instance ID for the other activity item.</param>
public new void RegisterRelationship(string otherActivityName, object location, object otherIdExtractionInfo)
{
if (location != null && (location.ToString() != this.StepName))
{
return;
}
this.SetValidity(this.bamActivityStepValidator.ValidateRelationship(otherActivityName, location, otherIdExtractionInfo));
base.RegisterRelationship(otherActivityName, location, otherIdExtractionInfo);
}
/// <summary>
/// Registers the reference associated with this instance.
/// </summary>
/// <param name="referenceName">The name of the reference.</param>
/// <param name="referenceType">The type of the reference.</param>
/// <param name="location">The identifier of a location (step) in the application code.</param>
/// <param name="instanceIdExtractionInfo">The callback argument to extract the instance ID for the other activity item.</param>
public new void RegisterReference(string referenceName, string referenceType, object location, object instanceIdExtractionInfo)
{
if (location != null && (location.ToString() != this.StepName))
{
return;
}
this.SetValidity(this.bamActivityStepValidator.ValidateReference(referenceName, referenceType, location, instanceIdExtractionInfo));
base.RegisterReference(referenceName, referenceType, location, instanceIdExtractionInfo);
}
/// <summary>
/// Registers the start of a new activity.
/// </summary>
/// <param name="location">The named location.</param>
/// <param name="activityIdExtractionInfo">The extraction information of the activity ID.</param>
public void RegisterStartNewEx(object location, object activityIdExtractionInfo)
{
this.RegisterStartNew(location, activityIdExtractionInfo);
this.RegisterEnd(location);
}
/// <summary>
/// Registers the continuation of an existing activity.
/// </summary>
/// <param name="location">The named location.</param>
/// <param name="continuationTokenExtractionInfo">The extraction information of the continuation ID.</param>
public void RegisterContinueEx(object location, object continuationTokenExtractionInfo)
{
this.RegisterContinueEx(location, continuationTokenExtractionInfo, null);
}
/// <summary>
/// Registers the continuation of an existing activity.
/// </summary>
/// <param name="location">The named location.</param>
/// <param name="continuationTokenExtractionInfo">The extraction information of the activity ID.</param>
/// <param name="prefix">A unique prefix used to convert the activity ID to a continuation ID.</param>
public void RegisterContinueEx(object location, object continuationTokenExtractionInfo, string prefix)
{
// Tokenise the whitespace in a string. We will deliberately replace each individual
// whitespace character with an underscore, rather han grouping whitespace characters.
// This handles situations where a developer decides to treat whitespace as significant.
Func<string, string> tokenizeWhitespace = str => Regex.Replace(str, @"\s", "_");
this.RegisterContinue(
location,
continuationTokenExtractionInfo,
prefix == null ? null : tokenizeWhitespace(prefix));
this.RegisterEnd(location);
}
/// <summary>
/// Registers the extension of an existing activity. This is really a continuation. The prefix is
/// manufactured using the name of another step.
/// </summary>
/// <param name="step">The name of step to be extended.</param>
/// <param name="extendedStep">The name of the step that is being extended.</param>
public void RegisterExtendStep(string step, string extendedStep)
{
if (step != this.StepName)
{
return;
}
this.SetValidity(this.bamActivityStepValidator.ValidateExtend(step, extendedStep));
this.IncrementActionCount("Start");
this.RegisterContinueEx(
step,
null,
string.Format("extends_{0}", extendedStep));
this.ExtendedStepName = extendedStep;
}
/// <summary>
/// Returns the number of times a given action has been set.
/// </summary>
/// <param name="actionName">The name of the action.</param>
/// <returns>A count of the number of times the action has been set.</returns>
internal int ActionCount(string actionName)
{
int count;
return this.actionCounts.TryGetValue(actionName, out count) ? count : 0;
}
/// <summary>
/// Increments the number of times a given action has been set.
/// </summary>
/// <param name="actionName">The name of the property.</param>
private void IncrementActionCount(string actionName)
{
if (!this.actionCounts.ContainsKey(actionName))
{
this.actionCounts.Add(actionName, 0);
}
this.actionCounts[actionName] = this.actionCounts[actionName] + 1;
}
/// <summary>
/// Sets the validity flag to false if invalidity is detected.
/// </summary>
/// <param name="valid">Validity of a specific validation test.</param>
private void SetValidity(bool valid)
{
if (!valid)
{
this.isValid = false;
}
}
}
}
| |
// 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.Reflection;
using Tests.Collections;
using Xunit;
namespace System.Collections.ObjectModel.Tests
{
public class BadKey<T> : IComparable<BadKey<T>>,
IEquatable<BadKey<T>>
{
private readonly T _key;
public BadKey(T key)
{
_key = key;
}
public T Key
{
get { return _key; }
}
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has the following
/// meanings: Value Meaning Less than zero This object is less than the <paramref name="other" /> parameter.Zero This
/// object is equal to <paramref name="other" />. Greater than zero This object is greater than
/// <paramref name="other" />.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public int CompareTo(BadKey<T> other)
{
return 0;
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <returns>
/// true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public bool Equals(BadKey<T> other)
{
return true;
}
/// <summary>
/// Serves as the default hash function.
/// </summary>
/// <returns>
/// A hash code for the current object.
/// </returns>
public override int GetHashCode()
{
return 0;
}
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// </summary>
/// <returns>
/// true if the specified object is equal to the current object; otherwise, false.
/// </returns>
/// <param name="obj">The object to compare with the current object. </param>
public override bool Equals(object obj)
{
return true;
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>
/// A string that represents the current object.
/// </returns>
public override string ToString()
{
return Key == null ? "<null>" : Key.ToString();
}
}
public class BadKeyComparer<T> : IEqualityComparer<BadKey<T>>
where T : IEquatable<T>
{
/// <summary>
/// Determines whether the specified objects are equal.
/// </summary>
/// <returns>
/// true if the specified objects are equal; otherwise, false.
/// </returns>
/// <param name="x">The first object of type <paramref name="T" /> to compare.</param>
/// <param name="y">The second object of type <paramref name="T" /> to compare.</param>
public bool Equals(BadKey<T> x, BadKey<T> y)
{
if (x == null)
{
return y == null;
}
if (y == null)
{
return false;
}
if (x.Key == null)
{
return y.Key == null;
}
return x.Key.Equals(y.Key);
}
/// <summary>
/// Returns a hash code for the specified object.
/// </summary>
/// <returns>
/// A hash code for the specified object.
/// </returns>
/// <param name="obj">The <see cref="T:System.Object" /> for which a hash code is to be returned.</param>
/// <exception cref="T:System.ArgumentNullException">
/// The type of <paramref name="obj" /> is a reference type and
/// <paramref name="obj" /> is null.
/// </exception>
public int GetHashCode(BadKey<T> obj)
{
if (obj == null)
{
return 0;
}
if (obj.Key == null)
{
return 0;
}
return obj.Key.GetHashCode();
}
}
public delegate void AddItemsFunc<TKey, TValue>(
KeyedCollection<TKey, TValue> collection,
Func<TValue> generateItem,
Func<TValue, TKey> getKey,
int numItems,
out TKey[] keys,
out TValue[] items,
out TValue[] itemsWithKeys);
public static class Helper
{
public static IDictionary<TKey, TValue> GetDictionary
<TKey, TValue>(
this KeyedCollection<TKey, TValue> collection)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
MethodInfo propGet =
typeof (KeyedCollection<TKey, TValue>).GetTypeInfo()
.DeclaredProperties
.Where(
f =>
f.Name
== "Dictionary")
.Select(
f =>
f.GetMethod)
.Where(
gm =>
gm != null)
.FirstOrDefault(
gm =>
gm.IsFamily);
if (propGet == null)
{
throw new InvalidOperationException(
"Could not get dictionary property from KeyedCollection");
}
object obj = propGet.Invoke(collection, new object[0]);
return (IDictionary<TKey, TValue>) obj;
}
public static Func<IKeyedItem<T1, T2>> Bind<T1, T2>(
this KeyedCollectionGetKeyedValue<T1, T2> function,
Func<T2> val1,
Func<T2, T1> val2)
{
return () => function(val1, val2);
}
public static void Verify<TKey, TValue>(
this KeyedCollection<TKey, TValue> collection,
TKey[] expectedKeys,
TValue[] expectedItems,
TValue[] expectedItemsWithKeys)
{
if (expectedItemsWithKeys.Length != expectedKeys.Length)
{
throw new ArgumentException(
"Expected Keys length and Expected Items length must be the same");
}
Assert.Equal(expectedItems.Length, collection.Count);
// uses enumerator
CollectionAssert.Equal(expectedItems, collection);
// use int indexer
for (var i = 0; i < expectedItems.Length; ++i)
{
Assert.Equal(expectedItems[i], collection[i]);
}
// use key indexer
for (var i = 0; i < expectedItemsWithKeys.Length; ++i)
{
Assert.Equal(
expectedItemsWithKeys[i],
collection[expectedKeys[i]]);
}
// check that all keys are contained
Assert.DoesNotContain(
expectedKeys,
key => !collection.Contains(key));
// check that all values are contained
Assert.DoesNotContain(
expectedItems,
item => !collection.Contains(item));
}
public static void AddItems<TKey, TValue>(
this KeyedCollection<TKey, TValue> collection,
Func<TValue> generateItem,
Func<TValue, TKey> getKey,
int numItems,
out TKey[] keys,
out TValue[] items,
out TValue[] itemsWithKeys)
{
items = new TValue[numItems];
keys = new TKey[numItems];
itemsWithKeys = new TValue[numItems];
var keyIndex = 0;
for (var i = 0; i < numItems; ++i)
{
TValue item = generateItem();
TKey key = getKey(item);
collection.Add(item);
items[i] = item;
if (null != key)
{
keys[keyIndex] = key;
itemsWithKeys[keyIndex] = item;
++keyIndex;
}
}
keys = keys.Slice(0, keyIndex);
itemsWithKeys = itemsWithKeys.Slice(0, keyIndex);
}
public static void InsertItems<TKey, TValue>(
this KeyedCollection<TKey, TValue> collection,
Func<TValue> generateItem,
Func<TValue, TKey> getKey,
int numItems,
out TKey[] keys,
out TValue[] items,
out TValue[] itemsWithKeys)
{
items = new TValue[numItems];
keys = new TKey[numItems];
itemsWithKeys = new TValue[numItems];
var keyIndex = 0;
for (var i = 0; i < numItems; ++i)
{
TValue item = generateItem();
TKey key = getKey(item);
collection.Insert(collection.Count, item);
items[i] = item;
if (null != key)
{
keys[keyIndex] = key;
itemsWithKeys[keyIndex] = item;
++keyIndex;
}
}
keys = keys.Slice(0, keyIndex);
itemsWithKeys = itemsWithKeys.Slice(0, keyIndex);
}
public static void InsertItemsObject<TKey, TValue>(
this KeyedCollection<TKey, TValue> collection,
Func<TValue> generateItem,
Func<TValue, TKey> getKey,
int numItems,
out TKey[] keys,
out TValue[] items,
out TValue[] itemsWithKeys)
{
items = new TValue[numItems];
keys = new TKey[numItems];
itemsWithKeys = new TValue[numItems];
var keyIndex = 0;
for (var i = 0; i < numItems; ++i)
{
TValue item = generateItem();
TKey key = getKey(item);
((IList) collection).Insert(collection.Count, item);
items[i] = item;
if (null != key)
{
keys[keyIndex] = key;
itemsWithKeys[keyIndex] = item;
++keyIndex;
}
}
keys = keys.Slice(0, keyIndex);
itemsWithKeys = itemsWithKeys.Slice(0, keyIndex);
}
public static void AddItemsObject<TKey, TValue>(
this KeyedCollection<TKey, TValue> collection,
Func<TValue> generateItem,
Func<TValue, TKey> getKey,
int numItems,
out TKey[] keys,
out TValue[] items,
out TValue[] itemsWithKeys)
{
items = new TValue[numItems];
keys = new TKey[numItems];
itemsWithKeys = new TValue[numItems];
var keyIndex = 0;
for (var i = 0; i < numItems; ++i)
{
TValue item = generateItem();
TKey key = getKey(item);
((IList) collection).Add(item);
items[i] = item;
if (null != key)
{
keys[keyIndex] = key;
itemsWithKeys[keyIndex] = item;
++keyIndex;
}
}
keys = keys.Slice(0, keyIndex);
itemsWithKeys = itemsWithKeys.Slice(0, keyIndex);
}
}
public struct Named<T>
{
private readonly string _name;
private readonly T _value;
public Named(string name, T value) : this()
{
_name = name;
_value = value;
}
public string Name
{
get { return _name; }
}
public T Value
{
get { return _value; }
}
/// <summary>
/// Returns the fully qualified type name of this instance.
/// </summary>
/// <returns>
/// A <see cref="T:System.String" /> containing a fully qualified type name.
/// </returns>
public override string ToString()
{
return Name;
}
}
public interface IKeyedItem<out TKey, out TValue>
{
TKey Key { get; }
TValue Item { get; }
}
public class KeyedItem<TKey, TValue> :
IComparable<KeyedItem<TKey, TValue>>, IKeyedItem<TKey, TValue>,
IEquatable<KeyedItem<TKey, TValue>>
where TValue : IComparable<TValue>
{
private readonly TValue _item;
public KeyedItem(TKey key, TValue item)
{
Key = key;
_item = item;
}
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has the following
/// meanings: Value Meaning Less than zero This object is less than the <paramref name="other" /> parameter.Zero This
/// object is equal to <paramref name="other" />. Greater than zero This object is greater than
/// <paramref name="other" />.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public int CompareTo(KeyedItem<TKey, TValue> other)
{
if (other == null)
{
return -1;
}
if (Item == null)
{
return other.Item == null ? 0 : -1;
}
return Item.CompareTo(other.Item);
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <returns>
/// true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public bool Equals(KeyedItem<TKey, TValue> other)
{
if (other == null)
{
return false;
}
if (Item == null)
{
return other.Item == null;
}
return Item.Equals(other.Item);
}
public TKey Key { get; set; }
public TValue Item
{
get { return _item; }
}
/// <summary>
/// Serves as the default hash function.
/// </summary>
/// <returns>
/// A hash code for the current object.
/// </returns>
public override int GetHashCode()
{
if (Item == null)
{
return 0;
}
return Item.GetHashCode();
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>
/// A string that represents the current object.
/// </returns>
public override string ToString()
{
string value = Item == null ? "<null>" : Item.ToString();
string key = Key == null ? "<null>" : Key.ToString();
return "key=" + key + " value=" + value;
}
}
public class TestKeyedCollection<TKey, TValue> :
KeyedCollection<TKey, TValue>
{
private readonly Func<TValue, TKey> _getKey;
public TestKeyedCollection(Func<TValue, TKey> getKey)
: base(null, 32)
{
if (getKey == null)
{
throw new ArgumentNullException("getKey");
}
_getKey = getKey;
}
public TestKeyedCollection(
Func<TValue, TKey> getKey,
IEqualityComparer<TKey> comp) : base(comp, 32)
{
if (getKey == null)
{
throw new ArgumentNullException("getKey");
}
_getKey = getKey;
}
protected override TKey GetKeyForItem(TValue item)
{
return _getKey(item);
}
public void MyChangeItemKey(TValue item, TKey newKey)
{
ChangeItemKey(item, newKey);
}
}
public class TestKeyedCollectionOfIKeyedItem<TKey, TValue> :
KeyedCollection<TKey, IKeyedItem<TKey, TValue>>
where TKey : IEquatable<TKey>
{
public TestKeyedCollectionOfIKeyedItem(
int collectionDictionaryThreshold = 32)
: base(null, collectionDictionaryThreshold)
{
}
public TestKeyedCollectionOfIKeyedItem(
IEqualityComparer<TKey> comp,
int collectionDictionaryThreshold = 32)
: base(comp, collectionDictionaryThreshold)
{
}
protected override TKey GetKeyForItem(
IKeyedItem<TKey, TValue> item)
{
return item.Key;
}
public void MyChangeItemKey(
IKeyedItem<TKey, TValue> item,
TKey newKey)
{
ChangeItemKey(item, newKey);
}
}
public delegate IKeyedItem<TKey, TValue>
KeyedCollectionGetKeyedValue<TKey, TValue>(
Func<TValue> getValue,
Func<TValue, TKey> getKeyForItem);
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="ZoomPercentageConverter.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: Contains the ZoomPercentageConverter: TypeConverter for the
// ZoomPercentage property of DocumentViewer.
//
// History:
// 01/11/2005 - JeremyNS - Created
//
//---------------------------------------------------------------------------
// Used to support the warnings disabled below
#pragma warning disable 1634, 1691
using System;
using System.Globalization;
using System.Windows.Data;
namespace System.Windows.Documents
{
/// <summary>
/// ValueConverter for DocumentViewer's ZoomPercentage property
/// </summary>
public sealed class ZoomPercentageConverter : IValueConverter
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
/// <summary>
/// Instantiates a new instance of a ZoomPercentageConverter
/// </summary>
public ZoomPercentageConverter() {}
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
/// <summary>
/// Convert a value. Called when moving a value from ZoomPercentage to UI.
/// </summary>
/// <param name="value">value produced by the ZoomPercentage property</param>
/// <param name="targetType">target type</param>
/// <param name="parameter">converter parameter</param>
/// <param name="culture">culture information</param>
/// <returns>
/// Converted value.
///
/// System.Windows.DependencyProperty.UnsetValue may be returned to indicate that
/// the converter produced no value and that the fallback (if available)
/// or default value should be used instead.
///
/// Binding.DoNothing may be returned to indicate that the binding
/// should not transfer the value or use the fallback or default value.
/// </returns>
/// <remarks>
/// The data binding engine does not catch exceptions thrown by a user-supplied
/// converter. Thus any exception thrown by Convert, or thrown by methods
/// it calls and not caught by the Convert, will be treated as a runtime error
/// (i.e. a crash). Convert should handle anticipated problems by returning
/// DependencyProperty.UnsetValue.
/// </remarks>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// Check if the targetType has been defined correctly.
if (targetType == null)
{
return DependencyProperty.UnsetValue;
}
// Ensure that the value given is a double.
if (value != null
&& value is double)
{
double percent = (double)value;
// If string requested, format string.
// If object is requested, then return a formated string. This covers cases
// similar to ButtonBase.CommandParameter, etc.
if ((targetType == typeof(string)) || (targetType == typeof(object)))
{
// Check that value is a valid double.
if ((double.IsNaN(percent)) || (double.IsInfinity(percent)))
{
return DependencyProperty.UnsetValue;
}
else
{
// Ensure output string is formatted to current globalization standards.
return String.Format(CultureInfo.CurrentCulture,
SR.Get(SRID.ZoomPercentageConverterStringFormat), percent);
}
}
// If double requested, return direct value.
else if (targetType == typeof(double))
{
return percent;
}
}
return DependencyProperty.UnsetValue;
}
/// <summary>
/// Convert back a value. Called when moving a value into a ZoomPercentage.
/// </summary>
/// <param name="value">value, as produced by target</param>
/// <param name="targetType">target type</param>
/// <param name="parameter">converter parameter</param>
/// <param name="culture">culture information</param>
/// <returns>
/// Converted back value.
///
/// Binding.DoNothing may be returned to indicate that no value
/// should be set on the source property.
///
/// System.Windows.DependencyProperty.UnsetValue may be returned to indicate
/// that the converter is unable to provide a value for the source
/// property, and no value will be set to it.
/// </returns>
/// <remarks>
/// The data binding engine does not catch exceptions thrown by a user-supplied
/// converter. Thus any exception thrown by ConvertBack, or thrown by methods
/// it calls and not caught by the ConvertBack, will be treated as a runtime error
/// (i.e. a crash). ConvertBack should handle anticipated problems by returning
/// DependencyProperty.UnsetValue.
/// </remarks>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((targetType == typeof(double)) && (value != null))
{
double zoomValue = 0.0;
bool isValidArg = false;
// If value an int, then cast
if (value is int)
{
zoomValue = (double)(int)value;
isValidArg = true;
}
// If value is a double, then cast
else if (value is double)
{
zoomValue = (double)value;
isValidArg = true;
}
// If value is a string, then parse
else if (value is string)
{
try
{
// Remove whitespace on either end of the string.
string zoomString = (string)value;
if ((culture != null) && !String.IsNullOrEmpty(zoomString))
{
zoomString = ((string)value).Trim();
// If this is not a neutral culture attempt to remove the percent symbol.
if ((!culture.IsNeutralCulture) && (zoomString.Length > 0) && (culture.NumberFormat != null))
{
// This will strip the percent sign (if it exists) depending on the culture information.
switch (culture.NumberFormat.PercentPositivePattern)
{
case 0: // n %
case 1: // n%
// Remove the last character if it is a percent sign
if (zoomString.Length - 1 == zoomString.LastIndexOf(
culture.NumberFormat.PercentSymbol,
StringComparison.CurrentCultureIgnoreCase))
{
zoomString = zoomString.Substring(0, zoomString.Length - 1);
}
break;
case 2: // %n
// Remove the first character if it is a percent sign.
if (0 == zoomString.IndexOf(
culture.NumberFormat.PercentSymbol,
StringComparison.CurrentCultureIgnoreCase))
{
zoomString = zoomString.Substring(1);
}
break;
}
}
// If this conversion throws then the string wasn't a valid zoom value.
zoomValue = System.Convert.ToDouble(zoomString, culture);
isValidArg = true;
}
}
// Allow empty catch statements.
#pragma warning disable 56502
// Catch only the expected parse exceptions
catch (ArgumentOutOfRangeException) { }
catch (ArgumentNullException) { }
catch (FormatException) { }
catch (OverflowException) { }
// Disallow empty catch statements.
#pragma warning restore 56502
}
// Argument wasn't a valid percent, set error value.
if (!isValidArg)
{
return DependencyProperty.UnsetValue;
}
return zoomValue;
}
// Requested type is not supported.
else
{
return DependencyProperty.UnsetValue;
}
}
}
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email [email protected] |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
namespace Reporting.Rdl
{
///<summary>
/// TableGroups definition and processing.
///</summary>
[Serializable]
internal class TableGroups : ReportLink
{
List<TableGroup> _Items; // list of TableGroup entries
internal TableGroups(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p)
{
TableGroup tg;
_Items = new List<TableGroup>();
// Loop thru all the child nodes
foreach(XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "TableGroup":
tg = new TableGroup(r, this, xNodeLoop);
break;
default:
tg=null; // don't know what this is
// don't know this element - log it
OwnerReport.rl.LogError(4, "Unknown TableGroups element '" + xNodeLoop.Name + "' ignored.");
break;
}
if (tg != null)
_Items.Add(tg);
}
if (_Items.Count == 0)
OwnerReport.rl.LogError(8, "For TableGroups at least one TableGroup is required.");
else
_Items.TrimExcess();
}
override internal void FinalPass()
{
foreach(TableGroup tg in _Items)
{
tg.FinalPass();
}
return;
}
internal float DefnHeight()
{
float height=0;
foreach(TableGroup tg in _Items)
{
height += tg.DefnHeight();
}
return height;
}
internal List<TableGroup> Items
{
get { return _Items; }
}
}
///<summary>
/// TableGroup definition and processing.
///</summary>
[Serializable]
internal class TableGroup : ReportLink
{
Grouping _Grouping; // The expressions to group the data by.
Sorting _Sorting; // The expressions to sort the data by.
Header _Header; // A group header row.
Footer _Footer; // A group footer row.
Visibility _Visibility; // Indicates if the group (and all groups embedded
// within it) should be hidden.
Textbox _ToggleTextbox; // resolved TextBox for toggling visibility
internal TableGroup(ReportDefn r, ReportLink p, XmlNode xNode)
: base(r, p)
{
_Grouping = null;
_Sorting = null;
_Header = null;
_Footer = null;
_Visibility = null;
_ToggleTextbox = null;
// Loop thru all the child nodes
foreach (XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "Grouping":
_Grouping = new Grouping(r, this, xNodeLoop);
break;
case "Sorting":
_Sorting = new Sorting(r, this, xNodeLoop);
break;
case "Header":
_Header = new Header(r, this, xNodeLoop);
break;
case "Footer":
_Footer = new Footer(r, this, xNodeLoop);
break;
case "Visibility":
_Visibility = new Visibility(r, this, xNodeLoop);
break;
default:
// don't know this element - log it
OwnerReport.rl.LogError(4, "Unknown TableGroup element '" + xNodeLoop.Name + "' ignored.");
break;
}
}
if (_Grouping == null)
OwnerReport.rl.LogError(8, "TableGroup requires the Grouping element.");
}
override internal void FinalPass()
{
if (_Grouping != null)
_Grouping.FinalPass();
if (_Sorting != null)
_Sorting.FinalPass();
if (_Header != null)
_Header.FinalPass();
if (_Footer != null)
_Footer.FinalPass();
if (_Visibility != null)
{
_Visibility.FinalPass();
if (_Visibility.ToggleItem != null)
{
_ToggleTextbox = (Textbox)(OwnerReport.LUReportItems[_Visibility.ToggleItem]);
if (_ToggleTextbox != null)
_ToggleTextbox.IsToggle = true;
}
}
return;
}
internal float DefnHeight()
{
float height = 0;
if (_Header != null)
height += _Header.TableRows.DefnHeight();
if (_Footer != null)
height += _Footer.TableRows.DefnHeight();
return height;
}
internal Grouping Grouping
{
get { return _Grouping; }
set { _Grouping = value; }
}
internal Sorting Sorting
{
get { return _Sorting; }
set { _Sorting = value; }
}
internal Header Header
{
get { return _Header; }
set { _Header = value; }
}
internal int HeaderCount
{
get
{
if (_Header == null)
return 0;
else
return _Header.TableRows.Items.Count;
}
}
internal Footer Footer
{
get { return _Footer; }
set { _Footer = value; }
}
internal int FooterCount
{
get
{
if (_Footer == null)
return 0;
else
return _Footer.TableRows.Items.Count;
}
}
internal Visibility Visibility
{
get { return _Visibility; }
set { _Visibility = value; }
}
internal Textbox ToggleTextbox
{
get { return _ToggleTextbox; }
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ScriptResourceAttribute.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.Handlers;
using System.Web.Resources;
using System.Web.Script.Serialization;
using System.Web.Util;
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class ScriptResourceAttribute : Attribute {
private string _scriptName;
private string _stringResourceName;
private string _stringResourceClientTypeName;
private static readonly Regex _webResourceRegEx = new Regex(
@"<%\s*=\s*(?<resourceType>WebResource|ScriptResource)\(""(?<resourceName>[^""]*)""\)\s*%>",
RegexOptions.Singleline | RegexOptions.Multiline);
public ScriptResourceAttribute(string scriptName)
: this(scriptName, null, null) {
}
[SuppressMessage("Microsoft.Naming","CA1720:IdentifiersShouldNotContainTypeNames", MessageId="string", Justification="Refers to 'string resource', not string the type.")]
public ScriptResourceAttribute(string scriptName, string stringResourceName, string stringResourceClientTypeName) {
if (String.IsNullOrEmpty(scriptName)) {
throw new ArgumentException(AtlasWeb.Common_NullOrEmpty, "scriptName");
}
_scriptName = scriptName;
_stringResourceName = stringResourceName;
_stringResourceClientTypeName = stringResourceClientTypeName;
}
public string ScriptName {
get {
return _scriptName;
}
}
[Obsolete("This property is obsolete. Use StringResourceName instead.")]
public string ScriptResourceName {
get {
return StringResourceName;
}
}
public string StringResourceClientTypeName {
get {
return _stringResourceClientTypeName;
}
}
public string StringResourceName {
get {
return _stringResourceName;
}
}
[Obsolete("This property is obsolete. Use StringResourceClientTypeName instead.")]
public string TypeName {
get {
return StringResourceClientTypeName;
}
}
private static void AddResources(Dictionary<String, String> resources,
ResourceManager resourceManager, ResourceSet neutralSet) {
foreach (DictionaryEntry res in neutralSet) {
string key = (string)res.Key;
string value = resourceManager.GetObject(key) as string;
if (value != null) {
resources[key] = value;
}
}
}
private static Dictionary<String, String> CombineResources(
ResourceManager resourceManager, ResourceSet neutralSet,
ResourceManager releaseResourceManager, ResourceSet releaseNeutralSet) {
Dictionary<String, String> resources = new Dictionary<String, String>(StringComparer.Ordinal);
// add release resources first
AddResources(resources, releaseResourceManager, releaseNeutralSet);
// then debug, overwriting any existing release resources
AddResources(resources, resourceManager, neutralSet);
return resources;
}
private static void CopyScriptToStringBuilderWithSubstitution(
string content, Assembly assembly, bool zip, StringBuilder output) {
// Looking for something of the form: WebResource("resourcename")
MatchCollection matches = _webResourceRegEx.Matches(content);
int startIndex = 0;
foreach (Match match in matches) {
output.Append(content.Substring(startIndex, match.Index - startIndex));
Group group = match.Groups["resourceName"];
string embeddedResourceName = group.Value;
bool isScriptResource = String.Equals(
match.Groups["resourceType"].Value, "ScriptResource", StringComparison.Ordinal);
try {
if (isScriptResource) {
output.Append(ScriptResourceHandler.GetScriptResourceUrl(
assembly, embeddedResourceName, CultureInfo.CurrentUICulture, zip));
}
else {
output.Append(AssemblyResourceLoader.GetWebResourceUrlInternal(
assembly, embeddedResourceName, htmlEncoded: false, forSubstitution: true, scriptManager: null));
}
}
catch (HttpException e) {
throw new HttpException(String.Format(CultureInfo.CurrentCulture,
AtlasWeb.ScriptResourceHandler_UnknownResource,
embeddedResourceName), e);
}
startIndex = match.Index + match.Length;
}
output.Append(content.Substring(startIndex, content.Length - startIndex));
}
internal static ResourceManager GetResourceManager(string resourceName, Assembly assembly) {
if (String.IsNullOrEmpty(resourceName)) {
return null;
}
return new ResourceManager(GetResourceName(resourceName), assembly);
}
private static string GetResourceName(string rawResourceName) {
if (rawResourceName.EndsWith(".resources", StringComparison.OrdinalIgnoreCase)) {
return rawResourceName.Substring(0, rawResourceName.Length - 10);
}
return rawResourceName;
}
internal static string GetScriptFromWebResourceInternal(
Assembly assembly, string resourceName, CultureInfo culture,
bool zip, out string contentType) {
ScriptResourceInfo resourceInfo = ScriptResourceInfo.GetInstance(assembly, resourceName);
ScriptResourceInfo releaseResourceInfo = null;
if (resourceName.EndsWith(".debug.js", StringComparison.OrdinalIgnoreCase)) {
// This is a debug script, we'll need to merge the debug resource
// with the release one.
string releaseResourceName = resourceName.Substring(0, resourceName.Length - 9) + ".js";
releaseResourceInfo = ScriptResourceInfo.GetInstance(assembly, releaseResourceName);
}
if ((resourceInfo == ScriptResourceInfo.Empty) &&
((releaseResourceInfo == null) || (releaseResourceInfo == ScriptResourceInfo.Empty))) {
throw new HttpException(AtlasWeb.ScriptResourceHandler_InvalidRequest);
}
ResourceManager resourceManager = null;
ResourceSet neutralSet = null;
ResourceManager releaseResourceManager = null;
ResourceSet releaseNeutralSet = null;
CultureInfo previousCulture = Thread.CurrentThread.CurrentUICulture;
try {
Thread.CurrentThread.CurrentUICulture = culture;
if (!String.IsNullOrEmpty(resourceInfo.ScriptResourceName)) {
resourceManager = GetResourceManager(resourceInfo.ScriptResourceName, assembly);
// The following may throw MissingManifestResourceException
neutralSet = resourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, true);
}
if ((releaseResourceInfo != null) &&
!String.IsNullOrEmpty(releaseResourceInfo.ScriptResourceName)) {
releaseResourceManager = GetResourceManager(releaseResourceInfo.ScriptResourceName, assembly);
releaseNeutralSet = releaseResourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, true);
}
if ((releaseResourceInfo != null) &&
!String.IsNullOrEmpty(releaseResourceInfo.ScriptResourceName) &&
!String.IsNullOrEmpty(resourceInfo.ScriptResourceName) &&
(releaseResourceInfo.TypeName != resourceInfo.TypeName)) {
throw new HttpException(String.Format(
CultureInfo.CurrentCulture,
AtlasWeb.ScriptResourceHandler_TypeNameMismatch,
releaseResourceInfo.ScriptResourceName));
}
StringBuilder builder = new StringBuilder();
WriteScript(assembly,
resourceInfo, releaseResourceInfo,
resourceManager, neutralSet,
releaseResourceManager, releaseNeutralSet,
zip, builder);
contentType = resourceInfo.ContentType;
return builder.ToString();
}
finally {
Thread.CurrentThread.CurrentUICulture = previousCulture;
if (releaseNeutralSet != null) {
releaseNeutralSet.Dispose();
}
if (neutralSet != null) {
neutralSet.Dispose();
}
}
}
private static void RegisterNamespace(StringBuilder builder, string typeName, bool isDebug) {
int lastDot = typeName.LastIndexOf('.');
if (lastDot != -1) {
builder.Append("Type.registerNamespace('");
builder.Append(typeName.Substring(0, lastDot));
builder.Append("');");
if (isDebug) builder.AppendLine();
}
}
private static void WriteResource(StringBuilder builder,
Dictionary<String, String> resources,
bool isDebug) {
bool first = true;
foreach (KeyValuePair<String,String> res in resources) {
if (first) {
first = false;
}
else {
builder.Append(',');
}
if (isDebug) {
builder.AppendLine();
}
builder.Append('"');
builder.Append(HttpUtility.JavaScriptStringEncode(res.Key));
builder.Append("\":\"");
builder.Append(HttpUtility.JavaScriptStringEncode(res.Value));
builder.Append('"');
}
}
private static void WriteResource(
StringBuilder builder,
ResourceManager resourceManager,
ResourceSet neutralSet,
bool isDebug) {
bool first = true;
foreach (DictionaryEntry res in neutralSet) {
string key = (string)res.Key;
string value = resourceManager.GetObject(key) as string;
if (value != null) {
if (first) {
first = false;
}
else {
builder.Append(',');
}
if (isDebug) builder.AppendLine();
builder.Append('"');
builder.Append(HttpUtility.JavaScriptStringEncode(key));
builder.Append("\":\"");
builder.Append(HttpUtility.JavaScriptStringEncode(value));
builder.Append('"');
}
}
}
private static void WriteResourceToStringBuilder(
ScriptResourceInfo resourceInfo,
ScriptResourceInfo releaseResourceInfo,
ResourceManager resourceManager,
ResourceSet neutralSet,
ResourceManager releaseResourceManager,
ResourceSet releaseNeutralSet,
StringBuilder builder) {
if ((resourceManager != null) || (releaseResourceManager != null)) {
string typeName = resourceInfo.TypeName;
if (String.IsNullOrEmpty(typeName)) {
typeName = releaseResourceInfo.TypeName;
}
WriteResources(builder, typeName, resourceManager, neutralSet,
releaseResourceManager, releaseNeutralSet, resourceInfo.IsDebug);
}
}
private static void WriteResources(StringBuilder builder, string typeName,
ResourceManager resourceManager, ResourceSet neutralSet,
ResourceManager releaseResourceManager, ResourceSet releaseNeutralSet,
bool isDebug) {
// DevDiv Bugs 131109: Resources and notification should go on a new line even in release mode
// because main script may not end in a semi-colon or may end in a javascript comment.
builder.AppendLine();
RegisterNamespace(builder, typeName, isDebug);
builder.Append(typeName);
builder.Append("={");
if ((resourceManager != null) && (releaseResourceManager != null)) {
WriteResource(builder, CombineResources(resourceManager, neutralSet, releaseResourceManager, releaseNeutralSet), isDebug);
}
else {
if (resourceManager != null) {
WriteResource(builder, resourceManager, neutralSet, isDebug);
}
else if (releaseResourceManager != null) {
WriteResource(builder, releaseResourceManager, releaseNeutralSet, isDebug);
}
}
if (isDebug) {
builder.AppendLine();
builder.AppendLine("};");
}
else{
builder.Append("};");
}
}
[SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts", Justification="Violation is no longer relevant due to 4.0 CAS model")]
[FileIOPermission(SecurityAction.Assert, Unrestricted = true)]
[SecuritySafeCritical]
private static void WriteScript(Assembly assembly,
ScriptResourceInfo resourceInfo, ScriptResourceInfo releaseResourceInfo,
ResourceManager resourceManager, ResourceSet neutralSet,
ResourceManager releaseResourceManager, ResourceSet releaseNeutralSet,
bool zip, StringBuilder output) {
using (StreamReader reader = new StreamReader(
assembly.GetManifestResourceStream(resourceInfo.ScriptName), true)) {
if (resourceInfo.IsDebug) {
// Output version information
AssemblyName assemblyName = assembly.GetName();
output.AppendLine("// Name: " + resourceInfo.ScriptName);
output.AppendLine("// Assembly: " + assemblyName.Name);
output.AppendLine("// Version: " + assemblyName.Version.ToString());
output.AppendLine("// FileVersion: " + AssemblyUtil.GetAssemblyFileVersion(assembly));
}
if (resourceInfo.PerformSubstitution) {
CopyScriptToStringBuilderWithSubstitution(
reader.ReadToEnd(), assembly, zip, output);
}
else {
output.Append(reader.ReadToEnd());
}
WriteResourceToStringBuilder(resourceInfo, releaseResourceInfo,
resourceManager, neutralSet,
releaseResourceManager, releaseNeutralSet,
output);
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="EntityWriter.cs" company="Genesys Source">
// Copyright (c) Genesys Source. All rights reserved.
// 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.
// </copyright>
//-----------------------------------------------------------------------
using Genesys.Extensions;
using Genesys.Extras.Configuration;
using Genesys.Framework.Activity;
using Genesys.Framework.Data;
using Genesys.Framework.Operation;
using System;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Linq.Expressions;
namespace Genesys.Framework.Repository
{
/// <summary>
/// EF DbContext for read-only GetBy* operations
/// </summary>
public partial class StoredProcedureWriter<TEntity> : DbContext,
ICreateOperation<TEntity>, IUpdateOperation<TEntity>, IDeleteOperation<TEntity> where TEntity : StoredProcedureEntity<TEntity>, new()
{
/// <summary>
/// Data set DbSet class that gets/saves the entity.
/// Note: EF requires public get/set
/// </summary>
public DbSet<TEntity> Data { get; set; }
/// <summary>
/// Constructor
/// </summary>
public StoredProcedureWriter()
: base(ConnectionStringGet())
{
AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Directory.GetCurrentDirectory());
Database.SetInitializer<StoredProcedureWriter<TEntity>>(null);
}
/// <summary>
/// Constructor. Explicitly set database connection.
/// </summary>
/// <param name="connectionString">Connection String to be used for this object data access</param>
protected StoredProcedureWriter(string connectionString)
: base(connectionString)
{
Database.SetInitializer<StoredProcedureWriter<TEntity>>(null);
}
/// <summary>
/// Create operation on the object
/// </summary>
/// <param name="entity">Entity to be saved to datastore</param>
/// <returns>Object pulled from datastore</returns>
public TEntity Create(TEntity entity)
{
try
{
if (entity.CreateStoredProcedure == null) throw new Exception("Create() requires CreateStoredProcedure to be initialized properly.");
if (entity.IsValid() && CanInsert(entity))
{
entity.Key = entity.Key == TypeExtension.DefaultGuid ? Guid.NewGuid() : entity.Key; // Required to re-pull data after save
entity.ActivityContextKey = entity.ActivityContextKey == TypeExtension.DefaultGuid ? ActivityContextWriter.Create().ActivityContextKey : entity.ActivityContextKey;
var rowsAffected = ExecuteSqlCommand(entity.CreateStoredProcedure);
if (rowsAffected > 0) entity.Fill(Read(x => x.Key == entity.Key).FirstOrDefaultSafe()); // Re-pull clean object, exactly as the DB has stored
}
}
catch (Exception ex)
{
ExceptionLogWriter.Create(ex, typeof(TEntity), $"StoredProcedureWriter.Create() on {this.ToString()}");
throw;
}
return entity;
}
/// <summary>
/// Retrieve TEntity objects operation
/// Default: Does Not read from a Get stored procedure.
/// Reads directly from DbSet defined in repository class.
/// </summary>
/// <param name="expression">Expression to query the datastore</param>
/// <returns>IQueryable of read operation</returns>
public IQueryable<TEntity> Read(Expression<Func<TEntity, bool>> expression)
{
return Data.Where(expression);
}
/// <summary>
/// Update the object
/// </summary>
public TEntity Update(TEntity entity)
{
try
{
if (entity.UpdateStoredProcedure == null) throw new Exception("Update() requires UpdateStoredProcedure to be initialized properly.");
if (entity.IsValid() && CanUpdate(entity))
{
entity.ActivityContextKey = entity.ActivityContextKey == TypeExtension.DefaultGuid ? ActivityContextWriter.Create().ActivityContextKey : entity.ActivityContextKey;
var rowsAffected = ExecuteSqlCommand(entity.UpdateStoredProcedure);
if (rowsAffected > 0) entity.Fill(Read(x => x.Key == entity.Key).FirstOrDefaultSafe());
}
}
catch (Exception ex)
{
ExceptionLogWriter.Create(ex, typeof(TEntity), $"StoredProcedureWriter.Update() on {this.ToString()}");
throw;
}
return entity;
}
/// <summary>
/// Worker that saves this object with automatic tracking.
/// </summary>
public virtual TEntity Save(TEntity entity)
{
if (CanInsert(entity))
entity = Create(entity);
else if (CanUpdate(entity))
entity = Update(entity);
return entity;
}
/// <summary>
/// Deletes operation on this entity
/// </summary>
public TEntity Delete(TEntity entity)
{
try
{
if (entity.DeleteStoredProcedure == null) throw new Exception("Delete() requires DeleteStoredProcedure to be initialized properly.");
if (CanDelete(entity))
{
entity.ActivityContextKey = entity.ActivityContextKey == TypeExtension.DefaultGuid ? ActivityContextWriter.Create().ActivityContextKey : entity.ActivityContextKey;
var rowsAffected = ExecuteSqlCommand(entity.DeleteStoredProcedure);
if (rowsAffected > 0) entity.Fill(Read(x => x.Key == entity.Key).FirstOrDefaultSafe());
}
}
catch (Exception ex)
{
ExceptionLogWriter.Create(ex, typeof(TEntity), $"StoredProcedureWriter.Delete() on {this.ToString()}");
throw;
}
return entity;
}
/// <summary>
/// Gets connection strings from connectionstrings.config
/// </summary>
/// <returns></returns>
private static string ConnectionStringGet()
{
var returnValue = TypeExtension.DefaultString;
var configDb = new ConfigurationEntity<TEntity>();
var configManager = new ConfigurationManagerFull();
var configConnectString = configManager.ConnectionString(configDb.ConnectionName);
var adoConnectionString = configConnectString.ToADO();
if (adoConnectionString.Length > 0)
{
returnValue = adoConnectionString;
}
else
{
throw new Exception("Connection string could not be found. A valid connection string required for data access.");
}
return returnValue;
}
/// <summary>
/// Set values when creating a model in the database
/// </summary>
/// <param name="modelBuilder"></param>
/// <remarks></remarks>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
if ((DatabaseConfig.ConnectionString.Length == 0 || !CanConnect))
throw new Exception("Database connection failed or the connection string could not be found. A valid connection string required for data access.");
modelBuilder.HasDefaultSchema(DatabaseConfig.DatabaseSchema);
// Table
modelBuilder.Entity<TEntity>().ToTable(DatabaseConfig.TableName);
modelBuilder.Entity<TEntity>().HasKey(p => p.Key);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
// Columns
modelBuilder.Entity<TEntity>().Property(x => x.Id)
.HasColumnName($"{DatabaseConfig.ColumnPrefix}Id");
modelBuilder.Entity<TEntity>().Property(x => x.Key)
.HasColumnName($"{DatabaseConfig.ColumnPrefix}Key");
// Ignored
modelBuilder.Ignore(DatabaseConfig.IgnoredTypes);
foreach (var item in DatabaseConfig.IgnoredProperties)
{
modelBuilder.Entity<TEntity>().Ignore(item);
}
base.OnModelCreating(modelBuilder);
}
/// <summary>
/// Executes stored procedure for specific parameter behavior
/// Named: @Param1 is used to match parameter with entity data.
/// - Uses: Database.ExecuteSqlCommand(entity.CreateStoredProcedure.ToString());
/// Ordinal: @Param1, @Param2 are assigned in ordinal position
/// - Uses: Database.ExecuteSqlCommand(entity.CreateStoredProcedure.SqlPrefix, entity.CreateStoredProcedure.Parameters.ToArray());
/// </summary>
public int ExecuteSqlCommand(StoredProcedure<TEntity> storedProc)
{
var returnValue = TypeExtension.DefaultInteger;
switch (ParameterBehavior)
{
case ParameterBehaviors.Named:
returnValue = Database.ExecuteSqlCommand(storedProc.ToString());
break;
case ParameterBehaviors.Ordinal:
default:
returnValue = Database.ExecuteSqlCommand(storedProc.SqlPrefix, storedProc.Parameters.ToArray());
break;
}
return returnValue;
}
}
}
| |
/* ****************************************************************************
*
* 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
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if FEATURE_CORE_DLR
using MSAst = System.Linq.Expressions;
#else
using MSAst = Microsoft.Scripting.Ast;
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
/*
* The name binding:
*
* The name binding happens in 2 passes.
* In the first pass (full recursive walk of the AST) we resolve locals.
* The second pass uses the "processed" list of all context statements (functions and class
* bodies) and has each context statement resolve its free variables to determine whether
* they are globals or references to lexically enclosing scopes.
*
* The second pass happens in post-order (the context statement is added into the "processed"
* list after processing its nested functions/statements). This way, when the function is
* processing its free variables, it also knows already which of its locals are being lifted
* to the closure and can report error if such closure variable is being deleted.
*
* This is illegal in Python:
*
* def f():
* x = 10
* if (cond): del x # illegal because x is a closure variable
* def g():
* print x
*/
namespace IronPython.Compiler.Ast {
using Ast = MSAst.Expression;
class DefineBinder : PythonWalkerNonRecursive {
private PythonNameBinder _binder;
public DefineBinder(PythonNameBinder binder) {
_binder = binder;
}
public override bool Walk(NameExpression node) {
_binder.DefineName(node.Name);
return false;
}
public override bool Walk(ParenthesisExpression node) {
return true;
}
public override bool Walk(TupleExpression node) {
return true;
}
public override bool Walk(ListExpression node) {
return true;
}
}
class ParameterBinder : PythonWalkerNonRecursive {
private PythonNameBinder _binder;
public ParameterBinder(PythonNameBinder binder) {
_binder = binder;
}
public override bool Walk(Parameter node) {
node.Parent = _binder._currentScope;
node.PythonVariable = _binder.DefineParameter(node.Name);
return false;
}
public override bool Walk(SublistParameter node) {
node.PythonVariable = _binder.DefineParameter(node.Name);
node.Parent = _binder._currentScope;
// we walk the node by hand to avoid walking the default values.
WalkTuple(node.Tuple);
return false;
}
private void WalkTuple(TupleExpression tuple) {
tuple.Parent = _binder._currentScope;
foreach (Expression innerNode in tuple.Items) {
NameExpression name = innerNode as NameExpression;
if (name != null) {
_binder.DefineName(name.Name);
name.Parent = _binder._currentScope;
name.Reference = _binder.Reference(name.Name);
} else {
WalkTuple((TupleExpression)innerNode);
}
}
}
public override bool Walk(TupleExpression node) {
node.Parent = _binder._currentScope;
return true;
}
}
class DeleteBinder : PythonWalkerNonRecursive {
private PythonNameBinder _binder;
public DeleteBinder(PythonNameBinder binder) {
_binder = binder;
}
public override bool Walk(NameExpression node) {
_binder.DefineDeleted(node.Name);
return false;
}
}
class PythonNameBinder : PythonWalker {
private PythonAst _globalScope;
internal ScopeStatement _currentScope;
private List<ScopeStatement> _scopes = new List<ScopeStatement>();
private List<ILoopStatement> _loops = new List<ILoopStatement>();
private List<int> _finallyCount = new List<int>();
#region Recursive binders
private DefineBinder _define;
private DeleteBinder _delete;
private ParameterBinder _parameter;
#endregion
private readonly CompilerContext _context;
public CompilerContext Context {
get {
return _context;
}
}
private PythonNameBinder(CompilerContext context) {
_define = new DefineBinder(this);
_delete = new DeleteBinder(this);
_parameter = new ParameterBinder(this);
_context = context;
}
#region Public surface
internal static void BindAst(PythonAst ast, CompilerContext context) {
Assert.NotNull(ast, context);
PythonNameBinder binder = new PythonNameBinder(context);
binder.Bind(ast);
}
#endregion
private void Bind(PythonAst unboundAst) {
Assert.NotNull(unboundAst);
_currentScope = _globalScope = unboundAst;
_finallyCount.Add(0);
// Find all scopes and variables
unboundAst.Walk(this);
// Bind
foreach (ScopeStatement scope in _scopes) {
scope.Bind(this);
}
// Finish the globals
unboundAst.Bind(this);
// Finish Binding w/ outer most scopes first.
for (int i = _scopes.Count - 1; i >= 0; i--) {
_scopes[i].FinishBind(this);
}
// Finish the globals
unboundAst.FinishBind(this);
// Run flow checker
foreach (ScopeStatement scope in _scopes) {
FlowChecker.Check(scope);
}
}
private void PushScope(ScopeStatement node) {
node.Parent = _currentScope;
_currentScope = node;
_finallyCount.Add(0);
}
private void PopScope() {
_scopes.Add(_currentScope);
_currentScope = _currentScope.Parent;
_finallyCount.RemoveAt(_finallyCount.Count - 1);
}
internal PythonReference Reference(string name) {
return _currentScope.Reference(name);
}
internal PythonVariable DefineName(string name) {
return _currentScope.EnsureVariable(name);
}
internal PythonVariable DefineParameter(string name) {
return _currentScope.DefineParameter(name);
}
internal PythonVariable DefineDeleted(string name) {
PythonVariable variable = _currentScope.EnsureVariable(name);
variable.Deleted = true;
return variable;
}
internal void ReportSyntaxWarning(string message, Node node) {
_context.Errors.Add(_context.SourceUnit, message, node.Span, -1, Severity.Warning);
}
internal void ReportSyntaxError(string message, Node node) {
// TODO: Change the error code (-1)
_context.Errors.Add(_context.SourceUnit, message, node.Span, -1, Severity.FatalError);
throw PythonOps.SyntaxError(message, _context.SourceUnit, node.Span, -1);
}
#region AstBinder Overrides
// AssignmentStatement
public override bool Walk(AssignmentStatement node) {
node.Parent = _currentScope;
foreach (Expression e in node.Left) {
e.Walk(_define);
}
return true;
}
public override bool Walk(AugmentedAssignStatement node) {
node.Parent = _currentScope;
node.Left.Walk(_define);
return true;
}
public override void PostWalk(CallExpression node) {
if (node.NeedsLocalsDictionary()) {
_currentScope.NeedsLocalsDictionary = true;
}
}
// ClassDefinition
public override bool Walk(ClassDefinition node) {
node.PythonVariable = DefineName(node.Name);
// Base references are in the outer context
foreach (Expression b in node.Bases) b.Walk(this);
// process the decorators in the outer context
if (node.Decorators != null) {
foreach (Expression dec in node.Decorators) {
dec.Walk(this);
}
}
PushScope(node);
node.ModuleNameVariable = _globalScope.EnsureGlobalVariable("__name__");
// define the __doc__ and the __module__
if (node.Body.Documentation != null) {
node.DocVariable = DefineName("__doc__");
}
node.ModVariable = DefineName("__module__");
// Walk the body
node.Body.Walk(this);
return false;
}
// ClassDefinition
public override void PostWalk(ClassDefinition node) {
Debug.Assert(node == _currentScope);
PopScope();
}
// DelStatement
public override bool Walk(DelStatement node) {
node.Parent = _currentScope;
foreach (Expression e in node.Expressions) {
e.Walk(_delete);
}
return true;
}
// ExecStatement
public override bool Walk(ExecStatement node) {
node.Parent = _currentScope;
if (node.Locals == null && node.Globals == null) {
Debug.Assert(_currentScope != null);
_currentScope.ContainsUnqualifiedExec = true;
}
return true;
}
public override void PostWalk(ExecStatement node) {
if (node.NeedsLocalsDictionary()) {
_currentScope.NeedsLocalsDictionary = true;
}
if (node.Locals == null) {
_currentScope.HasLateBoundVariableSets = true;
}
}
public override bool Walk(SetComprehension node) {
node.Parent = _currentScope;
PushScope(node.Scope);
return base.Walk(node);
}
public override void PostWalk(SetComprehension node) {
base.PostWalk(node);
PopScope();
if (node.Scope.NeedsLocalsDictionary) {
_currentScope.NeedsLocalsDictionary = true;
}
}
public override bool Walk(DictionaryComprehension node) {
node.Parent = _currentScope;
PushScope(node.Scope);
return base.Walk(node);
}
public override void PostWalk(DictionaryComprehension node) {
base.PostWalk(node);
PopScope();
if (node.Scope.NeedsLocalsDictionary) {
_currentScope.NeedsLocalsDictionary = true;
}
}
public override void PostWalk(ConditionalExpression node) {
node.Parent = _currentScope;
base.PostWalk(node);
}
// This is generated by the scripts\generate_walker.py script.
// That will scan all types that derive from the IronPython AST nodes that aren't interesting for scopes
// and inject into here.
#region Generated Python Name Binder Propagate Current Scope
// *** BEGIN GENERATED CODE ***
// generated by function: gen_python_name_binder from: generate_walker.py
// AndExpression
public override bool Walk(AndExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// Arg
public override bool Walk(Arg node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// AssertStatement
public override bool Walk(AssertStatement node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// BackQuoteExpression
public override bool Walk(BackQuoteExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// BinaryExpression
public override bool Walk(BinaryExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// CallExpression
public override bool Walk(CallExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ComprehensionIf
public override bool Walk(ComprehensionIf node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ConditionalExpression
public override bool Walk(ConditionalExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ConstantExpression
public override bool Walk(ConstantExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// DictionaryExpression
public override bool Walk(DictionaryExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// DottedName
public override bool Walk(DottedName node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// EmptyStatement
public override bool Walk(EmptyStatement node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ErrorExpression
public override bool Walk(ErrorExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ExpressionStatement
public override bool Walk(ExpressionStatement node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// GeneratorExpression
public override bool Walk(GeneratorExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// IfStatement
public override bool Walk(IfStatement node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// IfStatementTest
public override bool Walk(IfStatementTest node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// IndexExpression
public override bool Walk(IndexExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// LambdaExpression
public override bool Walk(LambdaExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ListComprehension
public override bool Walk(ListComprehension node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ListExpression
public override bool Walk(ListExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// MemberExpression
public override bool Walk(MemberExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ModuleName
public override bool Walk(ModuleName node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// OrExpression
public override bool Walk(OrExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// Parameter
public override bool Walk(Parameter node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// ParenthesisExpression
public override bool Walk(ParenthesisExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// RelativeModuleName
public override bool Walk(RelativeModuleName node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// SetExpression
public override bool Walk(SetExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// SliceExpression
public override bool Walk(SliceExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// SublistParameter
public override bool Walk(SublistParameter node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// SuiteStatement
public override bool Walk(SuiteStatement node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// TryStatementHandler
public override bool Walk(TryStatementHandler node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// TupleExpression
public override bool Walk(TupleExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// UnaryExpression
public override bool Walk(UnaryExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// YieldExpression
public override bool Walk(YieldExpression node) {
node.Parent = _currentScope;
return base.Walk(node);
}
// *** END GENERATED CODE ***
#endregion
public override bool Walk(RaiseStatement node) {
node.Parent = _currentScope;
node.InFinally = _finallyCount[_finallyCount.Count - 1] != 0;
return base.Walk(node);
}
// ForEachStatement
public override bool Walk(ForStatement node) {
node.Parent = _currentScope;
if (_currentScope is FunctionDefinition) {
_currentScope.ShouldInterpret = false;
}
// we only push the loop for the body of the loop
// so we need to walk the for statement ourselves
node.Left.Walk(_define);
if (node.Left != null) {
node.Left.Walk(this);
}
if (node.List != null) {
node.List.Walk(this);
}
PushLoop(node);
if (node.Body != null) {
node.Body.Walk(this);
}
PopLoop();
if (node.Else != null) {
node.Else.Walk(this);
}
return false;
}
#if DEBUG
private static int _labelId;
#endif
private void PushLoop(ILoopStatement node) {
#if DEBUG
node.BreakLabel = Ast.Label("break" + _labelId++);
node.ContinueLabel = Ast.Label("continue" + _labelId++);
#else
node.BreakLabel = Ast.Label("break");
node.ContinueLabel = Ast.Label("continue");
#endif
_loops.Add(node);
}
private void PopLoop() {
_loops.RemoveAt(_loops.Count - 1);
}
public override bool Walk(WhileStatement node) {
node.Parent = _currentScope;
// we only push the loop for the body of the loop
// so we need to walk the while statement ourselves
if (node.Test != null) {
node.Test.Walk(this);
}
PushLoop(node);
if (node.Body != null) {
node.Body.Walk(this);
}
PopLoop();
if (node.ElseStatement != null) {
node.ElseStatement.Walk(this);
}
return false;
}
public override bool Walk(BreakStatement node) {
node.Parent = _currentScope;
node.LoopStatement = _loops[_loops.Count - 1];
return base.Walk(node);
}
public override bool Walk(ContinueStatement node) {
node.Parent = _currentScope;
node.LoopStatement = _loops[_loops.Count - 1];
return base.Walk(node);
}
public override bool Walk(ReturnStatement node) {
node.Parent = _currentScope;
FunctionDefinition funcDef = _currentScope as FunctionDefinition;
if (funcDef != null) {
funcDef._hasReturn = true;
}
return base.Walk(node);
}
// WithStatement
public override bool Walk(WithStatement node) {
node.Parent = _currentScope;
_currentScope.ContainsExceptionHandling = true;
if (node.Variable != null) {
node.Variable.Walk(_define);
}
return true;
}
// FromImportStatement
public override bool Walk(FromImportStatement node) {
node.Parent = _currentScope;
if (node.Names != FromImportStatement.Star) {
PythonVariable[] variables = new PythonVariable[node.Names.Count];
node.Root.Parent = _currentScope;
for (int i = 0; i < node.Names.Count; i++) {
string name = node.AsNames[i] != null ? node.AsNames[i] : node.Names[i];
variables[i] = DefineName(name);
}
node.Variables = variables;
} else {
Debug.Assert(_currentScope != null);
_currentScope.ContainsImportStar = true;
_currentScope.NeedsLocalsDictionary = true;
_currentScope.HasLateBoundVariableSets = true;
}
return true;
}
// FunctionDefinition
public override bool Walk(FunctionDefinition node) {
node._nameVariable = _globalScope.EnsureGlobalVariable("__name__");
// Name is defined in the enclosing context
if (!node.IsLambda) {
node.PythonVariable = DefineName(node.Name);
}
// process the default arg values in the outer context
foreach (Parameter p in node.Parameters) {
if (p.DefaultValue != null) {
p.DefaultValue.Walk(this);
}
}
// process the decorators in the outer context
if (node.Decorators != null) {
foreach (Expression dec in node.Decorators) {
dec.Walk(this);
}
}
PushScope(node);
foreach (Parameter p in node.Parameters) {
p.Walk(_parameter);
}
node.Body.Walk(this);
return false;
}
// FunctionDefinition
public override void PostWalk(FunctionDefinition node) {
Debug.Assert(_currentScope == node);
PopScope();
}
// GlobalStatement
public override bool Walk(GlobalStatement node) {
node.Parent = _currentScope;
foreach (string n in node.Names) {
PythonVariable conflict;
// Check current scope for conflicting variable
bool assignedGlobal = false;
if (_currentScope.TryGetVariable(n, out conflict)) {
// conflict?
switch (conflict.Kind) {
case VariableKind.Global:
case VariableKind.Local:
assignedGlobal = true;
ReportSyntaxWarning(
String.Format(
System.Globalization.CultureInfo.InvariantCulture,
"name '{0}' is assigned to before global declaration",
n
),
node
);
break;
case VariableKind.Parameter:
ReportSyntaxError(
String.Format(
System.Globalization.CultureInfo.InvariantCulture,
"Name '{0}' is a function parameter and declared global",
n),
node);
break;
}
}
// Check for the name being referenced previously. If it has been, issue warning.
if (_currentScope.IsReferenced(n) && !assignedGlobal) {
ReportSyntaxWarning(
String.Format(
System.Globalization.CultureInfo.InvariantCulture,
"name '{0}' is used prior to global declaration",
n),
node);
}
// Create the variable in the global context and mark it as global
PythonVariable variable = _globalScope.EnsureGlobalVariable(n);
variable.Kind = VariableKind.Global;
if (conflict == null) {
// no previously definied variables, add it to the current scope
_currentScope.AddGlobalVariable(variable);
}
}
return true;
}
public override bool Walk(NameExpression node) {
node.Parent = _currentScope;
node.Reference = Reference(node.Name);
return true;
}
// PythonAst
public override bool Walk(PythonAst node) {
if (node.Module) {
node.NameVariable = DefineName("__name__");
node.FileVariable = DefineName("__file__");
node.DocVariable = DefineName("__doc__");
// commonly used module variables that we want defined for optimization purposes
DefineName("__path__");
DefineName("__builtins__");
DefineName("__package__");
}
return true;
}
// PythonAst
public override void PostWalk(PythonAst node) {
// Do not add the global suite to the list of processed nodes,
// the publishing must be done after the class local binding.
Debug.Assert(_currentScope == node);
_currentScope = _currentScope.Parent;
_finallyCount.RemoveAt(_finallyCount.Count - 1);
}
// ImportStatement
public override bool Walk(ImportStatement node) {
node.Parent = _currentScope;
PythonVariable[] variables = new PythonVariable[node.Names.Count];
for (int i = 0; i < node.Names.Count; i++) {
string name = node.AsNames[i] != null ? node.AsNames[i] : node.Names[i].Names[0];
variables[i] = DefineName(name);
node.Names[i].Parent = _currentScope;
}
node.Variables = variables;
return true;
}
// TryStatement
public override bool Walk(TryStatement node) {
// we manually walk the TryStatement so we can track finally blocks.
node.Parent = _currentScope;
_currentScope.ContainsExceptionHandling = true;
node.Body.Walk(this);
if (node.Handlers != null) {
foreach (TryStatementHandler tsh in node.Handlers) {
if (tsh.Target != null) {
tsh.Target.Walk(_define);
}
tsh.Parent = _currentScope;
tsh.Walk(this);
}
}
if (node.Else != null) {
node.Else.Walk(this);
}
if (node.Finally != null) {
_finallyCount[_finallyCount.Count - 1]++;
node.Finally.Walk(this);
_finallyCount[_finallyCount.Count - 1]--;
}
return false;
}
// ListComprehensionFor
public override bool Walk(ComprehensionFor node) {
node.Parent = _currentScope;
node.Left.Walk(_define);
return true;
}
#endregion
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="EditTypeDataControl.xaml.cs" company="None">
// None
// </copyright>
// <summary>
// Interaction logic for EditItemControl.xaml
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using TfsWorkbench.UIElements.ValueConverters;
namespace TfsWorkbench.WpfUI.Controls
{
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using Core.DataObjects;
using Core.Interfaces;
using UIElements;
/// <summary>
/// Interaction logic for EditItemControl.xaml
/// </summary>
public partial class EditTypeDataControl
{
/// <summary>
/// The null selection text.
/// </summary>
private const string NullSelectionText = "[None]";
/// <summary>
/// The project data property.
/// </summary>
private static readonly DependencyProperty projectDataProperty = DependencyProperty.Register(
"ProjectData",
typeof(IProjectData),
typeof(EditTypeDataControl),
new PropertyMetadata(null, OnProjectDataChanged));
/// <summary>
/// The captionField dependency property.
/// </summary>
private static readonly DependencyProperty captionFieldProperty = DependencyProperty.Register(
"CaptionField",
typeof(string),
typeof(EditTypeDataControl));
/// <summary>
/// The bodyField dependency property.
/// </summary>
private static readonly DependencyProperty bodyFieldProperty = DependencyProperty.Register(
"BodyField",
typeof(string),
typeof(EditTypeDataControl));
/// <summary>
/// The numericField dependency property.
/// </summary>
private static readonly DependencyProperty numericFieldProperty = DependencyProperty.Register(
"NumericField",
typeof(string),
typeof(EditTypeDataControl));
/// <summary>
/// The ownerField dependency property.
/// </summary>
private static readonly DependencyProperty ownerFieldProperty = DependencyProperty.Register(
"OwnerField",
typeof(string),
typeof(EditTypeDataControl));
/// <summary>
/// The is initialising flag.
/// </summary>
private bool isInitialising;
/// <summary>
/// Initializes a new instance of the <see cref="EditTypeDataControl"/> class.
/// </summary>
public EditTypeDataControl()
{
this.ItemTypeNames = new ObservableCollection<string>();
this.AvailableDisplayFields = new ObservableCollection<string>();
this.ColourOptions = new ObservableCollection<string>(BackgroundBrushConverter.ColourOptions);
this.InitializeComponent();
}
/// <summary>
/// Gets the project data property.
/// </summary>
/// <value>The project data property.</value>
public static DependencyProperty ProjectDataProperty
{
get { return projectDataProperty; }
}
/// <summary>
/// Gets the CaptionField property.
/// </summary>
/// <value>The name property.</value>
public static DependencyProperty CaptionFieldProperty
{
get { return captionFieldProperty; }
}
/// <summary>
/// Gets the NumericField property.
/// </summary>
/// <value>The name property.</value>
public static DependencyProperty NumericFieldProperty
{
get { return numericFieldProperty; }
}
/// <summary>
/// Gets the BodyField property.
/// </summary>
/// <value>The name property.</value>
public static DependencyProperty BodyFieldProperty
{
get { return bodyFieldProperty; }
}
/// <summary>
/// Gets the OwnerField property.
/// </summary>
/// <value>The name property.</value>
public static DependencyProperty OwnerFieldProperty
{
get { return ownerFieldProperty; }
}
/// <summary>
/// Gets or sets the control items.
/// </summary>
/// <value>The control items.</value>
public IProjectData ProjectData
{
get { return (IProjectData)this.GetValue(ProjectDataProperty); }
set { this.SetValue(ProjectDataProperty, value); }
}
/// <summary>
/// Gets the type names.
/// </summary>
/// <value>The type names.</value>
public ObservableCollection<string> ItemTypeNames { get; private set; }
/// <summary>
/// Gets the available fields.
/// </summary>
/// <value>The available fields.</value>
public ObservableCollection<string> AvailableDisplayFields { get; private set; }
public ObservableCollection<string> ColourOptions { get; private set; }
/// <summary>
/// Gets or sets the instance CaptionField.
/// </summary>
/// <returns>The instance CaptionField.</returns>
public string CaptionField
{
get { return (string)this.GetValue(CaptionFieldProperty); }
set { this.SetValue(CaptionFieldProperty, value); }
}
/// <summary>
/// Gets or sets the instance BodyField.
/// </summary>
/// <returns>The instance BodyField.</returns>
public string BodyField
{
get { return (string)this.GetValue(BodyFieldProperty); }
set { this.SetValue(BodyFieldProperty, value); }
}
/// <summary>
/// Gets or sets the instance NumericField.
/// </summary>
/// <returns>The instance NumericField.</returns>
public string NumericField
{
get { return (string)this.GetValue(NumericFieldProperty); }
set { this.SetValue(NumericFieldProperty, value); }
}
/// <summary>
/// Gets or sets the instance OwnerField.
/// </summary>
/// <returns>The instance OwnerField.</returns>
public string OwnerField
{
get { return (string)this.GetValue(OwnerFieldProperty); }
set { this.SetValue(OwnerFieldProperty, value); }
}
public string SelectedColour { get; private set; }
/// <summary>
/// Called when [project data changed].
/// </summary>
/// <param name="dependencyObject">The dependency object.</param>
/// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
private static void OnProjectDataChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var control = dependencyObject as EditTypeDataControl;
if (control == null)
{
return;
}
control.ItemTypeNames.Clear();
if (control.ProjectData == null)
{
return;
}
foreach (var typeName in control.ProjectData.ItemTypes.Select(t => t.TypeName).OrderBy(n => n))
{
control.ItemTypeNames.Add(typeName);
}
}
/// <summary>
/// Tries to get the ref name.
/// </summary>
/// <param name="selectedTypeData">The selected type data.</param>
/// <param name="displayName">The display name.</param>
/// <param name="refName">The ref name.</param>
/// <returns>
/// <c>True</c> if the ref name is found; otherwise <c>false</c>.
/// </returns>
private static bool TryGetRefName(ItemTypeData selectedTypeData, string displayName, out string refName)
{
var field = selectedTypeData.Fields.FirstOrDefault(f => Equals(f.DisplayName, displayName));
refName = field == null ? null : field.ReferenceName;
return !string.IsNullOrEmpty(refName);
}
/// <summary>
/// Tries to get the display name.
/// </summary>
/// <param name="selectedTypeData">The selected type data.</param>
/// <param name="refName">The ref name.</param>
/// <param name="displayName">The display name.</param>
/// <returns><c>True</c> if the display name is found; otherwise <c>false</c>.</returns>
private static bool TryGetDisplayName(ItemTypeData selectedTypeData, string refName, out string displayName)
{
var field = selectedTypeData.Fields.FirstOrDefault(f => Equals(f.ReferenceName, refName));
displayName = field == null ? null : field.DisplayName;
return !string.IsNullOrEmpty(displayName);
}
/// <summary>
/// Handles the Click event of the CloseButton control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
private void CloseButtonClick(object sender, RoutedEventArgs e)
{
CommandLibrary.CloseDialogCommand.Execute(this, Application.Current.MainWindow);
this.CommitDisplayFieldChanges();
foreach (var workbenchItem in this.ProjectData.WorkbenchItems)
{
workbenchItem.OnPropertyChanged();
}
this.ReleaseReferencedObjects();
}
/// <summary>
/// Commits the display field changes.
/// </summary>
private void CommitDisplayFieldChanges()
{
ItemTypeData selectedTypeData;
if (!this.TryGetSelectedType(out selectedTypeData))
{
return;
}
string refName;
selectedTypeData.CaptionField = TryGetRefName(selectedTypeData, this.CaptionField, out refName) ? refName : string.Empty;
selectedTypeData.BodyField = TryGetRefName(selectedTypeData, this.BodyField, out refName) ? refName : string.Empty;
selectedTypeData.NumericField = TryGetRefName(selectedTypeData, this.NumericField, out refName) ? refName : string.Empty;
selectedTypeData.OwnerField = TryGetRefName(selectedTypeData, this.OwnerField, out refName) ? refName : string.Empty;
selectedTypeData.DefaultColour = PART_ColourSelector.SelectedValue as string;
}
/// <summary>
/// Releases the control collection.
/// </summary>
private void ReleaseReferencedObjects()
{
this.ProjectData = null;
this.ItemTypeNames.Clear();
}
/// <summary>
/// Handles the Click event of the AddItem control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
private void AddItemClick(object sender, RoutedEventArgs e)
{
ItemTypeData selectedTypeData;
if (!this.TryGetSelectedType(out selectedTypeData))
{
return;
}
var selectedItems = this.PART_AvailableFields.SelectedItems.OfType<string>().ToArray();
if (!selectedItems.Any())
{
return;
}
foreach (var selectedItem in selectedItems)
{
var localSelectedItem = selectedItem;
this.PART_SelectedFields.Items.Add(localSelectedItem);
this.PART_AvailableFields.Items.Remove(localSelectedItem);
var fieldData = selectedTypeData.Fields.FirstOrDefault(f => f.DisplayName.Equals(localSelectedItem));
if (fieldData == null)
{
continue;
}
selectedTypeData.ContextFields.Add(fieldData.ReferenceName);
}
}
/// <summary>
/// Handles the Click event of the RemoveItem control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
private void RemoveItemClick(object sender, RoutedEventArgs e)
{
ItemTypeData selectedTypeData;
if (!this.TryGetSelectedType(out selectedTypeData))
{
return;
}
var selectedItems = this.PART_SelectedFields.SelectedItems.OfType<string>().ToArray();
if (!selectedItems.Any())
{
return;
}
foreach (var selectedItem in selectedItems)
{
var localSelectedItem = selectedItem;
this.PART_SelectedFields.Items.Remove(localSelectedItem);
this.PART_AvailableFields.Items.Add(localSelectedItem);
var fieldData = selectedTypeData.Fields.FirstOrDefault(f => f.DisplayName.Equals(localSelectedItem));
if (fieldData == null)
{
continue;
}
selectedTypeData.ContextFields.Remove(fieldData.ReferenceName);
}
}
/// <summary>
/// Handles the SelectionChanged event of the ItemType control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Controls.SelectionChangedEventArgs"/> instance containing the event data.</param>
private void ItemTypeSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (this.ProjectData == null)
{
return;
}
this.isInitialising = true;
this.PART_AvailableFields.Items.Clear();
this.PART_SelectedFields.Items.Clear();
this.PART_AvailableDuplicationFields.Items.Clear();
this.PART_SelectedDuplicationFields.Items.Clear();
this.PART_SelectedFields.Items.Clear();
this.AvailableDisplayFields.Clear();
this.AvailableDisplayFields.Add(NullSelectionText);
ItemTypeData selectedTypeData;
if (!this.TryGetSelectedType(out selectedTypeData))
{
return;
}
string displayName;
this.CaptionField = TryGetDisplayName(selectedTypeData, selectedTypeData.CaptionField, out displayName) ? displayName : NullSelectionText;
this.BodyField = TryGetDisplayName(selectedTypeData, selectedTypeData.BodyField, out displayName) ? displayName : NullSelectionText;
this.NumericField = TryGetDisplayName(selectedTypeData, selectedTypeData.NumericField, out displayName) ? displayName : NullSelectionText;
this.OwnerField = TryGetDisplayName(selectedTypeData, selectedTypeData.OwnerField, out displayName) ? displayName : NullSelectionText;
PART_ColourSelector.SelectedValue = selectedTypeData.DefaultColour;
foreach (var field in selectedTypeData.Fields.OrderBy(f => f.DisplayName))
{
this.AvailableDisplayFields.Add(field.DisplayName);
if (field.IsEditable && !selectedTypeData.DuplicationFields.Contains(field.ReferenceName))
{
this.PART_AvailableDuplicationFields.Items.Add(field.DisplayName);
}
if (field.IsDisplayField && !selectedTypeData.ContextFields.Contains(field.ReferenceName))
{
this.PART_AvailableFields.Items.Add(field.DisplayName);
}
}
foreach (var contextField in
selectedTypeData.ContextFields
.Select(name => selectedTypeData.Fields.FirstOrDefault(f => f.ReferenceName.Equals(name)))
.Where(field => field != null))
{
this.PART_SelectedFields.Items.Add(contextField.DisplayName);
}
foreach (var duplicationField in
selectedTypeData.DuplicationFields
.Select(name => selectedTypeData.Fields.FirstOrDefault(f => f.ReferenceName.Equals(name)))
.Where(field => field != null))
{
this.PART_SelectedDuplicationFields.Items.Add(duplicationField.DisplayName);
}
var binding = this.PART_Body.GetBindingExpression(Selector.SelectedValueProperty);
if (binding != null)
{
binding.UpdateTarget();
}
binding = this.PART_Caption.GetBindingExpression(Selector.SelectedValueProperty);
if (binding != null)
{
binding.UpdateTarget();
}
binding = this.PART_Numeric.GetBindingExpression(Selector.SelectedValueProperty);
if (binding != null)
{
binding.UpdateTarget();
}
binding = this.PART_Owner.GetBindingExpression(Selector.SelectedValueProperty);
if (binding != null)
{
binding.UpdateTarget();
}
this.isInitialising = false;
}
/// <summary>
/// Tries the type of the get selected.
/// </summary>
/// <param name="typeData">The type data.</param>
/// <returns><c>True</c> if type data is matched; otherwise <c>false</c>.</returns>
private bool TryGetSelectedType(out ItemTypeData typeData)
{
var selectedType = this.PART_SelectedItemType.SelectedItem as string;
return this.ProjectData.ItemTypes.TryGetValue(selectedType, out typeData);
}
/// <summary>
/// Handles the SelectionChanged event of the DisplayField control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Controls.SelectionChangedEventArgs"/> instance containing the event data.</param>
private void DisplayField_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (this.isInitialising)
{
return;
}
this.CommitDisplayFieldChanges();
}
private void AddDuplicationItemClick(object sender, RoutedEventArgs e)
{
ItemTypeData selectedTypeData;
if (!this.TryGetSelectedType(out selectedTypeData))
{
return;
}
var selectedItems = this.PART_AvailableDuplicationFields.SelectedItems.OfType<string>().ToArray();
if (!selectedItems.Any())
{
return;
}
foreach (var selectedItem in selectedItems)
{
var localSelectedItem = selectedItem;
this.PART_SelectedDuplicationFields.Items.Add(localSelectedItem);
this.PART_AvailableDuplicationFields.Items.Remove(localSelectedItem);
var fieldData = selectedTypeData.Fields.FirstOrDefault(f => f.DisplayName.Equals(localSelectedItem));
if (fieldData == null)
{
continue;
}
selectedTypeData.DuplicationFields.Add(fieldData.ReferenceName);
}
}
private void RemoveDuplicationItemClick(object sender, RoutedEventArgs e)
{
ItemTypeData selectedTypeData;
if (!this.TryGetSelectedType(out selectedTypeData))
{
return;
}
var selectedItems = this.PART_SelectedDuplicationFields.SelectedItems.OfType<string>().ToArray();
if (!selectedItems.Any())
{
return;
}
foreach (var selectedItem in selectedItems)
{
var localSelectedItem = selectedItem;
this.PART_SelectedDuplicationFields.Items.Remove(localSelectedItem);
this.PART_AvailableDuplicationFields.Items.Add(localSelectedItem);
var fieldData = selectedTypeData.Fields.FirstOrDefault(f => f.DisplayName.Equals(localSelectedItem));
if (fieldData == null)
{
continue;
}
selectedTypeData.DuplicationFields.Remove(fieldData.ReferenceName);
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
namespace Palaso.UI.WindowsForms.Widgets
{
/// <summary>
/// possible button states
/// </summary>
public enum BtnState
{
/// <summary>
/// The button is disabled.
/// </summary>
Inactive = 0,
/// <summary>
/// The button is in it normal unpressed state
/// </summary>
Normal = 1,
/// <summary>
/// The location of the mouse is over the button
/// </summary>
MouseOver = 2,
/// <summary>
/// The button is currently being pressed
/// </summary>
Pushed = 3,
}
/// <summary>
/// The purpose of this class is to continue to provide the regular functionality of button class with
/// some additional bitmap enhancments. These enhancements allow the specification of bitmaps for each
/// state of the button. In addition, it makes use of the alignment properties already provided by the
/// base button class. Since this class renders the image, it should appear similar accross platforms.
/// </summary>
public class BitmapButton : System.Windows.Forms.Button
{
#region Private Variables
private System.Drawing.Image _ImageNormal = null;
private System.Drawing.Image _ImageFocused = null;
private System.Drawing.Image _ImagePressed = null;
private System.Drawing.Image _ImageMouseOver = null;
private System.Drawing.Image _ImageInactive = null;
private System.Drawing.Color _BorderColor = System.Drawing.Color.DarkBlue;
private System.Drawing.Color _InnerBorderColor = System.Drawing.Color.LightGray;
private System.Drawing.Color _InnerBorderColor_Focus = System.Drawing.Color.LightBlue;
private System.Drawing.Color _InnerBorderColor_MouseOver = System.Drawing.Color.Gold;
private System.Drawing.Color _ImageBorderColor = System.Drawing.Color.Chocolate;
private bool _StretchImage = false;
private bool _TextDropShadow = true;
private int _Padding = 5;
private bool _OffsetPressedContent = true;
private bool _ImageBorderEnabled = true;
private bool _ImageDropShadow = true;
private bool _FocusRectangleEnabled = true;
public BtnState State = BtnState.Normal;
private bool CapturingMouse = false;
#endregion
#region Public Properties
[Browsable(false)]
new public System.Drawing.Image Image
{
get{return base.Image;}
set{base.Image = value;}
}
[Browsable(false)]
new public System.Windows.Forms.ImageList ImageList
{
get{return base.ImageList;}
set{base.ImageList = value;}
}
[Browsable(false)]
new public int ImageIndex
{
get{return base.ImageIndex;}
set{base.ImageIndex = value;}
}
/// <summary>
/// Enable the shadowing of the button text
/// </summary>
[Browsable(true),
Category("Appearance"),
Description("enables the text to cast a shadow"),
System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)
]
public bool TextDropShadow
{
get{return _TextDropShadow;}
set{_TextDropShadow = value;}
}
/// <summary>
/// Enables the dashed focus rectangle
/// </summary>
[Browsable(true),
Category("Appearance"),
Description("enables the focus rectangle"),
System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)
]
public bool FocusRectangleEnabled
{
get{return _FocusRectangleEnabled;}
set{_FocusRectangleEnabled = value;}
}
/// <summary>
/// Enable the shadowing of the image in the button
/// </summary>
[Browsable(true),
Category("Appearance"),
Description("enables the image to cast a shadow"),
System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)
]
public bool ImageDropShadow
{
get{return _ImageDropShadow;}
set{_ImageDropShadow = value;}
}
/// <summary>
/// This specifies the color of image border. Note, this is only valid if ImageBorder is enabled.
/// </summary>
[Browsable(true),
Category("Appearance"),
Description("Color of the border around the image"),
System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)
]
public System.Drawing.Color ImageBorderColor
{
get{return _ImageBorderColor;}
set{_ImageBorderColor = value;}
}
/// <summary>
/// This enables/disables the bordering of the image.
/// </summary>
[Browsable(true),
Category("Appearance"),
Description("Enables the bordering of the image"),
System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)
]
public bool ImageBorderEnabled
{
get{return _ImageBorderEnabled;}
set{_ImageBorderEnabled = value;}
}
/// <summary>
/// Color of the inner border when the button does not have focus
/// </summary>
[Browsable(true),
Category("Appearance"),
Description("Color of the button text when enabled = false"),
System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)
]
public System.Drawing.Color DisabledTextColor
{
get;
set;
}
/// <summary>
/// Color of the border around the button
/// </summary>
[Browsable(true),
Category("Appearance"),
Description("Color of the border around the button"),
System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)
]
public System.Drawing.Color BorderColor
{
get{return _BorderColor;}
set{_BorderColor = value;}
}
/// <summary>
/// Color of the inner border when the button has focus
/// </summary>
[Browsable(true),
Category("Appearance"),
Description("Color of the inner border when the button has focus"),
System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)
]
public System.Drawing.Color InnerBorderColor_Focus
{
get{return _InnerBorderColor_Focus;}
set{_InnerBorderColor_Focus = value;}
}
/// <summary>
/// Color of the inner border when the button does not have focus
/// </summary>
[Browsable(true),
Category("Appearance"),
Description("Color of the inner border when the button does not hvae focus"),
System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)
]
public System.Drawing.Color InnerBorderColor
{
get{return _InnerBorderColor;}
set{_InnerBorderColor = value;}
}
/// <summary>
/// Color of the inner border when the mouse is over the button.
/// </summary>
[Browsable(true),
Category("Appearance"),
Description("color of the inner border when the mouse is over the button"),
System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)
]
public System.Drawing.Color InnerBorderColor_MouseOver
{
get{return _InnerBorderColor_MouseOver;}
set{_InnerBorderColor_MouseOver = value;}
}
/// <summary>
/// Stretches the image across the button
/// </summary>
[Browsable(true),
Category("Appearance"),
Description("stretch the impage to the size of the button"),
System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)
]
public bool StretchImage
{
get{return _StretchImage;}
set{_StretchImage = value;}
}
/// <summary>
/// Specifies the padding in units of pixels around the button button elements. Currently,
/// the button elements consist of the image and text.
/// </summary>
[Browsable(true),
Category("Appearance"),
Description("padded pixels around the image and text"),
System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)
]
public int Padding
{
get{return _Padding;}
set{_Padding = value;}
}
/// <summary>
/// Set to true if to offset button elements when button is pressed
/// </summary>
[Browsable(true),
Category("Appearance"),
Description("Set to true if to offset image/text when button is pressed"),
System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)
]
public bool OffsetPressedContent
{
get{return
_OffsetPressedContent;}
set{_OffsetPressedContent = value;}
}
/// <summary>
/// Image to be displayed while the button state is in normal state. If the other
/// states do not specify an image, this image is used as a substitute.
/// </summary>
[Browsable(true),
Category("Appearance"),
Description("Image to be displayed while the button state is in normal state"),
System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)
]
public System.Drawing.Image ImageNormal
{
get{return _ImageNormal;}
set{_ImageNormal = value;}
}
/// <summary>
/// Specifies an image to use while the button has focus.
/// </summary>
[Browsable(true),
Category("Appearance"),
Description("Image to be displayed while the button has focus"),
System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)
]
public System.Drawing.Image ImageFocused
{
get{return _ImageFocused;}
set{_ImageFocused = value;}
}
/// <summary>
/// Specifies an image to use while the button is enactive.
/// </summary>
[Browsable(true),
Category("Appearance"),
Description("Image to be displayed while the button is inactive"),
System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)
]
public System.Drawing.Image ImageInactive
{
get{return _ImageInactive;}
set{_ImageInactive = value;}
}
/// <summary>
/// Specifies an image to use while the button is pressed.
/// </summary>
[Browsable(true),
Category("Appearance"),
Description("Image to be displayed while the button state is pressed"),
System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)
]
public System.Drawing.Image ImagePressed
{
get{return _ImagePressed;}
set
{
_ImagePressed = value;
Refresh();
}
}
/// <summary>
/// Specifies an image to use while the mouse is over the button.
/// </summary>
[Browsable(true),
Category("Appearance"),
Description("Image to be displayed while the button state is MouseOver"),
System.ComponentModel.RefreshProperties(RefreshProperties.Repaint)
]
public System.Drawing.Image ImageMouseOver
{
get{return _ImageMouseOver;}
set{_ImageMouseOver = value;}
}
#endregion
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
/// <summary>
/// The BitmapButton constructor
/// </summary>
public BitmapButton()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// TODO: Add any initialization after the InitComponent call
//LoadGraphics();
ImageAttributes = new ImageAttributes();
DisabledTextColor = System.Drawing.Color.DimGray;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if( components != null )
components.Dispose();
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
#region Paint Methods
/// <summary>
/// This method paints the button in its entirety.
/// </summary>
/// <param name="e">paint arguments use to paint the button</param>
protected override void OnPaint(PaintEventArgs e)
{
CreateRegion(0);
paint_Background(e);
paint_Text(e);
paint_Image(e);
paint_Border(e);
paint_InnerBorder(e);
paint_FocusBorder(e);
}
/// <summary>
/// This method fills the background of the button.
/// </summary>
/// <param name="e">paint arguments use to paint the button</param>
private void paint_Background(PaintEventArgs e)
{
if(e == null)
return;
if(e.Graphics == null)
return;
Graphics g =e.Graphics;
System.Drawing.Rectangle rect = new Rectangle(0,0,Size.Width,Size.Height);
//
// get color of background
//
System.Drawing.Color color = this.BackColor;;
if(State == BtnState.Inactive)
color = System.Drawing.Color.LightGray;
//
// intialize ColorArray and Positions Array
//
Color[] ColorArray = null;
float[] PositionArray = null;
//
// initialize color array for a button that is pushed
//
if(State == BtnState.Pushed)
{
ColorArray = new Color[]{
Blend(this.BackColor,System.Drawing.Color.White,80),
Blend(this.BackColor,System.Drawing.Color.White,40),
Blend(this.BackColor,System.Drawing.Color.Black,0),
Blend(this.BackColor,System.Drawing.Color.Black,0),
Blend(this.BackColor,System.Drawing.Color.White,40),
Blend(this.BackColor,System.Drawing.Color.White,80),
};
PositionArray = new float[]{0.0f,.05f,.40f,.60f,.95f,1.0f};
}
//
// else, initialize color array for a button that is normal or disabled
//
else
{
ColorArray = new Color[]{
Blend(color,System.Drawing.Color.White,80),
Blend(color,System.Drawing.Color.White,90),
Blend(color,System.Drawing.Color.White,30),
Blend(color,System.Drawing.Color.White,00),
Blend(color,System.Drawing.Color.Black,30),
Blend(color,System.Drawing.Color.Black,20),
};
PositionArray = new float[]{0.0f,.15f,.40f,.65f,.80f,1.0f};
}
//
// create blend variable for the interpolate the colors
//
System.Drawing.Drawing2D.ColorBlend blend = new System.Drawing.Drawing2D.ColorBlend();
blend.Colors = ColorArray;
blend.Positions = PositionArray;
if (FlatStyle == FlatStyle.Flat)
{
using (var brush = new SolidBrush(BackColor))
{
g.FillRectangle(brush,rect);
}
}
else
{
//
// create vertical gradient brush
//
using(System.Drawing.Drawing2D.LinearGradientBrush brush =
new System.Drawing.Drawing2D.LinearGradientBrush(rect, this.BackColor,
Blend(this.BackColor, this.BackColor, 10),
System.Drawing.Drawing2D.LinearGradientMode.
Vertical))
{
brush.InterpolationColors = blend;
g.FillRectangle(brush, rect);
}
}
}
/// <summary>
/// paints the 1 pixel border around the button. The color of
/// the border is defined by BorderColor
/// </summary>
/// <param name="e">paint arguments use to paint the button</param>
private void paint_Border(PaintEventArgs e)
{
if (FlatStyle == FlatStyle.Flat && FlatAppearance.BorderSize == 0)
return;
if(e == null)
return;
if(e.Graphics == null)
return;
//
// create the pen
//
Pen pen = new Pen(this.BorderColor,1);
//
// get the points for the border
//
Point[] pts = border_Get(0,0,this.Width-1,this.Height-1);
//
// paint the border
//
e.Graphics.DrawLines(pen,pts);
//
// release resources
//
pen.Dispose();
}
/// <summary>
/// paints the focus rectangle.
/// </summary>
/// <param name="e">paint arguments use to paint the button</param>
private void paint_FocusBorder(PaintEventArgs e)
{
if(e == null)
return;
if(e.Graphics == null)
return;
//
// if the button has focus, and focus rectangle is enabled,
// draw the focus box
//
if (this.Focused)
{
if(FocusRectangleEnabled)
{
ControlPaint.DrawFocusRectangle(e.Graphics, new Rectangle(3, 3, this.Width-6, this.Height-6), System.Drawing.Color.Black, this.BackColor);
}
}
}
/// <summary>
/// paint the inner border of the button.
/// </summary>
/// <param name="e">paint arguments use to paint the button</param>
private void paint_InnerBorder(PaintEventArgs e)
{
if(e == null)
return;
if(e.Graphics == null)
return;
#if ENABLE_BITMAPBUTTON_PAINT_INNERBORDER
Graphics g = e.Graphics;
System.Drawing.Rectangle rect = new Rectangle(0,0,Size.Width,Size.Height);
System.Drawing.Color color = this.BackColor;
//
// get color of inner border
//
switch(State)
{
case BtnState.Inactive:
color = System.Drawing.Color.Gray;
break;
case BtnState.Normal:
if(this.Focused)
color = this.InnerBorderColor_Focus;
else
color = this.InnerBorderColor;
break;
case BtnState.Pushed:
color = Blend(InnerBorderColor_Focus,System.Drawing.Color.Black,10);
break;
case BtnState.MouseOver:
color = InnerBorderColor_MouseOver;
break;
}
//
// populate color and position arrays
//
Color[] ColorArray = null;
float[] PositionArray = null;
if(State == BtnState.Pushed)
{
ColorArray = new System.Drawing.Color [] {
Blend(color,System.Drawing.Color.Black,20),
Blend(color,System.Drawing.Color.Black,10),
Blend(color,System.Drawing.Color.White,00),
Blend(color,System.Drawing.Color.White,50),
Blend(color,System.Drawing.Color.White,85),
Blend(color,System.Drawing.Color.White,90),
};
PositionArray = new float[] {0.0f,.20f,.50f,.60f,.90f,1.0f};
}
else
{
ColorArray = new System.Drawing.Color [] {
Blend(color,System.Drawing.Color.White,80),
Blend(color,System.Drawing.Color.White,60),
Blend(color,System.Drawing.Color.White,10),
Blend(color,System.Drawing.Color.White,00),
Blend(color,System.Drawing.Color.Black,20),
Blend(color,System.Drawing.Color.Black,50),
};
PositionArray = new float[] {0.0f,.20f,.50f,.60f,.90f,1.0f};
}
//
// create blend object
//
System.Drawing.Drawing2D.ColorBlend blend = new System.Drawing.Drawing2D.ColorBlend();
blend.Colors = ColorArray;
blend.Positions = PositionArray;
//
// create gradient brush and pen
//
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(rect, this.BackColor,Blend(this.BackColor,this.BackColor,10), System.Drawing.Drawing2D.LinearGradientMode.Vertical);
brush.InterpolationColors = blend;
System.Drawing.Pen pen0 = new System.Drawing.Pen(brush,1);
//
// get points array to draw the line
//
Point[] pts = border_Get(0,0,this.Width-1,this.Height-1);
//
// draw line 0
//
this.border_Contract(1,ref pts);
e.Graphics.DrawLines(pen0,pts);
//
// draw line 1
//
this.border_Contract(1,ref pts);
e.Graphics.DrawLines(pen0,pts);
//
// release resources
//
pen0.Dispose();
brush.Dispose();
#endif
}
/// <summary>
/// This method paints the text and text shadow for the button.
/// </summary>
/// <param name="e">paint arguments use to paint the button</param>
private void paint_Text(PaintEventArgs e)
{
if(e == null)
return;
if(e.Graphics == null)
return;
System.Drawing.Rectangle rect = GetTextDestinationRect();
//
// do offset if button is pushed
//
if( (State == BtnState.Pushed) && (OffsetPressedContent) )
rect.Offset(1,1);
//
// caculate bounding rectagle for the text
//
System.Drawing.SizeF size = txt_Size(e.Graphics,this.Text,this.Font);
//
// calculate the starting location to paint the text
//
System.Drawing.Point pt = Calculate_LeftEdgeTopEdge(this.TextAlign, rect, (int) size.Width, (int) size.Height);
//
// If button state is inactive, paint the inactive text
//
if(State == BtnState.Inactive)
{
using(var solidBrush = new SolidBrush(DisabledTextColor))
{
e.Graphics.DrawString(this.Text, this.Font, solidBrush, pt.X + 1, pt.Y + 1);
}
}
//
// else, paint the text and text shadow
//
else
{
//
// paint text shadow
//
if(TextDropShadow)
{
System.Drawing.Brush TransparentBrush0 = new System.Drawing.SolidBrush( System.Drawing.Color.FromArgb(50, System.Drawing.Color.Black ) ) ;
System.Drawing.Brush TransparentBrush1 = new System.Drawing.SolidBrush( System.Drawing.Color.FromArgb(20, System.Drawing.Color.Black ) ) ;
e.Graphics.DrawString(this.Text,this.Font, TransparentBrush0,pt.X,pt.Y+1);
e.Graphics.DrawString(this.Text,this.Font, TransparentBrush0,pt.X+1,pt.Y);
e.Graphics.DrawString(this.Text,this.Font, TransparentBrush1,pt.X+1,pt.Y+1);
e.Graphics.DrawString(this.Text,this.Font, TransparentBrush1,pt.X,pt.Y+2);
e.Graphics.DrawString(this.Text,this.Font, TransparentBrush1,pt.X+2,pt.Y);
TransparentBrush0.Dispose();
TransparentBrush1.Dispose();
}
//
// paint text
//
using(var solidBrush = new SolidBrush(this.ForeColor))
{
e.Graphics.DrawString(this.Text,this.Font, solidBrush,pt.X,pt.Y);
}
}
}
/// <summary>
/// Paints a border around the image. If Image drop shadow is enabled,
/// a shodow is drawn too.
/// </summary>
/// <param name="g">The graphics object</param>
/// <param name="ImageRect">the rectangle region of the image</param>
private void paint_ImageBorder(System.Drawing.Graphics g, System.Drawing.Rectangle ImageRect)
{
System.Drawing.Rectangle rect = ImageRect;
//
// If ImageDropShadow = true, draw shadow
//
if(ImageDropShadow)
{
System.Drawing.Pen p0 = new System.Drawing.Pen(System.Drawing.Color.FromArgb(80,0,0,0));
System.Drawing.Pen p1 = new System.Drawing.Pen(System.Drawing.Color.FromArgb(40,0,0,0));
g.DrawLine(p0, new Point(rect.Right,rect.Bottom),new Point(rect.Right+1,rect.Bottom));
g.DrawLine(p0, new Point(rect.Right+1,rect.Top+1),new Point(rect.Right+1,rect.Bottom+0));
g.DrawLine(p1, new Point(rect.Right+2,rect.Top+2),new Point(rect.Right+2,rect.Bottom+1));
g.DrawLine(p0, new Point(rect.Left+1,rect.Bottom+1),new Point(rect.Right+0,rect.Bottom+1));
g.DrawLine(p1, new Point(rect.Left+1,rect.Bottom+2),new Point(rect.Right+1,rect.Bottom+2));
}
//
// Draw Image Border
//
if(ImageBorderEnabled)
{
Color[] ColorArray = null;
float[] PositionArray = null;
System.Drawing.Color color = this.ImageBorderColor;
if(!this.Enabled)
color = System.Drawing.Color.LightGray;
//
// initialize color and position array
//
ColorArray = new Color[]{
Blend(color,System.Drawing.Color.White,40),
Blend(color,System.Drawing.Color.White,20),
Blend(color,System.Drawing.Color.White,30),
Blend(color,System.Drawing.Color.White,00),
Blend(color,System.Drawing.Color.Black,30),
Blend(color,System.Drawing.Color.Black,70),
};
PositionArray = new float[]{0.0f,.20f,.50f,.60f,.90f,1.0f};
//
// create blend object
//
System.Drawing.Drawing2D.ColorBlend blend = new System.Drawing.Drawing2D.ColorBlend();
blend.Colors = ColorArray;
blend.Positions = PositionArray;
//
// create brush and pens
//
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(rect, this.BackColor,Blend(this.BackColor,this.BackColor,10), System.Drawing.Drawing2D.LinearGradientMode.Vertical);
brush.InterpolationColors = blend;
System.Drawing.Pen pen0 = new System.Drawing.Pen(brush,1);
System.Drawing.Pen pen1 = new System.Drawing.Pen(System.Drawing.Color.Black);
//
// calculate points to draw line
//
rect.Inflate(1,1);
Point[] pts = border_Get(rect.Left,rect.Top,rect.Width,rect.Height);
this.border_Contract(1,ref pts);
//
// draw line 0
//
g.DrawLines(pen1,pts);
//
// draw line 1
//
this.border_Contract(1,ref pts);
g.DrawLines(pen0,pts);
//
// release resources
//
pen1.Dispose();
pen0.Dispose();
brush.Dispose();
}
}
/// <summary>
/// Use this to recolor the image
/// </summary>
public ImageAttributes ImageAttributes { get; set; }
/// <summary>
/// Paints the image on the button.
/// </summary>
/// <param name="e"></param>
private void paint_Image(PaintEventArgs e)
{
if(e == null)
return;
if(e.Graphics == null)
return;
Image image = GetCurrentImage(State);
if(image != null)
{
Graphics g =e.Graphics;
System.Drawing.Rectangle rect = GetImageDestinationRect();
if( (State == BtnState.Pushed) && (_OffsetPressedContent) )
rect.Offset(1,1);
if(this.StretchImage)
{
g.DrawImage(image,rect, 0, 0 ,image.Width,image.Height, GraphicsUnit.Pixel, ImageAttributes);
}
else
{
System.Drawing.Rectangle r = GetImageDestinationRect();
//g.DrawImage(image,rect.Left,rect.Top);
g.DrawImage(image,rect, 0, 0 ,image.Width,image.Height, GraphicsUnit.Pixel, ImageAttributes);
}
paint_ImageBorder(g,rect);
}
}
#endregion
#region Helper Methods
/// <summary>
/// Calculates the required size to draw a text string
/// </summary>
/// <param name="g">the graphics object</param>
/// <param name="strText">string to calculate text region</param>
/// <param name="font">font to use for the string</param>
/// <returns>returns the size required to draw a text string</returns>
private System.Drawing.SizeF txt_Size(Graphics g,string strText,Font font)
{
System.Drawing.SizeF size = g.MeasureString(strText,font);
return (size);
}
/// <summary>
/// Calculates the rectangular region used for text display.
/// </summary>
/// <returns>returns the rectangular region for the text display</returns>
private System.Drawing.Rectangle GetTextDestinationRect()
{
System.Drawing.Rectangle ImageRect = GetImageDestinationRect();
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0,0,0,0);
switch(this.ImageAlign)
{
case System.Drawing.ContentAlignment.BottomCenter:
rect = new System.Drawing.Rectangle(0,0,this.Width,ImageRect.Top);
break;
case System.Drawing.ContentAlignment.BottomLeft:
rect = new System.Drawing.Rectangle(0,0,this.Width,ImageRect.Top);
break;
case System.Drawing.ContentAlignment.BottomRight:
rect = new System.Drawing.Rectangle(0,0,this.Width,ImageRect.Top);
break;
case System.Drawing.ContentAlignment.MiddleCenter:
rect = new System.Drawing.Rectangle(0,ImageRect.Bottom,this.Width,this.Height-ImageRect.Bottom);
break;
case System.Drawing.ContentAlignment.MiddleLeft:
rect = new System.Drawing.Rectangle(ImageRect.Right,0,this.Width-ImageRect.Right,this.Height);
break;
case System.Drawing.ContentAlignment.MiddleRight:
rect = new System.Drawing.Rectangle(0,0,ImageRect.Left,this.Height);
break;
case System.Drawing.ContentAlignment.TopCenter:
rect = new System.Drawing.Rectangle(0,ImageRect.Bottom,this.Width,this.Height-ImageRect.Bottom);
break;
case System.Drawing.ContentAlignment.TopLeft:
rect = new System.Drawing.Rectangle(0,ImageRect.Bottom,this.Width,this.Height-ImageRect.Bottom);
break;
case System.Drawing.ContentAlignment.TopRight:
rect = new System.Drawing.Rectangle(0,ImageRect.Bottom,this.Width,this.Height-ImageRect.Bottom);
break;
}
rect.Inflate(-this.Padding,-this.Padding);
return (rect);
}
/// <summary>
/// Calculates the rectangular region used for image display.
/// </summary>
/// <returns>returns the rectangular region used to display the image</returns>
private System.Drawing.Rectangle GetImageDestinationRect()
{
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0,0,0,0);
System.Drawing.Image image = GetCurrentImage(this.State);
if(image!=null)
{
if(this.StretchImage)
{
rect.Width = this.Width;
rect.Height= this.Height;
}
else
{
rect.Width = image.Width;
rect.Height = image.Height;
System.Drawing.Rectangle drect = new System.Drawing.Rectangle(0,0,this.Width,this.Height);
drect.Inflate(-this.Padding,-this.Padding);
System.Drawing.Point pt = Calculate_LeftEdgeTopEdge(this.ImageAlign,drect, image.Width,image.Height);
rect.Offset(pt);
}
}
return(rect);
}
/// <summary>
/// This method is used to retrieve the image used by the button for the given state.
/// </summary>
/// <param name="btnState">holds the state of the button</param>
/// <returns>returns the button Image</returns>
private System.Drawing.Image GetCurrentImage(BtnState btnState)
{
System.Drawing.Image image = ImageNormal;
switch(btnState)
{
case BtnState.Normal:
if(this.Focused)
{
if(this.ImageFocused != null)
image = this.ImageFocused;
}
if (!this.Enabled && ImageInactive != null)
image = ImageInactive;
break;
case BtnState.MouseOver:
if(ImageMouseOver != null)
image = ImageMouseOver;
break;
case BtnState.Pushed:
if(ImagePressed != null)
image = ImagePressed;
break;
case BtnState.Inactive:
if(ImageInactive != null)
image = ImageInactive;
else
{
if(image != null)
{
ImageInactive = ConvertToGrayscale( new Bitmap(ImageNormal));
}
image = ImageNormal;
}
break;
}
return(image);
}
/// <summary>
/// converts a bitmap image to grayscale
/// </summary>
/// <param name="source">bitmap source</param>
/// <returns>returns a grayscaled bitmap</returns>
public Bitmap ConvertToGrayscale(Bitmap source)
{
Bitmap bm = new Bitmap(source.Width,source.Height);
for(int y=0;y<bm.Height;y++)
{
for(int x=0;x<bm.Width;x++)
{
Color c=source.GetPixel(x,y);
int luma = (int)(c.R*0.3 + c.G*0.59+ c.B*0.11);
bm.SetPixel(x,y,Color.FromArgb(luma,luma,luma));
}
}
return bm;
}
/// <summary>
/// calculates the left/top edge for content.
/// </summary>
/// <param name="Alignment">the alignment of the content</param>
/// <param name="rect">rectagular region to place content</param>
/// <param name="nWidth">with of content</param>
/// <param name="nHeight">height of content</param>
/// <returns>returns the left/top edge to place content</returns>
private System.Drawing.Point Calculate_LeftEdgeTopEdge(System.Drawing.ContentAlignment Alignment, System.Drawing.Rectangle rect, int nWidth, int nHeight)
{
System.Drawing.Point pt = new System.Drawing.Point(0,0);
switch(Alignment)
{
case System.Drawing.ContentAlignment.BottomCenter:
pt.X = (rect.Width - nWidth)/2;
pt.Y = rect.Height - nHeight;
break;
case System.Drawing.ContentAlignment.BottomLeft:
pt.X = 0;
pt.Y = rect.Height - nHeight;
break;
case System.Drawing.ContentAlignment.BottomRight:
pt.X = rect.Width - nWidth;
pt.Y = rect.Height - nHeight;
break;
case System.Drawing.ContentAlignment.MiddleCenter:
pt.X = (rect.Width - nWidth)/2;
pt.Y = (rect.Height - nHeight)/2;
break;
case System.Drawing.ContentAlignment.MiddleLeft:
pt.X = 0;
pt.Y = (rect.Height - nHeight)/2;
break;
case System.Drawing.ContentAlignment.MiddleRight:
pt.X = rect.Width - nWidth;
pt.Y = (rect.Height - nHeight)/2;
break;
case System.Drawing.ContentAlignment.TopCenter:
pt.X = (rect.Width - nWidth)/2;
pt.Y = 0;
break;
case System.Drawing.ContentAlignment.TopLeft:
pt.X = 0;
pt.Y = 0;
break;
case System.Drawing.ContentAlignment.TopRight:
pt.X = rect.Width - nWidth;
pt.Y = 0;
break;
}
pt.X += rect.Left;
pt.Y += rect.Top;
return(pt);
}
/// <summary>
/// creates the region for the control. The region will have curved edges.
/// This prevents any drawing outside of the region.
/// </summary>
private void CreateRegion(int nContract)
{
Point[] points = border_Get(0,0,this.Width,this.Height);
border_Contract(nContract,ref points);
System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
path.AddLines(points);
this.Region = new Region(path);
}
/// <summary>
/// contract the array of points that define the border.
/// </summary>
/// <param name="nPixel">number of pixels to conract</param>
/// <param name="pts">array of points that define the border</param>
private void border_Contract(int nPixel, ref Point[] pts)
{
int a = nPixel;
pts[0].X += a; pts[0].Y += a;
pts[1].X -= a; pts[1].Y += a;
pts[2].X -= a; pts[2].Y += a;
pts[3].X -= a; pts[3].Y += a;
pts[4].X -= a; pts[4].Y -= a;
pts[5].X -= a; pts[5].Y -= a;
pts[6].X -= a; pts[6].Y -= a;
pts[7].X += a; pts[7].Y -= a;
pts[8].X += a; pts[8].Y -= a;
pts[9].X += a; pts[9].Y -= a;
pts[10].X += a; pts[10].Y += a;
pts[11].X += a; pts[10].Y += a;
}
/// <summary>
/// calculates the array of points that make up a border
/// </summary>
/// <param name="nLeftEdge">left edge of border</param>
/// <param name="nTopEdge">top edge of border</param>
/// <param name="nWidth">width of border</param>
/// <param name="nHeight">height of border</param>
/// <returns>returns an array of points that make up the border</returns>
private Point[] border_Get(int nLeftEdge, int nTopEdge, int nWidth, int nHeight)
{
int X = nWidth;
int Y = nHeight;
Point[] points =
{
new Point(1 , 0 ),
new Point(X-1 , 0 ),
new Point(X-1 , 1 ),
new Point(X , 1 ),
new Point(X , Y-1),
new Point(X-1 , Y-1),
new Point(X-1 , Y ),
new Point(1 , Y ),
new Point(1 , Y-1),
new Point(0 , Y-1),
new Point(0 , 1 ),
new Point(1 , 1 )
};
for(int i = 0; i < points.Length; i++)
{
points[i].Offset(nLeftEdge,nTopEdge);
}
return points;
}
/// <summary>
/// Increments or decrements the red/green/blue values of a color. It enforces that the
/// values do not go out of the bounds of 0..255
/// </summary>
/// <param name="SColor">source color</param>
/// <param name="RED">red shift</param>
/// <param name="GREEN">green shift</param>
/// <param name="BLUE">blue shift</param>
/// <returns>returns the calculated color</returns>
private static Color Shade(Color SColor,int RED, int GREEN, int BLUE)
{
int r = SColor.R;
int g = SColor.G;
int b = SColor.B;
r += RED;
if (r > 0xFF) r = 0xFF;
if (r < 0) r = 0;
g += GREEN;
if (g > 0xFF) g = 0xFF;
if (g < 0) g = 0;
b += BLUE;
if (b > 0xFF) b = 0xFF;
if (b < 0) b = 0;
return Color.FromArgb(r,g,b);
}
/// <summary>
/// Calculates a blended color using the specified parameters.
/// </summary>
/// <param name="SColor">Source Color (color moving from)</param>
/// <param name="DColor">Dest Color (color movving towards)</param>
/// <param name="Percentage">Percentage of Dest Color (0..100)</param>
/// <returns></returns>
private static Color Blend(Color SColor, Color DColor, int Percentage)
{
int r = SColor.R + ((DColor.R - SColor.R)*Percentage)/100;
int g = SColor.G + ((DColor.G - SColor.G)*Percentage)/100;
int b = SColor.B + ((DColor.B - SColor.B)*Percentage)/100;
return Color.FromArgb(r,g,b);
}
#endregion
#region Events Methods
/// <summary>
/// Mouse Down Event:
/// set BtnState to Pushed and Capturing mouse to true
/// </summary>
/// <param name="e"></param>
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown (e);
this.Capture = true;
this.CapturingMouse = true;
State = BtnState.Pushed;
this.Invalidate();
}
/// <summary>
/// Mouse Up Event:
/// Set BtnState to Normal and set CapturingMouse to false
/// </summary>
/// <param name="e"></param>
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp (e);
State = BtnState.Normal;
this.Invalidate();
this.CapturingMouse = false;
this.Capture = false;
this.Invalidate();
}
/// <summary>
/// Mouse Leave Event:
/// Set BtnState to normal if we CapturingMouse = true
/// </summary>
/// <param name="e"></param>
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave (e);
if(!CapturingMouse)
{
State = BtnState.Normal;
this.Invalidate();
}
}
/// <summary>
/// Mouse Move Event:
/// If CapturingMouse = true and mouse coordinates are within button region,
/// set BtnState to Pushed, otherwise set BtnState to Normal.
/// If CapturingMouse = false, then set BtnState to MouseOver
/// </summary>
/// <param name="e"></param>
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove (e);
if(CapturingMouse)
{
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0,0,this.Width,this.Height);
State = BtnState.Normal;
if( (e.X >= rect.Left) && (e.X <= rect.Right) )
{
if( (e.Y >= rect.Top) && (e.Y <= rect.Bottom) )
{
State = BtnState.Pushed;
}
}
this.Capture = true;
this.Invalidate();
}
else
{
//if(!this.Focused)
{
if(State != BtnState.MouseOver)
{
State = BtnState.MouseOver;
this.Invalidate();
}
}
}
}
/// <summary>
/// Enable/Disable Event:
/// If button became enabled, set BtnState to Normal
/// else set BtnState to Inactive
/// </summary>
/// <param name="e"></param>
protected override void OnEnabledChanged(EventArgs e)
{
base.OnEnabledChanged (e);
if(this.Enabled)
{
this.State = BtnState.Normal;
}
else
{
this.State = BtnState.Inactive;
}
this.Invalidate();
}
/// <summary>
/// Lose Focus Event:
/// set btnState to Normal
/// </summary>
/// <param name="e"></param>
protected override void OnLostFocus(EventArgs e)
{
base.OnLostFocus (e);
if(this.Enabled)
{
this.State = BtnState.Normal;
}
this.Invalidate();
}
#endregion
}
}
| |
using System;
using System.IO;
using System.Text;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Bitmap = Android.Graphics.Bitmap;
using Env = Android.OS.Environment;
namespace Similardio
{
public class DiskCache
{
enum JournalOp {
Created = 'c',
Modified = 'm',
Deleted = 'd'
}
const string JournalFileName = ".journal";
const string Magic = "MONOID";
readonly Encoding encoding = Encoding.UTF8;
string basePath;
string journalPath;
string version;
//Timer cleanupTimer;
struct CacheEntry
{
public DateTime Origin;
public TimeSpan TimeToLive;
public CacheEntry (DateTime o, TimeSpan ttl)
{
Origin = o;
TimeToLive = ttl;
}
}
Dictionary<string, CacheEntry> entries = new Dictionary<string, CacheEntry> ();
public DiskCache (string basePath, string version)
{
this.basePath = basePath;
if (!Directory.Exists (basePath))
Directory.CreateDirectory (basePath);
this.journalPath = Path.Combine (basePath, JournalFileName);
this.version = version;
try {
InitializeWithJournal ();
} catch {
Directory.Delete (basePath, true);
Directory.CreateDirectory (basePath);
}
ThreadPool.QueueUserWorkItem (CleanCallback);
}
public static DiskCache CreateCache (Android.Content.Context ctx, string cacheName, string version = "1.0")
{
string cachePath = ctx.CacheDir.AbsolutePath;
return new DiskCache (Path.Combine (cachePath, cacheName), version);
}
void InitializeWithJournal ()
{
if (!File.Exists (journalPath)) {
using (var writer = new StreamWriter (journalPath, false, encoding)) {
writer.WriteLine (Magic);
writer.WriteLine (version);
}
return;
}
string line = null;
using (var reader = new StreamReader (journalPath, encoding)) {
if (!EnsureHeader (reader))
throw new InvalidOperationException ("Invalid header");
while ((line = reader.ReadLine ()) != null) {
try {
var op = ParseOp (line);
string key;
DateTime origin;
TimeSpan duration;
switch (op) {
case JournalOp.Created:
ParseEntry (line, out key, out origin, out duration);
entries.Add (key, new CacheEntry (origin, duration));
break;
case JournalOp.Modified:
ParseEntry (line, out key, out origin, out duration);
entries[key] = new CacheEntry (origin, duration);
break;
case JournalOp.Deleted:
ParseEntry (line, out key);
entries.Remove (key);
break;
}
} catch {
break;
}
}
}
}
void CleanCallback (object state)
{
KeyValuePair<string, CacheEntry>[] kvps;
lock (entries) {
var now = DateTime.UtcNow;
kvps = entries.Where (kvp => kvp.Value.Origin + kvp.Value.TimeToLive < now).Take (10).ToArray ();
Android.Util.Log.Info ("DiskCacher", "Removing {0} elements from the cache", kvps.Length);
foreach (var kvp in kvps) {
entries.Remove (kvp.Key);
try {
File.Delete (Path.Combine (basePath, kvp.Key));
} catch {}
}
}
}
bool EnsureHeader (StreamReader reader)
{
var m = reader.ReadLine ();
var v = reader.ReadLine ();
return m == Magic && v == version;
}
JournalOp ParseOp (string line)
{
return (JournalOp)line[0];
}
void ParseEntry (string line, out string key)
{
key = line.Substring (2);
}
void ParseEntry (string line, out string key, out DateTime origin, out TimeSpan duration)
{
key = null;
origin = DateTime.MinValue;
duration = TimeSpan.MinValue;
var parts = line.Substring (2).Split (' ');
if (parts.Length != 3)
throw new InvalidOperationException ("Invalid entry");
key = parts[0];
long dateTime, timespan;
if (!long.TryParse (parts[1], out dateTime))
throw new InvalidOperationException ("Corrupted origin");
else
origin = new DateTime (dateTime);
if (!long.TryParse (parts[2], out timespan))
throw new InvalidOperationException ("Corrupted duration");
else
duration = TimeSpan.FromMilliseconds (timespan);
}
public void AddOrUpdate (string key, Bitmap bmp, TimeSpan duration)
{
key = SanitizeKey (key);
lock (entries) {
bool existed = entries.ContainsKey (key);
using (var stream = new BufferedStream (File.OpenWrite (Path.Combine (basePath, key))))
bmp.Compress (Bitmap.CompressFormat.Png, 100, stream);
AppendToJournal (existed ? JournalOp.Modified : JournalOp.Created,
key,
DateTime.UtcNow,
duration);
entries[key] = new CacheEntry (DateTime.UtcNow, duration);
}
}
public bool TryGet (string key, out Bitmap bmp)
{
key = SanitizeKey (key);
lock (entries) {
bmp = null;
if (!entries.ContainsKey (key))
return false;
try {
bmp = Android.Graphics.BitmapFactory.DecodeFile (Path.Combine (basePath, key));
} catch {
return false;
}
return true;
}
}
void AppendToJournal (JournalOp op, string key)
{
using (var writer = new StreamWriter (journalPath, true, encoding)) {
writer.Write ((char)op);
writer.Write (' ');
writer.Write (key);
writer.WriteLine ();
}
}
void AppendToJournal (JournalOp op, string key, DateTime origin, TimeSpan ttl)
{
using (var writer = new StreamWriter (journalPath, true, encoding)) {
writer.Write ((char)op);
writer.Write (' ');
writer.Write (key);
writer.Write (' ');
writer.Write (origin.Ticks);
writer.Write (' ');
writer.Write ((long)ttl.TotalMilliseconds);
writer.WriteLine ();
}
}
string SanitizeKey (string key)
{
return new string (key
.Where (c => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
.ToArray ());
}
}
}
| |
/**
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Diagnostics;
using System.Net.Sockets;
using System.Threading;
using Avro.ipc;
using Avro.ipc.Specific;
using NUnit.Framework;
using org.apache.avro.test;
namespace Avro.Test.Ipc
{
[TestFixture]
public class SocketServerWithCallbacksTest
{
private static volatile bool ackFlag;
private static volatile CountdownLatch ackLatch = new CountdownLatch(1);
private SocketServer server;
private SocketTransceiver transceiver;
private SimpleCallback simpleClient;
[OneTimeSetUp]
public void Init()
{
var responder = new SpecificResponder<Simple>(new SimpleImpl());
server = new SocketServer("localhost", 0, responder);
server.Start();
transceiver = new SocketTransceiver("localhost", server.Port);
simpleClient = SpecificRequestor.CreateClient<SimpleCallback>(transceiver);
}
[OneTimeTearDown]
public void TearDown()
{
try
{
if (transceiver != null)
{
transceiver.Disconnect();
}
}
catch
{
}
try
{
server.Stop();
}
catch
{
}
}
// AVRO-625 [Test]
public void CancelPendingRequestsOnTransceiverClose()
{
// Start up a second server so that closing the server doesn't
// interfere with the other unit tests:
var blockingSimpleImpl = new BlockingSimpleImpl();
var responder = new SpecificResponder<Simple>(blockingSimpleImpl);
var server2 = new SocketServer("localhost", 0, responder);
server2.Start();
try
{
int serverPort = server2.Port;
var transceiver2 = new SocketTransceiver("localhost", serverPort);
var addFuture = new CallFuture<int>();
try
{
var simpleClient2 = SpecificRequestor.CreateClient<SimpleCallback>(transceiver2);
// The first call has to block for the handshake:
Assert.AreEqual(3, simpleClient2.add(1, 2));
// Now acquire the semaphore so that the server will block:
blockingSimpleImpl.acquireRunPermit();
simpleClient2.add(1, 2, addFuture);
}
finally
{
// When the transceiver is closed, the CallFuture should get
// an IOException
transceiver2.Close();
}
bool ioeThrown = false;
try
{
addFuture.WaitForResult(2000);
}
catch (Exception)
{
}
//catch (ExecutionException e) {
// ioeThrown = e.getCause() instanceof IOException;
// Assert.assertTrue(e.getCause() instanceof IOException);
//} catch (Exception e) {
// e.printStackTrace();
// Assert.fail("Unexpected Exception: " + e.toString());
//}
Assert.IsTrue(ioeThrown, "Expected IOException to be thrown");
}
finally
{
blockingSimpleImpl.releaseRunPermit();
server2.Stop();
}
}
// AVRO-625 [Test]
public void CancelPendingRequestsAfterChannelCloseByServerShutdown()
{
// The purpose of this test is to verify that a client doesn't stay
// blocked when a server is unexpectedly killed (or when for some
// other reason the channel is suddenly closed) while the server
// was in the process of handling a request (thus after it received
// the request, and before it returned the response).
// Start up a second server so that closing the server doesn't
// interfere with the other unit tests:
var blockingSimpleImpl = new BlockingSimpleImpl();
var responder = new SpecificResponder<Simple>(blockingSimpleImpl);
var server2 = new SocketServer("localhost", 0, responder);
server2.Start();
SocketTransceiver transceiver2 = null;
try
{
transceiver2 = new SocketTransceiver("localhost", server2.Port);
var simpleClient2 = SpecificRequestor.CreateClient<SimpleCallback>(transceiver2);
// Acquire the method-enter permit, which will be released by the
// server method once we call it
blockingSimpleImpl.acquireEnterPermit();
// Acquire the run permit, to avoid that the server method returns immediately
blockingSimpleImpl.acquireRunPermit();
var t = new Thread(() =>
{
try
{
simpleClient2.add(3, 4);
Assert.Fail("Expected an exception");
}
catch (Exception)
{
// expected
}
});
// Start client call
t.Start();
// Wait until method is entered on the server side
blockingSimpleImpl.acquireEnterPermit();
// The server side method is now blocked waiting on the run permit
// (= is busy handling the request)
// Stop the server
server2.Stop();
// With the server gone, we expect the client to get some exception and exit
// Wait for client thread to exit
t.Join(10000);
Assert.IsFalse(t.IsAlive, "Client request should not be blocked on server shutdown");
}
finally
{
blockingSimpleImpl.releaseRunPermit();
server2.Stop();
if (transceiver2 != null)
transceiver2.Close();
}
}
private class CallbackCallFuture<T> : CallFuture<T>
{
private readonly Action<Exception> _handleException;
private readonly Action<T> _handleResult;
public CallbackCallFuture(Action<T> handleResult = null, Action<Exception> handleException = null)
{
_handleResult = handleResult;
_handleException = handleException;
}
public override void HandleResult(T result)
{
_handleResult(result);
}
public override void HandleException(Exception exception)
{
_handleException(exception);
}
}
private class NestedCallFuture<T> : CallFuture<T>
{
private readonly CallFuture<T> cf;
public NestedCallFuture(CallFuture<T> cf)
{
this.cf = cf;
}
public override void HandleResult(T result)
{
cf.HandleResult(result);
}
public override void HandleException(Exception exception)
{
cf.HandleException(exception);
}
}
private string Hello(string howAreYou)
{
var response = new CallFuture<string>();
simpleClient.hello(howAreYou, response);
return response.WaitForResult(2000);
}
private void Hello(string howAreYou, CallFuture<string> future1)
{
simpleClient.hello(howAreYou, future1);
}
private class BlockingSimpleImpl : SimpleImpl
{
/** Semaphore that is released when the method is entered. */
private readonly Semaphore enterSemaphore = new Semaphore(1, 1);
/** Semaphore that must be acquired for the method to run and exit. */
private readonly Semaphore runSemaphore = new Semaphore(1, 1);
public override string hello(string greeting)
{
releaseEnterPermit();
acquireRunPermit();
try
{
return base.hello(greeting);
}
finally
{
releaseRunPermit();
}
}
public override TestRecord echo(TestRecord record)
{
releaseEnterPermit();
acquireRunPermit();
try
{
return base.echo(record);
}
finally
{
releaseRunPermit();
}
}
public override int add(int arg1, int arg2)
{
releaseEnterPermit();
acquireRunPermit();
try
{
return base.add(arg1, arg2);
}
finally
{
releaseRunPermit();
}
}
public override byte[] echoBytes(byte[] data)
{
releaseEnterPermit();
acquireRunPermit();
try
{
return base.echoBytes(data);
}
finally
{
releaseRunPermit();
}
}
public override object error()
{
releaseEnterPermit();
acquireRunPermit();
try
{
return base.error();
}
finally
{
releaseRunPermit();
}
}
public override void ack()
{
releaseEnterPermit();
acquireRunPermit();
try
{
base.ack();
}
finally
{
releaseRunPermit();
}
}
/**
* Acquires a single permit from the semaphore.
*/
public void acquireRunPermit()
{
try
{
runSemaphore.WaitOne();
// } catch (InterruptedException e) {
// Thread.currentThread().interrupt();
// throw new RuntimeException(e);
//}
}
finally
{
}
}
/**
* Releases a single permit to the semaphore.
*/
public void releaseRunPermit()
{
try
{
runSemaphore.Release();
}
catch //(SemaphoreFullException)
{
}
}
private void releaseEnterPermit()
{
try
{
enterSemaphore.Release();
}
catch //(SemaphoreFullException)
{
}
}
/**
* Acquires a single permit from the semaphore.
*/
public void acquireEnterPermit()
{
try
{
enterSemaphore.WaitOne();
// } catch (InterruptedException e) {
// Thread.currentThread().interrupt();
// throw new RuntimeException(e);
//}
}
finally
{
}
}
}
[Test]
public void Ack()
{
simpleClient.ack();
ackLatch.Wait(2000);
Assert.IsTrue(ackFlag, "Expected ack flag to be set");
ackLatch = new CountdownLatch(1);
simpleClient.ack();
ackLatch.Wait(2000);
Assert.IsFalse(ackFlag, "Expected ack flag to be cleared");
}
[Test]
public void Add()
{
// Test synchronous RPC:
Assert.AreEqual(8, simpleClient.add(2, 6));
// Test asynchronous RPC (future):
var future1 = new CallFuture<int>();
simpleClient.add(8, 8, future1);
Assert.AreEqual(16, future1.WaitForResult(2000));
Assert.IsNull(future1.Error);
// Test asynchronous RPC (callback):
var future2 = new CallFuture<int>();
simpleClient.add(512, 256, new NestedCallFuture<int>(future2));
Assert.AreEqual(768, future2.WaitForResult(2000));
Assert.IsNull(future2.Error);
}
[Test]
public void ClientReconnectAfterServerRestart()
{
// Start up a second server so that closing the server doesn't
// interfere with the other unit tests:
SimpleImpl simpleImpl = new BlockingSimpleImpl();
var responder = new SpecificResponder<Simple>(simpleImpl);
var server2 = new SocketServer("localhost", 0, responder);
server2.Start();
try
{
int serverPort = server2.Port;
// Initialize a client, and establish a connection to the server:
Transceiver transceiver2 = new SocketTransceiver("localhost", serverPort);
var simpleClient2 =
SpecificRequestor.CreateClient<SimpleCallback>(transceiver2);
Assert.AreEqual(3, simpleClient2.add(1, 2));
// Restart the server:
server2.Stop();
try
{
simpleClient2.add(2, -1);
Assert.Fail("Client should not be able to invoke RPCs because server is no longer running");
}
catch (Exception)
{
// Expected since server is no longer running
}
Thread.Sleep(2000);
server2 = new SocketServer("localhost", serverPort, new SpecificResponder<Simple>(new SimpleImpl()));
server2.Start();
// Invoke an RPC using the same client, which should reestablish the
// connection to the server:
Assert.AreEqual(3, simpleClient2.add(1, 2));
}
finally
{
server2.Stop();
}
}
[Test]
public void Echo()
{
var record = new TestRecord
{
hash =
new MD5
{
Value =
new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8}
},
kind = Kind.FOO,
name = "My Record"
};
// Test synchronous RPC:
TestRecord testRecord = simpleClient.echo(record);
Assert.AreEqual(record, testRecord);
// Test asynchronous RPC (future):
var future1 = new CallFuture<TestRecord>();
simpleClient.echo(record, future1);
Assert.AreEqual(record, future1.WaitForResult(2000));
Assert.IsNull(future1.Error);
// Test asynchronous RPC (callback):
var future2 = new CallFuture<TestRecord>();
simpleClient.echo(record, new NestedCallFuture<TestRecord>(future2));
Assert.AreEqual(record, future2.WaitForResult(2000));
Assert.IsNull(future2.Error);
}
[Test]
public void EchoBytes()
{
var byteBuffer = new byte[] {1, 2, 3, 4, 5, 6, 7, 8};
// Test synchronous RPC:
Assert.AreEqual(byteBuffer, simpleClient.echoBytes(byteBuffer));
// Test asynchronous RPC (future):
var future1 = new CallFuture<byte[]>();
simpleClient.echoBytes(byteBuffer, future1);
Assert.AreEqual(byteBuffer, future1.WaitForResult(2000));
Assert.IsNull(future1.Error);
// Test asynchronous RPC (callback):
var future2 = new CallFuture<byte[]>();
simpleClient.echoBytes(byteBuffer, new NestedCallFuture<byte[]>(future2));
Assert.AreEqual(byteBuffer, future2.WaitForResult(2000));
Assert.IsNull(future2.Error);
}
[Test, TestCase(false, TestName = "Specific error"), TestCase(true, TestName = "System error")]
public void Error(bool systemError)
{
Type expected;
if(systemError)
{
expected = typeof(Exception);
SimpleImpl.throwSystemError = true;
}
else
{
expected = typeof(TestError);
SimpleImpl.throwSystemError = false;
}
// Test synchronous RPC:
try
{
simpleClient.error();
Assert.Fail("Expected " + expected.Name + " to be thrown");
}
catch (Exception e)
{
Assert.AreEqual(expected, e.GetType());
}
// Test asynchronous RPC (future):
var future = new CallFuture<object>();
simpleClient.error(future);
try
{
future.WaitForResult(2000);
Assert.Fail("Expected " + expected.Name + " to be thrown");
}
catch (Exception e)
{
Assert.AreEqual(expected, e.GetType());
}
Assert.IsNotNull(future.Error);
Assert.AreEqual(expected, future.Error.GetType());
Assert.IsNull(future.Result);
// Test asynchronous RPC (callback):
Exception errorRef = null;
var latch = new CountdownLatch(1);
simpleClient.error(new CallbackCallFuture<object>(
result => Assert.Fail("Expected " + expected.Name),
exception =>
{
errorRef = exception;
latch.Signal();
}));
Assert.IsTrue(latch.Wait(2000), "Timed out waiting for error");
Assert.IsNotNull(errorRef);
Assert.AreEqual(expected, errorRef.GetType());
}
[Test]
public void Greeting()
{
// Test synchronous RPC:
string response = Hello("how are you?");
Assert.AreEqual("Hello, how are you?", response);
// Test asynchronous RPC (future):
var future1 = new CallFuture<String>();
Hello("World!", future1);
string result = future1.WaitForResult();
Assert.AreEqual("Hello, World!", result);
Assert.IsNull(future1.Error);
// Test asynchronous RPC (callback):
var future2 = new CallFuture<String>();
Hello("what's up?", new NestedCallFuture<string>(future2));
Assert.AreEqual("Hello, what's up?", future2.WaitForResult());
Assert.IsNull(future2.Error);
}
//[Test]
public void PerformanceTest()
{
const int threadCount = 8;
const long runTimeMillis = 10*1000L;
long rpcCount = 0;
int[] runFlag = {1};
var startLatch = new CountdownLatch(threadCount);
for (int ii = 0; ii < threadCount; ii++)
{
new Thread(() =>
{
{
try
{
startLatch.Signal();
startLatch.Wait(2000);
while (Interlocked.Add(ref runFlag[0], 0) == 1)
{
Interlocked.Increment(ref rpcCount);
Assert.AreEqual("Hello, World!", simpleClient.hello("World!"));
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}).Start();
}
startLatch.Wait(2000);
Thread.Sleep(2000);
Interlocked.Exchange(ref runFlag[0], 1);
string results = "Completed " + rpcCount + " RPCs in " + runTimeMillis +
"ms => " + ((rpcCount/(double) runTimeMillis)*1000) + " RPCs/sec, " +
(runTimeMillis/(double) rpcCount) + " ms/RPC.";
Debug.WriteLine(results);
}
[Test]
public void TestSendAfterChannelClose()
{
// Start up a second server so that closing the server doesn't
// interfere with the other unit tests:
var responder = new SpecificResponder<Simple>(new SimpleImpl());
var server2 = new SocketServer("localhost", 0, responder);
server2.Start();
try
{
var transceiver2 = new SocketTransceiver("localhost", server2.Port);
try
{
var simpleClient2 = SpecificRequestor.CreateClient<SimpleCallback>(transceiver2);
// Verify that connection works:
Assert.AreEqual(3, simpleClient2.add(1, 2));
// Try again with callbacks:
var addFuture = new CallFuture<int>();
simpleClient2.add(1, 2, addFuture);
Assert.AreEqual(3, addFuture.WaitForResult(2000));
// Shut down server:
server2.Stop();
// Send a new RPC, and verify that it throws an Exception that
// can be detected by the client:
bool ioeCaught = false;
try
{
simpleClient2.add(1, 2);
Assert.Fail("Send after server close should have thrown Exception");
}
catch (SocketException)
{
ioeCaught = true;
}
Assert.IsTrue(ioeCaught, "Expected IOException");
// Send a new RPC with callback, and verify that the correct Exception
// is thrown:
ioeCaught = false;
try
{
addFuture = new CallFuture<int>();
simpleClient2.add(1, 2, addFuture);
addFuture.WaitForResult(2000);
Assert.Fail("Send after server close should have thrown Exception");
}
catch (SocketException)
{
ioeCaught = true;
}
Assert.IsTrue(ioeCaught, "Expected IOException");
}
finally
{
transceiver2.Disconnect();
}
}
finally
{
server2.Stop();
Thread.Sleep(1000);
}
}
private class SimpleImpl : Simple
{
public static bool throwSystemError = false;
public override string hello(string greeting)
{
return "Hello, " + greeting;
}
public override TestRecord echo(TestRecord record)
{
return record;
}
public override int add(int arg1, int arg2)
{
return arg1 + arg2;
}
public override byte[] echoBytes(byte[] data)
{
return data;
}
public override object error()
{
if(throwSystemError)
throw new SystemException("System error");
else
throw new TestError { message = "Test Message" };
}
public override void ack()
{
ackFlag = !ackFlag;
ackLatch.Signal();
}
}
}
}
| |
// 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.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
namespace System.Collections.Generic
{
/// <summary>
/// Used internally to control behavior of insertion into a <see cref="Dictionary{TKey, TValue}"/>.
/// </summary>
internal enum InsertionBehavior : byte
{
/// <summary>
/// The default insertion behavior.
/// </summary>
None = 0,
/// <summary>
/// Specifies that an existing entry with the same key should be overwritten if encountered.
/// </summary>
OverwriteExisting = 1,
/// <summary>
/// Specifies that if an existing entry with the same key is encountered, an exception should be thrown.
/// </summary>
ThrowOnExisting = 2
}
[DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback
{
private struct Entry
{
public int hashCode; // Lower 31 bits of hash code, -1 if unused
public int next; // Index of next entry, -1 if last
public TKey key; // Key of entry
public TValue value; // Value of entry
}
private int[] _buckets;
private Entry[] _entries;
private int _count;
private int _freeList;
private int _freeCount;
private int _version;
private IEqualityComparer<TKey> _comparer;
private KeyCollection _keys;
private ValueCollection _values;
private object _syncRoot;
// constants for serialization
private const string VersionName = "Version"; // Do not rename (binary serialization)
private const string HashSizeName = "HashSize"; // Do not rename (binary serialization). Must save buckets.Length
private const string KeyValuePairsName = "KeyValuePairs"; // Do not rename (binary serialization)
private const string ComparerName = "Comparer"; // Do not rename (binary serialization)
public Dictionary() : this(0, null) { }
public Dictionary(int capacity) : this(capacity, null) { }
public Dictionary(IEqualityComparer<TKey> comparer) : this(0, comparer) { }
public Dictionary(int capacity, IEqualityComparer<TKey> comparer)
{
if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
if (capacity > 0) Initialize(capacity);
if (comparer != EqualityComparer<TKey>.Default)
{
_comparer = comparer;
}
if (typeof(TKey) == typeof(string) && _comparer == null)
{
// To start, move off default comparer for string which is randomised
_comparer = (IEqualityComparer<TKey>)NonRandomizedStringEqualityComparer.Default;
}
}
public Dictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { }
public Dictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) :
this(dictionary != null ? dictionary.Count : 0, comparer)
{
if (dictionary == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
// It is likely that the passed-in dictionary is Dictionary<TKey,TValue>. When this is the case,
// avoid the enumerator allocation and overhead by looping through the entries array directly.
// We only do this when dictionary is Dictionary<TKey,TValue> and not a subclass, to maintain
// back-compat with subclasses that may have overridden the enumerator behavior.
if (dictionary.GetType() == typeof(Dictionary<TKey, TValue>))
{
Dictionary<TKey, TValue> d = (Dictionary<TKey, TValue>)dictionary;
int count = d._count;
Entry[] entries = d._entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
{
Add(entries[i].key, entries[i].value);
}
}
return;
}
foreach (KeyValuePair<TKey, TValue> pair in dictionary)
{
Add(pair.Key, pair.Value);
}
}
public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection) : this(collection, null) { }
public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer) :
this((collection as ICollection<KeyValuePair<TKey, TValue>>)?.Count ?? 0, comparer)
{
if (collection == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
foreach (KeyValuePair<TKey, TValue> pair in collection)
{
Add(pair.Key, pair.Value);
}
}
protected Dictionary(SerializationInfo info, StreamingContext context)
{
// We can't do anything with the keys and values until the entire graph has been deserialized
// and we have a resonable estimate that GetHashCode is not going to fail. For the time being,
// we'll just cache this. The graph is not valid until OnDeserialization has been called.
HashHelpers.SerializationInfoTable.Add(this, info);
}
public IEqualityComparer<TKey> Comparer
{
get
{
return (_comparer == null || _comparer is NonRandomizedStringEqualityComparer) ? EqualityComparer<TKey>.Default : _comparer;
}
}
public int Count
{
get { return _count - _freeCount; }
}
public KeyCollection Keys
{
get
{
if (_keys == null) _keys = new KeyCollection(this);
return _keys;
}
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get
{
if (_keys == null) _keys = new KeyCollection(this);
return _keys;
}
}
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys
{
get
{
if (_keys == null) _keys = new KeyCollection(this);
return _keys;
}
}
public ValueCollection Values
{
get
{
if (_values == null) _values = new ValueCollection(this);
return _values;
}
}
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get
{
if (_values == null) _values = new ValueCollection(this);
return _values;
}
}
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values
{
get
{
if (_values == null) _values = new ValueCollection(this);
return _values;
}
}
public TValue this[TKey key]
{
get
{
int i = FindEntry(key);
if (i >= 0) return _entries[i].value;
ThrowHelper.ThrowKeyNotFoundException(key);
return default(TValue);
}
set
{
bool modified = TryInsert(key, value, InsertionBehavior.OverwriteExisting);
Debug.Assert(modified);
}
}
public void Add(TKey key, TValue value)
{
bool modified = TryInsert(key, value, InsertionBehavior.ThrowOnExisting);
Debug.Assert(modified); // If there was an existing key and the Add failed, an exception will already have been thrown.
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair)
{
Add(keyValuePair.Key, keyValuePair.Value);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair)
{
int i = FindEntry(keyValuePair.Key);
if (i >= 0 && EqualityComparer<TValue>.Default.Equals(_entries[i].value, keyValuePair.Value))
{
return true;
}
return false;
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair)
{
int i = FindEntry(keyValuePair.Key);
if (i >= 0 && EqualityComparer<TValue>.Default.Equals(_entries[i].value, keyValuePair.Value))
{
Remove(keyValuePair.Key);
return true;
}
return false;
}
public void Clear()
{
int count = _count;
if (count > 0)
{
Array.Clear(_buckets, 0, _buckets.Length);
_count = 0;
_freeList = -1;
_freeCount = 0;
_version++;
Array.Clear(_entries, 0, count);
}
}
public bool ContainsKey(TKey key)
{
return FindEntry(key) >= 0;
}
public bool ContainsValue(TValue value)
{
if (value == null)
{
for (int i = 0; i < _count; i++)
{
if (_entries[i].hashCode >= 0 && _entries[i].value == null) return true;
}
}
else
{
for (int i = 0; i < _count; i++)
{
if (_entries[i].hashCode >= 0 && EqualityComparer<TValue>.Default.Equals(_entries[i].value, value)) return true;
}
}
return false;
}
private void CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = _count;
Entry[] entries = _entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
{
array[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value);
}
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info);
}
info.AddValue(VersionName, _version);
info.AddValue(ComparerName, _comparer ?? EqualityComparer<TKey>.Default, typeof(IEqualityComparer<TKey>));
info.AddValue(HashSizeName, _buckets == null ? 0 : _buckets.Length); // This is the length of the bucket array
if (_buckets != null)
{
var array = new KeyValuePair<TKey, TValue>[Count];
CopyTo(array, 0);
info.AddValue(KeyValuePairsName, array, typeof(KeyValuePair<TKey, TValue>[]));
}
}
private int FindEntry(TKey key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
int i = -1;
int[] buckets = _buckets;
Entry[] entries = _entries;
if (buckets != null)
{
IEqualityComparer<TKey> comparer = _comparer;
if (comparer == null)
{
int hashCode = key.GetHashCode() & 0x7FFFFFFF;
// Value in _buckets is 1-based
i = buckets[hashCode % buckets.Length] - 1;
do
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test in if to drop range check for following array access
if ((uint)i >= (uint)entries.Length || (entries[i].hashCode == hashCode && EqualityComparer<TKey>.Default.Equals(entries[i].key, key)))
{
break;
}
i = entries[i].next;
} while (true);
}
else
{
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
// Value in _buckets is 1-based
i = buckets[hashCode % buckets.Length] - 1;
do
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test in if to drop range check for following array access
if ((uint)i >= (uint)entries.Length ||
(entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)))
{
break;
}
i = entries[i].next;
} while (true);
}
}
return i;
}
private int Initialize(int capacity)
{
int size = HashHelpers.GetPrime(capacity);
_freeList = -1;
_buckets = new int[size];
_entries = new Entry[size];
return size;
}
private bool TryInsert(TKey key, TValue value, InsertionBehavior behavior)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (_buckets == null)
{
Initialize(0);
}
Entry[] entries = _entries;
IEqualityComparer<TKey> comparer = _comparer;
int hashCode = ((comparer == null) ? key.GetHashCode() : comparer.GetHashCode(key)) & 0x7FFFFFFF;
int collisionCount = 0;
ref int bucket = ref _buckets[hashCode % _buckets.Length];
// Value in _buckets is 1-based
int i = bucket - 1;
if (comparer == null)
{
do
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test uint in if rather than loop condition to drop range check for following array access
if ((uint)i >= (uint)entries.Length)
{
break;
}
if (entries[i].hashCode == hashCode && EqualityComparer<TKey>.Default.Equals(entries[i].key, key))
{
if (behavior == InsertionBehavior.OverwriteExisting)
{
entries[i].value = value;
_version++;
return true;
}
if (behavior == InsertionBehavior.ThrowOnExisting)
{
ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
}
return false;
}
i = entries[i].next;
collisionCount++;
} while (true);
}
else
{
do
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test uint in if rather than loop condition to drop range check for following array access
if ((uint)i >= (uint)entries.Length)
{
break;
}
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key))
{
if (behavior == InsertionBehavior.OverwriteExisting)
{
entries[i].value = value;
_version++;
return true;
}
if (behavior == InsertionBehavior.ThrowOnExisting)
{
ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
}
return false;
}
i = entries[i].next;
collisionCount++;
} while (true);
}
// Can be improved with "Ref Local Reassignment"
// https://github.com/dotnet/csharplang/blob/master/proposals/ref-local-reassignment.md
bool resized = false;
bool updateFreeList = false;
int index;
if (_freeCount > 0)
{
index = _freeList;
updateFreeList = true;
_freeCount--;
}
else
{
int count = _count;
if (count == entries.Length)
{
Resize();
resized = true;
}
index = count;
_count = count + 1;
entries = _entries;
}
ref int targetBucket = ref resized ? ref _buckets[hashCode % _buckets.Length] : ref bucket;
ref Entry entry = ref entries[index];
if (updateFreeList)
{
_freeList = entry.next;
}
entry.hashCode = hashCode;
// Value in _buckets is 1-based
entry.next = targetBucket - 1;
entry.key = key;
entry.value = value;
// Value in _buckets is 1-based
targetBucket = index + 1;
_version++;
// Value types never rehash
if (default(TKey) == null && collisionCount > HashHelpers.HashCollisionThreshold && comparer is NonRandomizedStringEqualityComparer)
{
// If we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing
// i.e. EqualityComparer<string>.Default.
_comparer = null;
Resize(entries.Length, true);
}
return true;
}
public virtual void OnDeserialization(object sender)
{
SerializationInfo siInfo;
HashHelpers.SerializationInfoTable.TryGetValue(this, out siInfo);
if (siInfo == null)
{
// We can return immediately if this function is called twice.
// Note we remove the serialization info from the table at the end of this method.
return;
}
int realVersion = siInfo.GetInt32(VersionName);
int hashsize = siInfo.GetInt32(HashSizeName);
_comparer = (IEqualityComparer<TKey>)siInfo.GetValue(ComparerName, typeof(IEqualityComparer<TKey>));
if (hashsize != 0)
{
Initialize(hashsize);
KeyValuePair<TKey, TValue>[] array = (KeyValuePair<TKey, TValue>[])
siInfo.GetValue(KeyValuePairsName, typeof(KeyValuePair<TKey, TValue>[]));
if (array == null)
{
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_MissingKeys);
}
for (int i = 0; i < array.Length; i++)
{
if (array[i].Key == null)
{
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_NullKey);
}
Add(array[i].Key, array[i].Value);
}
}
else
{
_buckets = null;
}
_version = realVersion;
HashHelpers.SerializationInfoTable.Remove(this);
}
private void Resize()
{
Resize(HashHelpers.ExpandPrime(_count), false);
}
private void Resize(int newSize, bool forceNewHashCodes)
{
// Value types never rehash
Debug.Assert(!forceNewHashCodes || default(TKey) == null);
Debug.Assert(newSize >= _entries.Length);
int[] buckets = new int[newSize];
Entry[] entries = new Entry[newSize];
int count = _count;
Array.Copy(_entries, 0, entries, 0, count);
if (default(TKey) == null && forceNewHashCodes)
{
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
{
Debug.Assert(_comparer == null);
entries[i].hashCode = (entries[i].key.GetHashCode() & 0x7FFFFFFF);
}
}
}
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
{
int bucket = entries[i].hashCode % newSize;
// Value in _buckets is 1-based
entries[i].next = buckets[bucket] - 1;
// Value in _buckets is 1-based
buckets[bucket] = i + 1;
}
}
_buckets = buckets;
_entries = entries;
}
// The overload Remove(TKey key, out TValue value) is a copy of this method with one additional
// statement to copy the value for entry being removed into the output parameter.
// Code has been intentionally duplicated for performance reasons.
public bool Remove(TKey key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (_buckets != null)
{
int hashCode = (_comparer?.GetHashCode(key) ?? key.GetHashCode()) & 0x7FFFFFFF;
int bucket = hashCode % _buckets.Length;
int last = -1;
// Value in _buckets is 1-based
int i = _buckets[bucket] - 1;
while (i >= 0)
{
ref Entry entry = ref _entries[i];
if (entry.hashCode == hashCode && (_comparer?.Equals(entry.key, key) ?? EqualityComparer<TKey>.Default.Equals(entry.key, key)))
{
if (last < 0)
{
// Value in _buckets is 1-based
_buckets[bucket] = entry.next + 1;
}
else
{
_entries[last].next = entry.next;
}
entry.hashCode = -1;
entry.next = _freeList;
if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>())
{
entry.key = default(TKey);
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>())
{
entry.value = default(TValue);
}
_freeList = i;
_freeCount++;
_version++;
return true;
}
last = i;
i = entry.next;
}
}
return false;
}
// This overload is a copy of the overload Remove(TKey key) with one additional
// statement to copy the value for entry being removed into the output parameter.
// Code has been intentionally duplicated for performance reasons.
public bool Remove(TKey key, out TValue value)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (_buckets != null)
{
int hashCode = (_comparer?.GetHashCode(key) ?? key.GetHashCode()) & 0x7FFFFFFF;
int bucket = hashCode % _buckets.Length;
int last = -1;
// Value in _buckets is 1-based
int i = _buckets[bucket] - 1;
while (i >= 0)
{
ref Entry entry = ref _entries[i];
if (entry.hashCode == hashCode && (_comparer?.Equals(entry.key, key) ?? EqualityComparer<TKey>.Default.Equals(entry.key, key)))
{
if (last < 0)
{
// Value in _buckets is 1-based
_buckets[bucket] = entry.next + 1;
}
else
{
_entries[last].next = entry.next;
}
value = entry.value;
entry.hashCode = -1;
entry.next = _freeList;
if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>())
{
entry.key = default(TKey);
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>())
{
entry.value = default(TValue);
}
_freeList = i;
_freeCount++;
_version++;
return true;
}
last = i;
i = entry.next;
}
}
value = default(TValue);
return false;
}
public bool TryGetValue(TKey key, out TValue value)
{
int i = FindEntry(key);
if (i >= 0)
{
value = _entries[i].value;
return true;
}
value = default(TValue);
return false;
}
public bool TryAdd(TKey key, TValue value) => TryInsert(key, value, InsertionBehavior.None);
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return false; }
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
{
CopyTo(array, index);
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[];
if (pairs != null)
{
CopyTo(pairs, index);
}
else if (array is DictionaryEntry[])
{
DictionaryEntry[] dictEntryArray = array as DictionaryEntry[];
Entry[] entries = _entries;
for (int i = 0; i < _count; i++)
{
if (entries[i].hashCode >= 0)
{
dictEntryArray[index++] = new DictionaryEntry(entries[i].key, entries[i].value);
}
}
}
else
{
object[] objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
try
{
int count = _count;
Entry[] entries = _entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
{
objects[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value);
}
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
/// <summary>
/// Ensures that the dictionary can hold up to 'capacity' entries without any further expansion of its backing storage
/// </summary>
public int EnsureCapacity(int capacity)
{
if (capacity < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
int currentCapacity = _entries == null ? 0 : _entries.Length;
if (currentCapacity >= capacity)
return currentCapacity;
if (_buckets == null)
return Initialize(capacity);
int newSize = HashHelpers.GetPrime(capacity);
Resize(newSize, forceNewHashCodes: false);
return newSize;
}
/// <summary>
/// Sets the capacity of this dictionary to what it would be if it had been originally initialized with all its entries
///
/// This method can be used to minimize the memory overhead
/// once it is known that no new elements will be added.
///
/// To allocate minimum size storage array, execute the following statements:
///
/// dictionary.Clear();
/// dictionary.TrimExcess();
/// </summary>
public void TrimExcess()
{
TrimExcess(Count);
}
/// <summary>
/// Sets the capacity of this dictionary to hold up 'capacity' entries without any further expansion of its backing storage
///
/// This method can be used to minimize the memory overhead
/// once it is known that no new elements will be added.
/// </summary>
public void TrimExcess(int capacity)
{
if (capacity < Count)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
int newSize = HashHelpers.GetPrime(capacity);
Entry[] oldEntries = _entries;
int currentCapacity = oldEntries == null ? 0 : oldEntries.Length;
if (newSize >= currentCapacity)
return;
int oldCount = _count;
Initialize(newSize);
Entry[] entries = _entries;
int[] buckets = _buckets;
int count = 0;
for (int i = 0; i < oldCount; i++)
{
int hashCode = oldEntries[i].hashCode;
if (hashCode >= 0)
{
ref Entry entry = ref entries[count];
entry = oldEntries[i];
int bucket = hashCode % newSize;
// Value in _buckets is 1-based
entry.next = buckets[bucket] - 1;
// Value in _buckets is 1-based
buckets[bucket] = count + 1;
count++;
}
}
_count = count;
_freeCount = 0;
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
bool IDictionary.IsFixedSize
{
get { return false; }
}
bool IDictionary.IsReadOnly
{
get { return false; }
}
ICollection IDictionary.Keys
{
get { return (ICollection)Keys; }
}
ICollection IDictionary.Values
{
get { return (ICollection)Values; }
}
object IDictionary.this[object key]
{
get
{
if (IsCompatibleKey(key))
{
int i = FindEntry((TKey)key);
if (i >= 0)
{
return _entries[i].value;
}
}
return null;
}
set
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value);
try
{
TKey tempKey = (TKey)key;
try
{
this[tempKey] = (TValue)value;
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
}
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
}
}
}
private static bool IsCompatibleKey(object key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
return (key is TKey);
}
void IDictionary.Add(object key, object value)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value);
try
{
TKey tempKey = (TKey)key;
try
{
Add(tempKey, (TValue)value);
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
}
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
}
}
bool IDictionary.Contains(object key)
{
if (IsCompatibleKey(key))
{
return ContainsKey((TKey)key);
}
return false;
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new Enumerator(this, Enumerator.DictEntry);
}
void IDictionary.Remove(object key)
{
if (IsCompatibleKey(key))
{
Remove((TKey)key);
}
}
public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>,
IDictionaryEnumerator
{
private Dictionary<TKey, TValue> _dictionary;
private int _version;
private int _index;
private KeyValuePair<TKey, TValue> _current;
private int _getEnumeratorRetType; // What should Enumerator.Current return?
internal const int DictEntry = 1;
internal const int KeyValuePair = 2;
internal Enumerator(Dictionary<TKey, TValue> dictionary, int getEnumeratorRetType)
{
_dictionary = dictionary;
_version = dictionary._version;
_index = 0;
_getEnumeratorRetType = getEnumeratorRetType;
_current = new KeyValuePair<TKey, TValue>();
}
public bool MoveNext()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
// Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends.
// dictionary.count+1 could be negative if dictionary.count is Int32.MaxValue
while ((uint)_index < (uint)_dictionary._count)
{
ref Entry entry = ref _dictionary._entries[_index++];
if (entry.hashCode >= 0)
{
_current = new KeyValuePair<TKey, TValue>(entry.key, entry.value);
return true;
}
}
_index = _dictionary._count + 1;
_current = new KeyValuePair<TKey, TValue>();
return false;
}
public KeyValuePair<TKey, TValue> Current
{
get { return _current; }
}
public void Dispose()
{
}
object IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
if (_getEnumeratorRetType == DictEntry)
{
return new System.Collections.DictionaryEntry(_current.Key, _current.Value);
}
else
{
return new KeyValuePair<TKey, TValue>(_current.Key, _current.Value);
}
}
}
void IEnumerator.Reset()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
_index = 0;
_current = new KeyValuePair<TKey, TValue>();
}
DictionaryEntry IDictionaryEnumerator.Entry
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return new DictionaryEntry(_current.Key, _current.Value);
}
}
object IDictionaryEnumerator.Key
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return _current.Key;
}
}
object IDictionaryEnumerator.Value
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return _current.Value;
}
}
}
[DebuggerTypeProxy(typeof(DictionaryKeyCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey>
{
private Dictionary<TKey, TValue> _dictionary;
public KeyCollection(Dictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
_dictionary = dictionary;
}
public Enumerator GetEnumerator()
{
return new Enumerator(_dictionary);
}
public void CopyTo(TKey[] array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < _dictionary.Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = _dictionary._count;
Entry[] entries = _dictionary._entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0) array[index++] = entries[i].key;
}
}
public int Count
{
get { return _dictionary.Count; }
}
bool ICollection<TKey>.IsReadOnly
{
get { return true; }
}
void ICollection<TKey>.Add(TKey item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
}
void ICollection<TKey>.Clear()
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
}
bool ICollection<TKey>.Contains(TKey item)
{
return _dictionary.ContainsKey(item);
}
bool ICollection<TKey>.Remove(TKey item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
return false;
}
IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator()
{
return new Enumerator(_dictionary);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(_dictionary);
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < _dictionary.Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
TKey[] keys = array as TKey[];
if (keys != null)
{
CopyTo(keys, index);
}
else
{
object[] objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = _dictionary._count;
Entry[] entries = _dictionary._entries;
try
{
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0) objects[index++] = entries[i].key;
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return ((ICollection)_dictionary).SyncRoot; }
}
public struct Enumerator : IEnumerator<TKey>, System.Collections.IEnumerator
{
private Dictionary<TKey, TValue> _dictionary;
private int _index;
private int _version;
private TKey _currentKey;
internal Enumerator(Dictionary<TKey, TValue> dictionary)
{
_dictionary = dictionary;
_version = dictionary._version;
_index = 0;
_currentKey = default(TKey);
}
public void Dispose()
{
}
public bool MoveNext()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
while ((uint)_index < (uint)_dictionary._count)
{
ref Entry entry = ref _dictionary._entries[_index++];
if (entry.hashCode >= 0)
{
_currentKey = entry.key;
return true;
}
}
_index = _dictionary._count + 1;
_currentKey = default(TKey);
return false;
}
public TKey Current
{
get
{
return _currentKey;
}
}
object System.Collections.IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return _currentKey;
}
}
void System.Collections.IEnumerator.Reset()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
_index = 0;
_currentKey = default(TKey);
}
}
}
[DebuggerTypeProxy(typeof(DictionaryValueCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue>
{
private Dictionary<TKey, TValue> _dictionary;
public ValueCollection(Dictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
_dictionary = dictionary;
}
public Enumerator GetEnumerator()
{
return new Enumerator(_dictionary);
}
public void CopyTo(TValue[] array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < _dictionary.Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = _dictionary._count;
Entry[] entries = _dictionary._entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0) array[index++] = entries[i].value;
}
}
public int Count
{
get { return _dictionary.Count; }
}
bool ICollection<TValue>.IsReadOnly
{
get { return true; }
}
void ICollection<TValue>.Add(TValue item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
}
bool ICollection<TValue>.Remove(TValue item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
return false;
}
void ICollection<TValue>.Clear()
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
}
bool ICollection<TValue>.Contains(TValue item)
{
return _dictionary.ContainsValue(item);
}
IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator()
{
return new Enumerator(_dictionary);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(_dictionary);
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < _dictionary.Count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
TValue[] values = array as TValue[];
if (values != null)
{
CopyTo(values, index);
}
else
{
object[] objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = _dictionary._count;
Entry[] entries = _dictionary._entries;
try
{
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0) objects[index++] = entries[i].value;
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return ((ICollection)_dictionary).SyncRoot; }
}
public struct Enumerator : IEnumerator<TValue>, System.Collections.IEnumerator
{
private Dictionary<TKey, TValue> _dictionary;
private int _index;
private int _version;
private TValue _currentValue;
internal Enumerator(Dictionary<TKey, TValue> dictionary)
{
_dictionary = dictionary;
_version = dictionary._version;
_index = 0;
_currentValue = default(TValue);
}
public void Dispose()
{
}
public bool MoveNext()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
while ((uint)_index < (uint)_dictionary._count)
{
ref Entry entry = ref _dictionary._entries[_index++];
if (entry.hashCode >= 0)
{
_currentValue = entry.value;
return true;
}
}
_index = _dictionary._count + 1;
_currentValue = default(TValue);
return false;
}
public TValue Current
{
get
{
return _currentValue;
}
}
object System.Collections.IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return _currentValue;
}
}
void System.Collections.IEnumerator.Reset()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
_index = 0;
_currentValue = default(TValue);
}
}
}
}
}
| |
using System;
using System.IO;
using System.Threading;
/*
* This class implements a read timeout over an arbitrary stream. The
* actual read operation is performed in another thread.
*
* We use this class instead of NetworkStream's inherent timeout support
* for two reasons:
*
* 1. We want to distinguish between a read timeout and other kinds of
* error; NetworkStream just throws a basic IOException on timeout
* (at least so says the documentation).
*
* 2. When we implement more extensive proxy support, the stream we
* are working with might be something else than a NetworkStream.
*/
class RTStream : Stream {
/*
* Read timeout is expressed in milliseconds; a negative value
* means "no timeout" (read blocks indefinitely).
*/
internal int RTimeout {
get {
return readTimeout;
}
set {
readTimeout = value;
}
}
Stream sub;
int readTimeout;
Thread reader;
object readerLock;
byte[] oneByte;
byte[] readBuf;
int readOff;
int readLen;
/*
* Create an instance over the provided stream (normally a
* network socket).
*/
internal RTStream(Stream sub)
{
this.sub = sub;
oneByte = new byte[1];
readerLock = new object();
readBuf = null;
readTimeout = -1;
reader = new Thread(ReadWorker);
reader.IsBackground = true;
reader.Start();
}
public override bool CanRead {
get {
return sub.CanRead;
}
}
public override bool CanSeek {
get {
return sub.CanSeek;
}
}
public override bool CanWrite {
get {
return sub.CanWrite;
}
}
public override long Length {
get {
return sub.Length;
}
}
public override long Position {
get {
return sub.Position;
}
set {
sub.Position = value;
}
}
public override long Seek(long offset, SeekOrigin origin)
{
return sub.Seek(offset, origin);
}
public override void SetLength(long value)
{
sub.SetLength(value);
}
public override void Flush()
{
sub.Flush();
}
public override void WriteByte(byte b)
{
sub.WriteByte(b);
}
public override void Write(byte[] buf, int off, int len)
{
sub.Write(buf, off, len);
}
public override int ReadByte()
{
if (Read(oneByte, 0, 1) == 1) {
return (int)oneByte[0];
} else {
return -1;
}
}
public override int Read(byte[] buf, int off, int len)
{
if (readTimeout < 0) {
return sub.Read(buf, off, len);
}
if (len < 0) {
throw new ArgumentException();
}
if (len == 0) {
return 0;
}
if (reader == null) {
return 0;
}
lock (readerLock) {
readBuf = buf;
readOff = off;
readLen = len;
Monitor.PulseAll(readerLock);
long lim = DateTime.UtcNow.Ticks
+ (long)readTimeout * (long)10000;
for (;;) {
if (readBuf == null) {
return readLen;
}
long now = DateTime.UtcNow.Ticks;
if (now >= lim) {
break;
}
long wtl = (lim - now) / (long)10000;
int wt;
if (wtl <= 0) {
wt = 1;
} else if (wtl > (long)Int32.MaxValue) {
wt = Int32.MaxValue;
} else {
wt = (int)wtl;
}
Monitor.Wait(readerLock, wt);
}
reader.Abort();
reader = null;
throw new ReadTimeoutException();
}
}
protected override void Dispose(bool disposing)
{
if (reader != null) {
reader.Abort();
reader = null;
}
try {
sub.Close();
} catch {
// ignored
}
}
void ReadWorker()
{
try {
for (;;) {
byte[] buf;
int off, len;
lock (readerLock) {
while (readBuf == null) {
Monitor.Wait(readerLock);
}
buf = readBuf;
off = readOff;
len = readLen;
}
len = sub.Read(buf, off, len);
lock (readerLock) {
readBuf = null;
readLen = len;
Monitor.PulseAll(readerLock);
}
}
} catch (Exception e) {
if (e.GetBaseException() is ThreadAbortException) {
Thread.ResetAbort();
}
lock (readerLock) {
readBuf = null;
readLen = 0;
Monitor.PulseAll(readerLock);
}
return;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace ODataValidator.Rule
{
#region Namesapces
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using ODataValidator.Rule.Helper;
using ODataValidator.RuleEngine;
using ODataValidator.RuleEngine.Common;
#endregion
/* Cannot know where is the specification for V4
[Export(typeof(ExtensionRule))]
public class CommonCore2002_V4 : CommonCore2002
{
/// <summary>
/// Gets rule description
/// </summary>
public override string Description
{
get
{
return "If a request includes a OData-Version header, the server MUST validate that the header value is less than or equal to the maximum version of this document the data service implements.";
}
}
/// <summary>
/// Gets the version.
/// </summary>
public override ODataVersion? Version
{
get
{
return ODataVersion.V4;
}
}
}*/
[Export(typeof(ExtensionRule))]
public class CommonCore2002_V1_V2_V3 : CommonCore2002
{
/// <summary>
/// Gets rule description
/// </summary>
public override string Description
{
get
{
return "If a request includes a DataServiceVersion header, the server MUST validate that the header value is less than or equal to the maximum version of this document the data service implements.";
}
}
/// <summary>
/// Gets the version.
/// </summary>
public override ODataVersion? Version
{
get
{
return ODataVersion.V1_V2_V3;
}
}
}
/// <summary>
/// Class of code rule #10
/// </summary>
//[Export(typeof(ExtensionRule))]
public abstract class CommonCore2002 : ExtensionRule
{
/// <summary>
/// Gets Category property
/// </summary>
public override string Category
{
get
{
return "core";
}
}
/// <summary>
/// Gets rule name
/// </summary>
public override string Name
{
get
{
return "Common.Core.2002";
}
}
/// <summary>
/// Gets rule description
/// </summary>
public override string Description
{
get
{
return "If a request includes a DataServiceVersion header, the server MUST validate that the header value is less than or equal to the maximum version of this document the data service implements.";
}
}
/// <summary>
/// Gets rule specification in OData document
/// </summary>
public override string SpecificationSection
{
get
{
return "3.2.5.1";
}
}
/// <summary>
/// Gets location of help information of the rule
/// </summary>
public override string HelpLink
{
get
{
return null;
}
}
/// <summary>
/// Gets the error message for validation failure
/// </summary>
public override string ErrorMessage
{
get
{
return this.Description;
}
}
/// <summary>
/// Gets the requirement level.
/// </summary>
public override RequirementLevel RequirementLevel
{
get
{
return RequirementLevel.Must;
}
}
/// <summary>
/// Gets the payload type to which the rule applies.
/// </summary>
public override PayloadType? PayloadType
{
get
{
return null;
}
}
/// <summary>
/// Gets the aspect property.
/// </summary>
public override string Aspect
{
get
{
return "semantic";
}
}
/// <summary>
/// Verifies the semantic rule
/// </summary>
/// <param name="context">The Interop service context</param>
/// <param name="info">out parameter to return violation information when rule does not pass</param>
/// <returns>true if rule passes; false otherwise</returns>
public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
{
const string VersionOutOfServerRange = "9999.0";
bool? passed = this.Verify(context, VersionOutOfServerRange, out info);
return passed;
}
private bool? Verify(ServiceContext context, string dsv, out ExtensionRuleViolationInfo info)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
bool? passed = false;
info = null;
string serviceVersionString = "DataServiceVersion";
if (context.Version == ODataVersion.V4)
{
serviceVersionString = "OData-Version";
}
var headers = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>(serviceVersionString, dsv) };
var resp = WebResponseHelper.GetWithHeaders(
context.Destination,
context.PayloadFormat == RuleEngine.PayloadFormat.Json || context.PayloadFormat == RuleEngine.PayloadFormat.JsonLight,
headers,
RuleEngineSetting.Instance().DefaultMaximumPayloadSize,
context);
if (resp.StatusCode.HasValue)
{
int code = (int)resp.StatusCode.Value;
if (code >= 400 && code < 500)
{
passed = true;
}
else
{
info = new ExtensionRuleViolationInfo(Resource.ExpectingError4xx, context.Destination, resp.StatusCode.Value.ToString());
}
}
else
{
info = new ExtensionRuleViolationInfo(Resource.ExpectingError4xx, context.Destination, null);
}
return passed;
}
}
}
| |
using System.Collections.Generic;
using System;
using FFImageLoading.Config;
using FFImageLoading.Work;
using System.Net.Http;
using FFImageLoading.Helpers;
using FFImageLoading.Cache;
using System.Threading;
using System.IO;
using System.Threading.Tasks;
namespace FFImageLoading
{
public static class ImageService
{
private const int HttpHeadersTimeout = 15;
private const int HttpReadTimeout = 30;
private static volatile bool _initialized;
private static object _initializeLock = new object();
private static readonly MD5Helper _md5Helper = new MD5Helper();
/// <summary>
/// Gets FFImageLoading configuration
/// </summary>
/// <value>The configuration used by FFImageLoading.</value>
public static Configuration Config { get; private set; }
/// <summary>
/// Initialize ImageService default values. This can only be done once: during app start.
/// </summary>
/// <param name="maxCacheSize">Max cache size. If zero then 20% of the memory will be used.</param>
/// <param name="httpClient">.NET HttpClient to use. If null then a.NET HttpClient is instanciated.</param>
/// <param name="scheduler">Work scheduler used to organize/schedule loading tasks.</param>
/// <param name="logger">Basic logger. If null a very simple implementation that prints to console is used.</param>
/// <param name="diskCache">Disk cache. If null a default disk cache is instanciated that uses a journal mechanism.</param>
/// <param name="downloadCache">Download cache. If null a default download cache is instanciated, which relies on the DiskCache</param>
/// <param name="loadWithTransparencyChannel">Gets a value indicating whether images should be loaded with transparency channel. On Android we save 50% of the memory without transparency since we use 2 bytes per pixel instead of 4.</param>
/// <param name="fadeAnimationEnabled">Defines if fading should be performed while loading images.</param>
/// <param name="transformPlaceholders">Defines if transforms should be applied to placeholders.</param>
/// <param name="downsampleInterpolationMode">Defines default downsample interpolation mode.</param>
/// <param name="httpHeadersTimeout">Maximum time in seconds to wait to receive HTTP headers before the HTTP request is cancelled.</param>
/// <param name="httpReadTimeout">Maximum time in seconds to wait before the HTTP request is cancelled.</param>
public static void Initialize(int? maxCacheSize = null, HttpClient httpClient = null, IWorkScheduler scheduler = null, IMiniLogger logger = null,
IDiskCache diskCache = null, IDownloadCache downloadCache = null, bool? loadWithTransparencyChannel = null, bool? fadeAnimationEnabled = null,
bool? transformPlaceholders = null, InterpolationMode? downsampleInterpolationMode = null, int httpHeadersTimeout = HttpHeadersTimeout, int httpReadTimeout = HttpReadTimeout
)
{
lock (_initializeLock)
{
_initialized = false;
if (Config != null)
{
// If DownloadCache is not updated but HttpClient is then we inform DownloadCache
if (httpClient != null && downloadCache == null)
{
downloadCache = Config.DownloadCache;
downloadCache.DownloadHttpClient = httpClient;
}
logger.Debug("Skip configuration for maxCacheSize and diskCache. They cannot be redefined.");
maxCacheSize = Config.MaxCacheSize;
diskCache = Config.DiskCache;
// Redefine these if they were provided only
httpClient = httpClient ?? Config.HttpClient;
scheduler = scheduler ?? Config.Scheduler;
logger = logger ?? Config.Logger;
downloadCache = downloadCache ?? Config.DownloadCache;
loadWithTransparencyChannel = loadWithTransparencyChannel ?? Config.LoadWithTransparencyChannel;
fadeAnimationEnabled = fadeAnimationEnabled ?? Config.FadeAnimationEnabled;
transformPlaceholders = transformPlaceholders ?? Config.TransformPlaceholders;
downsampleInterpolationMode = downsampleInterpolationMode ?? Config.DownsampleInterpolationMode;
}
InitializeIfNeeded(maxCacheSize ?? 0, httpClient, scheduler, logger, diskCache, downloadCache,
loadWithTransparencyChannel ?? false, fadeAnimationEnabled ?? true,
transformPlaceholders ?? true, downsampleInterpolationMode ?? InterpolationMode.Default,
httpHeadersTimeout, httpReadTimeout
);
}
}
private static void InitializeIfNeeded(int maxCacheSize = 0, HttpClient httpClient = null, IWorkScheduler scheduler = null, IMiniLogger logger = null,
IDiskCache diskCache = null, IDownloadCache downloadCache = null, bool loadWithTransparencyChannel = false, bool fadeAnimationEnabled = true,
bool transformPlaceholders = true, InterpolationMode downsampleInterpolationMode = InterpolationMode.Default, int httpHeadersTimeout = HttpHeadersTimeout, int httpReadTimeout = HttpReadTimeout
)
{
if (_initialized)
return;
lock (_initializeLock)
{
if (_initialized)
return;
var userDefinedConfig = new Configuration(maxCacheSize, httpClient, scheduler, logger, diskCache, downloadCache,
loadWithTransparencyChannel, fadeAnimationEnabled, transformPlaceholders, downsampleInterpolationMode,
httpHeadersTimeout, httpReadTimeout);
Config = GetDefaultConfiguration(userDefinedConfig);
_initialized = true;
}
}
private static Configuration GetDefaultConfiguration(Configuration userDefinedConfig)
{
var httpClient = userDefinedConfig.HttpClient ?? new HttpClient();
if (userDefinedConfig.HttpReadTimeout > 0)
{
httpClient.Timeout = TimeSpan.FromSeconds(userDefinedConfig.HttpReadTimeout);
}
var logger = userDefinedConfig.Logger ?? new MiniLogger();
var scheduler = userDefinedConfig.Scheduler ?? new WorkScheduler(logger);
var diskCache = userDefinedConfig.DiskCache ?? DiskCache.CreateCache(typeof(ImageService).Name);
var downloadCache = userDefinedConfig.DownloadCache ?? new DownloadCache(httpClient, diskCache);
return new Configuration(
userDefinedConfig.MaxCacheSize,
httpClient,
scheduler,
logger,
diskCache,
downloadCache,
userDefinedConfig.LoadWithTransparencyChannel,
userDefinedConfig.FadeAnimationEnabled,
userDefinedConfig.TransformPlaceholders,
userDefinedConfig.DownsampleInterpolationMode,
userDefinedConfig.HttpHeadersTimeout,
userDefinedConfig.HttpReadTimeout
);
}
private static IWorkScheduler Scheduler
{
get {
InitializeIfNeeded();
return Config.Scheduler;
}
}
/// <summary>
/// Constructs a new TaskParameter to load an image from a file.
/// </summary>
/// <returns>The new TaskParameter.</returns>
/// <param name="filepath">Path to the file.</param>
public static TaskParameter LoadFile(string filepath)
{
InitializeIfNeeded();
return TaskParameter.FromFile(filepath);
}
/// <summary>
/// Constructs a new TaskParameter to load an image from a URL.
/// </summary>
/// <returns>The new TaskParameter.</returns>
/// <param name="url">URL to the file</param>
/// <param name="cacheDuration">How long the file will be cached on disk</param>
public static TaskParameter LoadUrl(string url, TimeSpan? cacheDuration = null)
{
InitializeIfNeeded();
return TaskParameter.FromUrl(url, cacheDuration);
}
/// <summary>
/// Constructs a new TaskParameter to load an image from a file from application bundle.
/// </summary>
/// <returns>The new TaskParameter.</returns>
/// <param name="filepath">Path to the file.</param>
public static TaskParameter LoadFileFromApplicationBundle(string filepath)
{
InitializeIfNeeded();
return TaskParameter.FromApplicationBundle(filepath);
}
/// <summary>
/// Constructs a new TaskParameter to load an image from a compiled drawable resource.
/// </summary>
/// <returns>The new TaskParameter.</returns>
/// <param name="resourceName">Name of the resource in drawable folder without extension</param>
public static TaskParameter LoadCompiledResource(string resourceName)
{
InitializeIfNeeded();
return TaskParameter.FromCompiledResource(resourceName);
}
public static TaskParameter LoadStream(Func<CancellationToken, Task<Stream>> stream)
{
InitializeIfNeeded();
return TaskParameter.FromStream(stream);
}
/// <summary>
/// Gets a value indicating whether ImageService will exit tasks earlier
/// </summary>
/// <value><c>true</c> if it should exit tasks early; otherwise, <c>false</c>.</value>
public static bool ExitTasksEarly
{
get
{
return Scheduler.ExitTasksEarly;
}
}
/// <summary>
/// Sets a value indicating whether ImageService will exit tasks earlier
/// </summary>
/// <param name="exitTasksEarly">If set to <c>true</c> exit tasks early.</param>
public static void SetExitTasksEarly(bool exitTasksEarly)
{
Scheduler.SetExitTasksEarly(exitTasksEarly);
}
/// <summary>
/// Sets a value indicating if all loading work should be paused (silently canceled).
/// </summary>
/// <param name="pauseWork">If set to <c>true</c> pause/cancel work.</param>
public static void SetPauseWork(bool pauseWork)
{
Scheduler.SetPauseWork(pauseWork);
}
/// <summary>
/// Cancel any loading work for the given ImageView
/// </summary>
/// <param name="task">Image loading task to cancel.</param>
public static void CancelWorkFor(IImageLoaderTask task)
{
Scheduler.Cancel(task);
}
/// <summary>
/// Removes a pending image loading task from the work queue.
/// </summary>
/// <param name="task">Image loading task to remove.</param>
public static void RemovePendingTask(IImageLoaderTask task)
{
Scheduler.RemovePendingTask(task);
}
/// <summary>
/// Queue an image loading task.
/// </summary>
/// <param name="task">Image loading task.</param>
public static void LoadImage(IImageLoaderTask task)
{
Scheduler.LoadImage(task);
}
/// <summary>
/// Invalidates the memory cache.
/// </summary>
public static void InvalidateMemoryCache()
{
InitializeIfNeeded();
ImageCache.Instance.Clear();
}
/// <summary>
/// Invalidates the disk cache.
/// </summary>
public static void InvalidateDiskCache()
{
InitializeIfNeeded();
Config.DiskCache.ClearAsync();
}
/// <summary>
/// Invalidates the cache for given key.
/// </summary>
public static void Invalidate(string key, CacheType cacheType)
{
InitializeIfNeeded();
if (cacheType == CacheType.All || cacheType == CacheType.Memory)
{
ImageCache.Instance.Remove(key);
}
if (cacheType == CacheType.All || cacheType == CacheType.Disk)
{
string hash = _md5Helper.MD5(key);
Config.DiskCache.RemoveAsync(hash);
}
}
}
}
| |
using System.Linq;
using System;
using System.Collections.Generic;
public enum RuleResult { Done, Working }
namespace Casanova.Prelude
{
public class Tuple<T,E> {
public T Item1 { get; set;}
public E Item2 { get; set;}
public Tuple(T item1, E item2)
{
Item1 = item1;
Item2 = item2;
}
}
public static class MyExtensions
{
//public T this[List<T> list]
//{
// get { return list.ElementAt(0); }
//}
public static T Head<T>(this List<T> list) { return list.ElementAt(0); }
public static T Head<T>(this IEnumerable<T> list) { return list.ElementAt(0); }
public static int Length<T>(this List<T> list) { return list.Count; }
public static int Length<T>(this IEnumerable<T> list) { return list.ToList<T>().Count; }
}
public class Cons<T> : IEnumerable<T>
{
public class Enumerator : IEnumerator<T>
{
public Enumerator(Cons<T> parent)
{
firstEnumerated = 0;
this.parent = parent;
tailEnumerator = parent.tail.GetEnumerator();
}
byte firstEnumerated;
Cons<T> parent;
IEnumerator<T> tailEnumerator;
public T Current
{
get
{
if (firstEnumerated == 0) return default(T);
if (firstEnumerated == 1) return parent.head;
else return tailEnumerator.Current;
}
}
object System.Collections.IEnumerator.Current { get { throw new Exception("Empty sequence has no elements"); } }
public bool MoveNext()
{
if (firstEnumerated == 0)
{
if (parent.head == null) return false;
firstEnumerated++;
return true;
}
if (firstEnumerated == 1) firstEnumerated++;
return tailEnumerator.MoveNext();
}
public void Reset() { firstEnumerated = 0; tailEnumerator.Reset(); }
public void Dispose() { }
}
T head;
IEnumerable<T> tail;
public Cons(T head, IEnumerable<T> tail)
{
this.head = head;
this.tail = tail;
}
public IEnumerator<T> GetEnumerator()
{
return new Enumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
}
public class Empty<T> : IEnumerable<T>
{
public Empty() { }
public class Enumerator : IEnumerator<T>
{
public T Current { get { throw new Exception("Empty sequence has no elements"); } }
object System.Collections.IEnumerator.Current { get { throw new Exception("Empty sequence has no elements"); } }
public bool MoveNext() { return false; }
public void Reset() { }
public void Dispose() { }
}
public IEnumerator<T> GetEnumerator()
{
return new Enumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator();
}
}
public abstract class Option<T> : IComparable, IEquatable<Option<T>>
{
public bool IsSome;
public bool IsNone { get { return !IsSome; } }
protected abstract Just<T> Some { get; }
public U Match<U>(Func<T,U> f, Func<U> g) {
if (this.IsSome)
return f(this.Some.Value);
else
return g();
}
public bool Equals(Option<T> b)
{
return this.Match(
x => b.Match(
y => x.Equals(y),
() => false),
() => b.Match(
y => false,
() => true));
}
public override bool Equals(System.Object other)
{
if (other == null) return false;
if (other is Option<T>)
{
var other1 = other as Option<T>;
return this.Equals(other1);
}
return false;
}
public override int GetHashCode() { return this.GetHashCode(); }
public static bool operator ==(Option<T> a, Option<T> b)
{
if ((System.Object)a == null || (System.Object)b == null) return System.Object.Equals(a, b);
return a.Equals(b);
}
public static bool operator !=(Option<T> a, Option<T> b)
{
if ((System.Object)a == null || (System.Object)b == null) return System.Object.Equals(a, b);
return !(a.Equals(b));
}
public int CompareTo(object obj)
{
if (obj == null) return 1;
if (obj is Option<T>)
{
var obj1 = obj as Option<T>;
if (this.Equals(obj1)) return 0;
}
return -1;
}
abstract public T Value { get; }
public override string ToString()
{
return "Option<" + typeof(T).ToString() + ">";
}
}
public class Just<T> : Option<T>
{
T elem;
public Just(T elem) { this.elem = elem; this.IsSome = true; }
protected override Just<T> Some { get { return this; } }
public override T Value { get { return elem; } }
}
public class Nothing<T> : Option<T>
{
public Nothing() { this.IsSome = false; }
protected override Just<T> Some { get { return null; } }
public override T Value { get { throw new Exception("Cant get a value from a None object"); } }
}
public class Utils
{
public static T IfThenElse<T>(Func<bool> c, Func<T> t, Func<T> e)
{
if (c())
return t();
else
return e();
}
}
}
public class FastStack
{
public int[] Elements;
public int Top;
public FastStack(int elems)
{
Top = 0;
Elements = new int[elems];
}
public void Clear() { Top = 0; }
public void Push(int x) { Elements[Top++] = x; }
}
public class RuleTable
{
public RuleTable(int elems)
{
ActiveIndices = new FastStack(elems);
SupportStack = new FastStack(elems);
ActiveSlots = new bool[elems];
}
public FastStack ActiveIndices;
public FastStack SupportStack;
public bool[] ActiveSlots;
public void Add(int i)
{
if (!ActiveSlots[i])
{
ActiveSlots[i] = true;
ActiveIndices.Push(i);
}
}
}
| |
/*
* Reactor 3D MIT License
*
* Copyright (c) 2010 Reiser Games
*
* 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 Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Content;
using System.Collections.Generic;
using System;
#if XBOX
using Microsoft.Xna.Framework.GamerServices;
#endif
namespace Reactor
{
public class RGame : IDisposable
{
ReactorGame game;
public REngine Reactor;
public RGame()
{
}
public void Run()
{
game = new ReactorGame(this);
Reactor = new REngine(game);
game.Run();
Dispose();
}
public void Exit()
{
game.Exit();
}
#if XBOX
public bool IsTrialMode()
{
return Guide.IsTrialMode;
}
#endif
public virtual void Init() { }
public virtual void Render() { }
public virtual void Render2D() { }
public virtual void Update() { }
public virtual void Destroy()
{
}
public virtual void Dispose()
{
}
public virtual void Load()
{
}
}
/// <summary>
/// This is the main type for your game
/// </summary>
public class ReactorGame : Game
{
internal GraphicsDeviceManager graphics;
internal Texture2D watermark;
internal SpriteBatch waterrenderer;
internal Rectangle waterrect;
internal ContentManager loader;
#if XBOX
internal GamerServicesComponent services;
#endif
//internal RCameraComponent cameraComponent;
//internal pmv1 pmv;
internal RGame game;
public ReactorGame(RGame RGameInstance)
{
game = RGameInstance;
graphics = new GraphicsDeviceManager(this);
loader = new ContentManager(Services);
//RGraphicEffect effect = new RGraphicEffect();
//effect.BloomInit(RBloomSettings.PresetSettings[0], this);
//cameraComponent = new RCameraComponent(this);
//Components.Add(cameraComponent);
}
internal bool AllowEscapeQuit = true;
internal void ReadWatermark()
{
//System.IO.Stream stream = (System.IO.Stream)System.IO.File.Open("watermark.dat", System.IO.FileMode.Open);
//System.IO.TextReader reader = System.IO.File.OpenText("watermark.dat");
watermark = new Texture2D(graphics.GraphicsDevice, 180, 60, false, SurfaceFormat.Color);
List<Color> cwatermark = new List<Color>();
// No Longer Included...
//REngine.Instance.PrepareWatermark();
int i = 0;
for (int it = 0; it < REngine.Instance.cwatermark.Length / 4; it++)
{
Color c = new Color(REngine.Instance.cwatermark[i], REngine.Instance.cwatermark[i + 1], REngine.Instance.cwatermark[i + 2], REngine.Instance.cwatermark[i + 3]);
cwatermark.Add(c);
i += 4;
}
watermark.SetData<Color>(cwatermark.ToArray());
cwatermark.Clear();
cwatermark = null;
REngine.Instance.cwatermark = null;
//reader.Close();
}
internal void WriteWatermark()
{
//System.IO.Stream stream = (System.IO.Stream)System.IO.File.Open("watermark.txt", System.IO.FileMode.Create);
System.IO.TextWriter writer = (System.IO.StreamWriter)System.IO.File.CreateText("watermark.txt");
watermark = loader.Load<Texture2D>(@"C:\\watermark");
Color[] cwatermark = new Color[watermark.Width * watermark.Height];
watermark.GetData<Color>(cwatermark);
foreach (Color c in cwatermark)
{
writer.WriteLine(c.R.ToString()+",");
writer.WriteLine(c.G.ToString() + ",");
writer.WriteLine(c.B.ToString() + ",");
writer.WriteLine(c.A.ToString() + ",");
}
writer.Close();
}
int wftimer = 0;
internal void RenderWatermark()
{
if (!REngine.Instance.cLicensed)
{
try
{
REngine.Instance.SetWatermarkPosition(REngine.Instance.watermarkposition);
RScreen2D.Instance._spritebatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
RScreen2D.Instance._spritebatch.Draw(watermark, REngine.Instance.cwaterrect, new Color(wc.ToVector4()));
RScreen2D.Instance._spritebatch.End();
//RScreen2D.IAction_End2D();
if (wftimer < 5000)
{
wftimer++;
}
if (wftimer > 900)
{
Vector4 vt = new Vector4(1f, 1f, 1f, ((wc.A - 1) / 256f * (0.0000000000001f * REngine.Instance.AccurateTimeElapsed())));
wc = new Color(vt);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
REngine.Instance.AddToLog(e.ToString());
}
}
}
Color wc = Color.White;
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
REngine.Instance._graphics = graphics;
//REngine.Instance._resourceContent = new ResourceContentManager(Services, Resources.ResourceManager);
#if !XBOX
//REngine.Instance._systemfont = REngine.Instance._resourceContent.Load<SpriteFont>("Arial");
#else
//REngine.Instance._systemfont = REngine.Instance._resourceContent.Load<SpriteFont>("Tahoma1");
#endif
game.Init();
#if XBOX
services = new GamerServicesComponent(this);
services.Initialize();
this.Components.Add(services);
#endif
//pmv = new pmv1(this, graphics);
//pmv.Initialize();
//Components.Add(pmv);
#if !XBOX
//this.TargetElapsedTime = TimeSpan.FromMilliseconds(1.0);
//this.InactiveSleepTime = TimeSpan.FromMilliseconds(1.0);
//this.IsFixedTimeStep = false;
#endif
//graphics.PreferredBackBufferFormat = SurfaceFormat.Color;
//graphics.PreferredDepthStencilFormat = DepthFormat.Depth32;
#if !XBOX
this.graphics.SynchronizeWithVerticalRetrace = true;
this.graphics.PreferMultiSampling = false;
#else
this.graphics.SynchronizeWithVerticalRetrace = true;
this.graphics.PreferMultiSampling = false;
#endif
this.graphics.ApplyChanges();
#if !XBOX || !XBOX360
//this.graphics.MinimumPixelShaderProfile = ShaderProfile.PS_3_0;
//this.graphics.MinimumVertexShaderProfile = ShaderProfile.VS_3_0;
#endif
game.Load();
}
/// <summary>
/// Load your graphics content. If loadAllContent is true, you should
/// load content from both ResourceManagementMode pools. Otherwise, just
/// load ResourceManagementMode.Manual content.
/// </summary>
/// <param name="loadAllContent">Which type of content to load.</param>
protected override void LoadContent()
{
if (waterrenderer == null)
{
waterrenderer = new SpriteBatch(graphics.GraphicsDevice);
}
// TODO: Load any ResourceManagementMode.Manual content
}
/// <summary>
/// Unload your graphics content. If unloadAllContent is true, you should
/// unload content from both ResourceManagementMode pools. Otherwise, just
/// unload ResourceManagementMode.Manual content. Manual content will get
/// Disposed by the GraphicsDevice during a Reset.
/// </summary>
/// <param name="unloadAllContent">Which type of content to unload.</param>
protected override void UnloadContent()
{
// TODO: Unload any ResourceManagementMode.Automatic content
try
{
//watermark = null;
//loader.Unload();
//loader = null;
//waterrenderer.Dispose();
//waterrenderer = null;
}
catch
{
}
//game.Destroy();
// TODO: Unload any ResourceManagementMode.Manual content
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
REngine.Instance._gameTime = gameTime;
game.Update();
#if XBOX
services.Update(gameTime);
#endif
// Allows the game to exit in case of emergency
if (AllowEscapeQuit)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
this.Exit();
}
//GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.CornflowerBlue, 1.0f, 0);
//pmv.Update(gameTime);
// TODO: Add your update logic here
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
if (RScene.Instance != null)
{
if (RScene.Instance._LandscapeList.Count > 0)
{
foreach (object land in RScene.Instance._LandscapeList)
{
if (land is RLandscape)
{
((RLandscape)land).OcclusionRender();
}
}
}
}
if (RGraphicEffect._instance != null)
{
RGraphicEffect._instance.Bloom_Render();
}
if (RWater.water != null)
{
try
{
RWater.water.UpdateWaterMaps();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
REngine.Instance.AddToLog(e.ToString());
}
graphics.GraphicsDevice.Clear(new Color(RWater.water.Options.WaterColor.vector));
}
else
{
graphics.GraphicsDevice.Clear(Color.Black);
}
game.Render();
// TODO: Add your drawing code here
//RenderWatermark();
REngine.Instance.DrawFps();
//pmv.Draw(gameTime);
base.Draw(gameTime);
if (RScreen2D.Instance != null)
RScreen2D.Instance.Update();
if (REngine.Instance._w32handle != null)
{
if (REngine.Instance._w32handle.ToInt32() != 0)
{
REngine.Instance._graphics.GraphicsDevice.Present();
}
}
//graphics.GraphicsDevice.SetRenderTarget(0, null);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.IntegrationTests
{
// Integration tests for binding top level models with [BindProperty]
public class BindPropertyIntegrationTest
{
private class Person
{
public string Name { get; set; }
}
[Fact]
public async Task BindModelAsync_WithBindProperty_BindsModel_WhenRequestIsNotGet()
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = "parameter",
ParameterType = typeof(Person),
BindingInfo = BindingInfo.GetBindingInfo(new[] { new BindPropertyAttribute() }),
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.Method = "POST";
request.QueryString = new QueryString("?parameter.Name=Joey");
});
// Act
var result = await parameterBinder.BindModelAsync(parameter, testContext);
// Assert
Assert.True(result.IsModelSet);
Assert.Equal("Joey", Assert.IsType<Person>(result.Model).Name);
}
[Fact]
public async Task BindModelAsync_WithBindProperty_SupportsGet_BindsModel_WhenRequestIsGet()
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = "parameter",
ParameterType = typeof(Person),
BindingInfo = BindingInfo.GetBindingInfo(new[] { new BindPropertyAttribute() { SupportsGet = true } }),
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.Method = "GET";
request.QueryString = new QueryString("?parameter.Name=Joey");
});
// Act
var result = await parameterBinder.BindModelAsync(parameter, testContext);
// Assert
Assert.True(result.IsModelSet);
Assert.Equal("Joey", Assert.IsType<Person>(result.Model).Name);
}
[Fact]
public async Task BindModelAsync_WithBindProperty_DoesNotBindModel_WhenRequestIsGet()
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = "parameter",
ParameterType = typeof(Person),
BindingInfo = BindingInfo.GetBindingInfo(new[] { new BindPropertyAttribute() }),
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.Method = "GET";
request.QueryString = new QueryString("?parameter.Name=Joey");
});
// Act
var result = await parameterBinder.BindModelAsync(parameter, testContext);
// Assert
Assert.False(result.IsModelSet);
}
[Fact]
public async Task BindModelAsync_WithBindProperty_BindNever_DoesNotBindModel()
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = nameof(TestController.BindNeverProp),
ParameterType = typeof(string),
BindingInfo = BindingInfo.GetBindingInfo(new[] { new BindPropertyAttribute() }),
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.Method = "POST";
request.QueryString = new QueryString($"?{parameter.Name}=Joey");
});
var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var modelMetadata = modelMetadataProvider
.GetMetadataForProperty(typeof(TestController), parameter.Name);
// Act
var result = await parameterBinder.BindModelAsync(
parameter,
testContext,
modelMetadataProvider,
modelMetadata);
// Assert
Assert.False(result.IsModelSet);
Assert.True(testContext.ModelState.IsValid);
}
[Theory]
[InlineData(null, false)]
[InlineData(123, true)]
public async Task BindModelAsync_WithBindProperty_EnforcesBindRequired(int? input, bool isValid)
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = nameof(TestController.BindRequiredProp),
ParameterType = typeof(string),
BindingInfo = BindingInfo.GetBindingInfo(new[] { new BindPropertyAttribute() }),
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.Method = "POST";
if (input.HasValue)
{
request.QueryString = new QueryString($"?{parameter.Name}={input.Value}");
}
});
var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var modelMetadata = modelMetadataProvider
.GetMetadataForProperty(typeof(TestController), parameter.Name);
// Act
var result = await parameterBinder.BindModelAsync(
parameter,
testContext,
modelMetadataProvider,
modelMetadata);
// Assert
Assert.Equal(input.HasValue, result.IsModelSet);
Assert.Equal(isValid, testContext.ModelState.IsValid);
if (isValid)
{
Assert.Equal(input.Value, Assert.IsType<int>(result.Model));
}
}
[Theory]
[InlineData(null, false)]
[InlineData(123, true)]
public async Task BindModelAsync_WithBindPageProperty_EnforcesBindRequired(int? input, bool isValid)
{
// Arrange
var propertyInfo = typeof(TestPage).GetProperty(nameof(TestPage.BindRequiredProperty));
var propertyDescriptor = new PageBoundPropertyDescriptor
{
BindingInfo = BindingInfo.GetBindingInfo(new[]
{
new FromQueryAttribute { Name = propertyInfo.Name },
}),
Name = propertyInfo.Name,
ParameterType = propertyInfo.PropertyType,
Property = propertyInfo,
};
var typeInfo = typeof(TestPage).GetTypeInfo();
var actionDescriptor = new CompiledPageActionDescriptor
{
BoundProperties = new[] { propertyDescriptor },
HandlerTypeInfo = typeInfo,
ModelTypeInfo = typeInfo,
PageTypeInfo = typeInfo,
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.Method = "POST";
if (input.HasValue)
{
request.QueryString = new QueryString($"?{propertyDescriptor.Name}={input.Value}");
}
});
var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var parameterBinder = ModelBindingTestHelper.GetParameterBinder(modelMetadataProvider);
var modelBinderFactory = ModelBindingTestHelper.GetModelBinderFactory(modelMetadataProvider);
var modelMetadata = modelMetadataProvider
.GetMetadataForProperty(typeof(TestPage), propertyDescriptor.Name);
var pageBinder = PageBinderFactory.CreatePropertyBinder(
parameterBinder,
modelMetadataProvider,
modelBinderFactory,
actionDescriptor);
var pageContext = new PageContext
{
ActionDescriptor = actionDescriptor,
HttpContext = testContext.HttpContext,
RouteData = testContext.RouteData,
ValueProviderFactories = testContext.ValueProviderFactories,
};
var page = new TestPage();
// Act
await pageBinder(pageContext, page);
// Assert
Assert.Equal(isValid, pageContext.ModelState.IsValid);
if (isValid)
{
Assert.Equal(input.Value, page.BindRequiredProperty);
}
}
[Theory]
[InlineData("RequiredAndStringLengthProp", null, false)]
[InlineData("RequiredAndStringLengthProp", "", false)]
[InlineData("RequiredAndStringLengthProp", "abc", true)]
[InlineData("RequiredAndStringLengthProp", "abcTooLong", false)]
[InlineData("DisplayNameStringLengthProp", null, true)]
[InlineData("DisplayNameStringLengthProp", "", true)]
[InlineData("DisplayNameStringLengthProp", "abc", true)]
[InlineData("DisplayNameStringLengthProp", "abcTooLong", false, "My Display Name")]
public async Task BindModelAsync_WithBindProperty_EnforcesDataAnnotationsAttributes(
string propertyName, string input, bool isValid, string displayName = null)
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = propertyName,
ParameterType = typeof(string),
BindingInfo = BindingInfo.GetBindingInfo(new[] { new BindPropertyAttribute() }),
};
var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.Method = "POST";
if (input != null)
{
request.QueryString = new QueryString($"?{parameter.Name}={input}");
}
});
var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
var modelMetadata = modelMetadataProvider
.GetMetadataForProperty(typeof(TestController), parameter.Name);
// Act
var result = await parameterBinder.BindModelAsync(
parameter,
testContext,
modelMetadataProvider,
modelMetadata);
// Assert
Assert.Equal(input != null, result.IsModelSet);
Assert.Equal(isValid, testContext.ModelState.IsValid);
if (!isValid)
{
var message = testContext.ModelState[propertyName].Errors.Single().ErrorMessage;
Assert.Contains(displayName ?? parameter.Name, message);
}
}
private class TestController
{
[BindNever] public string BindNeverProp { get; set; }
[BindRequired] public int BindRequiredProp { get; set; }
[Required, StringLength(3)] public string RequiredAndStringLengthProp { get; set; }
[DisplayName("My Display Name"), StringLength(3)] public string DisplayNameStringLengthProp { get; set; }
}
private class TestPage : PageModel
{
[BindRequired]
public int BindRequiredProperty { get; set; }
}
}
}
| |
#region License
// Distributed under the MIT License
// ============================================================
// Copyright (c) 2019 Hotcakes Commerce, LLC
// Copyright (c) 2020 Upendo Ventures, 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.
#endregion
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.SessionState;
using Hotcakes.Commerce.Accounts;
using Hotcakes.Commerce.Orders;
using Hotcakes.Commerce.Utilities;
using Hotcakes.Web;
namespace Hotcakes.Commerce
{
public class SessionManager
{
private const string CategoryLastIdVariable = "HccCategoryLastVisited";
// Admin Settings
private const string _AdminProductSearchCriteriaKeyword = "HccAdminProductSearchCriteriaKeyword";
private const string _AdminProductSearchCriteriaManufacturer = "HccAdminProductSearchCriteriaManufacturer";
private const string _AdminProductSearchCriteriaVendor = "HccAdminProductSearchCriteriaVendor";
private const string _AdminProductSearchCriteriaCategory = "HccAdminProductSearchCriteriaCategory";
private const string _AdminProductSearchCriteriaStatus = "HccAdminProductSearchCriteriaStatus";
private const string _AdminProductSearchCriteriaInventoryStatus = "HccAdminProductSearchCriteriaInventoryStatus";
private const string _AdminProductSearchCriteriaProductType = "HccAdminProductSearchCriteriaProductType";
private const string _AdminProductImportProgress = "HccAdminProductImportProgress";
private const string _AdminProductImportLog = "HccAdminProductImportLog";
private const string _AdminOrderSearchKeyword = "HccAdminOrderSearchKeyword";
private const string _AdminOrderSearchPaymentFilter = "HccAdminOrderSearchPaymentFilter";
private const string _AdminOrderSearchShippingFilter = "HccAdminOrderSearchShippingFilter";
private const string _AdminOrderSearchStatusFilter = "HccAdminOrderSearchStatusFilter";
private const string _AdminOrderSearchDateRange = "HccAdminOrderSearchDateRange";
private const string _AdminOrderSearchStartDate = "HccAdminOrderSearchStartDate";
private const string _AdminOrderSearchEndDate = "HccAdminOrderSearchEndDate";
private const string _AdminOrderSearchLastPage = "HccAdminOrderSearchLastPage";
private const string _AdminOrderSearchNewestFirst = "HccAdminOrderSearchNewestFirst";
private const string _AdminPromotionKeywords = "HccAdminPromotionKeywords";
private const string _AdminPromotionShowDisabled = "HccAdminPromotionShowDisabled";
private const string _AnalyticsOrderId = "HccAnalyticsOrderId";
private const string _AdminCurrentLanguage = "HccAdminCurrentLanguage";
private const string _AdminVendorKeywords = "HccAdminVendorKeywords";
private const string _AdminManufacturerKeywords = "HccAdminManufacturerKeywords";
private const string _AdminCustomerKeywords = "HccAdminCustomerKeywords";
private readonly HttpSessionState _session;
public static HotcakesApplication HccApp
{
get { return HotcakesApplication.Current; }
}
public SessionManager(HttpSessionState session)
{
_session = session;
}
public static string AdminCurrentLanguage
{
get { return GetCookieString(_AdminCurrentLanguage); }
set { SetCookieString(_AdminCurrentLanguage, value); }
}
public static string CategoryLastId
{
get { return GetSessionString(CategoryLastIdVariable); }
set { SetSessionString(CategoryLastIdVariable, value); }
}
// Admin Settings
public static string AdminProductCriteriaKeyword
{
get { return GetSessionString(_AdminProductSearchCriteriaKeyword); }
set { SetSessionString(_AdminProductSearchCriteriaKeyword, value); }
}
public static string AdminProductCriteriaManufacturer
{
get { return GetSessionString(_AdminProductSearchCriteriaManufacturer); }
set { SetSessionString(_AdminProductSearchCriteriaManufacturer, value); }
}
public static string AdminProductCriteriaVendor
{
get { return GetSessionString(_AdminProductSearchCriteriaVendor); }
set { SetSessionString(_AdminProductSearchCriteriaVendor, value); }
}
public static string AdminProductCriteriaCategory
{
get { return GetSessionString(_AdminProductSearchCriteriaCategory); }
set { SetSessionString(_AdminProductSearchCriteriaCategory, value); }
}
public static string AdminProductCriteriaStatus
{
get { return GetSessionString(_AdminProductSearchCriteriaStatus); }
set { SetSessionString(_AdminProductSearchCriteriaStatus, value); }
}
public static string AdminProductCriteriaInventoryStatus
{
get { return GetSessionString(_AdminProductSearchCriteriaInventoryStatus); }
set { SetSessionString(_AdminProductSearchCriteriaInventoryStatus, value); }
}
public static string AdminProductCriteriaProductType
{
get { return GetSessionString(_AdminProductSearchCriteriaProductType); }
set { SetSessionString(_AdminProductSearchCriteriaProductType, value); }
}
public List<string> AdminProductImportLog
{
get { return (List<string>) GetSessionObjectInt(_AdminProductImportLog) ?? new List<string>(); }
set { SetSessionObjectInt(_AdminProductImportLog, value); }
}
public double AdminProductImportProgress
{
get { return (double?) GetSessionObjectInt(_AdminProductImportProgress) ?? 0; }
set { SetSessionObjectInt(_AdminProductImportProgress, value); }
}
public static string AdminOrderSearchKeyword
{
get { return GetSessionString(_AdminOrderSearchKeyword); }
set { SetSessionString(_AdminOrderSearchKeyword, value); }
}
public static string AdminOrderSearchPaymentFilter
{
get { return GetSessionString(_AdminOrderSearchPaymentFilter); }
set { SetSessionString(_AdminOrderSearchPaymentFilter, value); }
}
public static string AdminOrderSearchShippingFilter
{
get { return GetSessionString(_AdminOrderSearchShippingFilter); }
set { SetSessionString(_AdminOrderSearchShippingFilter, value); }
}
public static string AdminOrderSearchStatusFilter
{
get { return GetSessionString(_AdminOrderSearchStatusFilter); }
set { SetSessionString(_AdminOrderSearchStatusFilter, value); }
}
public static DateRangeType AdminOrderSearchDateRange
{
get
{
var result = DateRangeType.AllDates;
if (GetSessionObject(_AdminOrderSearchDateRange) != null)
{
result = (DateRangeType) GetSessionObject(_AdminOrderSearchDateRange);
}
return result;
}
set { SetSessionObject(_AdminOrderSearchDateRange, value); }
}
public static DateTime AdminOrderSearchStartDate
{
get
{
var result = DateTime.Now.AddDays(1);
if (GetSessionObject(_AdminOrderSearchStartDate) != null)
{
result = (DateTime) GetSessionObject(_AdminOrderSearchStartDate);
}
return result;
}
set { SetSessionObject(_AdminOrderSearchStartDate, value); }
}
public static DateTime AdminOrderSearchEndDate
{
get
{
var result = DateTime.Now.AddDays(1);
if (GetSessionObject(_AdminOrderSearchEndDate) != null)
{
result = (DateTime) GetSessionObject(_AdminOrderSearchEndDate);
}
return result;
}
set { SetSessionObject(_AdminOrderSearchEndDate, value); }
}
public static int AdminOrderSearchLastPage
{
get
{
var result = 1;
var o = GetSessionObject(_AdminOrderSearchLastPage);
if (o != null)
{
result = (int) o;
}
return result;
}
set { SetSessionObject(_AdminOrderSearchLastPage, value); }
}
public static bool AdminOrderSearchNewestFirst
{
get
{
var temp = GetSessionObject(_AdminOrderSearchNewestFirst);
if (temp != null) return (bool) temp;
return true;
}
set { SetSessionObject(_AdminOrderSearchNewestFirst, value); }
}
public static string AdminPromotionKeywords
{
get { return GetSessionString(_AdminPromotionKeywords); }
set { SetSessionString(_AdminPromotionKeywords, value); }
}
public static string AdminVendorKeywords
{
get { return GetSessionString(_AdminVendorKeywords); }
set { SetSessionString(_AdminVendorKeywords, value); }
}
public static string AdminManufacturerKeywords
{
get { return GetSessionString(_AdminManufacturerKeywords); }
set { SetSessionString(_AdminManufacturerKeywords, value); }
}
public static string AdminCustomerKeywords
{
get { return GetSessionString(_AdminCustomerKeywords); }
set { SetSessionString(_AdminCustomerKeywords, value); }
}
public static bool AdminPromotionShowDisabled
{
get { return (bool?) GetSessionObject(_AdminPromotionShowDisabled) ?? false; }
set { SetSessionObject(_AdminPromotionShowDisabled, value); }
}
public static string AnalyticsOrderId
{
get { return GetSessionString(_AnalyticsOrderId); }
set { SetSessionString(_AnalyticsOrderId, value); }
}
public static string CardSecurityCode
{
get { return GetSessionString("CardSecurityCode"); }
set { SetSessionString("CardSecurityCode", value); }
}
public static string UserRegistrationPassword
{
get { return GetSessionString("UserRegistrationPassword"); }
set { SetSessionString("UserRegistrationPassword", value); }
}
public static bool IsUserAuthenticated(HotcakesApplication app)
{
return app.CurrentCustomer != null;
}
public static Guid? GetCurrentSessionGuid()
{
var sessionGuid = Cookies.GetCookieGuid(
WebAppSettings.CookieNameSessionGuid,
Factory.HttpContext.Request.RequestContext.HttpContext,
Factory.CreateEventLogger());
return sessionGuid;
}
public static void SetCurrentSessionGuid(Guid value)
{
Cookies.SetCookieGuid(WebAppSettings.CookieNameSessionGuid,
value,
Factory.HttpContext.Request.RequestContext.HttpContext,
false,
Factory.CreateEventLogger());
}
public static Guid? GetCurrentShoppingSessionGuid()
{
var sessionGuid = Cookies.GetCookieGuid(
WebAppSettings.CookieNameShoppingSessionGuid,
Factory.HttpContext.Request.RequestContext.HttpContext,
Factory.CreateEventLogger());
return sessionGuid;
}
public static void SetCurrentShoppingSessionGuid(Guid value)
{
Cookies.SetCookieGuid(WebAppSettings.CookieNameShoppingSessionGuid,
value,
Factory.HttpContext.Request.RequestContext.HttpContext,
true,
Factory.CreateEventLogger());
}
public static string GetCurrentCartID(Store currentStore)
{
var result = string.Empty;
if (currentStore.Settings.PreserveCartInSession)
{
result = GetSessionString(WebAppSettings.CookieNameCartId(currentStore.Id));
}
else
{
result = GetCookieString(WebAppSettings.CookieNameCartId(currentStore.Id));
}
return result;
}
public static void SetCurrentCartId(Store currentStore, string value)
{
if (currentStore.Settings.PreserveCartInSession)
{
SetSessionString(WebAppSettings.CookieNameCartId(currentStore.Id), value);
}
else
{
SetCookieString(WebAppSettings.CookieNameCartId(currentStore.Id), value);
}
}
public static string GetCurrentPaymentPendingCartId(Store currentStore)
{
return GetCookieString(WebAppSettings.CookieNameCartIdPaymentPending(currentStore.Id));
}
public static void SetCurrentPaymentPendingCartId(Store currentStore, string value)
{
SetCookieString(WebAppSettings.CookieNameCartIdPaymentPending(currentStore.Id), value, DateTime.Now.AddDays(14));
}
public static void SetCurrentAffiliateId(long id, DateTime expirationDate)
{
SetCookieString(WebAppSettings.CookieNameAffiliateId, id.ToString(), expirationDate);
}
public static long? CurrentAffiliateID(Store currentStore)
{
var refVal = GetCookieString(WebAppSettings.CookieNameAffiliateId);
if (!string.IsNullOrEmpty(refVal))
{
long id = 0;
if (long.TryParse(refVal, out id))
{
return id;
}
}
return null;
}
public static bool CurrentUserHasCart(Store currentStore)
{
var cartId = GetCurrentCartID(currentStore);
return !string.IsNullOrWhiteSpace(cartId);
}
#region " Private Set and Get "
private object GetSessionObjectInt(string variableName)
{
object result = null;
if (_session[variableName] != null)
{
result = _session[variableName];
}
return result;
}
private void SetSessionObjectInt(string variableName, object value)
{
_session[variableName] = value;
}
public static string GetSessionString(string variableName)
{
var result = string.Empty;
var temp = GetSessionObject(variableName);
if (temp != null)
{
result = (string) GetSessionObject(variableName);
}
return result;
}
public static void SetSessionString(string variableName, string value)
{
if (Factory.HttpContext != null)
{
if (Factory.HttpContext.Session != null)
{
Factory.HttpContext.Session[variableName] = value ?? string.Empty;
}
}
}
public static object GetSessionObject(string variableName)
{
object result = null;
if (Factory.HttpContext != null)
{
if (Factory.HttpContext.Session != null)
{
if (Factory.HttpContext.Session[variableName] != null)
{
result = Factory.HttpContext.Session[variableName];
}
}
}
return result;
}
public static void SetSessionObject(string variableName, object value)
{
if (Factory.HttpContext != null)
{
Factory.HttpContext.Session[variableName] = value;
}
}
public static string GetCookieString(string cookieName)
{
try
{
if (Factory.HttpContext != null)
{
var cookies = Factory.HttpContext.Request.Cookies;
return GetCookieString(cookieName, cookies);
}
}
catch
{
return string.Empty;
}
return string.Empty;
}
public static string GetCookieString(string cookieName, HttpCookieCollection cookies)
{
var result = string.Empty;
if (cookies == null) return string.Empty;
try
{
var checkCookie = cookies[cookieName];
if (checkCookie != null)
{
result = checkCookie.Value;
}
if (string.IsNullOrEmpty(result))
{
for (var i = 0; i < cookies.Count; i++)
{
checkCookie = cookies[i];
if (checkCookie.Name == cookieName)
{
result = checkCookie.Value;
if (!string.IsNullOrEmpty(result))
{
break;
}
}
}
}
}
catch
{
result = string.Empty;
}
return result;
}
public static void SetCookieString(string cookieName, string value)
{
SetCookieString(cookieName, value, null);
}
public static void SetCookieString(string cookieName, string value, DateTime? expirationDate)
{
if (Factory.HttpContext != null)
{
try
{
var isSecure = false;
if (HccApp != null)
{
isSecure = HccApp.CurrentStore.Settings.ForceAdminSSL;
}
else
{
isSecure = Factory.HttpContext.Request.IsSecureConnection;
}
var saveCookie = new HttpCookie(cookieName, value);
if (expirationDate.HasValue)
{
saveCookie.Expires = expirationDate.Value;
}
else
{
saveCookie.Expires = DateTime.Now.AddYears(50);
}
saveCookie.Secure = isSecure;
Factory.HttpContext.Request.Cookies.Remove(cookieName);
Factory.HttpContext.Response.Cookies.Add(saveCookie);
}
catch (Exception Ex)
{
EventLog.LogEvent(Ex);
}
}
}
#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 Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.abstract001.abstract001
{
// <Title>Classes</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
abstract public class Base
{
public abstract int Foo(dynamic o);
}
public class Derived : Base
{
public override int Foo(object o)
{
Test.Status = 1;
return 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Derived d = new Derived();
d.Foo(2);
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.abstract002.abstract002
{
// <Title>Classes</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
abstract public class Base
{
public abstract int Foo(dynamic o);
}
public class Derived : Base
{
public override int Foo(object o)
{
Test.Status = 1;
return 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Base d = new Derived();
d.Foo(2);
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.abstract003.abstract003
{
// <Title>Classes</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public interface IFoo
{
void Foo();
}
abstract public class Base
{
public abstract int Foo(dynamic o);
}
public class Derived : Base, IFoo
{
void IFoo.Foo()
{
Test.Status = 2;
}
public override int Foo(object o)
{
Test.Status = 1;
return 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Derived d = new Derived();
IFoo x = d as IFoo;
d.Foo(2);
if (Test.Status != 1)
return 1;
x.Foo();
if (Test.Status != 2)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.abstract004.abstract004
{
// <Title>Classes</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
abstract public class Base
{
public abstract int Foo(object o);
}
public class Derived : Base
{
public override int Foo(dynamic o)
{
Test.Status = 1;
return 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Derived d = new Derived();
d.Foo(2);
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.abstract005.abstract005
{
// <Title>Classes</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
abstract public class Base
{
public abstract int Foo(dynamic o);
}
public class Derived : Base
{
public override int Foo(dynamic o)
{
Test.Status = 1;
return 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Derived d = new Derived();
d.Foo(2);
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual001.virtual001
{
// <Title>Classes</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public virtual int Foo(object o)
{
Test.Status = 2;
return 1;
}
}
public class Derived : Base
{
public override int Foo(dynamic d)
{
Test.Status = 1;
return 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Derived d = new Derived();
d.Foo(3);
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual002.virtual002
{
// <Title>Classes</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public virtual int Foo(dynamic o)
{
Test.Status = 2;
return 1;
}
}
public class Derived : Base
{
public override int Foo(object d)
{
Test.Status = 1;
return 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Derived d = new Derived();
d.Foo(3);
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual003.virtual003
{
// <Title>Classes</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public virtual int Foo(dynamic o)
{
Test.Status = 2;
return 1;
}
}
public class Derived : Base
{
public override int Foo(dynamic d)
{
Test.Status = 1;
return 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Derived d = new Derived();
d.Foo(3);
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual004.virtual004
{
// <Title>Classes</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public virtual int Foo(object o)
{
Test.Status = 3;
return 1;
}
}
public class Derived : Base
{
public override int Foo(dynamic d)
{
Test.Status = 2;
return 1;
}
}
public class FurtherDerived : Derived
{
public override int Foo(object d)
{
Test.Status = 1;
return 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
FurtherDerived d = new FurtherDerived();
d.Foo(3);
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual005.virtual005
{
// <Title>Classes</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public virtual int Foo(dynamic o)
{
Test.Status = 3;
return 1;
}
}
public class Derived : Base
{
public override int Foo(object d)
{
Test.Status = 2;
return 1;
}
}
public class FurtherDerived : Derived
{
public override int Foo(dynamic d)
{
Test.Status = 1;
return 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
FurtherDerived d = new FurtherDerived();
d.Foo(3);
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.virtual006.virtual006
{
// <Title>Classes</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public virtual int this[object o]
{
get
{
Test.Status = 2;
return 2;
}
}
}
public class Derived : Base
{
public override int this[dynamic d]
{
get
{
Test.Status = 1;
return 1;
}
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Derived d = new Derived();
int x = d[3];
if (Test.Status != 1 || x != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.simplename001.simplename001
{
// <Title>Classes - Simple Name (Method) Calling</Title>
// <Description> ICE </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
namespace NS
{
public class C
{
public static int Bar(C t)
{
return 1;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic v2 = new C();
return (1 == Bar(v2)) ? 0 : 1;
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.simplename003.simplename003
{
// <Title>Classes - Simple Name (Method) Calling</Title>
// <Description> </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
namespace NS
{
abstract public class Base
{
protected static int result = 0;
public static bool Bar(object o)
{
result = 1;
return false;
}
public abstract int Foo(dynamic o);
public virtual int Hoo(object o)
{
return 0;
}
public virtual int Poo(int n, dynamic o)
{
return 0;
}
}
public class Derived : Base
{
public override int Foo(object o)
{
result = 2;
return 0;
}
public new int Hoo(dynamic o)
{
result = 3;
return 0;
}
public sealed override int Poo(int n, dynamic o)
{
result = 4;
return 0;
}
public bool RunTest()
{
bool ret = true;
dynamic d = new Derived();
Bar(d);
ret &= (1 == result);
Foo(d);
ret &= (2 == result);
Hoo(d);
ret &= (3 == result);
dynamic x = 100;
Poo(x, d);
ret &= (4 == result);
return ret;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
var v = new Derived();
return v.RunTest() ? 0 : 1;
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.simplename004.simplename004
{
// <Title>Classes - Simple Name (Method) Calling</Title>
// <Description> </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
namespace NS
{
public struct MyType
{
public static int Bar<T>(object o)
{
return 1;
}
public int Foo<U>(object p1, object p2)
{
return 2;
}
public int Har<V>(object o, params int[] ary)
{
return 3;
}
public int Poo<W>(object p1, ref object p2, out dynamic p3)
{
p3 = default(dynamic);
return 4;
}
public int Dar<Y>(object p1, int p2 = 100, long p3 = 200)
{
return 5;
}
public bool RunTest()
{
bool ret = true;
dynamic d = null;
ret &= (1 == Bar<string>(d));
ret &= (2 == Foo<double>(d, d));
d = new MyType();
dynamic d1 = 999;
ret &= (1 == Bar<float>(d));
ret &= (2 == Foo<ulong>(d, d1));
ret &= (3 == Har<long>(d));
ret &= (4 == Poo<short>(d, ref d1, out d1));
ret &= (3 == Har<long>(d, d1));
ret &= (5 == Dar<char>(d));
ret &= (5 == Dar<char>(d, p2: 100));
ret &= (5 == Dar<char>(d, p3: 99, p2: 88));
return ret;
}
}
public class Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
var v = new MyType();
return v.RunTest() ? 0 : 1;
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.simplename005.simplename005
{
// <Title>Classes - Simple Name (Method) Calling</Title>
// <Description> ICE </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
namespace NS1
{
public delegate void MyDel01(object p1);
public delegate void MyDel02(string p1);
public delegate bool MyDel03(object p1, string p2);
public delegate bool MyDel04(string p1, string p2);
public delegate void MyDel05(string p1, out int p2, ref long p3);
public delegate void MyDel06(object p1, out int p2, ref long p3);
public delegate int MyDel07(int p1, int p2 = -1, int p3 = -2);
public delegate int MyDel08(object p1, byte p2 = 101);
public delegate int MyDel09(object p1, int p2 = 1, long p3 = 2);
public class Test
{
private static int s_result = -1;
public void MyMtd01(object p1)
{
s_result = 1;
}
public void MyMtd02(string p1)
{
s_result = 2;
}
public bool MyMtd03(object p1, string p2)
{
s_result = 3;
return true;
}
public bool MyMtd04(string p1, string p2)
{
s_result = 4;
return false;
}
public void MyMtd05(string p1, out int p2, ref long p3)
{
s_result = 5;
p2 = -30;
}
public void MyMtd06(object p1, out int p2, ref long p3)
{
s_result = 6;
p2 = -40;
}
public int MyMtd07(int p1, int p2 = -10, int p3 = -20)
{
s_result = 7;
return p3;
}
public int MyMtd08(object p1, byte p2 = 99)
{
s_result = 8;
return 1;
}
public int MyMtd09(object p1, int p2 = 10, long p3 = 20)
{
s_result = 9;
return p2;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var t = new Test();
return (t.RunTest()) ? 0 : 1;
}
public bool RunTest()
{
dynamic v1 = new MyDel01(MyMtd01);
dynamic d = null;
dynamic d1 = "12345";
v1(d);
bool ret = (1 == s_result);
v1 = new MyDel02(MyMtd02);
v1(d);
ret &= (2 == s_result);
v1 = new MyDel03(MyMtd03);
v1(d, d1);
ret &= (3 == s_result);
v1 = new MyDel04(MyMtd04);
v1(d, d1);
ret &= (4 == s_result);
d = 12345;
v1 = new MyDel05(MyMtd05);
//v1(d1, out d, ref d); // by design
//ret &= (5 == result);
v1 = new MyDel06(MyMtd06);
//v1(d1, out d, ref d);
//ret &= (6 == result);
v1 = new MyDel07(MyMtd07);
v1(d);
ret &= (7 == s_result);
s_result = -1;
v1(d, p3: 100);
ret &= (7 == s_result);
s_result = -1;
v1(d, p3: 100, p2: 200);
ret &= (7 == s_result);
d = null;
v1 = new MyDel08(MyMtd08);
v1(d); //
ret &= (8 == s_result);
v1 = new MyDel09(MyMtd09);
v1(d); //
ret &= (9 == s_result);
return ret;
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.classes.memberaccess002.memberaccess002
{
// <Title> Operator -.is, as</Title>
// <Description>(By Design)</Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class A
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic x = DayOfWeek.Monday;
try
{
var y = x.value__;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) // Should not EX
{
System.Console.WriteLine(e);
return 1;
}
return 0;
}
}
//</Code>
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#nullable enable
namespace Marten.Events
{
public interface IEventOperations
{
/// <summary>
/// Append one or more events in order to an existing stream
/// </summary>
/// <param name="stream"></param>
/// <param name="events"></param>
StreamAction Append(Guid stream, IEnumerable<object> events);
/// <summary>
/// Append one or more events in order to an existing stream
/// </summary>
/// <param name="stream"></param>
/// <param name="events"></param>
StreamAction Append(Guid stream, params object[] events);
/// <summary>
/// Append one or more events in order to an existing stream
/// </summary>
/// <param name="stream"></param>
/// <param name="events"></param>
StreamAction Append(string stream, IEnumerable<object> events);
/// <summary>
/// Append one or more events in order to an existing stream
/// </summary>
/// <param name="stream"></param>
/// <param name="events"></param>
StreamAction Append(string stream, params object[] events);
/// <summary>
/// Append one or more events in order to an existing stream and verify that maximum event id for the stream
/// matches supplied expected version or transaction is aborted.
/// </summary>
/// <param name="stream"></param>
/// <param name="expectedVersion">Expected maximum event version after append</param>
/// <param name="events"></param>
StreamAction Append(Guid stream, long expectedVersion, params object[] events);
/// <summary>
/// Append one or more events in order to an existing stream and verify that maximum event id for the stream
/// matches supplied expected version or transaction is aborted.
/// </summary>
/// <param name="stream"></param>
/// <param name="expectedVersion">Expected maximum event version after append</param>
/// <param name="events"></param>
StreamAction Append(string stream, long expectedVersion, IEnumerable<object> events);
/// <summary>
/// Append one or more events in order to an existing stream and verify that maximum event id for the stream
/// matches supplied expected version or transaction is aborted.
/// </summary>
/// <param name="stream"></param>
/// <param name="expectedVersion">Expected maximum event version after append</param>
/// <param name="events"></param>
StreamAction Append(string stream, long expectedVersion, params object[] events);
/// <summary>
/// Creates a new event stream based on a user-supplied Guid and appends the events in order to the new stream
/// </summary>
/// <typeparam name="TAggregate"></typeparam>
/// <param name="id"></param>
/// <param name="events"></param>
/// <returns></returns>
StreamAction StartStream<TAggregate>(Guid id, params object[] events) where TAggregate : class;
/// <summary>
/// Creates a new event stream based on a user-supplied Guid and appends the events in order to the new stream
/// </summary>
/// <param name="aggregateType"></param>
/// <param name="id"></param>
/// <param name="events"></param>
/// <returns></returns>
StreamAction StartStream(Type aggregateType, Guid id, IEnumerable<object> events);
/// <summary>
/// Creates a new event stream based on a user-supplied Guid and appends the events in order to the new stream
/// </summary>
/// <param name="aggregateType"></param>
/// <param name="id"></param>
/// <param name="events"></param>
/// <returns></returns>
StreamAction StartStream(Type aggregateType, Guid id, params object[] events);
/// <summary>
/// Creates a new event stream based on a user-supplied Guid and appends the events in order to the new stream
/// - WILL THROW AN EXCEPTION IF THE STREAM ALREADY EXISTS
/// </summary>
/// <typeparam name="TAggregate"></typeparam>
/// <param name="streamKey">String identifier of this stream</param>
/// <param name="events"></param>
/// <returns></returns>
StreamAction StartStream<TAggregate>(string streamKey, IEnumerable<object> events) where TAggregate : class;
/// <summary>
/// Creates a new event stream based on a user-supplied Guid and appends the events in order to the new stream
/// - WILL THROW AN EXCEPTION IF THE STREAM ALREADY EXISTS
/// </summary>
/// <typeparam name="TAggregate"></typeparam>
/// <param name="streamKey">String identifier of this stream</param>
/// <param name="events"></param>
/// <returns></returns>
StreamAction StartStream<TAggregate>(string streamKey, params object[] events) where TAggregate : class;
/// <summary>
/// Creates a new event stream based on a user-supplied Guid and appends the events in order to the new stream
/// - WILL THROW AN EXCEPTION IF THE STREAM ALREADY EXISTS
/// </summary>
/// <param name="aggregateType"></param>
/// <param name="streamKey">String identifier of this stream</param>
/// <param name="events"></param>
/// <returns></returns>
StreamAction StartStream(Type aggregateType, string streamKey, IEnumerable<object> events);
/// <summary>
/// Creates a new event stream based on a user-supplied Guid and appends the events in order to the new stream
/// - WILL THROW AN EXCEPTION IF THE STREAM ALREADY EXISTS
/// </summary>
/// <param name="aggregateType"></param>
/// <param name="streamKey">String identifier of this stream</param>
/// <param name="events"></param>
/// <returns></returns>
StreamAction StartStream(Type aggregateType, string streamKey, params object[] events);
/// <summary>
/// Creates a new event stream based on a user-supplied Guid and appends the events in order to the new stream - WILL THROW AN EXCEPTION IF THE STREAM ALREADY EXISTS
/// </summary>
/// <param name="id"></param>
/// <param name="events"></param>
/// <returns></returns>
StreamAction StartStream(Guid id, IEnumerable<object> events);
/// <summary>
/// Creates a new event stream based on a user-supplied Guid and appends the events in order to the new stream - WILL THROW AN EXCEPTION IF THE STREAM ALREADY EXISTS
/// </summary>
/// <param name="id"></param>
/// <param name="events"></param>
/// <returns></returns>
StreamAction StartStream(Guid id, params object[] events);
/// <summary>
/// Creates a new event stream based on a user-supplied Guid and appends the events in order to the new stream
/// - WILL THROW AN EXCEPTION IF THE STREAM ALREADY EXISTS
/// </summary>
/// <param name="streamKey"></param>
/// <param name="events"></param>
/// <returns></returns>
StreamAction StartStream(string streamKey, IEnumerable<object> events);
/// <summary>
/// Creates a new event stream based on a user-supplied Guid and appends the events in order to the new stream
/// - WILL THROW AN EXCEPTION IF THE STREAM ALREADY EXISTS
/// </summary>
/// <param name="streamKey"></param>
/// <param name="events"></param>
/// <returns></returns>
StreamAction StartStream(string streamKey, params object[] events);
/// <summary>
/// Creates a new event stream, assigns a new Guid id, and appends the events in order to the new stream
/// - WILL THROW AN EXCEPTION IF THE STREAM ALREADY EXISTS
/// </summary>
/// <typeparam name="TAggregate"></typeparam>
/// <param name="events"></param>
/// <returns></returns>
StreamAction StartStream<TAggregate>(IEnumerable<object> events) where TAggregate : class;
/// <summary>
/// Creates a new event stream, assigns a new Guid id, and appends the events in order to the new stream
/// - WILL THROW AN EXCEPTION IF THE STREAM ALREADY EXISTS
/// </summary>
/// <typeparam name="TAggregate"></typeparam>
/// <param name="events"></param>
/// <returns></returns>
StreamAction StartStream<TAggregate>(params object[] events) where TAggregate : class;
/// <summary>
/// Creates a new event stream, assigns a new Guid id, and appends the events in order to the new stream
/// - WILL THROW AN EXCEPTION IF THE STREAM ALREADY EXISTS
/// </summary>
/// <typeparam name="TAggregate"></typeparam>
/// <param name="events"></param>
/// <returns></returns>
StreamAction StartStream(Type aggregateType, IEnumerable<object> events);
/// <summary>
/// Creates a new event stream, assigns a new Guid id, and appends the events in order to the new stream
/// - WILL THROW AN EXCEPTION IF THE STREAM ALREADY EXISTS
/// </summary>
/// <typeparam name="TAggregate"></typeparam>
/// <param name="events"></param>
/// <returns></returns>
StreamAction StartStream(Type aggregateType, params object[] events);
/// <summary>
/// Creates a new event stream, assigns a new Guid id, and appends the events in order to the new stream
/// - WILL THROW AN EXCEPTION IF THE STREAM ALREADY EXISTS
/// </summary>
/// <typeparam name="TAggregate"></typeparam>
/// <param name="events"></param>
/// <returns></returns>
StreamAction StartStream(IEnumerable<object> events);
/// <summary>
/// Creates a new event stream, assigns a new Guid id, and appends the events in order to the new stream
/// - WILL THROW AN EXCEPTION IF THE STREAM ALREADY EXISTS
/// </summary>
/// <typeparam name="TAggregate"></typeparam>
/// <param name="events"></param>
/// <returns></returns>
StreamAction StartStream(params object[] events);
}
public interface IEventStore: IEventOperations, IQueryEventStore
{
/// <summary>
/// Append one or more events in order to an existing stream and verify that maximum event id for the stream
/// matches supplied expected version or transaction is aborted.
/// </summary>
/// <param name="stream"></param>
/// <param name="expectedVersion">Expected maximum event version after append</param>
/// <param name="events"></param>
StreamAction Append(Guid stream, long expectedVersion, IEnumerable<object> events);
/// <summary>
/// Creates a new event stream based on a user-supplied Guid and appends the events in order to the new stream
/// </summary>
/// <typeparam name="TAggregate"></typeparam>
/// <param name="id"></param>
/// <param name="events"></param>
/// <returns></returns>
StreamAction StartStream<TAggregate>(Guid id, IEnumerable<object> events) where TAggregate : class;
/// <summary>
/// Append events to an existing stream with optimistic concurrency checks against the
/// existing version of the stream
/// </summary>
/// <param name="streamKey"></param>
/// <param name="token"></param>
/// <param name="events"></param>
/// <exception cref="NonExistentStreamException"></exception>
/// <returns></returns>
Task AppendOptimistic(string streamKey, CancellationToken token, params object[] events);
/// <summary>
/// Append events to an existing stream with optimistic concurrency checks against the
/// existing version of the stream
/// </summary>
/// <param name="streamKey"></param>
/// <param name="events"></param>
/// <exception cref="NonExistentStreamException"></exception>
/// <returns></returns>
Task AppendOptimistic(string streamKey, params object[] events);
/// <summary>
/// Append events to an existing stream with optimistic concurrency checks against the
/// existing version of the stream
/// </summary>
/// <param name="streamId"></param>
/// <param name="token"></param>
/// <param name="events"></param>
/// <exception cref="NonExistentStreamException"></exception>
/// <returns></returns>
Task AppendOptimistic(Guid streamId, CancellationToken token, params object[] events);
/// <summary>
/// Append events to an existing stream with optimistic concurrency checks against the
/// existing version of the stream
/// </summary>
/// <param name="streamId"></param>
/// <param name="events"></param>
/// <exception cref="NonExistentStreamException"></exception>
/// <returns></returns>
Task AppendOptimistic(Guid streamId, params object[] events);
/// <summary>
/// Append events to an existing stream with an exclusive lock against the
/// stream until this session is saved
/// </summary>
/// <param name="streamKey"></param>
/// <param name="token"></param>
/// <param name="events"></param>
/// <exception cref="NonExistentStreamException"></exception>
/// <returns></returns>
Task AppendExclusive(string streamKey, CancellationToken token, params object[] events);
/// <summary>
/// Append events to an existing stream with an exclusive lock against the
/// stream until this session is saved
/// </summary>
/// <param name="streamKey"></param>
/// <param name="events"></param>
/// <exception cref="NonExistentStreamException"></exception>
/// <returns></returns>
Task AppendExclusive(string streamKey, params object[] events);
/// <summary>
/// Append events to an existing stream with an exclusive lock against the
/// stream until this session is saved
/// </summary>
/// <param name="streamId"></param>
/// <param name="events"></param>
/// <exception cref="NonExistentStreamException"></exception>
/// <returns></returns>
Task AppendExclusive(Guid streamId, CancellationToken token, params object[] events);
/// <summary>
/// Append events to an existing stream with an exclusive lock against the
/// stream until this session is saved
/// </summary>
/// <param name="streamId"></param>
/// <param name="events"></param>
/// <exception cref="NonExistentStreamException"></exception>
/// <returns></returns>
Task AppendExclusive(Guid streamId, params object[] events);
/// <summary>
/// Mark a stream and all its events as archived
/// </summary>
/// <param name="streamId"></param>
void ArchiveStream(Guid streamId);
/// <summary>
/// Mark a stream and all its events as archived
/// </summary>
/// <param name="streamKey"></param>
void ArchiveStream(string streamKey);
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityModel;
using IdentityServer4.Configuration;
using IdentityServer4.Events;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IdentityServer4.Logging.Models;
using Microsoft.AspNetCore.Authentication;
namespace IdentityServer4.Validation
{
internal class TokenRequestValidator : ITokenRequestValidator
{
private readonly IdentityServerOptions _options;
private readonly IAuthorizationCodeStore _authorizationCodeStore;
private readonly ExtensionGrantValidator _extensionGrantValidator;
private readonly ICustomTokenRequestValidator _customRequestValidator;
private readonly ScopeValidator _scopeValidator;
private readonly ITokenValidator _tokenValidator;
private readonly IEventService _events;
private readonly IResourceOwnerPasswordValidator _resourceOwnerValidator;
private readonly IProfileService _profile;
private readonly IDeviceCodeValidator _deviceCodeValidator;
private readonly ISystemClock _clock;
private readonly ILogger _logger;
private ValidatedTokenRequest _validatedRequest;
/// <summary>
/// Initializes a new instance of the <see cref="TokenRequestValidator" /> class.
/// </summary>
/// <param name="options">The options.</param>
/// <param name="authorizationCodeStore">The authorization code store.</param>
/// <param name="resourceOwnerValidator">The resource owner validator.</param>
/// <param name="profile">The profile.</param>
/// <param name="deviceCodeValidator">The device code validator.</param>
/// <param name="extensionGrantValidator">The extension grant validator.</param>
/// <param name="customRequestValidator">The custom request validator.</param>
/// <param name="scopeValidator">The scope validator.</param>
/// <param name="tokenValidator">The token validator.</param>
/// <param name="events">The events.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The logger.</param>
public TokenRequestValidator(IdentityServerOptions options, IAuthorizationCodeStore authorizationCodeStore, IResourceOwnerPasswordValidator resourceOwnerValidator, IProfileService profile, IDeviceCodeValidator deviceCodeValidator, ExtensionGrantValidator extensionGrantValidator, ICustomTokenRequestValidator customRequestValidator, ScopeValidator scopeValidator, ITokenValidator tokenValidator, IEventService events, ISystemClock clock, ILogger<TokenRequestValidator> logger)
{
_logger = logger;
_options = options;
_clock = clock;
_authorizationCodeStore = authorizationCodeStore;
_resourceOwnerValidator = resourceOwnerValidator;
_profile = profile;
_deviceCodeValidator = deviceCodeValidator;
_extensionGrantValidator = extensionGrantValidator;
_customRequestValidator = customRequestValidator;
_scopeValidator = scopeValidator;
_tokenValidator = tokenValidator;
_events = events;
}
/// <summary>
/// Validates the request.
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <param name="clientValidationResult">The client validation result.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException">
/// parameters
/// or
/// client
/// </exception>
public async Task<TokenRequestValidationResult> ValidateRequestAsync(NameValueCollection parameters, ClientSecretValidationResult clientValidationResult)
{
_logger.LogDebug("Start token request validation");
_validatedRequest = new ValidatedTokenRequest
{
Raw = parameters ?? throw new ArgumentNullException(nameof(parameters)),
Options = _options
};
if (clientValidationResult == null) throw new ArgumentNullException(nameof(clientValidationResult));
_validatedRequest.SetClient(clientValidationResult.Client, clientValidationResult.Secret, clientValidationResult.Confirmation);
/////////////////////////////////////////////
// check client protocol type
/////////////////////////////////////////////
if (_validatedRequest.Client.ProtocolType != IdentityServerConstants.ProtocolTypes.OpenIdConnect)
{
LogError("Invalid protocol type for client",
new
{
clientId = _validatedRequest.Client.ClientId,
expectedProtocolType = IdentityServerConstants.ProtocolTypes.OpenIdConnect,
actualProtocolType = _validatedRequest.Client.ProtocolType
});
return Invalid(OidcConstants.TokenErrors.InvalidClient);
}
/////////////////////////////////////////////
// check grant type
/////////////////////////////////////////////
var grantType = parameters.Get(OidcConstants.TokenRequest.GrantType);
if (grantType.IsMissing())
{
LogError("Grant type is missing");
return Invalid(OidcConstants.TokenErrors.UnsupportedGrantType);
}
if (grantType.Length > _options.InputLengthRestrictions.GrantType)
{
LogError("Grant type is too long");
return Invalid(OidcConstants.TokenErrors.UnsupportedGrantType);
}
_validatedRequest.GrantType = grantType;
switch (grantType)
{
case OidcConstants.GrantTypes.AuthorizationCode:
return await RunValidationAsync(ValidateAuthorizationCodeRequestAsync, parameters);
case OidcConstants.GrantTypes.ClientCredentials:
return await RunValidationAsync(ValidateClientCredentialsRequestAsync, parameters);
case OidcConstants.GrantTypes.Password:
return await RunValidationAsync(ValidateResourceOwnerCredentialRequestAsync, parameters);
case OidcConstants.GrantTypes.RefreshToken:
return await RunValidationAsync(ValidateRefreshTokenRequestAsync, parameters);
case OidcConstants.GrantTypes.DeviceCode:
return await RunValidationAsync(ValidateDeviceCodeRequestAsync, parameters);
default:
return await RunValidationAsync(ValidateExtensionGrantRequestAsync, parameters);
}
}
private async Task<TokenRequestValidationResult> RunValidationAsync(Func<NameValueCollection, Task<TokenRequestValidationResult>> validationFunc, NameValueCollection parameters)
{
// run standard validation
var result = await validationFunc(parameters);
if (result.IsError)
{
return result;
}
// run custom validation
_logger.LogTrace("Calling into custom request validator: {type}", _customRequestValidator.GetType().FullName);
var customValidationContext = new CustomTokenRequestValidationContext { Result = result };
await _customRequestValidator.ValidateAsync(customValidationContext);
if (customValidationContext.Result.IsError)
{
if (customValidationContext.Result.Error.IsPresent())
{
LogError("Custom token request validator", new { error = customValidationContext.Result.Error });
}
else
{
LogError("Custom token request validator error");
}
return customValidationContext.Result;
}
LogSuccess();
return customValidationContext.Result;
}
private async Task<TokenRequestValidationResult> ValidateAuthorizationCodeRequestAsync(NameValueCollection parameters)
{
_logger.LogDebug("Start validation of authorization code token request");
/////////////////////////////////////////////
// check if client is authorized for grant type
/////////////////////////////////////////////
if (!_validatedRequest.Client.AllowedGrantTypes.ToList().Contains(GrantType.AuthorizationCode) &&
!_validatedRequest.Client.AllowedGrantTypes.ToList().Contains(GrantType.Hybrid))
{
LogError("Client not authorized for code flow");
return Invalid(OidcConstants.TokenErrors.UnauthorizedClient);
}
/////////////////////////////////////////////
// validate authorization code
/////////////////////////////////////////////
var code = parameters.Get(OidcConstants.TokenRequest.Code);
if (code.IsMissing())
{
LogError("Authorization code is missing");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
if (code.Length > _options.InputLengthRestrictions.AuthorizationCode)
{
LogError("Authorization code is too long");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
_validatedRequest.AuthorizationCodeHandle = code;
var authZcode = await _authorizationCodeStore.GetAuthorizationCodeAsync(code);
if (authZcode == null)
{
LogError("Invalid authorization code", new { code });
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
await _authorizationCodeStore.RemoveAuthorizationCodeAsync(code);
if (authZcode.CreationTime.HasExceeded(authZcode.Lifetime, _clock.UtcNow.UtcDateTime))
{
LogError("Authorization code expired", new { code });
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
/////////////////////////////////////////////
// populate session id
/////////////////////////////////////////////
if (authZcode.SessionId.IsPresent())
{
_validatedRequest.SessionId = authZcode.SessionId;
}
/////////////////////////////////////////////
// validate client binding
/////////////////////////////////////////////
if (authZcode.ClientId != _validatedRequest.Client.ClientId)
{
LogError("Client is trying to use a code from a different client", new { clientId = _validatedRequest.Client.ClientId, codeClient = authZcode.ClientId });
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
/////////////////////////////////////////////
// validate code expiration
/////////////////////////////////////////////
if (authZcode.CreationTime.HasExceeded(_validatedRequest.Client.AuthorizationCodeLifetime, _clock.UtcNow.UtcDateTime))
{
LogError("Authorization code is expired");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
_validatedRequest.AuthorizationCode = authZcode;
_validatedRequest.Subject = authZcode.Subject;
/////////////////////////////////////////////
// validate redirect_uri
/////////////////////////////////////////////
var redirectUri = parameters.Get(OidcConstants.TokenRequest.RedirectUri);
if (redirectUri.IsMissing())
{
LogError("Redirect URI is missing");
return Invalid(OidcConstants.TokenErrors.UnauthorizedClient);
}
if (redirectUri.Equals(_validatedRequest.AuthorizationCode.RedirectUri, StringComparison.Ordinal) == false)
{
LogError("Invalid redirect_uri", new { redirectUri, expectedRedirectUri = _validatedRequest.AuthorizationCode.RedirectUri });
return Invalid(OidcConstants.TokenErrors.UnauthorizedClient);
}
/////////////////////////////////////////////
// validate scopes are present
/////////////////////////////////////////////
if (_validatedRequest.AuthorizationCode.RequestedScopes == null ||
!_validatedRequest.AuthorizationCode.RequestedScopes.Any())
{
LogError("Authorization code has no associated scopes");
return Invalid(OidcConstants.TokenErrors.InvalidRequest);
}
/////////////////////////////////////////////
// validate PKCE parameters
/////////////////////////////////////////////
var codeVerifier = parameters.Get(OidcConstants.TokenRequest.CodeVerifier);
if (_validatedRequest.Client.RequirePkce || _validatedRequest.AuthorizationCode.CodeChallenge.IsPresent())
{
_logger.LogDebug("Client required a proof key for code exchange. Starting PKCE validation");
var proofKeyResult = ValidateAuthorizationCodeWithProofKeyParameters(codeVerifier, _validatedRequest.AuthorizationCode);
if (proofKeyResult.IsError)
{
return proofKeyResult;
}
_validatedRequest.CodeVerifier = codeVerifier;
}
else
{
if (codeVerifier.IsPresent())
{
LogError("Unexpected code_verifier: {codeVerifier}. This happens when the client is trying to use PKCE, but it is not enabled. Set RequirePkce to true.", codeVerifier);
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
}
/////////////////////////////////////////////
// make sure user is enabled
/////////////////////////////////////////////
var isActiveCtx = new IsActiveContext(_validatedRequest.AuthorizationCode.Subject, _validatedRequest.Client, IdentityServerConstants.ProfileIsActiveCallers.AuthorizationCodeValidation);
await _profile.IsActiveAsync(isActiveCtx);
if (isActiveCtx.IsActive == false)
{
LogError("User has been disabled", new { subjectId = _validatedRequest.AuthorizationCode.Subject.GetSubjectId() });
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
_logger.LogDebug("Validation of authorization code token request success");
return Valid();
}
private async Task<TokenRequestValidationResult> ValidateClientCredentialsRequestAsync(NameValueCollection parameters)
{
_logger.LogDebug("Start client credentials token request validation");
/////////////////////////////////////////////
// check if client is authorized for grant type
/////////////////////////////////////////////
if (!_validatedRequest.Client.AllowedGrantTypes.ToList().Contains(GrantType.ClientCredentials))
{
LogError("Client not authorized for client credentials flow, check the AllowedGrantTypes setting", new { clientId = _validatedRequest.Client.ClientId });
return Invalid(OidcConstants.TokenErrors.UnauthorizedClient);
}
/////////////////////////////////////////////
// check if client is allowed to request scopes
/////////////////////////////////////////////
if (!await ValidateRequestedScopesAsync(parameters, ignoreImplicitIdentityScopes: true, ignoreImplicitOfflineAccess: true))
{
return Invalid(OidcConstants.TokenErrors.InvalidScope);
}
if (_validatedRequest.ValidatedScopes.ContainsOpenIdScopes)
{
LogError("Client cannot request OpenID scopes in client credentials flow", new { clientId = _validatedRequest.Client.ClientId });
return Invalid(OidcConstants.TokenErrors.InvalidScope);
}
if (_validatedRequest.ValidatedScopes.ContainsOfflineAccessScope)
{
LogError("Client cannot request a refresh token in client credentials flow", new { clientId = _validatedRequest.Client.ClientId });
return Invalid(OidcConstants.TokenErrors.InvalidScope);
}
_logger.LogDebug("{clientId} credentials token request validation success", _validatedRequest.Client.ClientId);
return Valid();
}
private async Task<TokenRequestValidationResult> ValidateResourceOwnerCredentialRequestAsync(NameValueCollection parameters)
{
_logger.LogDebug("Start resource owner password token request validation");
/////////////////////////////////////////////
// check if client is authorized for grant type
/////////////////////////////////////////////
if (!_validatedRequest.Client.AllowedGrantTypes.Contains(GrantType.ResourceOwnerPassword))
{
LogError("Client not authorized for resource owner flow, check the AllowedGrantTypes setting", new { client_id = _validatedRequest.Client.ClientId });
return Invalid(OidcConstants.TokenErrors.UnauthorizedClient);
}
/////////////////////////////////////////////
// check if client is allowed to request scopes
/////////////////////////////////////////////
if (!(await ValidateRequestedScopesAsync(parameters)))
{
return Invalid(OidcConstants.TokenErrors.InvalidScope);
}
/////////////////////////////////////////////
// check resource owner credentials
/////////////////////////////////////////////
var userName = parameters.Get(OidcConstants.TokenRequest.UserName);
var password = parameters.Get(OidcConstants.TokenRequest.Password);
if (userName.IsMissing())
{
LogError("Username is missing");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
if (password.IsMissing())
{
password = "";
}
if (userName.Length > _options.InputLengthRestrictions.UserName ||
password.Length > _options.InputLengthRestrictions.Password)
{
LogError("Username or password too long");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
_validatedRequest.UserName = userName;
/////////////////////////////////////////////
// authenticate user
/////////////////////////////////////////////
var resourceOwnerContext = new ResourceOwnerPasswordValidationContext
{
UserName = userName,
Password = password,
Request = _validatedRequest
};
await _resourceOwnerValidator.ValidateAsync(resourceOwnerContext);
if (resourceOwnerContext.Result.IsError)
{
// protect against bad validator implementations
resourceOwnerContext.Result.Error = resourceOwnerContext.Result.Error ?? OidcConstants.TokenErrors.InvalidGrant;
if (resourceOwnerContext.Result.Error == OidcConstants.TokenErrors.UnsupportedGrantType)
{
LogError("Resource owner password credential grant type not supported");
await RaiseFailedResourceOwnerAuthenticationEventAsync(userName, "password grant type not supported", resourceOwnerContext.Request.Client.ClientId);
return Invalid(OidcConstants.TokenErrors.UnsupportedGrantType, customResponse: resourceOwnerContext.Result.CustomResponse);
}
var errorDescription = "invalid_username_or_password";
if (resourceOwnerContext.Result.ErrorDescription.IsPresent())
{
errorDescription = resourceOwnerContext.Result.ErrorDescription;
}
LogInformation("User authentication failed: ", errorDescription ?? resourceOwnerContext.Result.Error);
await RaiseFailedResourceOwnerAuthenticationEventAsync(userName, errorDescription, resourceOwnerContext.Request.Client.ClientId);
return Invalid(resourceOwnerContext.Result.Error, errorDescription, resourceOwnerContext.Result.CustomResponse);
}
if (resourceOwnerContext.Result.Subject == null)
{
var error = "User authentication failed: no principal returned";
LogError(error);
await RaiseFailedResourceOwnerAuthenticationEventAsync(userName, error, resourceOwnerContext.Request.Client.ClientId);
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
/////////////////////////////////////////////
// make sure user is enabled
/////////////////////////////////////////////
var isActiveCtx = new IsActiveContext(resourceOwnerContext.Result.Subject, _validatedRequest.Client, IdentityServerConstants.ProfileIsActiveCallers.ResourceOwnerValidation);
await _profile.IsActiveAsync(isActiveCtx);
if (isActiveCtx.IsActive == false)
{
LogError("User has been disabled", new { subjectId = resourceOwnerContext.Result.Subject.GetSubjectId() });
await RaiseFailedResourceOwnerAuthenticationEventAsync(userName, "user is inactive", resourceOwnerContext.Request.Client.ClientId);
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
_validatedRequest.UserName = userName;
_validatedRequest.Subject = resourceOwnerContext.Result.Subject;
await RaiseSuccessfulResourceOwnerAuthenticationEventAsync(userName, resourceOwnerContext.Result.Subject.GetSubjectId(), resourceOwnerContext.Request.Client.ClientId);
_logger.LogDebug("Resource owner password token request validation success.");
return Valid(resourceOwnerContext.Result.CustomResponse);
}
private async Task<TokenRequestValidationResult> ValidateRefreshTokenRequestAsync(NameValueCollection parameters)
{
_logger.LogDebug("Start validation of refresh token request");
var refreshTokenHandle = parameters.Get(OidcConstants.TokenRequest.RefreshToken);
if (refreshTokenHandle.IsMissing())
{
LogError("Refresh token is missing");
return Invalid(OidcConstants.TokenErrors.InvalidRequest);
}
if (refreshTokenHandle.Length > _options.InputLengthRestrictions.RefreshToken)
{
LogError("Refresh token too long");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
var result = await _tokenValidator.ValidateRefreshTokenAsync(refreshTokenHandle, _validatedRequest.Client);
if (result.IsError)
{
LogWarning("Refresh token validation failed. aborting");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
_validatedRequest.RefreshToken = result.RefreshToken;
_validatedRequest.RefreshTokenHandle = refreshTokenHandle;
_validatedRequest.Subject = result.RefreshToken.Subject;
_logger.LogDebug("Validation of refresh token request success");
return Valid();
}
private async Task<TokenRequestValidationResult> ValidateDeviceCodeRequestAsync(NameValueCollection parameters)
{
_logger.LogDebug("Start validation of device code request");
/////////////////////////////////////////////
// check if client is authorized for grant type
/////////////////////////////////////////////
if (!_validatedRequest.Client.AllowedGrantTypes.ToList().Contains(GrantType.DeviceFlow))
{
LogError("Client not authorized for device flow");
return Invalid(OidcConstants.TokenErrors.UnauthorizedClient);
}
/////////////////////////////////////////////
// validate device code parameter
/////////////////////////////////////////////
var deviceCode = parameters.Get(OidcConstants.TokenRequest.DeviceCode);
if (deviceCode.IsMissing())
{
LogError("Device code is missing");
return Invalid(OidcConstants.TokenErrors.InvalidRequest);
}
if (deviceCode.Length > _options.InputLengthRestrictions.DeviceCode)
{
LogError("Device code too long");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
/////////////////////////////////////////////
// validate device code
/////////////////////////////////////////////
var deviceCodeContext = new DeviceCodeValidationContext {DeviceCode = deviceCode, Request = _validatedRequest};
await _deviceCodeValidator.ValidateAsync(deviceCodeContext);
if (deviceCodeContext.Result.IsError) return deviceCodeContext.Result;
_logger.LogDebug("Validation of authorization code token request success");
return Valid();
}
private async Task<TokenRequestValidationResult> ValidateExtensionGrantRequestAsync(NameValueCollection parameters)
{
_logger.LogDebug("Start validation of custom grant token request");
/////////////////////////////////////////////
// check if client is allowed to use grant type
/////////////////////////////////////////////
if (!_validatedRequest.Client.AllowedGrantTypes.Contains(_validatedRequest.GrantType))
{
LogError("Client does not have the custom grant type in the allowed list, therefore requested grant is not allowed", new { clientId = _validatedRequest.Client.ClientId });
return Invalid(OidcConstants.TokenErrors.UnsupportedGrantType);
}
/////////////////////////////////////////////
// check if a validator is registered for the grant type
/////////////////////////////////////////////
if (!_extensionGrantValidator.GetAvailableGrantTypes().Contains(_validatedRequest.GrantType, StringComparer.Ordinal))
{
LogError("No validator is registered for the grant type", new { grantType = _validatedRequest.GrantType });
return Invalid(OidcConstants.TokenErrors.UnsupportedGrantType);
}
/////////////////////////////////////////////
// check if client is allowed to request scopes
/////////////////////////////////////////////
if (!await ValidateRequestedScopesAsync(parameters))
{
return Invalid(OidcConstants.TokenErrors.InvalidScope);
}
/////////////////////////////////////////////
// validate custom grant type
/////////////////////////////////////////////
var result = await _extensionGrantValidator.ValidateAsync(_validatedRequest);
if (result == null)
{
LogError("Invalid extension grant");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
if (result.IsError)
{
if (result.Error.IsPresent())
{
LogError("Invalid extension grant", new { error = result.Error });
return Invalid(result.Error, result.ErrorDescription, result.CustomResponse);
}
else
{
LogError("Invalid extension grant");
return Invalid(OidcConstants.TokenErrors.InvalidGrant, customResponse: result.CustomResponse);
}
}
if (result.Subject != null)
{
/////////////////////////////////////////////
// make sure user is enabled
/////////////////////////////////////////////
var isActiveCtx = new IsActiveContext(
result.Subject,
_validatedRequest.Client,
IdentityServerConstants.ProfileIsActiveCallers.ExtensionGrantValidation);
await _profile.IsActiveAsync(isActiveCtx);
if (isActiveCtx.IsActive == false)
{
// todo: raise event?
LogError("User has been disabled", new { subjectId = result.Subject.GetSubjectId() });
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
_validatedRequest.Subject = result.Subject;
}
_logger.LogDebug("Validation of extension grant token request success");
return Valid(result.CustomResponse);
}
private async Task<bool> ValidateRequestedScopesAsync(NameValueCollection parameters, bool ignoreImplicitIdentityScopes = false, bool ignoreImplicitOfflineAccess = false)
{
var ignoreIdentityScopes = false;
var scopes = parameters.Get(OidcConstants.TokenRequest.Scope);
if (scopes.IsMissing())
{
if (ignoreImplicitIdentityScopes)
{
ignoreIdentityScopes = true;
}
_logger.LogTrace("Client provided no scopes - checking allowed scopes list");
if (!_validatedRequest.Client.AllowedScopes.IsNullOrEmpty())
{
var clientAllowedScopes = new List<string>(_validatedRequest.Client.AllowedScopes);
if (!ignoreImplicitOfflineAccess)
{
if (_validatedRequest.Client.AllowOfflineAccess)
{
clientAllowedScopes.Add(IdentityServerConstants.StandardScopes.OfflineAccess);
}
}
scopes = clientAllowedScopes.ToSpaceSeparatedString();
_logger.LogTrace("Defaulting to: {scopes}", scopes);
}
else
{
LogError("No allowed scopes configured for client", new { clientId = _validatedRequest.Client.ClientId });
return false;
}
}
if (scopes.Length > _options.InputLengthRestrictions.Scope)
{
LogError("Scope parameter exceeds max allowed length");
return false;
}
var requestedScopes = scopes.ParseScopesString();
if (requestedScopes == null)
{
LogError("No scopes found in request");
return false;
}
if (!await _scopeValidator.AreScopesAllowedAsync(_validatedRequest.Client, requestedScopes))
{
LogError();
return false;
}
if (!(await _scopeValidator.AreScopesValidAsync(requestedScopes, ignoreIdentityScopes)))
{
LogError();
return false;
}
_validatedRequest.Scopes = requestedScopes;
_validatedRequest.ValidatedScopes = _scopeValidator;
return true;
}
private TokenRequestValidationResult ValidateAuthorizationCodeWithProofKeyParameters(string codeVerifier, AuthorizationCode authZcode)
{
if (authZcode.CodeChallenge.IsMissing() || authZcode.CodeChallengeMethod.IsMissing())
{
LogError("Client is missing code challenge or code challenge method", new { clientId = _validatedRequest.Client.ClientId });
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
if (codeVerifier.IsMissing())
{
LogError("Missing code_verifier");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
if (codeVerifier.Length < _options.InputLengthRestrictions.CodeVerifierMinLength ||
codeVerifier.Length > _options.InputLengthRestrictions.CodeVerifierMaxLength)
{
LogError("code_verifier is too short or too long");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
if (Constants.SupportedCodeChallengeMethods.Contains(authZcode.CodeChallengeMethod) == false)
{
LogError("Unsupported code challenge method", new { codeChallengeMethod = authZcode.CodeChallengeMethod });
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
if (ValidateCodeVerifierAgainstCodeChallenge(codeVerifier, authZcode.CodeChallenge, authZcode.CodeChallengeMethod) == false)
{
LogError("Transformed code verifier does not match code challenge");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
return Valid();
}
private bool ValidateCodeVerifierAgainstCodeChallenge(string codeVerifier, string codeChallenge, string codeChallengeMethod)
{
if (codeChallengeMethod == OidcConstants.CodeChallengeMethods.Plain)
{
return TimeConstantComparer.IsEqual(codeVerifier.Sha256(), codeChallenge);
}
var codeVerifierBytes = Encoding.ASCII.GetBytes(codeVerifier);
var hashedBytes = codeVerifierBytes.Sha256();
var transformedCodeVerifier = Base64Url.Encode(hashedBytes);
return TimeConstantComparer.IsEqual(transformedCodeVerifier.Sha256(), codeChallenge);
}
private TokenRequestValidationResult Valid(Dictionary<string, object> customResponse = null)
{
return new TokenRequestValidationResult(_validatedRequest, customResponse);
}
private TokenRequestValidationResult Invalid(string error, string errorDescription = null, Dictionary<string, object> customResponse = null)
{
return new TokenRequestValidationResult(_validatedRequest, error, errorDescription, customResponse);
}
private void LogError(string message = null, object values = null)
{
LogWithRequestDetails(LogLevel.Error, message, values);
}
private void LogWarning(string message = null, object values = null)
{
LogWithRequestDetails(LogLevel.Warning, message, values);
}
private void LogInformation(string message = null, object values = null)
{
LogWithRequestDetails(LogLevel.Information, message, values);
}
private void LogWithRequestDetails(LogLevel logLevel, string message = null, object values = null)
{
var details = new TokenRequestValidationLog(_validatedRequest);
if (message.IsPresent())
{
try
{
if (values == null)
{
_logger.Log(logLevel, message + ", {@details}", details);
}
else
{
_logger.Log(logLevel, message + "{@values}, details: {@details}", values, details);
}
}
catch (Exception ex)
{
_logger.LogError("Error logging {exception}, request details: {@details}", ex.Message, details);
}
}
else
{
_logger.Log(logLevel, "{@details}", details);
}
}
private void LogSuccess()
{
LogWithRequestDetails(LogLevel.Information, "Token request validation success");
}
private Task RaiseSuccessfulResourceOwnerAuthenticationEventAsync(string userName, string subjectId, string clientId)
{
return _events.RaiseAsync(new UserLoginSuccessEvent(userName, subjectId, null, false, clientId));
}
private Task RaiseFailedResourceOwnerAuthenticationEventAsync(string userName, string error, string clientId)
{
return _events.RaiseAsync(new UserLoginFailureEvent(userName, error, clientId: clientId));
}
}
}
| |
using System;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Prism.Events;
using Prism.Logging;
using Prism.Modularity;
using Prism.Regions;
namespace Prism.Unity.Wpf.Tests
{
[TestClass]
public class UnityBootstrapperRunMethodFixture
{
[TestMethod]
public void CanRunBootstrapper()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
}
[TestMethod]
public void RunShouldNotFailIfReturnedNullShell()
{
var bootstrapper = new DefaultUnityBootstrapper { ShellObject = null };
bootstrapper.Run();
}
[TestMethod]
public void RunConfiguresServiceLocatorProvider()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
Assert.IsTrue(Microsoft.Practices.ServiceLocation.ServiceLocator.Current is UnityServiceLocatorAdapter);
}
[TestMethod]
public void RunShouldInitializeContainer()
{
var bootstrapper = new DefaultUnityBootstrapper();
var container = bootstrapper.BaseContainer;
Assert.IsNull(container);
bootstrapper.Run();
container = bootstrapper.BaseContainer;
Assert.IsNotNull(container);
Assert.IsInstanceOfType(container, typeof(UnityContainer));
}
[TestMethod]
public void RunAddsCompositionContainerToContainer()
{
var bootstrapper = new DefaultUnityBootstrapper();
var createdContainer = bootstrapper.CallCreateContainer();
var returnedContainer = createdContainer.Resolve<IUnityContainer>();
Assert.IsNotNull(returnedContainer);
Assert.AreEqual(typeof(UnityContainer), returnedContainer.GetType());
}
[TestMethod]
public void RunShouldCallInitializeModules()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.InitializeModulesCalled);
}
[TestMethod]
public void RunShouldCallConfigureDefaultRegionBehaviors()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.ConfigureDefaultRegionBehaviorsCalled);
}
[TestMethod]
public void RunShouldCallConfigureRegionAdapterMappings()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.ConfigureRegionAdapterMappingsCalled);
}
[TestMethod]
public void RunShouldAssignRegionManagerToReturnedShell()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
Assert.IsNotNull(RegionManager.GetRegionManager(bootstrapper.BaseShell));
}
[TestMethod]
public void RunShouldCallCreateLogger()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.CreateLoggerCalled);
}
[TestMethod]
public void RunShouldCallCreateModuleCatalog()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.CreateModuleCatalogCalled);
}
[TestMethod]
public void RunShouldCallConfigureModuleCatalog()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.ConfigureModuleCatalogCalled);
}
[TestMethod]
public void RunShouldCallCreateContainer()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.CreateContainerCalled);
}
[TestMethod]
public void RunShouldCallCreateShell()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.CreateShellCalled);
}
[TestMethod]
public void RunShouldCallConfigureContainer()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.ConfigureContainerCalled);
}
[TestMethod]
public void RunShouldCallConfigureServiceLocator()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.ConfigureServiceLocatorCalled);
}
[TestMethod]
public void RunShouldCallConfigureViewModelLocator()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
Assert.IsTrue(bootstrapper.ConfigureViewModelLocatorCalled);
}
[TestMethod]
public void RunRegistersInstanceOfILoggerFacade()
{
var mockedContainer = new Mock<IUnityContainer>();
SetupMockedContainerForVerificationTests(mockedContainer);
var bootstrapper = new MockedContainerBootstrapper(mockedContainer.Object);
bootstrapper.Run();
mockedContainer.Verify(c => c.RegisterInstance(typeof(ILoggerFacade), null, bootstrapper.BaseLogger, It.IsAny<LifetimeManager>()), Times.Once());
}
[TestMethod]
public void RunRegistersInstanceOfIModuleCatalog()
{
var mockedContainer = new Mock<IUnityContainer>();
SetupMockedContainerForVerificationTests(mockedContainer);
var bootstrapper = new MockedContainerBootstrapper(mockedContainer.Object);
bootstrapper.Run();
mockedContainer.Verify(c => c.RegisterInstance(typeof(IModuleCatalog), null, It.IsAny<object>(), It.IsAny<LifetimeManager>()), Times.Once());
}
[TestMethod]
public void RunRegistersTypeForIServiceLocator()
{
var mockedContainer = new Mock<IUnityContainer>();
SetupMockedContainerForVerificationTests(mockedContainer);
var bootstrapper = new MockedContainerBootstrapper(mockedContainer.Object);
bootstrapper.Run();
mockedContainer.Verify(c => c.RegisterType(typeof(IServiceLocator), typeof(UnityServiceLocatorAdapter), null, It.IsAny<LifetimeManager>()), Times.Once());
}
[TestMethod]
public void RunRegistersTypeForIModuleInitializer()
{
var mockedContainer = new Mock<IUnityContainer>();
SetupMockedContainerForVerificationTests(mockedContainer);
var bootstrapper = new MockedContainerBootstrapper(mockedContainer.Object);
bootstrapper.Run();
mockedContainer.Verify(c => c.RegisterType(typeof(IModuleInitializer), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Once());
}
[TestMethod]
public void RunRegistersTypeForIRegionManager()
{
var mockedContainer = new Mock<IUnityContainer>();
SetupMockedContainerForVerificationTests(mockedContainer);
var bootstrapper = new MockedContainerBootstrapper(mockedContainer.Object);
bootstrapper.Run();
mockedContainer.Verify(c => c.RegisterType(typeof(IRegionManager), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Once());
}
[TestMethod]
public void RunRegistersTypeForRegionAdapterMappings()
{
var mockedContainer = new Mock<IUnityContainer>();
SetupMockedContainerForVerificationTests(mockedContainer);
var bootstrapper = new MockedContainerBootstrapper(mockedContainer.Object);
bootstrapper.Run();
mockedContainer.Verify(c => c.RegisterType(typeof(RegionAdapterMappings), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Once());
}
[TestMethod]
public void RunRegistersTypeForIRegionViewRegistry()
{
var mockedContainer = new Mock<IUnityContainer>();
SetupMockedContainerForVerificationTests(mockedContainer);
var bootstrapper = new MockedContainerBootstrapper(mockedContainer.Object);
bootstrapper.Run();
mockedContainer.Verify(c => c.RegisterType(typeof(IRegionViewRegistry), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Once());
}
[TestMethod]
public void RunRegistersTypeForIRegionBehaviorFactory()
{
var mockedContainer = new Mock<IUnityContainer>();
SetupMockedContainerForVerificationTests(mockedContainer);
var bootstrapper = new MockedContainerBootstrapper(mockedContainer.Object);
bootstrapper.Run();
mockedContainer.Verify(c => c.RegisterType(typeof(IRegionBehaviorFactory), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Once());
}
[TestMethod]
public void RunRegistersTypeForIEventAggregator()
{
var mockedContainer = new Mock<IUnityContainer>();
SetupMockedContainerForVerificationTests(mockedContainer);
var bootstrapper = new MockedContainerBootstrapper(mockedContainer.Object);
bootstrapper.Run();
mockedContainer.Verify(c => c.RegisterType(typeof(IEventAggregator), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Once());
}
[TestMethod]
public void RunFalseShouldNotRegisterDefaultServicesAndTypes()
{
var mockedContainer = new Mock<IUnityContainer>();
SetupMockedContainerForVerificationTests(mockedContainer);
var bootstrapper = new MockedContainerBootstrapper(mockedContainer.Object);
bootstrapper.Run(false);
mockedContainer.Verify(c => c.RegisterType(typeof(IEventAggregator), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Never());
mockedContainer.Verify(c => c.RegisterType(typeof(IRegionManager), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Never());
mockedContainer.Verify(c => c.RegisterType(typeof(RegionAdapterMappings), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Never());
mockedContainer.Verify(c => c.RegisterType(typeof(IServiceLocator), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Never());
mockedContainer.Verify(c => c.RegisterType(typeof(IModuleInitializer), It.IsAny<Type>(), null, It.IsAny<LifetimeManager>()), Times.Never());
}
[TestMethod]
public void ModuleManagerRunCalled()
{
// Have to use a non-mocked container because of IsRegistered<> extension method, Registrations property,and ContainerRegistration
var container = new UnityContainer();
var mockedModuleInitializer = new Mock<IModuleInitializer>();
var mockedModuleManager = new Mock<IModuleManager>();
var regionAdapterMappings = new RegionAdapterMappings();
var serviceLocatorAdapter = new UnityServiceLocatorAdapter(container);
var regionBehaviorFactory = new RegionBehaviorFactory(serviceLocatorAdapter);
container.RegisterInstance<IServiceLocator>(serviceLocatorAdapter);
container.RegisterInstance<UnityBootstrapperExtension>(new UnityBootstrapperExtension());
container.RegisterInstance<IModuleCatalog>(new ModuleCatalog());
container.RegisterInstance<IModuleInitializer>(mockedModuleInitializer.Object);
container.RegisterInstance<IModuleManager>(mockedModuleManager.Object);
container.RegisterInstance<RegionAdapterMappings>(regionAdapterMappings);
container.RegisterInstance<SelectorRegionAdapter>(new SelectorRegionAdapter(regionBehaviorFactory));
container.RegisterInstance<ItemsControlRegionAdapter>(new ItemsControlRegionAdapter(regionBehaviorFactory));
container.RegisterInstance<ContentControlRegionAdapter>(new ContentControlRegionAdapter(regionBehaviorFactory));
var bootstrapper = new MockedContainerBootstrapper(container);
bootstrapper.Run();
mockedModuleManager.Verify(mm => mm.Run(), Times.Once());
}
[TestMethod]
public void RunShouldCallTheMethodsInOrder()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
Assert.AreEqual("CreateLogger", bootstrapper.MethodCalls[0]);
Assert.AreEqual("CreateModuleCatalog", bootstrapper.MethodCalls[1]);
Assert.AreEqual("ConfigureModuleCatalog", bootstrapper.MethodCalls[2]);
Assert.AreEqual("CreateContainer", bootstrapper.MethodCalls[3]);
Assert.AreEqual("ConfigureContainer", bootstrapper.MethodCalls[4]);
Assert.AreEqual("ConfigureServiceLocator", bootstrapper.MethodCalls[5]);
Assert.AreEqual("ConfigureViewModelLocator", bootstrapper.MethodCalls[6]);
Assert.AreEqual("ConfigureRegionAdapterMappings", bootstrapper.MethodCalls[7]);
Assert.AreEqual("ConfigureDefaultRegionBehaviors", bootstrapper.MethodCalls[8]);
Assert.AreEqual("RegisterFrameworkExceptionTypes", bootstrapper.MethodCalls[9]);
Assert.AreEqual("CreateShell", bootstrapper.MethodCalls[10]);
Assert.AreEqual("InitializeShell", bootstrapper.MethodCalls[11]);
Assert.AreEqual("InitializeModules", bootstrapper.MethodCalls[12]);
}
[TestMethod]
public void RunShouldLogBootstrapperSteps()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
var messages = bootstrapper.BaseLogger.Messages;
Assert.IsTrue(messages[0].Contains("Logger was created successfully."));
Assert.IsTrue(messages[1].Contains("Creating module catalog."));
Assert.IsTrue(messages[2].Contains("Configuring module catalog."));
Assert.IsTrue(messages[3].Contains("Creating Unity container."));
Assert.IsTrue(messages[4].Contains("Configuring the Unity container."));
Assert.IsTrue(messages[5].Contains("Adding UnityBootstrapperExtension to container."));
Assert.IsTrue(messages[6].Contains("Configuring ServiceLocator singleton."));
Assert.IsTrue(messages[7].Contains("Configuring the ViewModelLocator to use Unity."));
Assert.IsTrue(messages[8].Contains("Configuring region adapters."));
Assert.IsTrue(messages[9].Contains("Configuring default region behaviors."));
Assert.IsTrue(messages[10].Contains("Registering Framework Exception Types."));
Assert.IsTrue(messages[11].Contains("Creating the shell."));
Assert.IsTrue(messages[12].Contains("Setting the RegionManager."));
Assert.IsTrue(messages[13].Contains("Updating Regions."));
Assert.IsTrue(messages[14].Contains("Initializing the shell."));
Assert.IsTrue(messages[15].Contains("Initializing modules."));
Assert.IsTrue(messages[16].Contains("Bootstrapper sequence completed."));
}
[TestMethod]
public void RunShouldLogLoggerCreationSuccess()
{
const string expectedMessageText = "Logger was created successfully.";
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
var messages = bootstrapper.BaseLogger.Messages;
Assert.IsTrue(messages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutModuleCatalogCreation()
{
const string expectedMessageText = "Creating module catalog.";
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
var messages = bootstrapper.BaseLogger.Messages;
Assert.IsTrue(messages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutConfiguringModuleCatalog()
{
const string expectedMessageText = "Configuring module catalog.";
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
var messages = bootstrapper.BaseLogger.Messages;
Assert.IsTrue(messages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutCreatingTheContainer()
{
const string expectedMessageText = "Creating Unity container.";
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
var messages = bootstrapper.BaseLogger.Messages;
Assert.IsTrue(messages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutConfiguringContainer()
{
const string expectedMessageText = "Configuring the Unity container.";
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
var messages = bootstrapper.BaseLogger.Messages;
Assert.IsTrue(messages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutConfiguringViewModelLocator()
{
const string expectedMessageText = "Configuring the ViewModelLocator to use Unity.";
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
var messages = bootstrapper.BaseLogger.Messages;
Assert.IsTrue(messages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutConfiguringRegionAdapters()
{
const string expectedMessageText = "Configuring region adapters.";
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
var messages = bootstrapper.BaseLogger.Messages;
Assert.IsTrue(messages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutConfiguringRegionBehaviors()
{
const string expectedMessageText = "Configuring default region behaviors.";
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
var messages = bootstrapper.BaseLogger.Messages;
Assert.IsTrue(messages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutRegisteringFrameworkExceptionTypes()
{
const string expectedMessageText = "Registering Framework Exception Types.";
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
var messages = bootstrapper.BaseLogger.Messages;
Assert.IsTrue(messages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutCreatingTheShell()
{
const string expectedMessageText = "Creating the shell.";
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
var messages = bootstrapper.BaseLogger.Messages;
Assert.IsTrue(messages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutInitializingTheShellIfShellCreated()
{
const string expectedMessageText = "Initializing the shell.";
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
var messages = bootstrapper.BaseLogger.Messages;
Assert.IsTrue(messages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldNotLogAboutInitializingTheShellIfShellIsNotCreated()
{
const string expectedMessageText = "Initializing shell";
var bootstrapper = new DefaultUnityBootstrapper { ShellObject = null };
bootstrapper.Run();
var messages = bootstrapper.BaseLogger.Messages;
Assert.IsFalse(messages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutInitializingModules()
{
const string expectedMessageText = "Initializing modules.";
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
var messages = bootstrapper.BaseLogger.Messages;
Assert.IsTrue(messages.Contains(expectedMessageText));
}
[TestMethod]
public void RunShouldLogAboutRunCompleting()
{
const string expectedMessageText = "Bootstrapper sequence completed.";
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
var messages = bootstrapper.BaseLogger.Messages;
Assert.IsTrue(messages.Contains(expectedMessageText));
}
private static void SetupMockedContainerForVerificationTests(Mock<IUnityContainer> mockedContainer)
{
var mockedModuleInitializer = new Mock<IModuleInitializer>();
var mockedModuleManager = new Mock<IModuleManager>();
var regionAdapterMappings = new RegionAdapterMappings();
var serviceLocatorAdapter = new UnityServiceLocatorAdapter(mockedContainer.Object);
var regionBehaviorFactory = new RegionBehaviorFactory(serviceLocatorAdapter);
mockedContainer.Setup(c => c.Resolve(typeof(IServiceLocator), (string)null)).Returns(serviceLocatorAdapter);
mockedContainer.Setup(c => c.RegisterInstance(It.IsAny<Type>(), It.IsAny<string>(), It.IsAny<object>(), It.IsAny<LifetimeManager>()));
mockedContainer.Setup(c => c.Resolve(typeof(UnityBootstrapperExtension), (string)null)).Returns(
new UnityBootstrapperExtension());
mockedContainer.Setup(c => c.Resolve(typeof(IModuleCatalog), (string)null)).Returns(
new ModuleCatalog());
mockedContainer.Setup(c => c.Resolve(typeof(IModuleInitializer), (string)null)).Returns(
mockedModuleInitializer.Object);
mockedContainer.Setup(c => c.Resolve(typeof(IModuleManager), (string)null)).Returns(
mockedModuleManager.Object);
mockedContainer.Setup(c => c.Resolve(typeof(RegionAdapterMappings), (string)null)).Returns(
regionAdapterMappings);
mockedContainer.Setup(c => c.Resolve(typeof(SelectorRegionAdapter), (string)null)).Returns(
new SelectorRegionAdapter(regionBehaviorFactory));
mockedContainer.Setup(c => c.Resolve(typeof(ItemsControlRegionAdapter), (string)null)).Returns(
new ItemsControlRegionAdapter(regionBehaviorFactory));
mockedContainer.Setup(c => c.Resolve(typeof(ContentControlRegionAdapter), (string)null)).Returns(
new ContentControlRegionAdapter(regionBehaviorFactory));
}
private class MockedContainerBootstrapper : UnityBootstrapper
{
private readonly IUnityContainer container;
public ILoggerFacade BaseLogger
{ get { return base.Logger; } }
public void CallConfigureContainer()
{
base.ConfigureContainer();
}
public MockedContainerBootstrapper(IUnityContainer container)
{
this.container = container;
}
protected override IUnityContainer CreateContainer()
{
return container;
}
protected override DependencyObject CreateShell()
{
return new UserControl();
}
protected override void InitializeShell()
{
// no op
}
}
}
}
| |
// 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.Xml.Linq;
using Xunit;
namespace System.Security.Cryptography.Dsa.Tests
{
public static class DSAXml
{
[Fact]
public static void TestRead512Parameters_Public()
{
DSAParameters expectedParameters = DSATestData.Dsa512Parameters;
expectedParameters.X = null;
TestReadXml(
// Bonus trait of this XML: it shows that the namespaces of the elements are not considered
@"
<DSAKeyValue xmlns:yep=""urn:ignored:yep"" xmlns:nope=""urn:ignored:nope"" xmlns:ign=""urn:ignored:ign"">
<yep:P>1qi38cr3ppZNB2Y/xpHSL2q81Vw3rvWNIHRnQNgv4U4UY2NifZGSUULc3uOEvgoeBO1b9fRxSG9NmG1CoufflQ==</yep:P>
<nope:Q>+rX2JdXV4WQwoe9jDr4ziXzCJPk=</nope:Q>
<G>CETEkOUu9Y4FkCxjbWTR1essYIKg1PO/0c4Hjoe0On73u+zhmk7+Km2cIp02AIPOqfch85sFuvlwUt78Z6WKKw==</G>
<ign:Y>wwDg5n2HfmztOf7qqsHywr1WjmoyRnIn4Stq5FqNlHhUGkgKyAA4qshjgn1uOYQGGiWQXBi9JJmoOWY8PKRWBQ==</ign:Y>
</DSAKeyValue>",
expectedParameters);
}
[Fact]
public static void TestRead512Parameters_Private()
{
TestReadXml(
// Bonus trait of this XML, it shows that the order doesn't matter in the elements,
// and unknown elements are ignored
@"
<DSAKeyValue>
<Y>wwDg5n2HfmztOf7qqsHywr1WjmoyRnIn4Stq5FqNlHhUGkgKyAA4qshjgn1uOYQGGiWQXBi9JJmoOWY8PKRWBQ==</Y>
<Q>+rX2JdXV4WQwoe9jDr4ziXzCJPk=</Q>
<BananaWeight unit=""lbs"">30000</BananaWeight>
<X>Lj16hMhbZnheH2/nlpgrIrDLmLw=</X>
<G>CETEkOUu9Y4FkCxjbWTR1essYIKg1PO/0c4Hjoe0On73u+zhmk7+Km2cIp02AIPOqfch85sFuvlwUt78Z6WKKw==</G>
<P>1qi38cr3ppZNB2Y/xpHSL2q81Vw3rvWNIHRnQNgv4U4UY2NifZGSUULc3uOEvgoeBO1b9fRxSG9NmG1CoufflQ==</P>
</DSAKeyValue>",
DSATestData.Dsa512Parameters);
}
[Fact]
public static void TestRead576Parameters_Public()
{
DSAParameters expectedParameters = DSATestData.Dsa576Parameters;
expectedParameters.X = null;
TestReadXml(
// Bonus trait of this XML: it shows that the default namespaces of the elements is not considered,
// and is the first test to show that whitespace is not considered.
@"
<DSAKeyValue xmlns=""urn:ignored:root"">
<P>
4hZzBr/9hrti9DJ7d4u/oHukIyPsVnsQa5VjiCvd1tfy7nNg8pmIjen0CmHHjQvY
RC76nDIrhorTZ7OUHXK3ozLJVOsWKRMr
</P>
<Q>zNzsz18LLI/iOOLwbyITfxf66xs=</Q>
<G>
rxfUBhMCB54zA0p3oFjdtLgyrLEUt7jS065EUd/4XrjdddRHQhg2nUhbIgZQZAYE
SrTmQH/apaKeldSWTKVZ6BxvfPzahyZl
</G>
<Y>
gVpUm2/QztrwRLALfP4TUZAtdyfW1/tzYAOk4cTNjfv0MeT/RzPz+pLHZfDP+UTj7VaoW3WVPrFpASSJhbtfiROY6rXjlkXn
</Y>
</DSAKeyValue>",
expectedParameters);
}
[Fact]
public static void TestRead576Parameters_Private()
{
TestReadXml(
// Bonus trait of this XML: it shows the root element name is not considered.
@"
<DSA>
<P>
4hZzBr/9hrti9DJ7d4u/oHukIyPsVnsQa5VjiCvd1tfy7nNg8pmIjen0CmHHjQvY
RC76nDIrhorTZ7OUHXK3ozLJVOsWKRMr
</P>
<Q>zNzsz18LLI/iOOLwbyITfxf66xs=</Q>
<G>
rxfUBhMCB54zA0p3oFjdtLgyrLEUt7jS065EUd/4XrjdddRHQhg2nUhbIgZQZAYE
SrTmQH/apaKeldSWTKVZ6BxvfPzahyZl
</G>
<Y>
gVpUm2/QztrwRLALfP4TUZAtdyfW1/tzYAOk4cTNjfv0MeT/RzPz+pLHZfDP+UTj7VaoW3WVPrFpASSJhbtfiROY6rXjlkXn
</Y>
<X>
rDJpPhzXKtY+GgtugVfrvKZx09s=
</X>
</DSA>",
DSATestData.Dsa576Parameters);
}
[Fact]
public static void TestRead1024Parameters_Public()
{
DSAParameters expectedParameters = DSATestData.GetDSA1024Params();
expectedParameters.X = null;
TestReadXml(
// Bonus trait of this XML: very odd whitespace
@"
<DSAKeyValue>
<P>
wW0mx01sFid5nAkYVI5VP+WMeIHaSEYpyvZDEfSyfP72vbDyEgaw/8SZmi/tU7Q7
nuKRDGjaLENqgBj0k49kcjafVkfQBbzJbiJZDMFePNTqDRMvXaWvaqoIB7DMTvNA
SvVC9FRrN73WpH5kETCDfbm
Tl8hFY1
1 9 w 2 0 F N + S o S z E =
</P>
<Q>2DwOy3NVHi/jDVH89CNsZRiDrdc=</Q>
<G>
a8NmtmNVVF4Jjx/pDlRptWfgn6edgX8rNntF3s1DAaWcgdaRH3aR03DhWsaSwEvB
GHLBcaf+ZU6WPX3aV1qemM4Cb7fTk0olhggTSo7F7WmirtyJQBtnrd5Cfxftrrct
evRdmrHVnhsT1O + 9F8dkMwJn3eNSwg4FuA2zwQn + i5w =
</G>
<Y>
aQuzepFF4F1ue0fEV4mKrt1yUBydFuebGtdahyzwF6qQu/uQ8bO39cA8h+RuhyVm
VSb9NBV7JvWWofCZf1nz5l78YVpVLV51acX
/
xFk9WgKZEQ5xyX4SIaWgP+mmk1rt
2I7ws7L3nTqZ7XX3uHHm6vJoDZbVdKX0
wTus47S0TeE=
</Y>
</DSAKeyValue>",
expectedParameters);
}
[Fact]
public static void TestRead1024Parameters_Private()
{
TestReadXml(
// Bonus trait of this XML: very odd whitespace
@"
<DSAKeyValue>
<P>
wW0mx01sFid5nAkYVI5VP+WMeIHaSEYpyvZDEfSyfP72vbDyEgaw/8SZmi/tU7Q7
nuKRDGjaLENqgBj0k49kcjafVkfQBbzJbiJZDMFePNTqDRMvXaWvaqoIB7DMTvNA
SvVC9FRrN73WpH5kETCDfbm
Tl8hFY1
1 9 w 2 0 F N + S o S z E =
</P>
<Q>2DwOy3NVHi/jDVH89CNsZRiDrdc=</Q>
<G>
a8NmtmNVVF4Jjx/pDlRptWfgn6edgX8rNntF3s1DAaWcgdaRH3aR03DhWsaSwEvB
GHLBcaf+ZU6WPX3aV1qemM4Cb7fTk0olhggTSo7F7WmirtyJQBtnrd5Cfxftrrct
evRdmrHVnhsT1O + 9F8dkMwJn3eNSwg4FuA2zwQn + i5w =
</G>
<Y>
aQuzepFF4F1ue0fEV4mKrt1yUBydFuebGtdahyzwF6qQu/uQ8bO39cA8h+RuhyVm
VSb9NBV7JvWWofCZf1nz5l78YVpVLV51acX
/
xFk9WgKZEQ5xyX4SIaWgP+mmk1rt
2I7ws7L3nTqZ7XX3uHHm6vJoDZbVdKX0
wTus47S0TeE=
</Y>
<X>
w C Z 4 A H d 5 5 S 4 2 B o I h
S 9 R / j 6 9 C v C
0 =
</X>
</DSAKeyValue>
",
DSATestData.GetDSA1024Params());
}
[ConditionalFact(typeof(DSAFactory), nameof(DSAFactory.SupportsFips186_3))]
public static void TestRead2048Parameters_Public()
{
DSAParameters expectedParameters = DSATestData.Dsa2048DeficientXParameters;
expectedParameters.X = null;
TestReadXml(
// Bonus trait of this XML: Canonical element order, pretty-printed.
// Includes the XML declaration.
@"<?xml version=""1.0"" encoding=""UTF-8""?>
<DSAKeyValue>
<P>
lNPks58XJz6PJ7MmkvfDTTVhi9J5VItHNpOcK6TnKRFsrqxgAelXBcJ9fPDDCLyn
ArtHEtS7RIoQeLYxFQ6rRVyRZ4phxRwtNx4Cu6xw6cLG2nV7V4IOyP0JbhBew2wH
ik/X3Yck0nXTAH+U8S/5YWcpPGZ7RncH8dyafAs0vE/EdbFdUSQKeJpTpWtk1pwe
ArfKOtNBs7b2yYbx4GW/5oDYfe5tlZHY445Xw3rCmDsnlL6v/ix7W2ykm5gSSHMy
XGHeb4IEEQGL6XI/4r2oMywTCIqjKghtFNbwAgEBP1FnhkPzKswAUl2yLwAg2S+c
L0CIuNNaHnZNzYtwwLPS6w==
</P>
<Q>23CgOhWOnMudk9v3Z5bL68pFqHA+gqRYAViO5LaYWrM=</Q>
<G>
PPDxRLcKu9RCYNksTgMq3wpZjmgyPiVK/4cQyejqm+GdDSr5OaoN7HbSB7bqzveC
TjZldTVjAcpfmF74/3r1UYuN8IhaasVw/i5cWVYXDnHydAGUAYyKCkp7D5z5av1+
JQJvqAuflya2xN/LxBBeuYaHyml/eXlAwTNbFEMR1H/yHk1cQ8AFhHhrwarkrYWK
wGM1HuRCNHC+URVShpTvzzEtnljU3dHAHig4M/TxSeX5vUVJMEQxthvg2tcXtTjF
zVL94ajmYZPonQnB4Hlo5vcH71YU6D5hEm9qXzk54HZzdFRL4yJcxPjzxQHVolJv
e7ZNZWp7vf5+cssW1x6KOA==
</G>
<Y>
cHLO4Kgw8hUDAviwzw8HFHtsaxMs5k309uE7nofw8txeBXRBGbaVgJU1GndCqeRc
cuI+6L8AmMgv0tB4fyGXRwv7DLwhRirTiT3vfBoN80/VKVf/AcafdsVkwmjrzUPe
w3bfU4qIdK807QB7TkbQZgBoE3kxqlmjLodbKUKdtVY13rbcjL+GfUSUytXt7n5/
IF7o6LLIoFK0Uo9HySsfjP7J7QU8IeOnMb/yaa0JnEE9X8h4U1EWXnmqehQ6DH5V
Ye8DvOPPDe2c7YMWgC+Z3a0DLejBknDzuvWoJgiIkX/Nc+Sx1W+tFWPHHbyS9nJW
kt3Wo5FBhE0R/aIwt75rrA==
</Y>
</DSAKeyValue>",
expectedParameters);
}
[ConditionalFact(typeof(DSAFactory), nameof(DSAFactory.SupportsFips186_3))]
public static void TestRead2048Parameters_Private_CryptoBinary()
{
TestReadXml(
// Bonus trait of this XML: The X parameter is encoded as a CryptoBinary,
// meaning the leading 0x00 byte is removed.
@"<?xml version=""1.0"" encoding=""UTF-8""?>
<DSAKeyValue>
<P>
lNPks58XJz6PJ7MmkvfDTTVhi9J5VItHNpOcK6TnKRFsrqxgAelXBcJ9fPDDCLyn
ArtHEtS7RIoQeLYxFQ6rRVyRZ4phxRwtNx4Cu6xw6cLG2nV7V4IOyP0JbhBew2wH
ik/X3Yck0nXTAH+U8S/5YWcpPGZ7RncH8dyafAs0vE/EdbFdUSQKeJpTpWtk1pwe
ArfKOtNBs7b2yYbx4GW/5oDYfe5tlZHY445Xw3rCmDsnlL6v/ix7W2ykm5gSSHMy
XGHeb4IEEQGL6XI/4r2oMywTCIqjKghtFNbwAgEBP1FnhkPzKswAUl2yLwAg2S+c
L0CIuNNaHnZNzYtwwLPS6w==
</P>
<Q>23CgOhWOnMudk9v3Z5bL68pFqHA+gqRYAViO5LaYWrM=</Q>
<G>
PPDxRLcKu9RCYNksTgMq3wpZjmgyPiVK/4cQyejqm+GdDSr5OaoN7HbSB7bqzveC
TjZldTVjAcpfmF74/3r1UYuN8IhaasVw/i5cWVYXDnHydAGUAYyKCkp7D5z5av1+
JQJvqAuflya2xN/LxBBeuYaHyml/eXlAwTNbFEMR1H/yHk1cQ8AFhHhrwarkrYWK
wGM1HuRCNHC+URVShpTvzzEtnljU3dHAHig4M/TxSeX5vUVJMEQxthvg2tcXtTjF
zVL94ajmYZPonQnB4Hlo5vcH71YU6D5hEm9qXzk54HZzdFRL4yJcxPjzxQHVolJv
e7ZNZWp7vf5+cssW1x6KOA==
</G>
<Y>
cHLO4Kgw8hUDAviwzw8HFHtsaxMs5k309uE7nofw8txeBXRBGbaVgJU1GndCqeRc
cuI+6L8AmMgv0tB4fyGXRwv7DLwhRirTiT3vfBoN80/VKVf/AcafdsVkwmjrzUPe
w3bfU4qIdK807QB7TkbQZgBoE3kxqlmjLodbKUKdtVY13rbcjL+GfUSUytXt7n5/
IF7o6LLIoFK0Uo9HySsfjP7J7QU8IeOnMb/yaa0JnEE9X8h4U1EWXnmqehQ6DH5V
Ye8DvOPPDe2c7YMWgC+Z3a0DLejBknDzuvWoJgiIkX/Nc+Sx1W+tFWPHHbyS9nJW
kt3Wo5FBhE0R/aIwt75rrA==
</Y>
<X>yHG344loXbl9k03XAR+rB2/yfsQoL7AMDWRtKdXk5Q==</X>
</DSAKeyValue>",
DSATestData.Dsa2048DeficientXParameters);
}
[ConditionalFact(typeof(DSAFactory), nameof(DSAFactory.SupportsFips186_3))]
public static void TestRead2048Parameters_Private_Base64Binary()
{
TestReadXml(
// Bonus trait of this XML: The X parameter is encoded as a Base64Binary,
// meaning the leading 0x00 byte is NOT removed.
@"<?xml version=""1.0"" encoding=""UTF-8""?>
<DSAKeyValue>
<P>
lNPks58XJz6PJ7MmkvfDTTVhi9J5VItHNpOcK6TnKRFsrqxgAelXBcJ9fPDDCLyn
ArtHEtS7RIoQeLYxFQ6rRVyRZ4phxRwtNx4Cu6xw6cLG2nV7V4IOyP0JbhBew2wH
ik/X3Yck0nXTAH+U8S/5YWcpPGZ7RncH8dyafAs0vE/EdbFdUSQKeJpTpWtk1pwe
ArfKOtNBs7b2yYbx4GW/5oDYfe5tlZHY445Xw3rCmDsnlL6v/ix7W2ykm5gSSHMy
XGHeb4IEEQGL6XI/4r2oMywTCIqjKghtFNbwAgEBP1FnhkPzKswAUl2yLwAg2S+c
L0CIuNNaHnZNzYtwwLPS6w==
</P>
<Q>23CgOhWOnMudk9v3Z5bL68pFqHA+gqRYAViO5LaYWrM=</Q>
<G>
PPDxRLcKu9RCYNksTgMq3wpZjmgyPiVK/4cQyejqm+GdDSr5OaoN7HbSB7bqzveC
TjZldTVjAcpfmF74/3r1UYuN8IhaasVw/i5cWVYXDnHydAGUAYyKCkp7D5z5av1+
JQJvqAuflya2xN/LxBBeuYaHyml/eXlAwTNbFEMR1H/yHk1cQ8AFhHhrwarkrYWK
wGM1HuRCNHC+URVShpTvzzEtnljU3dHAHig4M/TxSeX5vUVJMEQxthvg2tcXtTjF
zVL94ajmYZPonQnB4Hlo5vcH71YU6D5hEm9qXzk54HZzdFRL4yJcxPjzxQHVolJv
e7ZNZWp7vf5+cssW1x6KOA==
</G>
<Y>
cHLO4Kgw8hUDAviwzw8HFHtsaxMs5k309uE7nofw8txeBXRBGbaVgJU1GndCqeRc
cuI+6L8AmMgv0tB4fyGXRwv7DLwhRirTiT3vfBoN80/VKVf/AcafdsVkwmjrzUPe
w3bfU4qIdK807QB7TkbQZgBoE3kxqlmjLodbKUKdtVY13rbcjL+GfUSUytXt7n5/
IF7o6LLIoFK0Uo9HySsfjP7J7QU8IeOnMb/yaa0JnEE9X8h4U1EWXnmqehQ6DH5V
Ye8DvOPPDe2c7YMWgC+Z3a0DLejBknDzuvWoJgiIkX/Nc+Sx1W+tFWPHHbyS9nJW
kt3Wo5FBhE0R/aIwt75rrA==
</Y>
<X>AMhxt+OJaF25fZNN1wEfqwdv8n7EKC+wDA1kbSnV5OU=</X>
</DSAKeyValue>",
DSATestData.Dsa2048DeficientXParameters);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void TestWrite512Parameters(bool includePrivateParameters)
{
TestWriteXml(
DSATestData.Dsa512Parameters,
includePrivateParameters,
(
"1qi38cr3ppZNB2Y/xpHSL2q81Vw3rvWNIHRnQNgv4U4UY2NifZGSUULc3uOEvgoe" +
"BO1b9fRxSG9NmG1CoufflQ=="
),
"+rX2JdXV4WQwoe9jDr4ziXzCJPk=",
(
"CETEkOUu9Y4FkCxjbWTR1essYIKg1PO/0c4Hjoe0On73u+zhmk7+Km2cIp02AIPO" +
"qfch85sFuvlwUt78Z6WKKw=="
),
(
"wwDg5n2HfmztOf7qqsHywr1WjmoyRnIn4Stq5FqNlHhUGkgKyAA4qshjgn1uOYQG" +
"GiWQXBi9JJmoOWY8PKRWBQ=="
),
"Lj16hMhbZnheH2/nlpgrIrDLmLw=");
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void TestWrite576Parameters(bool includePrivateParameters)
{
TestWriteXml(
DSATestData.Dsa576Parameters,
includePrivateParameters,
(
"4hZzBr/9hrti9DJ7d4u/oHukIyPsVnsQa5VjiCvd1tfy7nNg8pmIjen0CmHHjQvY" +
"RC76nDIrhorTZ7OUHXK3ozLJVOsWKRMr"
),
"zNzsz18LLI/iOOLwbyITfxf66xs=",
(
"rxfUBhMCB54zA0p3oFjdtLgyrLEUt7jS065EUd/4XrjdddRHQhg2nUhbIgZQZAYE" +
"SrTmQH/apaKeldSWTKVZ6BxvfPzahyZl"
),
(
"gVpUm2/QztrwRLALfP4TUZAtdyfW1/tzYAOk4cTNjfv0MeT/RzPz+pLHZfDP+UTj" +
"7VaoW3WVPrFpASSJhbtfiROY6rXjlkXn"
),
"rDJpPhzXKtY+GgtugVfrvKZx09s=");
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void TestWrite1024Parameters(bool includePrivateParameters)
{
TestWriteXml(
DSATestData.GetDSA1024Params(),
includePrivateParameters,
(
"wW0mx01sFid5nAkYVI5VP+WMeIHaSEYpyvZDEfSyfP72vbDyEgaw/8SZmi/tU7Q7" +
"nuKRDGjaLENqgBj0k49kcjafVkfQBbzJbiJZDMFePNTqDRMvXaWvaqoIB7DMTvNA" +
"SvVC9FRrN73WpH5kETCDfbmTl8hFY119w20FN+SoSzE="
),
"2DwOy3NVHi/jDVH89CNsZRiDrdc=",
(
"a8NmtmNVVF4Jjx/pDlRptWfgn6edgX8rNntF3s1DAaWcgdaRH3aR03DhWsaSwEvB" +
"GHLBcaf+ZU6WPX3aV1qemM4Cb7fTk0olhggTSo7F7WmirtyJQBtnrd5Cfxftrrct" +
"evRdmrHVnhsT1O+9F8dkMwJn3eNSwg4FuA2zwQn+i5w="
),
(
"aQuzepFF4F1ue0fEV4mKrt1yUBydFuebGtdahyzwF6qQu/uQ8bO39cA8h+RuhyVm" +
"VSb9NBV7JvWWofCZf1nz5l78YVpVLV51acX/xFk9WgKZEQ5xyX4SIaWgP+mmk1rt" +
"2I7ws7L3nTqZ7XX3uHHm6vJoDZbVdKX0wTus47S0TeE="
),
"wCZ4AHd55S42BoIhS9R/j69CvC0=");
}
[ConditionalTheory(typeof(DSAFactory), nameof(DSAFactory.SupportsFips186_3))]
[InlineData(true)]
[InlineData(false)]
public static void TestWriteDeficientXParameters(bool includePrivateParameters)
{
TestWriteXml(
DSATestData.Dsa2048DeficientXParameters,
includePrivateParameters,
(
"lNPks58XJz6PJ7MmkvfDTTVhi9J5VItHNpOcK6TnKRFsrqxgAelXBcJ9fPDDCLyn" +
"ArtHEtS7RIoQeLYxFQ6rRVyRZ4phxRwtNx4Cu6xw6cLG2nV7V4IOyP0JbhBew2wH" +
"ik/X3Yck0nXTAH+U8S/5YWcpPGZ7RncH8dyafAs0vE/EdbFdUSQKeJpTpWtk1pwe" +
"ArfKOtNBs7b2yYbx4GW/5oDYfe5tlZHY445Xw3rCmDsnlL6v/ix7W2ykm5gSSHMy" +
"XGHeb4IEEQGL6XI/4r2oMywTCIqjKghtFNbwAgEBP1FnhkPzKswAUl2yLwAg2S+c" +
"L0CIuNNaHnZNzYtwwLPS6w=="
),
"23CgOhWOnMudk9v3Z5bL68pFqHA+gqRYAViO5LaYWrM=",
(
"PPDxRLcKu9RCYNksTgMq3wpZjmgyPiVK/4cQyejqm+GdDSr5OaoN7HbSB7bqzveC" +
"TjZldTVjAcpfmF74/3r1UYuN8IhaasVw/i5cWVYXDnHydAGUAYyKCkp7D5z5av1+" +
"JQJvqAuflya2xN/LxBBeuYaHyml/eXlAwTNbFEMR1H/yHk1cQ8AFhHhrwarkrYWK" +
"wGM1HuRCNHC+URVShpTvzzEtnljU3dHAHig4M/TxSeX5vUVJMEQxthvg2tcXtTjF" +
"zVL94ajmYZPonQnB4Hlo5vcH71YU6D5hEm9qXzk54HZzdFRL4yJcxPjzxQHVolJv" +
"e7ZNZWp7vf5+cssW1x6KOA=="
),
(
"cHLO4Kgw8hUDAviwzw8HFHtsaxMs5k309uE7nofw8txeBXRBGbaVgJU1GndCqeRc" +
"cuI+6L8AmMgv0tB4fyGXRwv7DLwhRirTiT3vfBoN80/VKVf/AcafdsVkwmjrzUPe" +
"w3bfU4qIdK807QB7TkbQZgBoE3kxqlmjLodbKUKdtVY13rbcjL+GfUSUytXt7n5/" +
"IF7o6LLIoFK0Uo9HySsfjP7J7QU8IeOnMb/yaa0JnEE9X8h4U1EWXnmqehQ6DH5V" +
"Ye8DvOPPDe2c7YMWgC+Z3a0DLejBknDzuvWoJgiIkX/Nc+Sx1W+tFWPHHbyS9nJW" +
"kt3Wo5FBhE0R/aIwt75rrA=="
),
// The rules from xmldsig say that these types are ds:CryptoBinary, which
// means they should leave off any leading 0x00 bytes.
//
// .NET Framework just treated it like base64Binary, though, and happily
// writes the unwanted zeroes.
"AMhxt+OJaF25fZNN1wEfqwdv8n7EKC+wDA1kbSnV5OU=");
}
[ConditionalFact(typeof(DSAFactory), nameof(DSAFactory.SupportsKeyGeneration))]
[OuterLoop("DSA key generation is very slow")]
public static void FromToXml()
{
using (DSA dsa = DSAFactory.Create())
{
DSAParameters pubOnly = dsa.ExportParameters(false);
DSAParameters pubPriv = dsa.ExportParameters(true);
string xmlPub = dsa.ToXmlString(false);
string xmlPriv = dsa.ToXmlString(true);
using (DSA dsaPub = DSAFactory.Create())
{
dsaPub.FromXmlString(xmlPub);
DSAImportExport.AssertKeyEquals(pubOnly, dsaPub.ExportParameters(false));
}
using (DSA dsaPriv = DSAFactory.Create())
{
dsaPriv.FromXmlString(xmlPriv);
DSAImportExport.AssertKeyEquals(pubPriv, dsaPriv.ExportParameters(true));
DSAImportExport.AssertKeyEquals(pubOnly, dsaPriv.ExportParameters(false));
}
}
}
[Fact]
public static void FromNullXml()
{
using (DSA dsa = DSAFactory.Create())
{
AssertExtensions.Throws<ArgumentNullException>(
"xmlString",
() => dsa.FromXmlString(null));
}
}
[Fact]
public static void FromInvalidXml()
{
using (DSA dsa = DSAFactory.Create())
{
// This is the DSA-512 test case, with an unfinished closing element.
Assert.Throws<CryptographicException>(
() => dsa.FromXmlString(
@"
<DSAKeyValue xmlns:yep=""urn:ignored:yep"" xmlns:nope=""urn:ignored:nope"" xmlns:ign=""urn:ignored:ign"">
<yep:P>1qi38cr3ppZNB2Y/xpHSL2q81Vw3rvWNIHRnQNgv4U4UY2NifZGSUULc3uOEvgoeBO1b9fRxSG9NmG1CoufflQ==</yep:P>
<nope:Q>+rX2JdXV4WQwoe9jDr4ziXzCJPk=</nope:Q>
<G>CETEkOUu9Y4FkCxjbWTR1essYIKg1PO/0c4Hjoe0On73u+zhmk7+Km2cIp02AIPOqfch85sFuvlwUt78Z6WKKw==</G>
<ign:Y>wwDg5n2HfmztOf7qqsHywr1WjmoyRnIn4Stq5FqNlHhUGkgKyAA4qshjgn1uOYQGGiWQXBi9JJmoOWY8PKRWBQ==</ign:Y>
</DSA"));
}
}
[Fact]
public static void FromNonsenseXml()
{
using (DSA dsa = DSAFactory.Create())
{
// This is the DSA-512 test case, with the G value from the DSA-1024 case.
try
{
dsa.FromXmlString(
@"
<DSAKeyValue xmlns:yep=""urn:ignored:yep"" xmlns:nope=""urn:ignored:nope"" xmlns:ign=""urn:ignored:ign"">
<yep:P>1qi38cr3ppZNB2Y/xpHSL2q81Vw3rvWNIHRnQNgv4U4UY2NifZGSUULc3uOEvgoeBO1b9fRxSG9NmG1CoufflQ==</yep:P>
<nope:Q>+rX2JdXV4WQwoe9jDr4ziXzCJPk=</nope:Q>
<G>
a8NmtmNVVF4Jjx/pDlRptWfgn6edgX8rNntF3s1DAaWcgdaRH3aR03DhWsaSwEvB
GHLBcaf+ZU6WPX3aV1qemM4Cb7fTk0olhggTSo7F7WmirtyJQBtnrd5Cfxftrrct
evRdmrHVnhsT1O + 9F8dkMwJn3eNSwg4FuA2zwQn + i5w =
</G>
<ign:Y>wwDg5n2HfmztOf7qqsHywr1WjmoyRnIn4Stq5FqNlHhUGkgKyAA4qshjgn1uOYQGGiWQXBi9JJmoOWY8PKRWBQ==</ign:Y>
</DSAKeyValue>");
}
catch (ArgumentException)
{
// DSACng, DSAOpenSsl
}
catch (CryptographicException)
{
// DSACryptoServiceProvider
}
}
}
[Fact]
public static void FromXml_MissingP()
{
using (DSA dsa = DSAFactory.Create())
{
// This is the DSA-576 test case, but with an element missing.
Assert.Throws<CryptographicException>(
() => dsa.FromXmlString(
@"
<DSAKeyValue>
<Y>wwDg5n2HfmztOf7qqsHywr1WjmoyRnIn4Stq5FqNlHhUGkgKyAA4qshjgn1uOYQGGiWQXBi9JJmoOWY8PKRWBQ==</Y>
<Q>+rX2JdXV4WQwoe9jDr4ziXzCJPk=</Q>
<BananaWeight unit=""lbs"">30000</BananaWeight>
<X>Lj16hMhbZnheH2/nlpgrIrDLmLw=</X>
<G>CETEkOUu9Y4FkCxjbWTR1essYIKg1PO/0c4Hjoe0On73u+zhmk7+Km2cIp02AIPOqfch85sFuvlwUt78Z6WKKw==</G>
</DSAKeyValue>"));
}
}
[Fact]
public static void FromXml_MissingQ()
{
using (DSA dsa = DSAFactory.Create())
{
// This is the DSA-576 test case, but with an element missing.
Assert.Throws<CryptographicException>(
() => dsa.FromXmlString(
@"
<DSAKeyValue>
<Y>wwDg5n2HfmztOf7qqsHywr1WjmoyRnIn4Stq5FqNlHhUGkgKyAA4qshjgn1uOYQGGiWQXBi9JJmoOWY8PKRWBQ==</Y>
<BananaWeight unit=""lbs"">30000</BananaWeight>
<X>Lj16hMhbZnheH2/nlpgrIrDLmLw=</X>
<G>CETEkOUu9Y4FkCxjbWTR1essYIKg1PO/0c4Hjoe0On73u+zhmk7+Km2cIp02AIPOqfch85sFuvlwUt78Z6WKKw==</G>
<P>1qi38cr3ppZNB2Y/xpHSL2q81Vw3rvWNIHRnQNgv4U4UY2NifZGSUULc3uOEvgoeBO1b9fRxSG9NmG1CoufflQ==</P>
</DSAKeyValue>"));
}
}
[Fact]
public static void FromXml_MissingG()
{
using (DSA dsa = DSAFactory.Create())
{
// This is the DSA-576 test case, but with an element missing.
Assert.Throws<CryptographicException>(
() => dsa.FromXmlString(
@"
<DSAKeyValue>
<Y>wwDg5n2HfmztOf7qqsHywr1WjmoyRnIn4Stq5FqNlHhUGkgKyAA4qshjgn1uOYQGGiWQXBi9JJmoOWY8PKRWBQ==</Y>
<Q>+rX2JdXV4WQwoe9jDr4ziXzCJPk=</Q>
<BananaWeight unit=""lbs"">30000</BananaWeight>
<X>Lj16hMhbZnheH2/nlpgrIrDLmLw=</X>
<P>1qi38cr3ppZNB2Y/xpHSL2q81Vw3rvWNIHRnQNgv4U4UY2NifZGSUULc3uOEvgoeBO1b9fRxSG9NmG1CoufflQ==</P>
</DSAKeyValue>"));
}
}
[Fact]
public static void FromXml_MissingY()
{
using (DSA dsa = DSAFactory.Create())
{
// This is the DSA-576 test case, but with an element missing.
Assert.Throws<CryptographicException>(
() => dsa.FromXmlString(
@"
<DSAKeyValue>
<Q>+rX2JdXV4WQwoe9jDr4ziXzCJPk=</Q>
<BananaWeight unit=""lbs"">30000</BananaWeight>
<X>Lj16hMhbZnheH2/nlpgrIrDLmLw=</X>
<G>CETEkOUu9Y4FkCxjbWTR1essYIKg1PO/0c4Hjoe0On73u+zhmk7+Km2cIp02AIPOqfch85sFuvlwUt78Z6WKKw==</G>
<P>1qi38cr3ppZNB2Y/xpHSL2q81Vw3rvWNIHRnQNgv4U4UY2NifZGSUULc3uOEvgoeBO1b9fRxSG9NmG1CoufflQ==</P>
</DSAKeyValue>"));
}
}
[Fact]
public static void FromXmlWithSeedAndCounterAndJ()
{
// This key comes from FIPS-186-2, Appendix 5, Example of the DSA.
// The version in DSATestData does not have the seed or counter supplied.
using (DSA dsa = DSAFactory.Create())
{
dsa.FromXmlString(@"
<DSAKeyValue>
<P>
jfKklEkidqo9JXWbsGhpy+rA2Dr7jQz3y7gyTw14guXQdi/FtyEOr8Lprawyq3qs
SWk9+/g3JMLsBzbuMcgCkQ==
</P>
<Q>x3MhjHN+yO6ZO08t7TD0jtrOkV8=</Q>
<G>
Ym0CeDnqChNBMWOlW0y1ACmdVSKVbO/LO/8Q85nOLC5xy53l+iS6v1jlt5Uhklyc
xC6fb0ZLCIzFcq9T5teIAg==
</G>
<Y>
GRMYcddbFhKoGfKdeNGw1zRveqd7tiqFm/1sVnXanSEtOjbvFnLvZguMfCVcwOx0
hY+6M/RMBmmWMKdrAw7jMw==
</Y>
<J>AgRO2deYCHK5/u5+ElWfz2J6fdI2PN/mnjBxceE11r5zt7x/DVqcoWAp2+dr</J>
<Seed>1QFOS2DvK6i2IRtAYroyJOBCfdM=</Seed>
<PgenCounter>aQ==</PgenCounter>
<X>IHCzIj26Ny/eHA/8ey47SYsmBhQ=</X>
</DSAKeyValue>");
DSATestData.GetDSA1024_186_2(out DSAParameters expected, out _, out _);
DSAImportExport.AssertKeyEquals(expected, dsa.ExportParameters(true));
}
}
[Fact]
public static void FromXmlWrongJ_OK()
{
// No one really reads the J value on import, but xmldsig defined it,
// so we read it.
// This key comes from FIPS-186-2, Appendix 5, Example of the DSA.
// The version in DSATestData does not have the seed or counter supplied.
using (DSA dsa = DSAFactory.Create())
{
dsa.FromXmlString(@"
<DSAKeyValue>
<P>
jfKklEkidqo9JXWbsGhpy+rA2Dr7jQz3y7gyTw14guXQdi/FtyEOr8Lprawyq3qs
SWk9+/g3JMLsBzbuMcgCkQ==
</P>
<Q>x3MhjHN+yO6ZO08t7TD0jtrOkV8=</Q>
<G>
Ym0CeDnqChNBMWOlW0y1ACmdVSKVbO/LO/8Q85nOLC5xy53l+iS6v1jlt5Uhklyc
xC6fb0ZLCIzFcq9T5teIAg==
</G>
<Y>
GRMYcddbFhKoGfKdeNGw1zRveqd7tiqFm/1sVnXanSEtOjbvFnLvZguMfCVcwOx0
hY+6M/RMBmmWMKdrAw7jMw==
</Y>
<J>AgRO2deYCHK5/u5+ElWfz2J6fdI2PN/mnjBxceE11r5zt7x/DVqcoWAp2+dR</J>
<Seed>1QFOS2DvK6i2IRtAYroyJOBCfdM=</Seed>
<PgenCounter>aQ==</PgenCounter>
<X>IHCzIj26Ny/eHA/8ey47SYsmBhQ=</X>
</DSAKeyValue>");
DSATestData.GetDSA1024_186_2(out DSAParameters expected, out _, out _);
DSAImportExport.AssertKeyEquals(expected, dsa.ExportParameters(true));
}
}
[Fact]
public static void FromXmlInvalidJ_Fails()
{
// No one really reads the J value on import, but xmldsig defined it,
// so we read it and pass it to ImportParameters.
// That means it has to be legal base64.
// This key comes from FIPS-186-2, Appendix 5, Example of the DSA.
// The version in DSATestData does not have the seed or counter supplied.
using (DSA dsa = DSAFactory.Create())
{
Assert.Throws<FormatException>(
() => dsa.FromXmlString(@"
<DSAKeyValue>
<P>
jfKklEkidqo9JXWbsGhpy+rA2Dr7jQz3y7gyTw14guXQdi/FtyEOr8Lprawyq3qs
SWk9+/g3JMLsBzbuMcgCkQ==
</P>
<Q>x3MhjHN+yO6ZO08t7TD0jtrOkV8=</Q>
<G>
Ym0CeDnqChNBMWOlW0y1ACmdVSKVbO/LO/8Q85nOLC5xy53l+iS6v1jlt5Uhklyc
xC6fb0ZLCIzFcq9T5teIAg==
</G>
<Y>
GRMYcddbFhKoGfKdeNGw1zRveqd7tiqFm/1sVnXanSEtOjbvFnLvZguMfCVcwOx0
hY+6M/RMBmmWMKdrAw7jMw==
</Y>
<J>AgRO2deYCHK5/u5+ElWfz2J6fdI2PN/mnjBxceE11r5zt7x/DVqcoWAp2+d</J>
<Seed>1QFOS2DvK6i2IRtAYroyJOBCfdM=</Seed>
<PgenCounter>aQ==</PgenCounter>
<X>IHCzIj26Ny/eHA/8ey47SYsmBhQ=</X>
</DSAKeyValue>"));
}
}
[Fact]
public static void FromXmlWrongCounter_SometimesOK()
{
// DSACryptoServiceProvider doesn't check this error state, DSACng does.
//
// So, either the import gets rejected (because the counter value should be 105,
// but says 106) and throws a CryptographicException derivitive, or it succeeds,
// and exports the correct key material.
// This key comes from FIPS-186-2, Appendix 5, Example of the DSA.
// The version in DSATestData does not have the seed or counter supplied.
using (DSA dsa = DSAFactory.Create())
{
bool checkKey = true;
try
{
dsa.FromXmlString(@"
<DSAKeyValue>
<P>
jfKklEkidqo9JXWbsGhpy+rA2Dr7jQz3y7gyTw14guXQdi/FtyEOr8Lprawyq3qs
SWk9+/g3JMLsBzbuMcgCkQ==
</P>
<Q>x3MhjHN+yO6ZO08t7TD0jtrOkV8=</Q>
<G>
Ym0CeDnqChNBMWOlW0y1ACmdVSKVbO/LO/8Q85nOLC5xy53l+iS6v1jlt5Uhklyc
xC6fb0ZLCIzFcq9T5teIAg==
</G>
<Y>
GRMYcddbFhKoGfKdeNGw1zRveqd7tiqFm/1sVnXanSEtOjbvFnLvZguMfCVcwOx0
hY+6M/RMBmmWMKdrAw7jMw==
</Y>
<J>AgRO2deYCHK5/u5+ElWfz2J6fdI2PN/mnjBxceE11r5zt7x/DVqcoWAp2+dr</J>
<Seed>1QFOS2DvK6i2IRtAYroyJOBCfdM=</Seed>
<PgenCounter>ag==</PgenCounter>
<X>IHCzIj26Ny/eHA/8ey47SYsmBhQ=</X>
</DSAKeyValue>");
}
catch (CryptographicException)
{
checkKey = false;
}
if (checkKey)
{
DSATestData.GetDSA1024_186_2(out DSAParameters expected, out _, out _);
DSAImportExport.AssertKeyEquals(expected, dsa.ExportParameters(true));
}
}
}
[Fact]
public static void FromXml_CounterOverflow_Succeeds()
{
// The counter value should be 105 (0x69).
// This payload says 0x01_00000069 (4294967401).
// Since we only end up looking at the last 4 bytes, this is /a/ right answer.
// This key comes from FIPS-186-2, Appendix 5, Example of the DSA.
// The version in DSATestData does not have the seed or counter supplied.
using (DSA dsa = DSAFactory.Create())
{
dsa.FromXmlString(@"
<DSAKeyValue>
<P>
jfKklEkidqo9JXWbsGhpy+rA2Dr7jQz3y7gyTw14guXQdi/FtyEOr8Lprawyq3qs
SWk9+/g3JMLsBzbuMcgCkQ==
</P>
<Q>x3MhjHN+yO6ZO08t7TD0jtrOkV8=</Q>
<G>
Ym0CeDnqChNBMWOlW0y1ACmdVSKVbO/LO/8Q85nOLC5xy53l+iS6v1jlt5Uhklyc
xC6fb0ZLCIzFcq9T5teIAg==
</G>
<Y>
GRMYcddbFhKoGfKdeNGw1zRveqd7tiqFm/1sVnXanSEtOjbvFnLvZguMfCVcwOx0
hY+6M/RMBmmWMKdrAw7jMw==
</Y>
<J>AgRO2deYCHK5/u5+ElWfz2J6fdI2PN/mnjBxceE11r5zt7x/DVqcoWAp2+dr</J>
<Seed>1QFOS2DvK6i2IRtAYroyJOBCfdM=</Seed>
<PgenCounter>AQAAAGk=</PgenCounter>
<X>IHCzIj26Ny/eHA/8ey47SYsmBhQ=</X>
</DSAKeyValue>");
DSATestData.GetDSA1024_186_2(out DSAParameters expected, out _, out _);
DSAImportExport.AssertKeyEquals(expected, dsa.ExportParameters(true));
}
}
[Fact]
public static void FromXmlSeedWithoutCounter()
{
// This key comes from FIPS-186-2, Appendix 5, Example of the DSA.
// The version in DSATestData does not have the seed or counter supplied.
using (DSA dsa = DSAFactory.Create())
{
Assert.Throws<CryptographicException>(
() => dsa.FromXmlString(@"
<DSAKeyValue>
<P>
jfKklEkidqo9JXWbsGhpy+rA2Dr7jQz3y7gyTw14guXQdi/FtyEOr8Lprawyq3qs
SWk9+/g3JMLsBzbuMcgCkQ==
</P>
<Q>x3MhjHN+yO6ZO08t7TD0jtrOkV8=</Q>
<G>
Ym0CeDnqChNBMWOlW0y1ACmdVSKVbO/LO/8Q85nOLC5xy53l+iS6v1jlt5Uhklyc
xC6fb0ZLCIzFcq9T5teIAg==
</G>
<Y>
GRMYcddbFhKoGfKdeNGw1zRveqd7tiqFm/1sVnXanSEtOjbvFnLvZguMfCVcwOx0
hY+6M/RMBmmWMKdrAw7jMw==
</Y>
<J>AgRO2deYCHK5/u5+ElWfz2J6fdI2PN/mnjBxceE11r5zt7x/DVqcoWAp2+dr</J>
<Seed>1QFOS2DvK6i2IRtAYroyJOBCfdM=</Seed>
<X>IHCzIj26Ny/eHA/8ey47SYsmBhQ=</X>
</DSAKeyValue>"));
}
}
[Fact]
public static void FromXmlCounterWithoutSeed()
{
// This key comes from FIPS-186-2, Appendix 5, Example of the DSA.
// The version in DSATestData does not have the seed or counter supplied.
using (DSA dsa = DSAFactory.Create())
{
Assert.Throws<CryptographicException>(
() => dsa.FromXmlString(@"
<DSAKeyValue>
<P>
jfKklEkidqo9JXWbsGhpy+rA2Dr7jQz3y7gyTw14guXQdi/FtyEOr8Lprawyq3qs
SWk9+/g3JMLsBzbuMcgCkQ==
</P>
<Q>x3MhjHN+yO6ZO08t7TD0jtrOkV8=</Q>
<G>
Ym0CeDnqChNBMWOlW0y1ACmdVSKVbO/LO/8Q85nOLC5xy53l+iS6v1jlt5Uhklyc
xC6fb0ZLCIzFcq9T5teIAg==
</G>
<Y>
GRMYcddbFhKoGfKdeNGw1zRveqd7tiqFm/1sVnXanSEtOjbvFnLvZguMfCVcwOx0
hY+6M/RMBmmWMKdrAw7jMw==
</Y>
<J>AgRO2deYCHK5/u5+ElWfz2J6fdI2PN/mnjBxceE11r5zt7x/DVqcoWAp2+dr</J>
<PgenCounter>aQ==</PgenCounter>
<X>IHCzIj26Ny/eHA/8ey47SYsmBhQ=</X>
</DSAKeyValue>"));
}
}
private static void TestReadXml(string xmlString, in DSAParameters expectedParameters)
{
using (DSA dsa = DSAFactory.Create())
{
dsa.FromXmlString(xmlString);
Assert.Equal(expectedParameters.P.Length * 8, dsa.KeySize);
bool includePrivateParameters = expectedParameters.X != null;
DSAImportExport.AssertKeyEquals(
expectedParameters,
dsa.ExportParameters(includePrivateParameters));
}
}
private static void TestWriteXml(
in DSAParameters keyParameters,
bool includePrivateParameters,
string expectedP,
string expectedQ,
string expectedG,
string expectedY,
string expectedX)
{
IEnumerator<XElement> iter;
using (DSA dsa = DSAFactory.Create(keyParameters))
{
iter = VerifyRootAndGetChildren(dsa, includePrivateParameters);
}
AssertNextElement(iter, "P", expectedP);
AssertNextElement(iter, "Q", expectedQ);
AssertNextElement(iter, "G", expectedG);
AssertNextElement(iter, "Y", expectedY);
// We don't produce J.
// Seed isn't present in the input parameters, so it shouldn't be here.
if (includePrivateParameters)
{
AssertNextElement(iter, "X", expectedX);
}
Assert.False(iter.MoveNext(), "Move after last expected value");
}
private static IEnumerator<XElement> VerifyRootAndGetChildren(
DSA dsa,
bool includePrivateParameters)
{
XDocument doc = XDocument.Parse(dsa.ToXmlString(includePrivateParameters));
XElement root = doc.Root;
Assert.Equal("DSAKeyValue", root.Name.LocalName);
// Technically the namespace name should be the xmldsig namespace, but
// .NET Framework wrote it as the empty namespace, so just assert that's true.
Assert.Equal("", root.Name.NamespaceName);
// Test that we're following the schema by looping over each node individually to see
// that they're in order.
IEnumerator<XElement> iter = root.Elements().GetEnumerator();
return iter;
}
private static void AssertNextElement(
IEnumerator<XElement> iter,
string localName,
string expectedValue)
{
Assert.True(iter.MoveNext(), $"Move to {localName}");
XElement cur = iter.Current;
Assert.Equal(localName, cur.Name.LocalName);
// Technically the namespace name should be the xmldsig namespace, but
// .NET Framework wrote it as the empty namespace, so just assert that's true.
Assert.Equal("", cur.Name.NamespaceName);
// Technically whitespace should be ignored here.
// But let the test be simple until needs prove otherwise.
Assert.Equal(expectedValue, cur.Value);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit01.inherit01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit01.inherit01;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(dynamic i = null)
{
return i ?? 1;
}
}
public class Derived : Parent
{
public override int Foo(dynamic i = default(dynamic))
{
return i ?? 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit01a.inherit01a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit01a.inherit01a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i = 1)
{
return (int)i;
}
}
public class Derived : Parent
{
public override int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit02.inherit02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit02.inherit02;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(dynamic i)
{
return 1;
}
}
public class Derived : Parent
{
public override int Foo(dynamic i = null)
{
return 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit02a.inherit02a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit02a.inherit02a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i)
{
return (int)i;
}
}
public class Derived : Parent
{
public override int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit03a.inherit03a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit03a.inherit03a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i = 0)
{
return (int)1;
}
}
public class Derived : Parent
{
public override int Foo(int? i)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
try
{
p.Foo();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgCount, e.Message, "Foo", "0");
if (ret)
return 0;
}
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit04.inherit04
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit04.inherit04;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual dynamic Foo(dynamic i = null)
{
return 0;
}
}
public class Derived : Parent
{
public new dynamic Foo(dynamic i)
{
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit04a.inherit04a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit04a.inherit04a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i = 0)
{
return (int)i;
}
}
public class Derived : Parent
{
public new int Foo(int? i)
{
return (int)1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit05.inherit05
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit05.inherit05;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual dynamic Foo(dynamic i = null)
{
return 1;
}
}
public class Derived : Parent
{
public new dynamic Foo(dynamic i = null)
{
return 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit05a.inherit05a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit05a.inherit05a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i = 1)
{
return 1;
}
}
public class Derived : Parent
{
public new int Foo(int? i = 0)
{
return 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit06.inherit06
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit06.inherit06;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual dynamic Foo(dynamic i = null)
{
return 1;
}
}
public class Child : Parent
{
public override dynamic Foo(dynamic i = null)
{
return 1;
}
}
public class Derived : Child
{
public override dynamic Foo(dynamic i = null)
{
return i ?? 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit06a.inherit06a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit06a.inherit06a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i = 0)
{
return 1;
}
}
public class Child : Parent
{
public override int Foo(int? i = 2)
{
return 1;
}
}
public class Derived : Child
{
public override int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit07.inherit07
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit07.inherit07;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual dynamic Foo(dynamic i = null)
{
return 1;
}
}
public class Child : Parent
{
public virtual new dynamic Foo(dynamic i = null)
{
return 1;
}
}
public class Derived : Child
{
public override dynamic Foo(dynamic i = null)
{
return i ?? 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit07a.inherit07a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit07a.inherit07a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i = 1)
{
return 1;
}
}
public class Child : Parent
{
public virtual new int Foo(int? i = 20)
{
return 1;
}
}
public class Derived : Child
{
public override int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit08.inherit08
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit08.inherit08;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual dynamic Foo(dynamic i = null)
{
return 1;
}
}
public class Child : Parent
{
public override dynamic Foo(dynamic i = null)
{
return 1;
}
}
public class Derived : Child
{
public new dynamic Foo(dynamic i = null)
{
return i ?? 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit08a.inherit08a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit08a.inherit08a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i = 1)
{
return 1;
}
}
public class Child : Parent
{
public override int Foo(int? i = 1)
{
return 1;
}
}
public class Derived : Child
{
public new int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit09.inherit09
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit09.inherit09;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
dynamic Foo(dynamic i = null);
}
public class Derived : Parent
{
public dynamic Foo(dynamic i = null)
{
return i ?? 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit09a.inherit09a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit09a.inherit09a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 1);
}
public class Derived : Parent
{
public int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit10.inherit10
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit10.inherit10;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(dynamic i);
}
public class Derived : Parent
{
public int Foo(dynamic i = null)
{
return i ?? 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit10a.inherit10a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit10a.inherit10a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i);
}
public class Derived : Parent
{
public int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit11a.inherit11a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit11a.inherit11a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 0);
}
public class Derived : Parent
{
public int Foo(int? i)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
try
{
p.Foo();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgCount, e.Message, "Foo", "0");
if (ret)
return 0;
}
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit12a.inherit12a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit12a.inherit12a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(14,17\).*CS0109</Expects>
public interface Parent
{
int Foo(int? i = 0);
}
public class Derived : Parent
{
public new int Foo(int? i)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
try
{
p.Foo();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgCount, e.Message, "Foo", "0");
if (ret)
return 0;
}
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit13.inherit13
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit13.inherit13;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
dynamic Foo(int i = 1);
}
public class Derived : Parent
{
public dynamic Foo(int i = 0)
{
return i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit13a.inherit13a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit13a.inherit13a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 1);
}
public class Derived : Parent
{
public int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit14.inherit14
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit14.inherit14;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
dynamic Foo(int i = 1);
}
public class Child : Parent
{
public virtual dynamic Foo(int i = 0)
{
return i - 2;
}
}
public class Derived : Child
{
public override dynamic Foo(int i = 0)
{
return i + 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Child c = new Child();
Derived p = new Derived();
return p.Foo() + c.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit14a.inherit14a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit14a.inherit14a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 1);
}
public class Child : Parent
{
public virtual int Foo(int? i = 0)
{
return (int)i - 2;
}
}
public class Derived : Child
{
public override int Foo(int? i = 0)
{
return (int)i + 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic c = new Child();
dynamic p = new Derived();
return p.Foo() + c.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit15.inherit15
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit15.inherit15;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(13,29\).*CS0109</Expects>
public interface Parent
{
dynamic Foo(int i = 1);
}
public class Child : Parent
{
public virtual new dynamic Foo(int i = 1)
{
return 1;
}
}
public class Derived : Child
{
public override dynamic Foo(int i = 0)
{
return i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit15a.inherit15a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit15a.inherit15a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(13,25\).*CS0109</Expects>
public interface Parent
{
int Foo(int? i = 1);
}
public class Child : Parent
{
public virtual new int Foo(int? i = 1)
{
return 1;
}
}
public class Derived : Child
{
public override int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit19.inherit19
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit19.inherit19;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
dynamic Foo(dynamic i = null);
}
public struct Derived : Parent
{
public dynamic Foo(dynamic i = null)
{
return 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit19a.inherit19a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit19a.inherit19a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 1);
}
public struct Derived : Parent
{
public int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit20.inherit20
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit20.inherit20;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
dynamic Foo(dynamic i = null);
}
public struct Derived : Parent
{
public dynamic Foo(dynamic i)
{
return i ?? 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit20a.inherit20a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit20a.inherit20a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 0);
}
public struct Derived : Parent
{
public int Foo(int? i)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p1 = new Derived();
dynamic p = p1;
return ((Parent)p).Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit21.inherit21
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit21.inherit21;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
dynamic Foo(dynamic i = null);
}
public class Child : Parent
{
public virtual dynamic Foo(dynamic i = null)
{
return i ?? 0 - 2;
}
}
public class Derived : Child
{
public override dynamic Foo(dynamic i = null)
{
return i ?? 0 + 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Child c = new Child();
Derived p = new Derived();
return p.Foo() + c.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit21a.inherit21a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit21a.inherit21a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 0);
}
public class Child : Parent
{
public virtual int Foo(int? i = 0)
{
return (int)i - 2;
}
}
public class Derived : Child
{
public override int Foo(int? i = 0)
{
return (int)i + 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic c = new Child();
dynamic p = new Derived();
return p.Foo() + c.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit22.inherit22
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit22.inherit22;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(dynamic i = null);
}
public struct Derived : Parent
{
public int Foo(dynamic i = null)
{
return 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit22a.inherit22a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit22a.inherit22a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 0);
}
public struct Derived : Parent
{
public int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p1 = new Derived();
dynamic p = p1;
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit23.inherit23
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit23.inherit23;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(dynamic i = null);
}
public class Derived : Parent
{
public int Foo(dynamic i = null)
{
return i - 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Derived();
return p.Foo(1);
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit23a.inherit23a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit23a.inherit23a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 1);
}
public class Derived : Parent
{
public int Foo(int? i = 0)
{
return (int)i - 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p1 = new Derived();
dynamic p = p1;
dynamic d = 1;
return p.Foo(d);
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit24a.inherit24a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit24a.inherit24a;
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 0);
}
public struct Derived : Parent
{
public int Foo(int? i)
{
return i.Value;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
try
{
p.Foo();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgCount, e.Message, "Foo", "0");
if (ret)
return 0;
}
return 1;
}
}
//</Code>
}
| |
namespace Incoding.UnitTest.MSpecGroup
{
#region << Using >>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Incoding.MSpecContrib;
using Incoding.MvcContrib;
using Machine.Specifications;
#endregion
[Subject(typeof(InventFactory<>))]
public class When_invent_factory_create : Context_invent_factory
{
It should_be_byte = () => new InventFactory<FakeGenerateObject>().Create().ByteValue.ShouldBeGreaterThan(0);
It should_be_byte_nullable = () => new InventFactory<FakeGenerateObject>().Create().ByteValueNullable.ShouldBeGreaterThan(0);
It should_be_bytes = () => new InventFactory<FakeGenerateObject>().Create().ByteArray.ShouldNotBeEmpty();
It should_be_short = () => new InventFactory<short>().Create().ShouldBeGreaterThan(0);
It should_be_sbyte = () => new InventFactory<sbyte>().Create().ShouldBeGreaterThan(0);
It should_be_callback = () =>
{
var inventFactory = new InventFactory<FakeGenerateObject>();
string callbackValue = Pleasure.Generator.String();
inventFactory.Callback(o => o.ValueSetInCtor = callbackValue);
inventFactory.Create().ValueSetInCtor.ShouldEqual(callbackValue);
};
It should_be_char = () => new InventFactory<FakeGenerateObject>().Create().CharValue.ShouldNotBeNull();
It should_be_char_nullable = () => new InventFactory<FakeGenerateObject>().Create().CharValueNullable.ShouldNotBeNull();
It should_be_create_byte = () => new InventFactory<byte>()
.Create()
.ShouldBeGreaterThan(0);
It should_be_create_enum = () => ((int)new InventFactory<DayOfWeek>()
.Create())
.ShouldBeGreaterThan(0);
It should_be_create_enum_as_nullable = () => ((int?)new InventFactory<DayOfWeek?>()
.Create())
.ShouldBeGreaterThan(0);
It should_be_create_int = () => new InventFactory<int>()
.Create()
.ShouldBeGreaterThan(0);
It should_be_create_int_nullable = () => new InventFactory<int?>()
.Create()
.ShouldBeGreaterThan(0);
It should_be_create_primitive_string = () => new InventFactory<string>()
.Create()
.ShouldNotBeEmpty();
It should_be_date_time = () => new InventFactory<FakeGenerateObject>().Create().DateTimeValue.ShouldNotEqual(DateTime.Now);
It should_be_date_time_nullable = () => new InventFactory<FakeGenerateObject>().Create().DateTimeValueNullable.ShouldNotBeNull();
It should_be_decimal = () => new InventFactory<FakeGenerateObject>().Create().DecimalValue.ShouldBeGreaterThan(0);
It should_be_decimal_nullable = () => new InventFactory<FakeGenerateObject>().Create().DecimalValueNullable.ShouldBeGreaterThan(0);
It should_be_dictionary = () => new InventFactory<FakeGenerateObject>().Create().DictionaryValue.ShouldNotBeEmpty();
It should_be_dictionary_object = () => new InventFactory<FakeGenerateObject>().Create().DictionaryObjectValue.ShouldNotBeEmpty();
It should_be_double = () => new InventFactory<FakeGenerateObject>().Create().DoubleValue.ShouldBeGreaterThan(0);
It should_be_double_nullable = () => new InventFactory<FakeGenerateObject>().Create().DoubleValueNullable.ShouldBeGreaterThan(0);
It should_be_enum = () => ((int)new InventFactory<FakeGenerateObject>().Create().EnumValue).ShouldBeGreaterThan(0);
It should_be_enum_as_nullable = () => ((int)new InventFactory<FakeGenerateObject>().Create().EnumAsNullableValue).ShouldBeGreaterThan(0);
It should_be_float = () => new InventFactory<FakeGenerateObject>().Create().FloatValue.ShouldBeGreaterThan(0);
It should_be_float_nullable = () => new InventFactory<FakeGenerateObject>().Create().FloatValueNullable.ShouldBeGreaterThan(0);
It should_be_generate_bytes = () => new InventFactory<byte[]>()
.Create()
.ShouldNotBeEmpty();
It should_be_generate_guids = () => new InventFactory<Guid[]>()
.Create()
.ShouldNotBeEmpty();
It should_be_generate_to = () =>
{
var inventFactory = new InventFactory<FakeGenerateObject>();
inventFactory.GenerateTo(r => r.Fake);
inventFactory.Create().Fake.ShouldNotBeNull();
};
It should_be_generate_to_array = () => new InventFactory<FakeGenerateObject[]>()
.Create()
.ShouldNotBeEmpty();
It should_be_generate_to_array_as_datetime = () => new InventFactory<DateTime[]>()
.Create()
.ShouldNotBeEmpty();
It should_be_generate_to_list = () => new InventFactory<List<FakeGenerateObject>>()
.Create()
.ShouldNotBeEmpty();
It should_be_generate_to_read_only_list = () => new InventFactory<ReadOnlyCollection<FakeGenerateObject>>()
.Create()
.ShouldNotBeEmpty();
It should_be_generate_to_with_generic_class_as_class = () =>
{
var inventFactory = new InventFactory<FakeGenerateGeneric<FakeGenerateObject>>();
inventFactory.GenerateTo(r => r.Result);
inventFactory.Create().Result.ShouldNotBeNull();
};
It should_be_generate_with_dsl = () =>
{
var inventFactory = new InventFactory<FakeGenerateObject>();
inventFactory.GenerateTo(r => r.Fake, dsl => dsl.Tuning(r => r.FloatValue, 5));
inventFactory.Create().Fake.FloatValue.ShouldEqual(5);
};
It should_be_generate_list_with_dsl = () =>
{
var inventFactory = new InventFactory<FakeGenerateObject>();
inventFactory.GenerateTo(r => r.Fakes, dsl => dsl.Tuning(r => r.FloatValue, 5));
inventFactory.Create().Fakes.Any().ShouldBeTrue();
inventFactory.Create().Fakes.All(r => r.FloatValue == 5).ShouldBeTrue();
};
It should_be_generic_class_as_class = () =>
{
var inventFactory = new InventFactory<FakeGenerateGeneric<FakeGenerateObject>>();
inventFactory.Create().Result.ShouldBeNull();
};
It should_be_generic_class_as_string = () =>
{
var inventFactory = new InventFactory<FakeGenerateGeneric<string>>();
inventFactory.Create().Result.ShouldNotBeNull();
};
It should_be_guid = () => new InventFactory<FakeGenerateObject>().Create().GuidValue.ShouldNotEqual(Guid.Empty);
It should_be_guid_nullable = () => new InventFactory<FakeGenerateObject>().Create().GuidValueNullable.ShouldNotEqual(Guid.Empty);
It should_be_http_post_file = () => new HttpMemoryPostedFile(new InventFactory<FakeGenerateObject>().Create().HttpPostFileValue).ContentAsBytes.ShouldNotBeEmpty();
It should_be_ignore_by_attribute = () =>
{
var inventFactory = new InventFactory<FakeGenerateObject>();
inventFactory.Create().IgnoreValueByAttr.ShouldBeNull();
};
It should_be_int = () => new InventFactory<FakeGenerateObject>().Create().IntValue.ShouldBeGreaterThan(0);
It should_be_int_array = () => new InventFactory<FakeGenerateObject>().Create().IntArray.ShouldNotBeEmpty();
It should_be_int_nullable = () => new InventFactory<FakeGenerateObject>().Create().IntValueNullable.ShouldBeGreaterThan(0);
It should_be_long = () => new InventFactory<FakeGenerateObject>().Create().LongValue.ShouldBeGreaterThan(0);
It should_be_long_nullable = () => new InventFactory<FakeGenerateObject>().Create().LongValueNullable.ShouldBeGreaterThan(0);
It should_be_object_as_string = () => new InventFactory<FakeGenerateObject>().Create().ObjValue.ShouldBeAssignableTo<string>();
It should_be_stream = () => new InventFactory<FakeGenerateObject>().Create().StreamValue.ShouldNotBeNull();
It should_be_string = () => new InventFactory<FakeGenerateObject>().Create().StrValue.ShouldNotBeEmpty();
It should_be_string_array = () => new InventFactory<FakeGenerateObject>().Create().StrArray.ShouldNotBeEmpty();
It should_be_time_span = () => new InventFactory<FakeGenerateObject>().Create().TimeSpanValue.ShouldBeGreaterThan(new TimeSpan(0, 0, 0));
It should_be_tuning = () =>
{
var inventFactory = new InventFactory<FakeGenerateObject>();
string tuningValue = Pleasure.Generator.String();
inventFactory.Tuning(r => r.StrValue, tuningValue);
inventFactory.Create().StrValue.ShouldEqual(tuningValue);
};
It should_be_tuning_cover_ignore_by_attribute = () =>
{
var inventFactory = new InventFactory<FakeGenerateObject>();
inventFactory.Tuning(r => r.IgnoreValueByAttr, Pleasure.Generator.TheSameString());
inventFactory.Create().IgnoreValueByAttr.ShouldBeTheSameString();
};
It should_be_tuning_default = () =>
{
var inventFactory = new InventFactory<FakeGenerateObject>();
inventFactory.Tuning(r => r.StrValue, default(string));
inventFactory.Create().StrValue.ShouldBeNull();
};
It should_be_tuning_for_only_get_with_exception = () =>
{
var inventFactory = new InventFactory<FakeGenerateObject>();
Catch.Exception(() => inventFactory.Tuning(r => r.OnlyGet, "")).ShouldNotBeNull();
};
It should_be_tuning_null = () =>
{
var inventFactory = new InventFactory<FakeGenerateObject>();
inventFactory.Tuning(r => r.StrValue, null);
inventFactory.Create().StrValue.ShouldBeNull();
};
It should_be_tuning_private = () =>
{
var inventFactory = new InventFactory<FakeGenerateObject>();
inventFactory.Tuning("privateValue", Pleasure.Generator.TheSameString());
inventFactory.Create().GetPrivateValue().ShouldBeTheSameString();
};
It should_be_tunings = () =>
{
var inventFactory = new InventFactory<FakeGenerateObject>();
int tuningValue = Pleasure.Generator.PositiveNumber();
inventFactory.Tunings(new
{
StrValue = tuningValue.ToString(),
IntValue = tuningValue
});
var fakeGenerateObject = inventFactory.Create();
fakeGenerateObject.StrValue.ShouldEqual(tuningValue.ToString());
fakeGenerateObject.IntValue.ShouldEqual(tuningValue);
};
It should_be_value_on_ctor = () => new InventFactory<FakeGenerateObject>()
.Create()
.ValueSetInCtor.ShouldBeTheSameString();
It should_be_value_on_ctor_with_empty = () =>
{
var inventFactory = new InventFactory<FakeGenerateObject>();
inventFactory.Empty(r => r.ValueSetInCtor);
inventFactory.Create()
.ValueSetInCtor.ShouldBeEmpty();
};
It should_be_value_on_ctor_with_tuning = () =>
{
var inventFactory = new InventFactory<FakeGenerateObject>();
string value = Pleasure.Generator.String();
inventFactory.Tuning(r => r.ValueSetInCtor, value);
inventFactory.Create()
.ValueSetInCtor.ShouldEqual(value);
};
It should_be_value_on_mute_ctor = () =>
{
var inventFactory = new InventFactory<FakeGenerateObject>();
inventFactory.MuteCtor();
inventFactory.Create()
.ValueSetInCtor.ShouldNotEqual(Pleasure.Generator.TheSameString());
};
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Structure;
using Point = System.Drawing.Point;
namespace Revit.SDK.Samples.NewPathReinforcement.CS
{
/// <summary>
/// window form contains one picture box to show the
/// profile of wall (or slab), and four command buttons and a check box.
/// User can draw PathReinforcement on picture box.
/// </summary>
public partial class NewPathReinforcementForm : System.Windows.Forms.Form
{
#region class members
private Profile m_profile; //save the profile date (ProfileFloor or ProfileWall)
private Matrix4 m_to2DMatrix; //save the matrix use to transform 3D to 2D
private Matrix4 m_moveToCenterMatrix; //save the matrix use to move point to origin
private Matrix4 m_scaleMatrix; //save the matrix use to scale
private Matrix4 m_transMatrix; //save the final matrix
private LineTool m_tool = null; //current using tool
private bool m_previewMode = false; //indicate whether in the Preview Mode
private List<List<XYZ>> m_pointsPreview; //store all the points of the preview
Size m_sizePictureBox; //size of picture box
#endregion
/// <summary>
/// constructor
/// </summary>
public NewPathReinforcementForm()
{
InitializeComponent();
}
/// <summary>
/// constructor
/// </summary>
/// <param name="profile">ProfileWall or ProfileFloor</param>
public NewPathReinforcementForm(Profile profile)
:this()
{
m_profile = profile;
m_to2DMatrix = m_profile.To2DMatrix;
m_moveToCenterMatrix = m_profile.ToCenterMatrix();
m_tool = new LineTool();
this.KeyPreview = true; //respond Form events first
m_pointsPreview = new List<List<XYZ>>();
m_sizePictureBox = this.pictureBox.Size;
}
/// <summary>
/// store mouse location when mouse down
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void PictureBox_MouseDown(object sender, MouseEventArgs e)
{
if (!m_previewMode)
{
Graphics graphics = this.pictureBox.CreateGraphics();
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
m_tool.OnMouseDown(e);
this.pictureBox.Refresh();
if (m_tool.PointsNumber >= 2)
{
this.previewButton.Enabled = true;
}
}
}
/// <summary>
/// draw the line to where mouse moved
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void PictureBox_MouseMove(object sender, MouseEventArgs e)
{
this.pictureBox.Refresh();
Graphics graphics = this.pictureBox.CreateGraphics();
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
m_tool.OnMouseMove(graphics, e);
}
/// <summary>
/// draw the curve of slab (or wall) and path of PathReinforcement
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void PictureBox_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
if (m_previewMode)
{
//Draw the geometry of Path Reinforcement
DrawPreview(e.Graphics);
//move the gdi origin to the picture center
e.Graphics.Transform = new
System.Drawing.Drawing2D.Matrix(1, 0, 0, 1, 0, 0);
m_tool.Draw(e.Graphics);
}
else
{
//Draw the pictures in the m_tools list
m_tool.Draw(e.Graphics);
}
//move the gdi origin to the picture center
e.Graphics.Transform = new System.Drawing.Drawing2D.Matrix(
1, 0, 0, 1, m_sizePictureBox.Width / 2, m_sizePictureBox.Height / 2);
//get matrix
Size scaleSize = new Size((int)(0.85 * m_sizePictureBox.Width),
(int)(0.85 * m_sizePictureBox.Height));
m_scaleMatrix = ComputeScaleMatrix(scaleSize);
m_transMatrix = Compute3DTo2DMatrix();
//draw profile
m_profile.Draw2D(e.Graphics, Pens.Blue, m_transMatrix);
}
/// <summary>
/// draw all the curves of PathReinforcement when click "Preview" Button
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void ButtonPreview_Click(object sender, EventArgs e)
{
m_previewMode = true;
m_tool.Finished = true;
//get points to create PathReinforcement
List<Point> points = m_tool.GetPoints();
if (points.Count <= 1)
{
MessageBox.Show("Please draw Path of Reinforcement before create!");
return;
}
List<Vector4> ps3D = Transform2DTo3D(points.ToArray());
//begin Transaction, so action here can be aborted.
Transaction transaction = new Transaction(m_profile.CommandData.Application.ActiveUIDocument.Document, "CreatePathReinforcement");
transaction.Start();
PathReinforcement pathRein = m_profile.CreatePathReinforcement(ps3D, this.flipCheckBox.Checked);
m_pointsPreview = GetGeometry(pathRein);
//Abort Transaction here, cancel what RevitAPI do after begin Transaction
transaction.RollBack();
this.pictureBox.Refresh();
}
/// <summary>
/// redraw curve of PathReinforcement when "flip" changed
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void FlipCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (m_previewMode)
{
ButtonPreview_Click(null, null);
}
}
/// <summary>
/// clean all the points of the PathReinforcement when click "Clean" Button
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void ButtonClean_Click(object sender, EventArgs e)
{
m_tool.Clear();
m_tool.Finished = false;
m_previewMode = false;
this.previewButton.Enabled = false;
this.pictureBox.Refresh();
}
/// <summary>
/// stop drawing path when click "Escape" button
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void NewPathReinforcementForm_KeyPress(object sender, KeyPressEventArgs e)
{
//finish the sketch when press "Escape"
if (27 == (int)e.KeyChar && m_tool.PointsNumber >= 2 && !m_tool.Finished)
{
m_tool.Finished = true;
this.pictureBox.Refresh();
}
//Close form if sketch has finished when press "Escape"
else if (27 == (int)e.KeyChar && (m_tool.Finished || 0 == m_tool.PointsNumber))
{
this.Close();
}
}
/// <summary>
/// create PathReinforcement in Revit
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void CreateButton_Click(object sender, EventArgs e)
{
List<Point> points = m_tool.GetPoints();
if (0 == points.Count || 1 == points.Count)
{
MessageBox.Show("Please draw Path of Reinforcement before create!");
return;
}
//begin Transaction, so action here can be aborted.
Transaction transaction = new Transaction(m_profile.CommandData.Application.ActiveUIDocument.Document, "CreatePathReinforcement");
transaction.Start();
List<Vector4> ps3D = Transform2DTo3D(points.ToArray());
m_profile.CreatePathReinforcement(ps3D, this.flipCheckBox.Checked);
transaction.Commit();
this.Close();
}
/// <summary>
/// close the form
/// </summary>
/// <param name="sender">object who sent this event</param>
/// <param name="e">event args</param>
private void CancelButton_Click(object sender, EventArgs e)
{
this.Close();
}
/// <summary>
/// transform the point on Form to 3d world coordinate of revit
/// </summary>
/// <param name="ps">contain the points to be transformed</param>
private List<Vector4> Transform2DTo3D(Point[] ps)
{
List<Vector4> result = new List<Vector4>();
TransformPoints(ps);
Matrix4 transformMatrix = Matrix4.Multiply(
m_scaleMatrix.Inverse(), m_moveToCenterMatrix);
transformMatrix = Matrix4.Multiply(transformMatrix, m_to2DMatrix);
foreach (Point point in ps)
{
Vector4 v = new Vector4(point.X, point.Y, 0);
v = transformMatrix.Transform(v);
result.Add(v);
}
return result;
}
/// <summary>
/// calculate the matrix use to scale
/// </summary>
/// <param name="size">pictureBox size</param>
private Matrix4 ComputeScaleMatrix(Size size)
{
PointF[] boundPoints = m_profile.GetFaceBounds();
float width = ((float)size.Width) / (boundPoints[1].X - boundPoints[0].X);
float hight = ((float)size.Height) / (boundPoints[1].Y - boundPoints[0].Y);
float factor = width <= hight ? width : hight;
return new Matrix4(factor);
}
/// <summary>
/// calculate the matrix used to transform 3D to 2D
/// </summary>
private Matrix4 Compute3DTo2DMatrix()
{
Matrix4 result = Matrix4.Multiply(
m_to2DMatrix.Inverse(), m_moveToCenterMatrix.Inverse());
result = Matrix4.Multiply(result, m_scaleMatrix);
return result;
}
/// <summary>
/// use matrix to transform point
/// </summary>
/// <param name="pts">contain the points to be transform</param>
private void TransformPoints(Point[] pts)
{
System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix(
1, 0, 0, 1, this.pictureBox.Width / 2, this.pictureBox.Height / 2);
matrix.Invert();
matrix.TransformPoints(pts);
}
/// <summary>
/// Get geometry of the pathReinforcement
/// </summary>
/// <param name="pathRein">pathReinforcement created</param>
private List<List<XYZ>> GetGeometry(PathReinforcement pathRein)
{
Options options = m_profile.CommandData.Application.Application.Create.NewGeometryOptions();
options.DetailLevel = DetailLevels.Medium;
options.ComputeReferences = true;
Autodesk.Revit.DB.GeometryElement geoElem = pathRein.get_Geometry(options);
List<Curve> curvesList = new List<Curve>();
GeometryObjectArray gObjects = geoElem.Objects;
foreach (GeometryObject geo in gObjects)
{
Curve curve = geo as Curve;
curvesList.Add(curve);
}
List<List<XYZ>> pointsPreview = new List<List<XYZ>>();
foreach (Curve curve in curvesList)
{
pointsPreview.Add(curve.Tessellate() as List<XYZ>);
}
return pointsPreview;
}
/// <summary>
/// draw points in the List on the form
/// </summary>
/// <param name="graphics">form graphic</param>
/// <param name="pen">pen used to draw line in pictureBox</param>
/// <param name="matrix4">Matrix used to transform 3d to 2d
/// and make picture in right scale </param>
/// <param name="points">points need to be drawn</param>
private void DrawPoints(Graphics graphics, Pen pen, Matrix4 matrix4, List<List<XYZ>> points)
{
foreach (List<XYZ> xyzArray in points)
{
for (int i = 0; i < xyzArray.Count - 1; i++)
{
Autodesk.Revit.DB.XYZ point1 = xyzArray[i];
Autodesk.Revit.DB.XYZ point2 = xyzArray[i + 1];
Vector4 v1 = new Vector4(point1);
Vector4 v2 = new Vector4(point2);
v1 = matrix4.Transform(v1);
v2 = matrix4.Transform(v2);
graphics.DrawLine(pen, new Point((int)v1.X, (int)v1.Y),
new Point((int)v2.X, (int)v2.Y));
}
}
}
/// <summary>
/// draw preview of Path Reinforcement on the form
/// </summary>
private void DrawPreview(Graphics graphics)
{
if (null == m_pointsPreview)
{
return;
}
//move the gdi origin to the picture center
graphics.Transform = new System.Drawing.Drawing2D.Matrix(
1, 0, 0, 1, m_sizePictureBox.Width / 2, m_sizePictureBox.Height / 2);
DrawPoints(graphics, Pens.Red, m_transMatrix, m_pointsPreview);
}
}
}
| |
// 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.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME;
using Microsoft.Win32.SafeHandles;
using static Interop.Crypt32;
using System.Security.Cryptography.Asn1;
namespace Internal.Cryptography.Pal.Windows
{
internal sealed partial class PkcsPalWindows : PkcsPal
{
public sealed unsafe override byte[] Encrypt(CmsRecipientCollection recipients, ContentInfo contentInfo, AlgorithmIdentifier contentEncryptionAlgorithm, X509Certificate2Collection originatorCerts, CryptographicAttributeObjectCollection unprotectedAttributes)
{
using (SafeCryptMsgHandle hCryptMsg = EncodeHelpers.CreateCryptMsgHandleToEncode(recipients, contentInfo.ContentType, contentEncryptionAlgorithm, originatorCerts, unprotectedAttributes))
{
byte[] encodedContent;
if (contentInfo.ContentType.Value.Equals(Oids.Pkcs7Data, StringComparison.OrdinalIgnoreCase))
{
unsafe
{
byte[] content = contentInfo.Content;
fixed (byte* pContent = content)
{
DATA_BLOB blob = new DATA_BLOB((IntPtr)pContent, (uint)(content.Length));
encodedContent = Interop.Crypt32.CryptEncodeObjectToByteArray(CryptDecodeObjectStructType.X509_OCTET_STRING, &blob);
}
}
}
else
{
encodedContent = contentInfo.Content;
if (encodedContent.Length > 0)
{
// Windows will throw if it encounters indefinite length encoding.
// Let's reencode if that is the case
ReencodeIfUsingIndefiniteLengthEncodingOnOuterStructure(ref encodedContent);
}
}
if (encodedContent.Length > 0)
{
// Pin to avoid copy during heap compaction
fixed (byte* pinnedContent = encodedContent)
{
try
{
if (!Interop.Crypt32.CryptMsgUpdate(hCryptMsg, encodedContent, encodedContent.Length, fFinal: true))
throw Marshal.GetLastWin32Error().ToCryptographicException();
}
finally
{
if (!object.ReferenceEquals(encodedContent, contentInfo.Content))
{
Array.Clear(encodedContent, 0, encodedContent.Length);
}
}
}
}
byte[] encodedMessage = hCryptMsg.GetMsgParamAsByteArray(CryptMsgParamType.CMSG_CONTENT_PARAM);
return encodedMessage;
}
}
private static void ReencodeIfUsingIndefiniteLengthEncodingOnOuterStructure(ref byte[] encodedContent)
{
AsnReader reader = new AsnReader(encodedContent, AsnEncodingRules.BER);
Asn1Tag tag = reader.ReadTagAndLength(out int? contentsLength, out int _);
if (contentsLength != null)
{
// definite length, do nothing
return;
}
using (AsnWriter writer = new AsnWriter(AsnEncodingRules.BER))
{
// Tag doesn't matter here as we won't write it into the document
writer.WriteOctetString(reader.PeekContentBytes().Span);
encodedContent = writer.Encode();
}
}
//
// The methods in this class have some pretty terrifying contracts with each other regarding the lifetimes of the pointers they hand around so we'll encapsulate them in a nested class so that
// only the top level method is accessible to everyone else.
//
private static class EncodeHelpers
{
public static SafeCryptMsgHandle CreateCryptMsgHandleToEncode(CmsRecipientCollection recipients, Oid innerContentType, AlgorithmIdentifier contentEncryptionAlgorithm, X509Certificate2Collection originatorCerts, CryptographicAttributeObjectCollection unprotectedAttributes)
{
using (HeapBlockRetainer hb = new HeapBlockRetainer())
{
// Deep copy the CmsRecipients (and especially their underlying X509Certificate2 objects). This will prevent malicious callers from altering them or disposing them while we're performing
// unsafe memory crawling inside them.
recipients = recipients.DeepCopy();
// We must keep all the certificates inside recipients alive until the call to CryptMsgOpenToEncode() finishes. The CMSG_ENVELOPED_ENCODE_INFO* structure we passed to it
// contains direct pointers to memory owned by the CERT_INFO memory block whose lifetime is that of the certificate.
hb.KeepAlive(recipients);
unsafe
{
CMSG_ENVELOPED_ENCODE_INFO* pEnvelopedEncodeInfo = CreateCmsEnvelopedEncodeInfo(recipients, contentEncryptionAlgorithm, originatorCerts, unprotectedAttributes, hb);
SafeCryptMsgHandle hCryptMsg = Interop.Crypt32.CryptMsgOpenToEncode(MsgEncodingType.All, 0, CryptMsgType.CMSG_ENVELOPED, pEnvelopedEncodeInfo, innerContentType.Value, IntPtr.Zero);
if (hCryptMsg == null || hCryptMsg.IsInvalid)
throw Marshal.GetLastWin32Error().ToCryptographicException();
return hCryptMsg;
}
}
}
//
// This returns an allocated native memory block. Its lifetime (and that of any allocated subblocks it may point to) is that of "hb".
//
private static unsafe CMSG_ENVELOPED_ENCODE_INFO* CreateCmsEnvelopedEncodeInfo(CmsRecipientCollection recipients, AlgorithmIdentifier contentEncryptionAlgorithm, X509Certificate2Collection originatorCerts, CryptographicAttributeObjectCollection unprotectedAttributes, HeapBlockRetainer hb)
{
CMSG_ENVELOPED_ENCODE_INFO* pEnvelopedEncodeInfo = (CMSG_ENVELOPED_ENCODE_INFO*)(hb.Alloc(sizeof(CMSG_ENVELOPED_ENCODE_INFO)));
pEnvelopedEncodeInfo->cbSize = sizeof(CMSG_ENVELOPED_ENCODE_INFO);
pEnvelopedEncodeInfo->hCryptProv = IntPtr.Zero;
string algorithmOidValue = contentEncryptionAlgorithm.Oid.Value;
pEnvelopedEncodeInfo->ContentEncryptionAlgorithm.pszObjId = hb.AllocAsciiString(algorithmOidValue);
// Desktop compat: Though it seems like we could copy over the contents of contentEncryptionAlgorithm.Parameters, that property is for retrieving information from decoded Cms's only, and it
// massages the raw data so it wouldn't be usable here anyway. To hammer home that fact, the EncryptedCms constructor rather rudely forces contentEncryptionAlgorithm.Parameters to be the empty array.
pEnvelopedEncodeInfo->ContentEncryptionAlgorithm.Parameters.cbData = 0;
pEnvelopedEncodeInfo->ContentEncryptionAlgorithm.Parameters.pbData = IntPtr.Zero;
pEnvelopedEncodeInfo->pvEncryptionAuxInfo = GenerateEncryptionAuxInfoIfNeeded(contentEncryptionAlgorithm, hb);
int numRecipients = recipients.Count;
pEnvelopedEncodeInfo->cRecipients = numRecipients;
pEnvelopedEncodeInfo->rgpRecipients = IntPtr.Zero;
CMSG_RECIPIENT_ENCODE_INFO* rgCmsRecipients = (CMSG_RECIPIENT_ENCODE_INFO*)(hb.Alloc(numRecipients, sizeof(CMSG_RECIPIENT_ENCODE_INFO)));
for (int index = 0; index < numRecipients; index++)
{
rgCmsRecipients[index] = EncodeRecipientInfo(recipients[index], contentEncryptionAlgorithm, hb);
}
pEnvelopedEncodeInfo->rgCmsRecipients = rgCmsRecipients;
int numCertificates = originatorCerts.Count;
pEnvelopedEncodeInfo->cCertEncoded = numCertificates;
pEnvelopedEncodeInfo->rgCertEncoded = null;
if (numCertificates != 0)
{
DATA_BLOB* pCertEncoded = (DATA_BLOB*)(hb.Alloc(numCertificates, sizeof(DATA_BLOB)));
for (int i = 0; i < numCertificates; i++)
{
byte[] certEncoded = originatorCerts[i].Export(X509ContentType.Cert);
pCertEncoded[i].cbData = (uint)(certEncoded.Length);
pCertEncoded[i].pbData = hb.AllocBytes(certEncoded);
}
pEnvelopedEncodeInfo->rgCertEncoded = pCertEncoded;
}
pEnvelopedEncodeInfo->cCrlEncoded = 0;
pEnvelopedEncodeInfo->rgCrlEncoded = null;
pEnvelopedEncodeInfo->cAttrCertEncoded = 0;
pEnvelopedEncodeInfo->rgAttrCertEncoded = null;
int numUnprotectedAttributes = unprotectedAttributes.Count;
pEnvelopedEncodeInfo->cUnprotectedAttr = numUnprotectedAttributes;
pEnvelopedEncodeInfo->rgUnprotectedAttr = null;
if (numUnprotectedAttributes != 0)
{
CRYPT_ATTRIBUTE* pCryptAttribute = (CRYPT_ATTRIBUTE*)(hb.Alloc(numUnprotectedAttributes, sizeof(CRYPT_ATTRIBUTE)));
for (int i = 0; i < numUnprotectedAttributes; i++)
{
CryptographicAttributeObject attribute = unprotectedAttributes[i];
pCryptAttribute[i].pszObjId = hb.AllocAsciiString(attribute.Oid.Value);
AsnEncodedDataCollection values = attribute.Values;
int numValues = values.Count;
pCryptAttribute[i].cValue = numValues;
DATA_BLOB* pValues = (DATA_BLOB*)(hb.Alloc(numValues, sizeof(DATA_BLOB)));
for (int j = 0; j < numValues; j++)
{
byte[] rawData = values[j].RawData;
pValues[j].cbData = (uint)(rawData.Length);
pValues[j].pbData = hb.AllocBytes(rawData);
}
pCryptAttribute[i].rgValue = pValues;
}
pEnvelopedEncodeInfo->rgUnprotectedAttr = pCryptAttribute;
}
return pEnvelopedEncodeInfo;
}
//
// This returns an allocated native memory block. Its lifetime (and that of any allocated subblocks it may point to) is that of "hb".
//
private static CMSG_RECIPIENT_ENCODE_INFO EncodeRecipientInfo(CmsRecipient recipient, AlgorithmIdentifier contentEncryptionAlgorithm, HeapBlockRetainer hb)
{
CMSG_RECIPIENT_ENCODE_INFO recipientEncodeInfo;
unsafe
{
switch (recipient.Certificate.GetKeyAlgorithm())
{
case Oids.Rsa:
case Oids.RsaOaep:
recipientEncodeInfo.dwRecipientChoice = CMsgCmsRecipientChoice.CMSG_KEY_TRANS_RECIPIENT;
recipientEncodeInfo.pCmsRecipientEncodeInfo = (IntPtr)EncodeKeyTransRecipientInfo(recipient, hb);
break;
case Oids.Esdh:
case Oids.DiffieHellman:
case Oids.DiffieHellmanPkcs3:
recipientEncodeInfo.dwRecipientChoice = CMsgCmsRecipientChoice.CMSG_KEY_AGREE_RECIPIENT;
recipientEncodeInfo.pCmsRecipientEncodeInfo = (IntPtr)EncodeKeyAgreeRecipientInfo(recipient, contentEncryptionAlgorithm, hb);
break;
default:
throw ErrorCode.CRYPT_E_UNKNOWN_ALGO.ToCryptographicException();
}
}
return recipientEncodeInfo;
}
//
// This returns an allocated native memory block. Its lifetime (and that of any allocated subblocks it may point to) is that of "hb".
//
private static unsafe CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO* EncodeKeyTransRecipientInfo(CmsRecipient recipient, HeapBlockRetainer hb)
{
// "recipient" is a deep-cloned CmsRecipient object whose lifetime this class controls. Because of this, we can pull out the CERT_CONTEXT* and CERT_INFO* pointers
// and embed pointers to them in the memory block we return. Yes, this code is scary.
//
// (The use of SafeCertContextHandle here is about using a consistent pattern to get the CERT_CONTEXT (rather than the ugly (CERT_CONTEXT*)(recipient.Certificate.Handle) pattern.)
// It's not about keeping the context alive.)
using (SafeCertContextHandle hCertContext = recipient.Certificate.CreateCertContextHandle())
{
CERT_CONTEXT* pCertContext = hCertContext.DangerousGetCertContext();
CERT_INFO* pCertInfo = pCertContext->pCertInfo;
CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO* pEncodeInfo = (CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO*)(hb.Alloc(sizeof(CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO)));
pEncodeInfo->cbSize = sizeof(CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO);
RSAEncryptionPadding padding = recipient.RSAEncryptionPadding;
if (padding is null)
{
if (recipient.Certificate.GetKeyAlgorithm() == Oids.RsaOaep)
{
byte[] parameters = recipient.Certificate.GetKeyAlgorithmParameters();
if (parameters == null || parameters.Length == 0)
{
padding = RSAEncryptionPadding.OaepSHA1;
}
else if (!PkcsHelpers.TryGetRsaOaepEncryptionPadding(parameters, out padding, out _))
{
throw ErrorCode.CRYPT_E_UNKNOWN_ALGO.ToCryptographicException();
}
}
else
{
padding = RSAEncryptionPadding.Pkcs1;
}
}
if (padding == RSAEncryptionPadding.Pkcs1)
{
pEncodeInfo->KeyEncryptionAlgorithm.pszObjId = hb.AllocAsciiString(Oids.Rsa);
pEncodeInfo->KeyEncryptionAlgorithm.Parameters.cbData = (uint)s_rsaPkcsParameters.Length;
pEncodeInfo->KeyEncryptionAlgorithm.Parameters.pbData = hb.AllocBytes(s_rsaPkcsParameters);
}
else if (padding == RSAEncryptionPadding.OaepSHA1)
{
pEncodeInfo->KeyEncryptionAlgorithm.pszObjId = hb.AllocAsciiString(Oids.RsaOaep);
pEncodeInfo->KeyEncryptionAlgorithm.Parameters.cbData = (uint)s_rsaOaepSha1Parameters.Length;
pEncodeInfo->KeyEncryptionAlgorithm.Parameters.pbData = hb.AllocBytes(s_rsaOaepSha1Parameters);
}
else if (padding == RSAEncryptionPadding.OaepSHA256)
{
pEncodeInfo->KeyEncryptionAlgorithm.pszObjId = hb.AllocAsciiString(Oids.RsaOaep);
pEncodeInfo->KeyEncryptionAlgorithm.Parameters.cbData = (uint)s_rsaOaepSha256Parameters.Length;
pEncodeInfo->KeyEncryptionAlgorithm.Parameters.pbData = hb.AllocBytes(s_rsaOaepSha256Parameters);
}
else if (padding == RSAEncryptionPadding.OaepSHA384)
{
pEncodeInfo->KeyEncryptionAlgorithm.pszObjId = hb.AllocAsciiString(Oids.RsaOaep);
pEncodeInfo->KeyEncryptionAlgorithm.Parameters.cbData = (uint)s_rsaOaepSha384Parameters.Length;
pEncodeInfo->KeyEncryptionAlgorithm.Parameters.pbData = hb.AllocBytes(s_rsaOaepSha384Parameters);
}
else if (padding == RSAEncryptionPadding.OaepSHA512)
{
pEncodeInfo->KeyEncryptionAlgorithm.pszObjId = hb.AllocAsciiString(Oids.RsaOaep);
pEncodeInfo->KeyEncryptionAlgorithm.Parameters.cbData = (uint)s_rsaOaepSha512Parameters.Length;
pEncodeInfo->KeyEncryptionAlgorithm.Parameters.pbData = hb.AllocBytes(s_rsaOaepSha512Parameters);
}
else
{
throw ErrorCode.CRYPT_E_UNKNOWN_ALGO.ToCryptographicException();
}
pEncodeInfo->pvKeyEncryptionAuxInfo = IntPtr.Zero;
pEncodeInfo->hCryptProv = IntPtr.Zero;
pEncodeInfo->RecipientPublicKey = pCertInfo->SubjectPublicKeyInfo.PublicKey;
pEncodeInfo->RecipientId = EncodeRecipientId(recipient, hCertContext, pCertContext, pCertInfo, hb);
return pEncodeInfo;
}
}
//
// This returns an allocated native memory block. Its lifetime (and that of any allocated subblocks it may point to) is that of "hb".
//
private static unsafe CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO* EncodeKeyAgreeRecipientInfo(CmsRecipient recipient, AlgorithmIdentifier contentEncryptionAlgorithm, HeapBlockRetainer hb)
{
// "recipient" is a deep-cloned CmsRecipient object whose lifetime this class controls. Because of this, we can pull out the CERT_CONTEXT* and CERT_INFO* pointers without
// bringing in all the SafeCertContextHandle machinery, and embed pointers to them in the memory block we return. Yes, this code is scary.
using (SafeCertContextHandle hCertContext = recipient.Certificate.CreateCertContextHandle())
{
CERT_CONTEXT* pCertContext = hCertContext.DangerousGetCertContext();
CERT_INFO* pCertInfo = pCertContext->pCertInfo;
CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO* pEncodeInfo = (CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO*)(hb.Alloc(sizeof(CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO)));
pEncodeInfo->cbSize = sizeof(CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO);
pEncodeInfo->KeyEncryptionAlgorithm.pszObjId = hb.AllocAsciiString(Oids.Esdh);
pEncodeInfo->KeyEncryptionAlgorithm.Parameters.cbData = 0;
pEncodeInfo->KeyEncryptionAlgorithm.Parameters.pbData = IntPtr.Zero;
pEncodeInfo->pvKeyEncryptionAuxInfo = null;
string oidValue;
AlgId algId = contentEncryptionAlgorithm.Oid.Value.ToAlgId();
if (algId == AlgId.CALG_RC2)
oidValue = Oids.CmsRc2Wrap;
else
oidValue = Oids.Cms3DesWrap;
pEncodeInfo->KeyWrapAlgorithm.pszObjId = hb.AllocAsciiString(oidValue);
pEncodeInfo->KeyWrapAlgorithm.Parameters.cbData = 0;
pEncodeInfo->KeyWrapAlgorithm.Parameters.pbData = IntPtr.Zero;
pEncodeInfo->pvKeyWrapAuxInfo = GenerateEncryptionAuxInfoIfNeeded(contentEncryptionAlgorithm, hb);
pEncodeInfo->hCryptProv = IntPtr.Zero;
pEncodeInfo->dwKeySpec = 0;
pEncodeInfo->dwKeyChoice = CmsKeyAgreeKeyChoice.CMSG_KEY_AGREE_EPHEMERAL_KEY_CHOICE;
pEncodeInfo->pEphemeralAlgorithm = (CRYPT_ALGORITHM_IDENTIFIER*)(hb.Alloc(sizeof(CRYPT_ALGORITHM_IDENTIFIER)));
*(pEncodeInfo->pEphemeralAlgorithm) = pCertInfo->SubjectPublicKeyInfo.Algorithm;
pEncodeInfo->UserKeyingMaterial.cbData = 0;
pEncodeInfo->UserKeyingMaterial.pbData = IntPtr.Zero;
CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO* pEncryptedKey = (CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO*)(hb.Alloc(sizeof(CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO)));
pEncryptedKey->cbSize = sizeof(CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO);
pEncryptedKey->RecipientPublicKey = pCertInfo->SubjectPublicKeyInfo.PublicKey;
pEncryptedKey->RecipientId = EncodeRecipientId(recipient, hCertContext, pCertContext, pCertInfo, hb);
pEncryptedKey->Date = default(FILETIME);
pEncryptedKey->pOtherAttr = null;
CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO** ppEncryptedKey = (CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO**)(hb.Alloc(sizeof(CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO*)));
ppEncryptedKey[0] = pEncryptedKey;
pEncodeInfo->cRecipientEncryptedKeys = 1;
pEncodeInfo->rgpRecipientEncryptedKeys = ppEncryptedKey;
return pEncodeInfo;
}
}
//
// This returns an allocated native memory block. Its lifetime (and that of any allocated subblocks it may point to) is that of "hb".
//
private static unsafe CERT_ID EncodeRecipientId(CmsRecipient recipient, SafeCertContextHandle hCertContext, CERT_CONTEXT* pCertContext, CERT_INFO* pCertInfo, HeapBlockRetainer hb)
{
CERT_ID recipientId = default(CERT_ID);
SubjectIdentifierType type = recipient.RecipientIdentifierType;
switch (type)
{
case SubjectIdentifierType.IssuerAndSerialNumber:
{
recipientId.dwIdChoice = CertIdChoice.CERT_ID_ISSUER_SERIAL_NUMBER;
recipientId.u.IssuerSerialNumber.Issuer = pCertInfo->Issuer;
recipientId.u.IssuerSerialNumber.SerialNumber = pCertInfo->SerialNumber;
break;
}
case SubjectIdentifierType.SubjectKeyIdentifier:
{
byte[] ski = hCertContext.GetSubjectKeyIdentifer();
IntPtr pSki = hb.AllocBytes(ski);
recipientId.dwIdChoice = CertIdChoice.CERT_ID_KEY_IDENTIFIER;
recipientId.u.KeyId.cbData = (uint)(ski.Length);
recipientId.u.KeyId.pbData = pSki;
break;
}
default:
// The public contract for CmsRecipient guarantees that SubjectKeyIdentifier and IssuerAndSerialNumber are the only two possibilities.
Debug.Fail($"Unexpected SubjectIdentifierType: {type}");
throw new NotSupportedException(SR.Format(SR.Cryptography_Cms_Invalid_Subject_Identifier_Type, type));
}
return recipientId;
}
//
// This returns an allocated native memory block. Its lifetime (and that of any allocated subblocks it may point to) is that of "hb".
//
private static IntPtr GenerateEncryptionAuxInfoIfNeeded(AlgorithmIdentifier contentEncryptionAlgorithm, HeapBlockRetainer hb)
{
string algorithmOidValue = contentEncryptionAlgorithm.Oid.Value;
AlgId algId = algorithmOidValue.ToAlgId();
if (!(algId == AlgId.CALG_RC2 || algId == AlgId.CALG_RC4))
return IntPtr.Zero;
unsafe
{
CMSG_RC2_AUX_INFO* pRc2AuxInfo = (CMSG_RC2_AUX_INFO*)(hb.Alloc(sizeof(CMSG_RC2_AUX_INFO)));
pRc2AuxInfo->cbSize = sizeof(CMSG_RC2_AUX_INFO);
pRc2AuxInfo->dwBitLen = contentEncryptionAlgorithm.KeyLength;
if (pRc2AuxInfo->dwBitLen == 0)
{
// Desktop compat: If the caller didn't set the KeyLength property, set dwBitLength to the maxmium key length supported by RC2/RC4. The desktop queries CAPI for this but
// since that requires us to use a prohibited api (CryptAcquireContext), we'll just hardcode what CAPI returns for RC2 and RC4.
pRc2AuxInfo->dwBitLen = KeyLengths.DefaultKeyLengthForRc2AndRc4;
}
return (IntPtr)pRc2AuxInfo;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Baseline;
using Marten.Internal.Operations;
using Marten.Linq;
using Marten.Linq.Fields;
using Marten.Linq.Filters;
using Marten.Linq.Parsing;
using Marten.Linq.QueryHandlers;
using Marten.Linq.Selectors;
using Marten.Linq.SqlGeneration;
using Weasel.Postgresql;
using Marten.Schema;
using Marten.Services;
using Marten.Storage;
using Marten.Util;
using Npgsql;
using Remotion.Linq;
using Weasel.Core;
using Weasel.Postgresql.SqlGeneration;
namespace Marten.Internal.Storage
{
internal class SubClassDocumentStorage<T, TRoot, TId>: IDocumentStorage<T, TId>
where T : TRoot
{
private readonly IDocumentStorage<TRoot, TId> _parent;
private readonly SubClassMapping _mapping;
private readonly ISqlFragment _defaultWhere;
private readonly string[] _fields;
public SubClassDocumentStorage(IDocumentStorage<TRoot, TId> parent, SubClassMapping mapping)
{
_parent = parent;
_mapping = mapping;
FromObject = _mapping.TableName.QualifiedName;
_defaultWhere = determineWhereFragment();
_fields = _parent.SelectFields();
}
public void TruncateDocumentStorage(ITenant tenant)
{
tenant.RunSql(
$"delete from {_parent.TableName.QualifiedName} where {SchemaConstants.DocumentTypeColumn} = '{_mapping.Alias}'");
}
public Task TruncateDocumentStorageAsync(ITenant tenant)
{
return tenant.RunSqlAsync(
$"delete from {_parent.TableName.QualifiedName} where {SchemaConstants.DocumentTypeColumn} = '{_mapping.Alias}'");
}
public TenancyStyle TenancyStyle => _parent.TenancyStyle;
object IDocumentStorage<T>.IdentityFor(T document)
{
return _parent.Identity(document);
}
public string FromObject { get; }
public Type SelectedType => typeof(T);
public void WriteSelectClause(CommandBuilder sql)
{
_parent.WriteSelectClause(sql);
}
public string[] SelectFields()
{
return _fields;
}
public ISelector BuildSelector(IMartenSession session)
{
var inner = _parent.BuildSelector(session);
return new CastingSelector<T, TRoot>((ISelector<TRoot>) inner);
}
public IQueryHandler<TResult> BuildHandler<TResult>(IMartenSession session, Statement statement,
Statement currentStatement)
{
var selector = (ISelector<T>)BuildSelector(session);
return LinqHandlerBuilder.BuildHandler<T, TResult>(selector, statement);
}
public ISelectClause UseStatistics(QueryStatistics statistics)
{
return new StatsSelectClause<T>(this, statistics);
}
public Type SourceType => typeof(TRoot);
public IFieldMapping Fields => _mapping.Parent;
public ISqlFragment FilterDocuments(QueryModel model, ISqlFragment query)
{
var extras = extraFilters(query).ToArray();
return query.CombineAnd(extras);
}
private IEnumerable<ISqlFragment> extraFilters(ISqlFragment query)
{
yield return toBasicWhere();
if (_mapping.DeleteStyle == DeleteStyle.SoftDelete && !query.Contains(SchemaConstants.DeletedColumn))
yield return ExcludeSoftDeletedFilter.Instance;
if (_mapping.Parent.TenancyStyle == TenancyStyle.Conjoined && !query.SpecifiesTenant())
yield return CurrentTenantFilter.Instance;
}
private IEnumerable<ISqlFragment> defaultFilters()
{
yield return toBasicWhere();
if (_mapping.Parent.TenancyStyle == TenancyStyle.Conjoined) yield return CurrentTenantFilter.Instance;
if (_mapping.DeleteStyle == DeleteStyle.SoftDelete) yield return ExcludeSoftDeletedFilter.Instance;
}
public ISqlFragment DefaultWhereFragment()
{
return _defaultWhere;
}
public ISqlFragment determineWhereFragment()
{
var defaults = defaultFilters().ToArray();
return defaults.Length switch
{
0 => null,
1 => defaults[0],
_ => CompoundWhereFragment.And(defaults)
};
}
private WhereFragment toBasicWhere()
{
var aliasValues = _mapping.Aliases.Select(a => $"d.{SchemaConstants.DocumentTypeColumn} = '{a}'").ToArray()
.Join(" or ");
var sql = _mapping.Alias.Length > 1 ? $"({aliasValues})" : aliasValues;
return new WhereFragment(sql);
}
public bool UseOptimisticConcurrency => _parent.UseOptimisticConcurrency;
public IOperationFragment DeleteFragment => _parent.DeleteFragment;
public IOperationFragment HardDeleteFragment { get; }
public DuplicatedField[] DuplicatedFields => _parent.DuplicatedFields;
public DbObjectName TableName => _parent.TableName;
public Type DocumentType => typeof(T);
public Type IdType => typeof(TId);
public Guid? VersionFor(T document, IMartenSession session)
{
return _parent.VersionFor(document, session);
}
public void Store(IMartenSession session, T document)
{
_parent.Store(session, document);
}
public void Store(IMartenSession session, T document, Guid? version)
{
_parent.Store(session, document, version);
}
public void Eject(IMartenSession session, T document)
{
_parent.Eject(session, document);
}
public IStorageOperation Update(T document, IMartenSession session, ITenant tenant)
{
return _parent.Update(document, session, tenant);
}
public IStorageOperation Insert(T document, IMartenSession session, ITenant tenant)
{
return _parent.Insert(document, session, tenant);
}
public IStorageOperation Upsert(T document, IMartenSession session, ITenant tenant)
{
return _parent.Upsert(document, session, tenant);
}
public IStorageOperation Overwrite(T document, IMartenSession session, ITenant tenant)
{
return _parent.Overwrite(document, session, tenant);
}
public IDeletion DeleteForDocument(T document, ITenant tenant)
{
return _parent.DeleteForDocument(document, tenant);
}
public void SetIdentity(T document, TId identity)
{
_parent.SetIdentity(document, identity);
}
public IDeletion DeleteForId(TId id, ITenant tenant)
{
return _parent.DeleteForId(id, tenant);
}
public T Load(TId id, IMartenSession session)
{
var doc = _parent.Load(id, session);
if (doc is T x) return x;
return default;
}
public async Task<T> LoadAsync(TId id, IMartenSession session, CancellationToken token)
{
var doc = await _parent.LoadAsync(id, session, token).ConfigureAwait(false);
if (doc is T x) return x;
return default;
}
public IReadOnlyList<T> LoadMany(TId[] ids, IMartenSession session)
{
return _parent.LoadMany(ids, session).OfType<T>().ToList();
}
public async Task<IReadOnlyList<T>> LoadManyAsync(TId[] ids, IMartenSession session, CancellationToken token)
{
return (await _parent.LoadManyAsync(ids, session, token).ConfigureAwait(false)).OfType<T>().ToList();
}
public TId AssignIdentity(T document, ITenant tenant)
{
return _parent.AssignIdentity(document, tenant);
}
public TId Identity(T document)
{
return _parent.Identity(document);
}
public ISqlFragment ByIdFilter(TId id)
{
return _parent.ByIdFilter(id);
}
public IDeletion HardDeleteForId(TId id, ITenant tenant)
{
return _parent.HardDeleteForId(id, tenant);
}
public NpgsqlCommand BuildLoadCommand(TId id, ITenant tenant)
{
return _parent.BuildLoadCommand(id, tenant);
}
public NpgsqlCommand BuildLoadManyCommand(TId[] ids, ITenant tenant)
{
return _parent.BuildLoadManyCommand(ids, tenant);
}
public void EjectById(IMartenSession session, object id)
{
_parent.EjectById(session, id);
}
public void RemoveDirtyTracker(IMartenSession session, object id)
{
_parent.RemoveDirtyTracker(session, id);
}
public IDeletion HardDeleteForDocument(T document, ITenant tenant)
{
return _parent.HardDeleteForDocument(document, tenant);
}
}
}
| |
using System;
using System.Threading;
using GHIElectronics.NETMF.FEZ;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
namespace WeatherStation
{
static class PressureSensor
{
/// <summary>
///
/// SPI interface for the MPL115A barometric sensor.
/// Created by deepnarc, deepnarc at gmail.com
///
/// Netduino platform
///
/// Sensor Breakout---------Netduino
/// ================================
/// SDN---------------------optional
/// CSN---------------------pin 0 (user definable)
/// SDO---------------------pin 12
/// SDI---------------------pin 11
/// SCK---------------------pin 13
/// GND---------------------GND
/// VDO---------------------VCC (3.3V)
///
/// References: (1) Freescale Semiconductor, Application Note, AN3785, Rev 5, 7/2009 by John Young
/// provided the code for the manipulations of the sensor coefficients; the original comments
/// were left in place without modification in that section. (2) Freescale Semiconductor, Document
/// Number: MPL115A1, Rev 6, 10/2011. (3) MPL115A1 SPI Digital Barometer Test Code Created on:
/// September 30, 2010 By: Jeremiah McConnell - miah at miah.com, Portions: Jim Lindblom - jim at
/// sparkfun.com. (4) MPL115A1 SPI Digital Barometer Test Code Created on: April 20, 2010 By: Jim
/// Lindblom - jim at sparkfun.com.
///
/// </summary>
public static double calculatePressure()
{
SPI SPI_Out = new SPI(new SPI.Configuration(
(Cpu.Pin)FEZ_Pin.Digital.Di7, // SS-pin
false, // SS-pin active state
0, // The setup time for the SS port
0, // The hold time for the SS port
false, // The idle state of the clock
true, // The sampling clock edge
1000, // The SPI clock rate in KHz
SPI.SPI_module.SPI1 // The used SPI bus (refers to a MOSI MISO and SCLK pinset)
)
);
string decPcomp_out;
sbyte sia0MSB, sia0LSB;
sbyte sib1MSB, sib1LSB;
sbyte sib2MSB, sib2LSB;
sbyte sic12MSB, sic12LSB;
sbyte sic11MSB, sic11LSB;
sbyte sic22MSB, sic22LSB;
int sia0, sib1, sib2, sic12, sic11, sic22;
uint uiPadc, uiTadc;
byte uiPH, uiPL, uiTH, uiTL;
long lt1, lt2, lt3, si_c11x1, si_a11, si_c12x2;
long si_a1, si_c22x2, si_a2, si_a1x1, si_y1, si_a2x2;
float siPcomp;//, decPcomp;
// start pressure & temp conversions
// command byte + r/w bit
const byte com1_writeData = 0x24 & 0x7F;
const byte com2_writeData = 0x00 & 0x7F;
byte[] WriteBuffer = { com1_writeData, com2_writeData };
SPI_Out.Write(WriteBuffer);
Thread.Sleep(3);
// write(0x24, 0x00); // Start Both Conversions
// write(0x20, 0x00); // Start Pressure Conversion
// write(0x22, 0x00); // Start temperature conversion
// delay_ms(10); // Typical wait time is 3ms
// read pressure
// address byte + r/w bit
// data byte + r/w bit
const byte PRESHw_writeData = 0x00 | 0x80;
const byte PRESHr_writeData = 0x00 | 0x80;
const byte PRESLw_writeData = 0x02 | 0x80;
const byte PRESLr_writeData = 0x00 | 0x80;
const byte TEMPHw_writeData = 0x04 | 0x80;
const byte TEMPHr_writeData = 0x00 | 0x80;
const byte TEMPLw_writeData = 0x06 | 0x80;
const byte TEMPLr_writeData = 0x00 | 0x80;
const byte BLANK1r_writeData = 0x00 | 0x80;
byte[] press_writeData = { PRESHw_writeData, PRESHr_writeData, PRESLw_writeData, PRESLr_writeData,
TEMPHw_writeData, TEMPHr_writeData, TEMPLw_writeData, TEMPLr_writeData, BLANK1r_writeData };
byte[] press_readBuffer = new byte[9];
SPI_Out.WriteRead(press_writeData, press_readBuffer);
uiPH = press_readBuffer[1];
uiPL = press_readBuffer[3];
uiTH = press_readBuffer[5];
uiTL = press_readBuffer[7];
uiPadc = (uint)uiPH << 8;
uiPadc += (uint)uiPL & 0x00FF;
uiTadc = (uint)uiTH << 8;
uiTadc += (uint)uiTL & 0x00FF;
// read coefficients
// address byte + r/w bit
// data byte + r/w bit
const byte A0MSBw_writeData = 0x08 | 0x80;
const byte A0MSBr_writeData = 0x00 | 0x80;
const byte A0LSBw_writeData = 0x0A | 0x80;
const byte A0LSBr_writeData = 0x00 | 0x80;
const byte B1MSBw_writeData = 0x0C | 0x80;
const byte B1MSBr_writeData = 0x00 | 0x80;
const byte B1LSBw_writeData = 0x0E | 0x80;
const byte B1LSBr_writeData = 0x00 | 0x80;
const byte B2MSBw_writeData = 0x10 | 0x80;
const byte B2MSBr_writeData = 0x00 | 0x80;
const byte B2LSBw_writeData = 0x12 | 0x80;
const byte B2LSBr_writeData = 0x00 | 0x80;
const byte C12MSBw_writeData = 0x14 | 0x80;
const byte C12MSBr_writeData = 0x00 | 0x80;
const byte C12LSBw_writeData = 0x16 | 0x80;
const byte C12LSBr_writeData = 0x00 | 0x80;
const byte C11MSBw_writeData = 0x18 | 0x80;
const byte C11MSBr_writeData = 0x00 | 0x80;
const byte C11LSBw_writeData = 0x1A | 0x80;
const byte C11LSBr_writeData = 0x00 | 0x80;
const byte C22MSBw_writeData = 0x1C | 0x80;
const byte C22MSBr_writeData = 0x00 | 0x80;
const byte C22LSBw_writeData = 0x1E | 0x80;
const byte C22LSBr_writeData = 0x00 | 0x80;
const byte BLANK2r_writeData = 0x00 | 0x80;
byte[] coeff_writeData = { A0MSBw_writeData, A0MSBr_writeData, A0LSBw_writeData, A0LSBr_writeData, B1MSBw_writeData,
B1MSBr_writeData, B1LSBw_writeData, B1LSBr_writeData, B2MSBw_writeData, B2MSBr_writeData,
B2LSBw_writeData, B2LSBr_writeData, C12MSBw_writeData, C12MSBr_writeData, C12LSBw_writeData,
C12LSBr_writeData, C11MSBw_writeData, C11MSBr_writeData, C11LSBw_writeData, C11LSBr_writeData,
C22MSBw_writeData, C22MSBr_writeData, C22LSBw_writeData, C22LSBr_writeData, BLANK2r_writeData };
byte[] coeff_readBuffer = new byte[25];
SPI_Out.WriteRead(coeff_writeData, coeff_readBuffer);
//====================================================
// MPL115A Placing Coefficients into 16 bit variables
//====================================================
//coeff a0 16bit
sia0MSB = (sbyte)coeff_readBuffer[1];
sia0LSB = (sbyte)coeff_readBuffer[3];
sia0 = (int)sia0MSB << 8; //s16 type //Shift to MSB
sia0 += (int)sia0LSB & 0x00FF; //Add LSB to 16bit number
//coeff b1 16bit
sib1MSB = (sbyte)coeff_readBuffer[5];
sib1LSB = (sbyte)coeff_readBuffer[7];
sib1 = (int)sib1MSB << 8; //Shift to MSB
sib1 += (int)sib1LSB & 0x00FF; //Add LSB to 16bit number
//coeff b2 16bit
sib2MSB = (sbyte)coeff_readBuffer[9];
sib2LSB = (sbyte)coeff_readBuffer[11];
sib2 = (int)sib2MSB << 8; //Shift to MSB
sib2 += (int)sib2LSB & 0x00FF; //Add LSB to 16bit number
//coeff c12 14bit
sic12MSB = (sbyte)coeff_readBuffer[13];
sic12LSB = (sbyte)coeff_readBuffer[15];
sic12 = (int)sic12MSB << 8; //Shift to MSB only by 8 for MSB
sic12 += (int)sic12LSB & 0x00FF;
//coeff c11 11bit
sic11MSB = (sbyte)coeff_readBuffer[17];
sic11LSB = (sbyte)coeff_readBuffer[19];
sic11 = (int)sic11MSB << 8; //Shift to MSB only by 8 for MSB
sic11 += (int)sic11LSB & 0x00FF;
//coeff c22 11bit
sic22MSB = (sbyte)coeff_readBuffer[21];
sic22LSB = (sbyte)coeff_readBuffer[23];
sic22 = (int)sic22MSB << 8; //Shift to MSB only by 8 for MSB
sic22 += (int)sic22LSB & 0x00FF;
//===================================================
//Coefficient 9 equation compensation
//===================================================
//
//Variable sizes:
//For placing high and low bytes of the Memory addresses for each of the 6 coefficients:
//signed char (S8) sia0MSB, sia0LSB, sib1MSB,sib1LSB, sib2MSB,sib2LSB, sic12MSB,sic12LSB, sic11MSB,sic11LSB, sic22MSB,sic22LSB; //
//Variable for use in the compensation, this is the 6 coefficients in 16bit form, MSB+LSB.
//signed int (S16) sia0, sib1, sib2, sic12, sic11, sic22;
//
//Variable used to do large calculation as 3 temp variables in the process below
//signed long (S32) lt1, lt2, lt3;
//
//Variables used for Pressure and Temperature Raw.
//unsigned int (U16) uiPadc, uiTadc.
//signed (N=number of bits in coefficient, F-fractional bits) //s(N,F)
//The below Pressure and Temp or uiPadc and uiTadc are shifted from the MSB+LSB values to remove the zeros in the LSB since this
// 10bit number is stored in 16 bits. i.e 0123456789XXXXXX becomes 0000000123456789
uiPadc = uiPadc >> 6; //Note that the PressCntdec is the raw value from the MPL115A data address. Its shifted >>6 since its 10 bit.
uiTadc = uiTadc >> 6; //Note that the TempCntdec is the raw value from the MPL115A data address. Its shifted >>6 since its 10 bit.
//******* STEP 1 c11x1= c11 * Padc
lt1 = (long)sic11; // s(16,27) s(N,F+zeropad) goes from s(11,10)+11ZeroPad = s(11,22) => Left Justified = s(16,27)
lt2 = (long)uiPadc; // u(10,0) s(N,F)
lt3 = lt1 * lt2; // s(26,27) /c11*Padc
si_c11x1 = (long)lt3; // s(26,27)- EQ 1 =c11x1 /checked
//divide this hex number by 2^30 to get the correct decimal value.
//b1 =s(14,11) => s(16,13) Left justified
//******* STEP 2 a11= b1 + c11x1
lt1 = ((long)sib1) << 14; // s(30,27) b1=s(16,13) Shift b1 so that the F matches c11x1(shift by 14)
lt2 = (long)si_c11x1; // s(26,27) //ensure fractional bits are compatible
lt3 = lt1 + lt2; // s(30,27) /b1+c11x1
si_a11 = (long)(lt3 >> 14); // s(16,13) - EQ 2 =a11 Convert this block back to s(16,X)
//******* STEP 3 c12x2= c12 * Tadc
// sic12 is s(14,13)+9zero pad = s(16,15)+9 => s(16,24) left justified
lt1 = (long)sic12; // s(16,24)
lt2 = (long)uiTadc; // u(10,0)
lt3 = lt1 * lt2; // s(26,24)
si_c12x2 = (long)lt3; // s(26,24) - EQ 3 =c12x2 /checked
//******* STEP 4 a1= a11 + c12x2
lt1 = ((long)si_a11 << 11); // s(27,24) This is done by s(16,13) <<11 goes to s(27,24) to match c12x2's F part
lt2 = (long)si_c12x2; // s(26,24)
lt3 = lt1 + lt2; // s(27,24) /a11+c12x2
si_a1 = (long)lt3 >> 11; // s(16,13) - EQ 4 =a1 /check
//******* STEP 5 c22x2= c22 * Tadc
// c22 is s(11,10)+9zero pad = s(11,19) => s(16,24) left justified
lt1 = (long)sic22; // s(16,30) This is done by s(11,10) + 15 zero pad goes to s(16,15)+15, to s(16,30)
lt2 = (long)uiTadc; // u(10,0)
lt3 = lt1 * lt2; // s(26,30) /c22*Tadc
si_c22x2 = (long)(lt3); // s(26,30) - EQ 5 /=c22x2
//******* STEP 6 a2= b2 + c22x2
//WORKS and loses the least in data. One extra execution. Note how the 31 is really a 32 due to possible overflow.
// b2 is s(16,14) User shifted left to => s(31,29) to match c22x2 F value
lt1 = ((long)sib2 << 15); //s(31,29)
lt2 = ((long)si_c22x2 >> 1); //s(25,29) s(26,30) goes to >>16 s(10,14) to match F from sib2
lt3 = lt1 + lt2; //s(32,29) but really is a s(31,29) due to overflow the 31 becomes a 32.
si_a2 = ((long)lt3 >> 16); //s(16,13)
//******* STEP 7 a1x1= a1 * Padc
lt1 = (long)si_a1; // s(16,13)
lt2 = (long)uiPadc; // u(10,0)
lt3 = lt1 * lt2; // s(26,13) /a1*Padc
si_a1x1 = (long)(lt3); // s(26,13) - EQ 7 /=a1x1 /check
//******* STEP 8 y1= a0 + a1x1
// a0 = s(16,3)
lt1 = ((long)sia0 << 10); // s(26,13) This is done since has to match a1x1 F value to add. So S(16,3) <<10 = S(26,13)
lt2 = (long)si_a1x1; // s(26,13)
lt3 = lt1 + lt2; // s(26,13) /a0+a1x1
si_y1 = ((long)lt3 >> 10); // s(16,3) - EQ 8 /=y1 /check
//******* STEP 9 a2x2= a2 *Tadc
lt1 = (long)si_a2; // s(16,13)
lt2 = (long)uiTadc; // u(10,0)
lt3 = lt1 * lt2; // s(26,13) /a2*Tadc
si_a2x2 = (long)(lt3); // s(26,13) - EQ 9 /=a2x2
//******* STEP 10 pComp = y1 +a2x2
// y1= s(16,3)
lt1 = ((long)si_y1 << 10); // s(26,13) This is done to match a2x2 F value so addition can match. s(16,3) <<10
lt2 = (long)si_a2x2; // s(26,13)
lt3 = lt1 + lt2; // s(26,13) /y1+a2x2
// FIXED POINT RESULT WITH ROUNDING:
siPcomp = (long)lt3 >> 13; // goes to no fractional parts since this is an ADC count.
//decPcomp is defined as a floating point number.
//Conversion to Decimal value from 1023 ADC count value. ADC counts are 0 to 1023. Pressure is 50 to 115kPa correspondingly.
var decPcomp = (double)((65.0 / 1023.0) * siPcomp) + 50;
var decPcompHg = decPcomp*0.295300586466965;
decPcomp_out = decPcomp.ToString();
Debug.Print("decPcomp: " + decPcomp_out + " millibars: " + decPcompHg);
SPI_Out.Dispose();
return decPcompHg;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.Extensions.Options;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.DataAnnotations
{
public class DataAnnotationsModelValidatorProviderTest
{
private readonly IModelMetadataProvider _metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
[Fact]
public void CreateValidators_ReturnsValidatorForIValidatableObject()
{
// Arrange
var provider = new DataAnnotationsModelValidatorProvider(
new ValidationAttributeAdapterProvider(),
Options.Create(new MvcDataAnnotationsLocalizationOptions()),
stringLocalizerFactory: null);
var mockValidatable = Mock.Of<IValidatableObject>();
var metadata = _metadataProvider.GetMetadataForType(mockValidatable.GetType());
var providerContext = new ModelValidatorProviderContext(metadata, GetValidatorItems(metadata));
// Act
provider.CreateValidators(providerContext);
// Assert
var validatorItem = Assert.Single(providerContext.Results);
Assert.IsType<ValidatableObjectAdapter>(validatorItem.Validator);
}
[Fact]
public void CreateValidators_InsertsRequiredValidatorsFirst()
{
var provider = new DataAnnotationsModelValidatorProvider(
new ValidationAttributeAdapterProvider(),
Options.Create(new MvcDataAnnotationsLocalizationOptions()),
stringLocalizerFactory: null);
var metadata = _metadataProvider.GetMetadataForProperty(
typeof(ClassWithProperty),
"PropertyWithMultipleValidationAttributes");
var providerContext = new ModelValidatorProviderContext(metadata, GetValidatorItems(metadata));
// Act
provider.CreateValidators(providerContext);
// Assert
Assert.Equal(4, providerContext.Results.Count);
Assert.IsAssignableFrom<RequiredAttribute>(((DataAnnotationsModelValidator)providerContext.Results[0].Validator).Attribute);
Assert.IsAssignableFrom<RequiredAttribute>(((DataAnnotationsModelValidator)providerContext.Results[1].Validator).Attribute);
}
[Fact]
public void UnknownValidationAttributeGetsDefaultAdapter()
{
// Arrange
var provider = new DataAnnotationsModelValidatorProvider(
new ValidationAttributeAdapterProvider(),
Options.Create(new MvcDataAnnotationsLocalizationOptions()),
stringLocalizerFactory: null);
var metadata = _metadataProvider.GetMetadataForType(typeof(DummyClassWithDummyValidationAttribute));
var providerContext = new ModelValidatorProviderContext(metadata, GetValidatorItems(metadata));
// Act
provider.CreateValidators(providerContext);
// Assert
var validatorItem = providerContext.Results.Single();
Assert.IsType<DataAnnotationsModelValidator>(validatorItem.Validator);
}
private class DummyValidationAttribute : ValidationAttribute
{
}
[DummyValidation]
private class DummyClassWithDummyValidationAttribute
{
}
// Default IValidatableObject adapter factory
[Fact]
public void IValidatableObjectGetsAValidator()
{
// Arrange
var provider = new DataAnnotationsModelValidatorProvider(
new ValidationAttributeAdapterProvider(),
Options.Create(new MvcDataAnnotationsLocalizationOptions()),
stringLocalizerFactory: null);
var mockValidatable = new Mock<IValidatableObject>();
var metadata = _metadataProvider.GetMetadataForType(mockValidatable.Object.GetType());
var providerContext = new ModelValidatorProviderContext(metadata, GetValidatorItems(metadata));
// Act
provider.CreateValidators(providerContext);
// Assert
Assert.Single(providerContext.Results);
}
[Fact]
public void HasValidators_ReturnsTrue_IfModelIsIValidatableObject()
{
// Arrange
var provider = GetProvider();
var mockValidatable = Mock.Of<IValidatableObject>();
// Act
var result = provider.HasValidators(mockValidatable.GetType(), Array.Empty<object>());
// Assert
Assert.True(result);
}
[Fact]
public void HasValidators_ReturnsTrue_IfMetadataContainsValidationAttribute()
{
// Arrange
var provider = GetProvider();
var attributes = new object[] { new BindNeverAttribute(), new DummyValidationAttribute() };
// Act
var result = provider.HasValidators(typeof(object), attributes);
// Assert
Assert.True(result);
}
[Fact]
public void HasValidators_ReturnsFalse_IfNoDataAnnotationsValidationIsAvailable()
{
// Arrange
var provider = GetProvider();
var attributes = new object[] { new BindNeverAttribute(), };
// Act
var result = provider.HasValidators(typeof(object), attributes);
// Assert
Assert.False(result);
}
private static DataAnnotationsModelValidatorProvider GetProvider()
{
return new DataAnnotationsModelValidatorProvider(
new ValidationAttributeAdapterProvider(),
Options.Create(new MvcDataAnnotationsLocalizationOptions()),
stringLocalizerFactory: null);
}
private IList<ValidatorItem> GetValidatorItems(ModelMetadata metadata)
{
var items = new List<ValidatorItem>(metadata.ValidatorMetadata.Count);
for (var i = 0; i < metadata.ValidatorMetadata.Count; i++)
{
items.Add(new ValidatorItem(metadata.ValidatorMetadata[i]));
}
return items;
}
private class ObservableModel
{
private bool _propertyWasRead;
public string TheProperty
{
get
{
_propertyWasRead = true;
return "Hello";
}
}
public bool PropertyWasRead()
{
return _propertyWasRead;
}
}
private class BaseModel
{
public virtual string MyProperty { get; set; }
}
private class DerivedModel : BaseModel
{
[StringLength(10)]
public override string MyProperty
{
get { return base.MyProperty; }
set { base.MyProperty = value; }
}
}
private class DummyRequiredAttributeHelperClass
{
[Required(ErrorMessage = "Custom Required Message")]
public int WithAttribute { get; set; }
public int WithoutAttribute { get; set; }
}
private class ClassWithProperty
{
[CustomNonRequiredAttribute1]
[CustomNonRequiredAttribute2]
[CustomRequiredAttribute1]
[CustomRequiredAttribute2]
public string PropertyWithMultipleValidationAttributes { get; set; }
}
public class CustomRequiredAttribute1 : RequiredAttribute
{
}
public class CustomRequiredAttribute2 : RequiredAttribute
{
}
public class CustomNonRequiredAttribute1 : ValidationAttribute
{
}
public class CustomNonRequiredAttribute2 : ValidationAttribute
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Resources;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Markup;
using System.Windows.Resources;
using System.IO;
using System.Windows.Media.Imaging;
using System.Reflection;
using System.Xml.Linq;
using Windows.Phone.Media.Capture;
using Windows.Phone.Media.Devices;
using System.Threading.Tasks;
using Windows.Foundation;
using System.Diagnostics;
using System.Windows.Media;
using Microsoft.Devices;
using System.Threading;
using System.Windows.Threading;
using System.ComponentModel;
using BarcodeLib;
using BarcodeScanners;
namespace BarcodeScannerPage
{
public partial class ScannerPage : PhoneApplicationPage
{
public enum OverlayMode
{
OM_MW = 1,
OM_IMAGE = 2
};
public ScannerPage()
{
InitializeComponent();
int ver = Scanner.MWBgetLibVersion();
int v1 = (ver >> 16);
int v2 = (ver >> 8) & 0xff;
int v3 = (ver & 0xff);
libVersion = String.Format("{0}.{1}.{2}", v1, v2, v3);
System.Diagnostics.Debug.WriteLine("Lib version: " + libVersion);
processingHandler = new DoWorkEventHandler(bw_DoWork);
previewFrameHandler = new TypedEventHandler<ICameraCaptureDevice, Object>(cam_PreviewFrameAvailable);
bw.WorkerReportsProgress = false;
bw.WorkerSupportsCancellation = true;
bw.DoWork += processingHandler;
}
public static OverlayMode param_OverlayMode = OverlayMode.OM_MW;
public static bool param_EnableHiRes = true;
public static bool param_EnableFlash = true;
public static bool param_DefaultFlashOn = false;
public static SupportedPageOrientation param_Orientation = SupportedPageOrientation.Landscape;
public int MAX_RESOLUTION = 1280 * 768;
public static PhotoCaptureDevice cameraDevice;
// public static AudioVideoCaptureDevice cameraDevice;
public static Boolean isProcessing = false;
private byte[] pixels = null;
private DateTime lastTime;
private BackgroundWorker bw = new BackgroundWorker();
private DoWorkEventHandler processingHandler;
private String libVersion;
private bool flashAvailable;
private bool flashActive = false;
DispatcherTimer focusTimer;
private TypedEventHandler<ICameraCaptureDevice, Object> previewFrameHandler;
private void stopCamera()
{
focusTimer.Stop();
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (param_Orientation == SupportedPageOrientation.Landscape)
{
this.Dispatcher.BeginInvoke((Action)(() =>
{
this.SupportedOrientations = SupportedPageOrientation.Landscape;
}));
} else
if (param_Orientation == SupportedPageOrientation.Portrait)
{
this.Dispatcher.BeginInvoke((Action)(() =>
{
this.SupportedOrientations = SupportedPageOrientation.Portrait;
}));
}
InitializeCamera(CameraSensorLocation.Back);
isProcessing = false;
fixOrientation(Orientation);
if ((param_OverlayMode & OverlayMode.OM_MW) > 0)
{
MWOverlay.addOverlay(canvas);
}
if ((param_OverlayMode & OverlayMode.OM_IMAGE) > 0)
{
cameraOverlay.Visibility = System.Windows.Visibility.Visible;
}
else
{
cameraOverlay.Visibility = System.Windows.Visibility.Collapsed;
}
}
protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
{
if (cameraDevice != null)
{
try
{
isProcessing = true;
stopCamera();
}
catch (Exception e2)
{
Debug.WriteLine("Camera closing error: " + e2.Message);
}
}
if ((param_OverlayMode & OverlayMode.OM_MW) > 0)
{
MWOverlay.removeOverlay();
}
base.OnNavigatingFrom(e);
}
private async Task InitializeCamera(CameraSensorLocation sensorLocation)
{
Windows.Foundation.Size captureResolution = new Windows.Foundation.Size(1280, 720);
Windows.Foundation.Size previewResolution = new Windows.Foundation.Size(1280, 720);
IReadOnlyList<Windows.Foundation.Size> prevSizes = PhotoCaptureDevice.GetAvailablePreviewResolutions(sensorLocation);
IReadOnlyList<Windows.Foundation.Size> captSizes = PhotoCaptureDevice.GetAvailableCaptureResolutions(sensorLocation);
double bestAspect = 1000;
int bestAspectResIndex = 0;
double aspect = Application.Current.Host.Content.ActualHeight / Application.Current.Host.Content.ActualWidth;
for (int i = 0; i < captSizes.Count; i++)
{
double w = captSizes[i].Width;
double h = captSizes[i].Height;
double resAspect = w / h;
double diff = aspect - resAspect;
if (diff < 0)
diff = -diff;
if (diff < bestAspect)
{
bestAspect = diff;
bestAspectResIndex = i;
}
}
if (bestAspectResIndex >= 0)
{
captureResolution.Width = captSizes[bestAspectResIndex].Width;
captureResolution.Height = captSizes[bestAspectResIndex].Height;
}
Windows.Foundation.Size initialResolution = captureResolution;
try
{
PhotoCaptureDevice d = null;
System.Diagnostics.Debug.WriteLine("Settinge camera initial resolution: " + initialResolution.Width + "x" + initialResolution.Height + "......");
bool initialized = false;
try
{
d = await PhotoCaptureDevice.OpenAsync(sensorLocation, initialResolution);
System.Diagnostics.Debug.WriteLine("Success " + initialResolution);
initialized = true;
captureResolution = initialResolution;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("Failed to set initial resolution: " + initialResolution + " error:" + e.Message);
}
if (!initialized)
try
{
d = await PhotoCaptureDevice.OpenAsync(sensorLocation, captSizes.ElementAt<Windows.Foundation.Size>(0));
System.Diagnostics.Debug.WriteLine("Success " + captSizes.ElementAt<Windows.Foundation.Size>(0));
initialized = true;
captureResolution = captSizes.ElementAt<Windows.Foundation.Size>(0);
}
catch
{
System.Diagnostics.Debug.WriteLine("Failed to set initial resolution: " + captSizes.ElementAt<Windows.Foundation.Size>(0));
}
//try to not use too high resolution
if (param_EnableHiRes)
{
MAX_RESOLUTION = 1280 * 800;
}
else
{
MAX_RESOLUTION = 800 * 480;
}
if (d.PreviewResolution.Height * d.PreviewResolution.Width > MAX_RESOLUTION)
{
bestAspectResIndex = -1;
aspect = (double)captureResolution.Width / captureResolution.Height;
for (int i = 0; i < prevSizes.Count; i++)
{
double w = prevSizes[i].Width;
double h = prevSizes[i].Height;
double resAspect = w / h;
double diff = aspect - resAspect;
if (diff < 0.01 && diff > -0.01)
{
if (w * h <= MAX_RESOLUTION)
{
previewResolution = prevSizes.ElementAt<Windows.Foundation.Size>(i);
bestAspectResIndex = i;
break;
}
}
}
if (bestAspectResIndex >= 0)
try
{
await d.SetPreviewResolutionAsync(previewResolution);
}
finally
{
}
}
System.Diagnostics.Debug.WriteLine("Preview resolution: " + d.PreviewResolution);
d.SetProperty(KnownCameraGeneralProperties.EncodeWithOrientation,
d.SensorLocation == CameraSensorLocation.Back ?
d.SensorRotationInDegrees : -d.SensorRotationInDegrees);
cameraDevice = d;
cameraDevice.PreviewFrameAvailable += previewFrameHandler;
IReadOnlyList<object> flashProperties = PhotoCaptureDevice.GetSupportedPropertyValues(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchMode);
if (param_EnableFlash)
{
if (flashProperties.ToList().Contains((UInt32)VideoTorchMode.On))
{
flashAvailable = true;
if (param_DefaultFlashOn)
{
flashActive = true;
cameraDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On);
flashButtonImage.Source = new BitmapImage(new Uri("/Plugins/com.manateeworks.barcodescanner/flashbuttonon.png", UriKind.Relative));
}
else
{
flashActive = false;
cameraDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.Off);
flashButtonImage.Source = new BitmapImage(new Uri("/Plugins/com.manateeworks.barcodescanner/flashbuttonoff.png", UriKind.Relative));
}
flashButton.Visibility = System.Windows.Visibility.Visible;
}
else
{
flashAvailable = false;
flashButton.Visibility = System.Windows.Visibility.Collapsed;
}
}
else
{
flashButton.Visibility = System.Windows.Visibility.Collapsed;
}
videoBrush.SetSource(cameraDevice);
focusTimer = new DispatcherTimer();
focusTimer.Interval = TimeSpan.FromSeconds(3);
focusTimer.Tick += delegate
{
cameraDevice.FocusAsync();
};
focusTimer.Start();
}
catch (Exception e)
{
Debug.WriteLine("Camera initialization error: " + e.Message);
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
Byte[] result = new Byte[10000];
BackgroundWorker worker = sender as BackgroundWorker;
ThreadArguments ta = e.Argument as ThreadArguments;
int resLen = Scanner.MWBscanGrayscaleImage(ta.pixels, ta.width, ta.height, result);
if (lastTime != null && lastTime.Ticks > 0)
{
long timePrev = lastTime.Ticks;
long timeNow = DateTime.Now.Ticks;
long timeDifference = (timeNow - timePrev) / 10000;
System.Diagnostics.Debug.WriteLine("frame time: {0}", timeDifference);
}
lastTime = DateTime.Now;
//ignore results shorter than 4 characters for barcodes with weak checksum
if (resLen > 4 || ((resLen > 0 && Scanner.MWBgetLastType() != Scanner.FOUND_39 && Scanner.MWBgetLastType() != Scanner.FOUND_25_INTERLEAVED && Scanner.MWBgetLastType() != Scanner.FOUND_25_STANDARD)))
{
string resultString = System.Text.Encoding.UTF8.GetString(result, 0, resLen);
int bcType = Scanner.MWBgetLastType();
String typeName = BarcodeHelper.getBarcodeName(bcType);
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
BarcodeHelper.scannerResult = new ScannerResult();
BarcodeHelper.resultAvailable = true;
BarcodeHelper.scannerResult.code = resultString;
BarcodeHelper.scannerResult.type = typeName;
BarcodeHelper.scannerResult.isGS1 = (Scanner.MWBisLastGS1() == 1);
Byte[] binArray = new Byte[resLen];
for (int i = 0; i < resLen; i++)
binArray[i] = result[i];
BarcodeHelper.scannerResult.bytes = binArray;
stopCamera();
NavigationService.GoBack();
});
}
else
{
isProcessing = false;
cameraDevice.PreviewFrameAvailable += previewFrameHandler;
}
}
private void flashButton_Click(object sender, RoutedEventArgs e)
{
if (flashAvailable)
{
flashActive = !flashActive;
if (flashActive)
{
cameraDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On);
flashButtonImage.Source = new BitmapImage(new Uri("/Plugins/com.manateeworks.barcodescanner/flashbuttonon.png", UriKind.Relative));
}
else
{
cameraDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.Off);
flashButtonImage.Source = new BitmapImage(new Uri("/Plugins/com.manateeworks.barcodescanner/flashbuttonoff.png", UriKind.Relative));
}
}
}
class ThreadArguments
{
public int width { get; set; }
public int height { get; set; }
public byte[] pixels { get; set; }
}
void cam_PreviewFrameAvailable(ICameraCaptureDevice device, object sender)
{
if (isProcessing)
{
return;
}
cameraDevice.PreviewFrameAvailable -= previewFrameHandler;
isProcessing = true;
int len = (int)device.PreviewResolution.Width * (int)device.PreviewResolution.Height;
if (pixels == null)
pixels = new byte[len];
device.GetPreviewBufferY(pixels);
// Byte[] result = new Byte[10000];
int width = (int)device.PreviewResolution.Width;
int height = (int)device.PreviewResolution.Height;
ThreadArguments ta = new ThreadArguments();
ta.height = height;
ta.width = width;
ta.pixels = pixels;
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
bw.RunWorkerAsync(ta);
});
}
private void fixOrientation(PageOrientation orientation)
{
if ((orientation & PageOrientation.LandscapeLeft) == (PageOrientation.LandscapeLeft))
{
videoBrush.RelativeTransform = new CompositeTransform()
{
CenterX = 0.5,
CenterY = 0.5,
Rotation = 0
};
}
else
if ((orientation & PageOrientation.LandscapeRight) == (PageOrientation.LandscapeRight))
{
videoBrush.RelativeTransform = new CompositeTransform()
{
CenterX = 0.5,
CenterY = 0.5,
Rotation = 180
};
}
else
if ((orientation & PageOrientation.PortraitUp) == (PageOrientation.PortraitUp))
{
videoBrush.RelativeTransform = new CompositeTransform()
{
CenterX = 0.5,
CenterY = 0.5,
Rotation = 90
};
}
else
if ((orientation & PageOrientation.PortraitDown) == (PageOrientation.PortraitDown))
{
videoBrush.RelativeTransform = new CompositeTransform()
{
CenterX = 0.5,
CenterY = 0.5,
Rotation = 270
};
}
}
private void PhoneApplicationPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
{
if (videoBrush == null)
return;
fixOrientation(e.Orientation);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Xml;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal.Filters;
namespace NUnit.Framework.Internal
{
/// <summary>
/// Interface to be implemented by filters applied to tests.
/// The filter applies when running the test, after it has been
/// loaded, since this is the only time an ITest exists.
/// </summary>
#if !PORTABLE && !NETSTANDARD1_6
[Serializable]
#endif
public abstract class TestFilter : ITestFilter
{
/// <summary>
/// Unique Empty filter.
/// </summary>
public readonly static TestFilter Empty = new EmptyFilter();
/// <summary>
/// Indicates whether this is the EmptyFilter
/// </summary>
public bool IsEmpty
{
get { return this is TestFilter.EmptyFilter; }
}
/// <summary>
/// Indicates whether this is a top-level filter,
/// not contained in any other filter.
/// </summary>
public bool TopLevel { get; set; }
/// <summary>
/// Determine if a particular test passes the filter criteria. The default
/// implementation checks the test itself, its parents and any descendants.
///
/// Derived classes may override this method or any of the Match methods
/// to change the behavior of the filter.
/// </summary>
/// <param name="test">The test to which the filter is applied</param>
/// <returns>True if the test passes the filter, otherwise false</returns>
public virtual bool Pass(ITest test)
{
return Match(test) || MatchParent(test) || MatchDescendant(test);
}
/// <summary>
/// Determine if a test matches the filter explicitly. That is, it must
/// be a direct match of the test itself or one of it's children.
/// </summary>
/// <param name="test">The test to which the filter is applied</param>
/// <returns>True if the test matches the filter explicitly, otherwise false</returns>
public virtual bool IsExplicitMatch(ITest test)
{
return Match(test) || MatchDescendant(test);
}
/// <summary>
/// Determine whether the test itself matches the filter criteria, without
/// examining either parents or descendants. This is overridden by each
/// different type of filter to perform the necessary tests.
/// </summary>
/// <param name="test">The test to which the filter is applied</param>
/// <returns>True if the filter matches the any parent of the test</returns>
public abstract bool Match(ITest test);
/// <summary>
/// Determine whether any ancestor of the test matches the filter criteria
/// </summary>
/// <param name="test">The test to which the filter is applied</param>
/// <returns>True if the filter matches the an ancestor of the test</returns>
public bool MatchParent(ITest test)
{
return test.Parent != null && (Match(test.Parent) || MatchParent(test.Parent));
}
/// <summary>
/// Determine whether any descendant of the test matches the filter criteria.
/// </summary>
/// <param name="test">The test to be matched</param>
/// <returns>True if at least one descendant matches the filter criteria</returns>
protected virtual bool MatchDescendant(ITest test)
{
if (test.Tests == null)
return false;
foreach (ITest child in test.Tests)
{
if (Match(child) || MatchDescendant(child))
return true;
}
return false;
}
/// <summary>
/// Create a TestFilter instance from an xml representation.
/// </summary>
public static TestFilter FromXml(string xmlText)
{
TNode topNode = TNode.FromXml(xmlText);
if (topNode.Name != "filter")
throw new Exception("Expected filter element at top level");
int count = topNode.ChildNodes.Count;
TestFilter filter = count == 0
? TestFilter.Empty
: count == 1
? FromXml(topNode.FirstChild)
: FromXml(topNode);
filter.TopLevel = true;
return filter;
}
/// <summary>
/// Create a TestFilter from it's TNode representation
/// </summary>
public static TestFilter FromXml(TNode node)
{
bool isRegex = node.Attributes["re"] == "1";
switch (node.Name)
{
case "filter":
case "and":
var andFilter = new AndFilter();
foreach (var childNode in node.ChildNodes)
andFilter.Add(FromXml(childNode));
return andFilter;
case "or":
var orFilter = new OrFilter();
foreach (var childNode in node.ChildNodes)
orFilter.Add(FromXml(childNode));
return orFilter;
case "not":
return new NotFilter(FromXml(node.FirstChild));
case "id":
return new IdFilter(node.Value);
case "test":
return new FullNameFilter(node.Value) { IsRegex = isRegex };
case "name":
return new TestNameFilter(node.Value) { IsRegex = isRegex };
case "method":
return new MethodNameFilter(node.Value) { IsRegex = isRegex };
case "class":
return new ClassNameFilter(node.Value) { IsRegex = isRegex };
case "namespace":
return new NamespaceFilter(node.Value) { IsRegex = isRegex };
case "cat":
return new CategoryFilter(node.Value) { IsRegex = isRegex };
case "prop":
string name = node.Attributes["name"];
if (name != null)
return new PropertyFilter(name, node.Value) { IsRegex = isRegex };
break;
}
throw new ArgumentException("Invalid filter element: " + node.Name, "xmlNode");
}
/// <summary>
/// Nested class provides an empty filter - one that always
/// returns true when called. It never matches explicitly.
/// </summary>
#if !PORTABLE && !NETSTANDARD1_6
[Serializable]
#endif
private class EmptyFilter : TestFilter
{
public override bool Match( ITest test )
{
return true;
}
public override bool Pass( ITest test )
{
return true;
}
public override bool IsExplicitMatch( ITest test )
{
return false;
}
public override TNode AddToXml(TNode parentNode, bool recursive)
{
return parentNode.AddElement("filter");
}
}
#region IXmlNodeBuilder Implementation
/// <summary>
/// Adds an XML node
/// </summary>
/// <param name="recursive">True if recursive</param>
/// <returns>The added XML node</returns>
public TNode ToXml(bool recursive)
{
return AddToXml(new TNode("dummy"), recursive);
}
/// <summary>
/// Adds an XML node
/// </summary>
/// <param name="parentNode">Parent node</param>
/// <param name="recursive">True if recursive</param>
/// <returns>The added XML node</returns>
public abstract TNode AddToXml(TNode parentNode, bool recursive);
#endregion
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using Microsoft.Xrm.Client.Configuration;
using Microsoft.Xrm.Client.Threading;
namespace Microsoft.Xrm.Client.Caching
{
/// <summary>
/// Provides <see cref="ObjectCache"/> operations.
/// </summary>
public class ObjectCacheProvider
{
/// <summary>
/// Retrieves a configured <see cref="ObjectCache"/>.
/// </summary>
/// <param name="objectCacheName"></param>
/// <returns></returns>
public virtual ObjectCache GetInstance(string objectCacheName = null)
{
return CrmConfigurationManager.CreateObjectCache(objectCacheName);
}
/// <summary>
/// Builds a <see cref="CacheItemPolicy"/> from a configuration element.
/// </summary>
/// <param name="objectCacheName"></param>
/// <returns></returns>
public virtual CacheItemPolicy GetCacheItemPolicy(string objectCacheName = null)
{
return CrmConfigurationManager.CreateCacheItemPolicy(objectCacheName, true);
}
/// <summary>
/// Builds a <see cref="CacheItemPolicy"/> from a configuration element and adds a single <see cref="ChangeMonitor"/> to the policy.
/// </summary>
/// <param name="monitor"></param>
/// <param name="objectCacheName"></param>
/// <returns></returns>
public virtual CacheItemPolicy GetCacheItemPolicy(ChangeMonitor monitor, string objectCacheName = null)
{
var policy = GetCacheItemPolicy(objectCacheName);
if (monitor != null) policy.ChangeMonitors.Add(monitor);
return policy;
}
/// <summary>
/// Builds a <see cref="CacheItemPolicy"/> from a configuration element and adds a set of <see cref="CacheEntryChangeMonitor"/> objects.
/// </summary>
/// <param name="dependencies"></param>
/// <param name="regionName"></param>
/// <param name="objectCacheName"></param>
/// <returns></returns>
public virtual CacheItemPolicy GetCacheItemPolicy(IEnumerable<string> dependencies, string regionName = null, string objectCacheName = null)
{
var cache = GetInstance(objectCacheName);
var monitorKeys = dependencies.Select(d => d.ToLower());
var monitor = GetChangeMonitor(cache, monitorKeys, regionName);
return GetCacheItemPolicy(monitor, objectCacheName);
}
/// <summary>
/// Builds a <see cref="CacheItemPolicy"/> and adds a set of <see cref="CacheEntryChangeMonitor"/> objects to the policy.
/// </summary>
/// <param name="cache"></param>
/// <param name="dependencies"></param>
/// <param name="regionName"></param>
/// <param name="objectCacheName"></param>
/// <returns></returns>
public virtual CacheItemPolicy GetCacheItemPolicy(ObjectCache cache, IEnumerable<string> dependencies, string regionName = null, string objectCacheName = null)
{
var monitorKeys = dependencies.Select(d => d.ToLower());
var monitor = GetChangeMonitor(cache, monitorKeys, regionName);
return GetCacheItemPolicy(monitor, cache.Name);
}
/// <summary>
/// Builds a <see cref="CacheEntryChangeMonitor"/> from a set of cache keys.
/// </summary>
/// <param name="cache"></param>
/// <param name="monitorKeys"></param>
/// <param name="regionName"></param>
/// <returns></returns>
public virtual CacheEntryChangeMonitor GetChangeMonitor(ObjectCache cache, IEnumerable<string> monitorKeys, string regionName)
{
if (!monitorKeys.Any()) return null;
// cache item dependencies need to be added to the cache prior to calling CreateCacheEntryChangeMonitor
foreach (var key in monitorKeys)
{
cache.AddOrGetExisting(key, key, ObjectCache.InfiniteAbsoluteExpiration, regionName);
}
return cache.CreateCacheEntryChangeMonitor(monitorKeys);
}
/// <summary>
/// Retrieves a cached object or loads the object if it does not exist in cache.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cache"></param>
/// <param name="cacheKey"></param>
/// <param name="load"></param>
/// <param name="insert"></param>
/// <param name="regionName"></param>
/// <returns></returns>
public virtual T Get<T>(
ObjectCache cache,
string cacheKey,
Func<ObjectCache, T> load,
Action<ObjectCache, T> insert,
string regionName = null)
{
return LockManager.Get(
cacheKey,
// try to load from cache
key => this.GetCacheItemValue(cache, key.ToLower(), regionName),
key =>
{
// load object from the service
var obj = load(cache);
if (insert != null)
{
// insert object into cache
insert(cache, obj);
}
return obj;
});
}
/// <summary>
/// Retrieves the cache item from cache, and returns value.
/// </summary>
/// <param name="cache">The cache.</param>
/// <param name="key">The cache key.</param>
/// <param name="regionName">The regionName.</param>
/// <returns></returns>
private object GetCacheItemValue(ObjectCache cache, string key, string regionName)
{
var obj = cache.Get(key.ToLower(), regionName);
var container = obj as CacheItemContainer;
if (container != null)
{
return container.Value;
}
return obj;
}
/// <summary>
/// Inserts an object into cache along with an associated <see cref="CacheItemDetail"/>.
/// </summary>
/// <param name="cache"></param>
/// <param name="cacheKey"></param>
/// <param name="value"></param>
/// <param name="policy"></param>
/// <param name="regionName"></param>
public virtual void Insert(
ObjectCache cache,
string cacheKey,
object value,
CacheItemPolicy policy = null,
string regionName = null)
{
var valueCacheKey = cacheKey.ToLower();
// Create the cache value container - which contains the actual cache value and the cache item detail.
var container = new CacheItemContainer(value, this.CreateCacheItemDetailObject(cache, cacheKey, policy, regionName));
// Insert into cache.
cache.Set(valueCacheKey, container, policy, regionName);
}
/// <summary>
/// Create the <see cref="CacheItemDetail"/> associated with a cache item.
/// </summary>
/// <param name="cache">The cache</param>
/// <param name="cacheKey">Cache item's key.</param>
/// <param name="policy">Cache item's policy.</param>
/// <param name="regionName">Region name.</param>
/// <returns>Returns new instance of <see cref="CacheItemDetail"/></returns>
public CacheItemDetail CreateCacheItemDetailObject(ObjectCache cache, string cacheKey, CacheItemPolicy policy, string regionName)
{
// Create CacheItemDetail
var cacheItemDetail = new CacheItemDetail(cacheKey, policy);
var cacheItemDetailPolicy = new CacheItemPolicy();
// CacheItemDetail should be dependent on its related cache item
cacheItemDetailPolicy.ChangeMonitors.Add(cache.CreateCacheEntryChangeMonitor(new[] { cacheKey }, regionName));
return cacheItemDetail;
}
/// <summary>
/// Retrieves the associated <see cref="CacheItemDetail"/> for a cache item.
/// </summary>
/// <param name="cache">The cache</param>
/// <param name="cacheKey">Cache item's key.</param>
/// <param name="regionName">Region name.</param>
/// <returns></returns>
public virtual CacheItemDetail GetCacheItemDetail(ObjectCache cache, string cacheKey, string regionName = null)
{
return (cache.Get(cacheKey.ToLower(), regionName) as CacheItemContainer)?.Detail;
}
/// <summary>
/// Removes all items from the cache.
/// </summary>
/// <param name="cache"></param>
public virtual void Clear(ObjectCache cache)
{
var items = cache.ToList();
foreach (var item in items)
{
cache.Remove(item.Key);
}
}
/// <summary>
/// Removes all items from the cache by invoking the <see cref="IExtendedObjectCache"/> if it is available.
/// </summary>
/// <param name="cache"></param>
/// <param name="regionName"></param>
public virtual void RemoveAll(ObjectCache cache, string regionName = null)
{
var extended = cache as IExtendedObjectCache;
if (extended != null)
{
extended.RemoveAll(regionName);
}
else
{
cache.Clear();
}
}
}
}
| |
// Copyright 2016 Serilog Contributors
//
// 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.Globalization;
using System.IO;
using Serilog.Data;
using Serilog.Events;
namespace Serilog.Formatting.Json
{
/// <summary>
/// Converts Serilog's structured property value format into JSON.
/// </summary>
public class JsonValueFormatter : LogEventPropertyValueVisitor<TextWriter, bool>
{
readonly string _typeTagName;
const string DefaultTypeTagName = "_typeTag";
/// <summary>
/// Construct a <see cref="JsonFormatter"/>.
/// </summary>
/// <param name="typeTagName">When serializing structured (object) values,
/// the property name to use for the Serilog <see cref="StructureValue.TypeTag"/> field
/// in the resulting JSON. If null, no type tag field will be written. The default is
/// "_typeTag".</param>
public JsonValueFormatter(string typeTagName = DefaultTypeTagName)
{
_typeTagName = typeTagName;
}
/// <summary>
/// Format <paramref name="value"/> as JSON to <paramref name="output"/>.
/// </summary>
/// <param name="value">The value to format</param>
/// <param name="output">The output</param>
public void Format(LogEventPropertyValue value, TextWriter output)
{
// Parameter order of ITextFormatter is the reverse of the visitor one.
// In this class, public methods and methods with Format*() names use the
// (x, output) parameter naming convention.
Visit(output, value);
}
/// <summary>
/// Visit a <see cref="ScalarValue"/> value.
/// </summary>
/// <param name="state">Operation state.</param>
/// <param name="scalar">The value to visit.</param>
/// <returns>The result of visiting <paramref name="scalar"/>.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="scalar"/> is <code>null</code></exception>
protected override bool VisitScalarValue(TextWriter state, ScalarValue scalar)
{
if (scalar == null) throw new ArgumentNullException(nameof(scalar));
FormatLiteralValue(scalar.Value, state);
return false;
}
/// <summary>
/// Visit a <see cref="SequenceValue"/> value.
/// </summary>
/// <param name="state">Operation state.</param>
/// <param name="sequence">The value to visit.</param>
/// <returns>The result of visiting <paramref name="sequence"/>.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="sequence"/> is <code>null</code></exception>
protected override bool VisitSequenceValue(TextWriter state, SequenceValue sequence)
{
if (sequence == null) throw new ArgumentNullException(nameof(sequence));
state.Write('[');
var delim = "";
for (var i = 0; i < sequence.Elements.Count; i++)
{
state.Write(delim);
delim = ",";
Visit(state, sequence.Elements[i]);
}
state.Write(']');
return false;
}
/// <summary>
/// Visit a <see cref="StructureValue"/> value.
/// </summary>
/// <param name="state">Operation state.</param>
/// <param name="structure">The value to visit.</param>
/// <returns>The result of visiting <paramref name="structure"/>.</returns>
protected override bool VisitStructureValue(TextWriter state, StructureValue structure)
{
state.Write('{');
var delim = "";
for (var i = 0; i < structure.Properties.Count; i++)
{
state.Write(delim);
delim = ",";
var prop = structure.Properties[i];
WriteQuotedJsonString(prop.Name, state);
state.Write(':');
Visit(state, prop.Value);
}
if (_typeTagName != null && structure.TypeTag != null)
{
state.Write(delim);
WriteQuotedJsonString(_typeTagName, state);
state.Write(':');
WriteQuotedJsonString(structure.TypeTag, state);
}
state.Write('}');
return false;
}
/// <summary>
/// Visit a <see cref="DictionaryValue"/> value.
/// </summary>
/// <param name="state">Operation state.</param>
/// <param name="dictionary">The value to visit.</param>
/// <returns>The result of visiting <paramref name="dictionary"/>.</returns>
protected override bool VisitDictionaryValue(TextWriter state, DictionaryValue dictionary)
{
state.Write('{');
var delim = "";
foreach (var element in dictionary.Elements)
{
state.Write(delim);
delim = ",";
WriteQuotedJsonString((element.Key.Value ?? "null").ToString(), state);
state.Write(':');
Visit(state, element.Value);
}
state.Write('}');
return false;
}
/// <summary>
/// Write a literal as a single JSON value, e.g. as a number or string. Override to
/// support more value types. Don't write arrays/structures through this method - the
/// active destructuring policies have already indicated the value should be scalar at
/// this point.
/// </summary>
/// <param name="value">The value to write.</param>
/// <param name="output">The output</param>
protected virtual void FormatLiteralValue(object value, TextWriter output)
{
if (value == null)
{
FormatNullValue(output);
return;
}
// Although the linear switch-on-type has apparently worse algorithmic performance than the O(1)
// dictionary lookup alternative, in practice, it's much to make a few equality comparisons
// than the hash/bucket dictionary lookup, and since most data will be string (one comparison),
// numeric (a handful) or an object (two comparisons) the real-world performance of the code
// as written is as fast or faster.
if (value is string str)
{
FormatStringValue(str, output);
return;
}
if (value is ValueType)
{
if (value is int or uint or long or ulong or decimal or byte or sbyte or short or ushort)
{
FormatExactNumericValue((IFormattable)value, output);
return;
}
if (value is double d)
{
FormatDoubleValue(d, output);
return;
}
if (value is float f)
{
FormatFloatValue(f, output);
return;
}
if (value is bool b)
{
FormatBooleanValue(b, output);
return;
}
if (value is char)
{
FormatStringValue(value.ToString(), output);
return;
}
if (value is DateTime or DateTimeOffset)
{
FormatDateTimeValue((IFormattable)value, output);
return;
}
if (value is TimeSpan timeSpan)
{
FormatTimeSpanValue(timeSpan, output);
return;
}
}
FormatLiteralObjectValue(value, output);
}
static void FormatBooleanValue(bool value, TextWriter output)
{
output.Write(value ? "true" : "false");
}
static void FormatFloatValue(float value, TextWriter output)
{
if (float.IsNaN(value) || float.IsInfinity(value))
{
FormatStringValue(value.ToString(CultureInfo.InvariantCulture), output);
return;
}
output.Write(value.ToString("R", CultureInfo.InvariantCulture));
}
static void FormatDoubleValue(double value, TextWriter output)
{
if (double.IsNaN(value) || double.IsInfinity(value))
{
FormatStringValue(value.ToString(CultureInfo.InvariantCulture), output);
return;
}
output.Write(value.ToString("R", CultureInfo.InvariantCulture));
}
static void FormatExactNumericValue(IFormattable value, TextWriter output)
{
output.Write(value.ToString(null, CultureInfo.InvariantCulture));
}
static void FormatDateTimeValue(IFormattable value, TextWriter output)
{
output.Write('\"');
output.Write(value.ToString("O", CultureInfo.InvariantCulture));
output.Write('\"');
}
static void FormatTimeSpanValue(TimeSpan value, TextWriter output)
{
output.Write('\"');
output.Write(value.ToString());
output.Write('\"');
}
static void FormatLiteralObjectValue(object value, TextWriter output)
{
if (value == null) throw new ArgumentNullException(nameof(value));
FormatStringValue(value.ToString() ?? "", output);
}
static void FormatStringValue(string str, TextWriter output)
{
WriteQuotedJsonString(str, output);
}
static void FormatNullValue(TextWriter output)
{
output.Write("null");
}
/// <summary>
/// Write a valid JSON string literal, escaping as necessary.
/// </summary>
/// <param name="str">The string value to write.</param>
/// <param name="output">The output.</param>
public static void WriteQuotedJsonString(string str, TextWriter output)
{
output.Write('\"');
var cleanSegmentStart = 0;
var anyEscaped = false;
for (var i = 0; i < str.Length; ++i)
{
var c = str[i];
if (c is < (char)32 or '\\' or '"')
{
anyEscaped = true;
output.Write(str.Substring(cleanSegmentStart, i - cleanSegmentStart));
cleanSegmentStart = i + 1;
switch (c)
{
case '"':
{
output.Write("\\\"");
break;
}
case '\\':
{
output.Write("\\\\");
break;
}
case '\n':
{
output.Write("\\n");
break;
}
case '\r':
{
output.Write("\\r");
break;
}
case '\f':
{
output.Write("\\f");
break;
}
case '\t':
{
output.Write("\\t");
break;
}
default:
{
output.Write("\\u");
output.Write(((int)c).ToString("X4"));
break;
}
}
}
}
if (anyEscaped)
{
if (cleanSegmentStart != str.Length)
output.Write(str.Substring(cleanSegmentStart));
}
else
{
output.Write(str);
}
output.Write('\"');
}
}
}
| |
using System;
using System.Diagnostics;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Utilities;
namespace Org.BouncyCastle.Crypto.Engines
{
/**
* an implementation of the AES (Rijndael)), from FIPS-197.
* <p>
* For further details see: <a href="http://csrc.nist.gov/encryption/aes/">http://csrc.nist.gov/encryption/aes/</a>.
*
* This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at
* <a href="http://fp.gladman.plus.com/cryptography_technology/rijndael/">http://fp.gladman.plus.com/cryptography_technology/rijndael/</a>
*
* There are three levels of tradeoff of speed vs memory
* Because java has no preprocessor), they are written as three separate classes from which to choose
*
* The fastest uses 8Kbytes of static tables to precompute round calculations), 4 256 word tables for encryption
* and 4 for decryption.
*
* The middle performance version uses only one 256 word table for each), for a total of 2Kbytes),
* adding 12 rotate operations per round to compute the values contained in the other tables from
* the contents of the first
*
* The slowest version uses no static tables at all and computes the values in each round
* </p>
* <p>
* This file contains the fast version with 8Kbytes of static tables for round precomputation
* </p>
*/
public class AesFastEngine
: IBlockCipher
{
// The S box
private static readonly byte[] S =
{
99, 124, 119, 123, 242, 107, 111, 197,
48, 1, 103, 43, 254, 215, 171, 118,
202, 130, 201, 125, 250, 89, 71, 240,
173, 212, 162, 175, 156, 164, 114, 192,
183, 253, 147, 38, 54, 63, 247, 204,
52, 165, 229, 241, 113, 216, 49, 21,
4, 199, 35, 195, 24, 150, 5, 154,
7, 18, 128, 226, 235, 39, 178, 117,
9, 131, 44, 26, 27, 110, 90, 160,
82, 59, 214, 179, 41, 227, 47, 132,
83, 209, 0, 237, 32, 252, 177, 91,
106, 203, 190, 57, 74, 76, 88, 207,
208, 239, 170, 251, 67, 77, 51, 133,
69, 249, 2, 127, 80, 60, 159, 168,
81, 163, 64, 143, 146, 157, 56, 245,
188, 182, 218, 33, 16, 255, 243, 210,
205, 12, 19, 236, 95, 151, 68, 23,
196, 167, 126, 61, 100, 93, 25, 115,
96, 129, 79, 220, 34, 42, 144, 136,
70, 238, 184, 20, 222, 94, 11, 219,
224, 50, 58, 10, 73, 6, 36, 92,
194, 211, 172, 98, 145, 149, 228, 121,
231, 200, 55, 109, 141, 213, 78, 169,
108, 86, 244, 234, 101, 122, 174, 8,
186, 120, 37, 46, 28, 166, 180, 198,
232, 221, 116, 31, 75, 189, 139, 138,
112, 62, 181, 102, 72, 3, 246, 14,
97, 53, 87, 185, 134, 193, 29, 158,
225, 248, 152, 17, 105, 217, 142, 148,
155, 30, 135, 233, 206, 85, 40, 223,
140, 161, 137, 13, 191, 230, 66, 104,
65, 153, 45, 15, 176, 84, 187, 22,
};
// The inverse S-box
private static readonly byte[] Si =
{
82, 9, 106, 213, 48, 54, 165, 56,
191, 64, 163, 158, 129, 243, 215, 251,
124, 227, 57, 130, 155, 47, 255, 135,
52, 142, 67, 68, 196, 222, 233, 203,
84, 123, 148, 50, 166, 194, 35, 61,
238, 76, 149, 11, 66, 250, 195, 78,
8, 46, 161, 102, 40, 217, 36, 178,
118, 91, 162, 73, 109, 139, 209, 37,
114, 248, 246, 100, 134, 104, 152, 22,
212, 164, 92, 204, 93, 101, 182, 146,
108, 112, 72, 80, 253, 237, 185, 218,
94, 21, 70, 87, 167, 141, 157, 132,
144, 216, 171, 0, 140, 188, 211, 10,
247, 228, 88, 5, 184, 179, 69, 6,
208, 44, 30, 143, 202, 63, 15, 2,
193, 175, 189, 3, 1, 19, 138, 107,
58, 145, 17, 65, 79, 103, 220, 234,
151, 242, 207, 206, 240, 180, 230, 115,
150, 172, 116, 34, 231, 173, 53, 133,
226, 249, 55, 232, 28, 117, 223, 110,
71, 241, 26, 113, 29, 41, 197, 137,
111, 183, 98, 14, 170, 24, 190, 27,
252, 86, 62, 75, 198, 210, 121, 32,
154, 219, 192, 254, 120, 205, 90, 244,
31, 221, 168, 51, 136, 7, 199, 49,
177, 18, 16, 89, 39, 128, 236, 95,
96, 81, 127, 169, 25, 181, 74, 13,
45, 229, 122, 159, 147, 201, 156, 239,
160, 224, 59, 77, 174, 42, 245, 176,
200, 235, 187, 60, 131, 83, 153, 97,
23, 43, 4, 126, 186, 119, 214, 38,
225, 105, 20, 99, 85, 33, 12, 125,
};
// vector used in calculating key schedule (powers of x in GF(256))
private static readonly byte[] rcon =
{
0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91
};
// precomputation tables of calculations for rounds
private static readonly uint[] T0 =
{
0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff,
0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x03010102,
0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d,
0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa,
0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, 0xecadad41,
0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453,
0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d,
0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83,
0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2,
0x73d8d8ab, 0x53313162, 0x3f15152a, 0x0c040408, 0x52c7c795,
0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a,
0xb59a9a2f, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df,
0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912,
0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc,
0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7,
0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413,
0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040,
0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d,
0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0,
0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed,
0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a,
0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78,
0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080,
0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1,
0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020,
0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18,
0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488,
0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a,
0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0,
0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54,
0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b,
0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad,
0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992,
0x0a06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd,
0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3,
0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda,
0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8,
0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4,
0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a,
0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697,
0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96,
0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c,
0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7,
0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969,
0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9,
0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9,
0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715,
0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5,
0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65,
0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929,
0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d,
0x3a16162c
};
private static readonly uint[] T1 =
{
0x6363c6a5, 0x7c7cf884, 0x7777ee99, 0x7b7bf68d, 0xf2f2ff0d,
0x6b6bd6bd, 0x6f6fdeb1, 0xc5c59154, 0x30306050, 0x01010203,
0x6767cea9, 0x2b2b567d, 0xfefee719, 0xd7d7b562, 0xabab4de6,
0x7676ec9a, 0xcaca8f45, 0x82821f9d, 0xc9c98940, 0x7d7dfa87,
0xfafaef15, 0x5959b2eb, 0x47478ec9, 0xf0f0fb0b, 0xadad41ec,
0xd4d4b367, 0xa2a25ffd, 0xafaf45ea, 0x9c9c23bf, 0xa4a453f7,
0x7272e496, 0xc0c09b5b, 0xb7b775c2, 0xfdfde11c, 0x93933dae,
0x26264c6a, 0x36366c5a, 0x3f3f7e41, 0xf7f7f502, 0xcccc834f,
0x3434685c, 0xa5a551f4, 0xe5e5d134, 0xf1f1f908, 0x7171e293,
0xd8d8ab73, 0x31316253, 0x15152a3f, 0x0404080c, 0xc7c79552,
0x23234665, 0xc3c39d5e, 0x18183028, 0x969637a1, 0x05050a0f,
0x9a9a2fb5, 0x07070e09, 0x12122436, 0x80801b9b, 0xe2e2df3d,
0xebebcd26, 0x27274e69, 0xb2b27fcd, 0x7575ea9f, 0x0909121b,
0x83831d9e, 0x2c2c5874, 0x1a1a342e, 0x1b1b362d, 0x6e6edcb2,
0x5a5ab4ee, 0xa0a05bfb, 0x5252a4f6, 0x3b3b764d, 0xd6d6b761,
0xb3b37dce, 0x2929527b, 0xe3e3dd3e, 0x2f2f5e71, 0x84841397,
0x5353a6f5, 0xd1d1b968, 0x00000000, 0xededc12c, 0x20204060,
0xfcfce31f, 0xb1b179c8, 0x5b5bb6ed, 0x6a6ad4be, 0xcbcb8d46,
0xbebe67d9, 0x3939724b, 0x4a4a94de, 0x4c4c98d4, 0x5858b0e8,
0xcfcf854a, 0xd0d0bb6b, 0xefefc52a, 0xaaaa4fe5, 0xfbfbed16,
0x434386c5, 0x4d4d9ad7, 0x33336655, 0x85851194, 0x45458acf,
0xf9f9e910, 0x02020406, 0x7f7ffe81, 0x5050a0f0, 0x3c3c7844,
0x9f9f25ba, 0xa8a84be3, 0x5151a2f3, 0xa3a35dfe, 0x404080c0,
0x8f8f058a, 0x92923fad, 0x9d9d21bc, 0x38387048, 0xf5f5f104,
0xbcbc63df, 0xb6b677c1, 0xdadaaf75, 0x21214263, 0x10102030,
0xffffe51a, 0xf3f3fd0e, 0xd2d2bf6d, 0xcdcd814c, 0x0c0c1814,
0x13132635, 0xececc32f, 0x5f5fbee1, 0x979735a2, 0x444488cc,
0x17172e39, 0xc4c49357, 0xa7a755f2, 0x7e7efc82, 0x3d3d7a47,
0x6464c8ac, 0x5d5dbae7, 0x1919322b, 0x7373e695, 0x6060c0a0,
0x81811998, 0x4f4f9ed1, 0xdcdca37f, 0x22224466, 0x2a2a547e,
0x90903bab, 0x88880b83, 0x46468cca, 0xeeeec729, 0xb8b86bd3,
0x1414283c, 0xdedea779, 0x5e5ebce2, 0x0b0b161d, 0xdbdbad76,
0xe0e0db3b, 0x32326456, 0x3a3a744e, 0x0a0a141e, 0x494992db,
0x06060c0a, 0x2424486c, 0x5c5cb8e4, 0xc2c29f5d, 0xd3d3bd6e,
0xacac43ef, 0x6262c4a6, 0x919139a8, 0x959531a4, 0xe4e4d337,
0x7979f28b, 0xe7e7d532, 0xc8c88b43, 0x37376e59, 0x6d6ddab7,
0x8d8d018c, 0xd5d5b164, 0x4e4e9cd2, 0xa9a949e0, 0x6c6cd8b4,
0x5656acfa, 0xf4f4f307, 0xeaeacf25, 0x6565caaf, 0x7a7af48e,
0xaeae47e9, 0x08081018, 0xbaba6fd5, 0x7878f088, 0x25254a6f,
0x2e2e5c72, 0x1c1c3824, 0xa6a657f1, 0xb4b473c7, 0xc6c69751,
0xe8e8cb23, 0xdddda17c, 0x7474e89c, 0x1f1f3e21, 0x4b4b96dd,
0xbdbd61dc, 0x8b8b0d86, 0x8a8a0f85, 0x7070e090, 0x3e3e7c42,
0xb5b571c4, 0x6666ccaa, 0x484890d8, 0x03030605, 0xf6f6f701,
0x0e0e1c12, 0x6161c2a3, 0x35356a5f, 0x5757aef9, 0xb9b969d0,
0x86861791, 0xc1c19958, 0x1d1d3a27, 0x9e9e27b9, 0xe1e1d938,
0xf8f8eb13, 0x98982bb3, 0x11112233, 0x6969d2bb, 0xd9d9a970,
0x8e8e0789, 0x949433a7, 0x9b9b2db6, 0x1e1e3c22, 0x87871592,
0xe9e9c920, 0xcece8749, 0x5555aaff, 0x28285078, 0xdfdfa57a,
0x8c8c038f, 0xa1a159f8, 0x89890980, 0x0d0d1a17, 0xbfbf65da,
0xe6e6d731, 0x424284c6, 0x6868d0b8, 0x414182c3, 0x999929b0,
0x2d2d5a77, 0x0f0f1e11, 0xb0b07bcb, 0x5454a8fc, 0xbbbb6dd6,
0x16162c3a
};
private static readonly uint[] T2 =
{
0x63c6a563, 0x7cf8847c, 0x77ee9977, 0x7bf68d7b, 0xf2ff0df2,
0x6bd6bd6b, 0x6fdeb16f, 0xc59154c5, 0x30605030, 0x01020301,
0x67cea967, 0x2b567d2b, 0xfee719fe, 0xd7b562d7, 0xab4de6ab,
0x76ec9a76, 0xca8f45ca, 0x821f9d82, 0xc98940c9, 0x7dfa877d,
0xfaef15fa, 0x59b2eb59, 0x478ec947, 0xf0fb0bf0, 0xad41ecad,
0xd4b367d4, 0xa25ffda2, 0xaf45eaaf, 0x9c23bf9c, 0xa453f7a4,
0x72e49672, 0xc09b5bc0, 0xb775c2b7, 0xfde11cfd, 0x933dae93,
0x264c6a26, 0x366c5a36, 0x3f7e413f, 0xf7f502f7, 0xcc834fcc,
0x34685c34, 0xa551f4a5, 0xe5d134e5, 0xf1f908f1, 0x71e29371,
0xd8ab73d8, 0x31625331, 0x152a3f15, 0x04080c04, 0xc79552c7,
0x23466523, 0xc39d5ec3, 0x18302818, 0x9637a196, 0x050a0f05,
0x9a2fb59a, 0x070e0907, 0x12243612, 0x801b9b80, 0xe2df3de2,
0xebcd26eb, 0x274e6927, 0xb27fcdb2, 0x75ea9f75, 0x09121b09,
0x831d9e83, 0x2c58742c, 0x1a342e1a, 0x1b362d1b, 0x6edcb26e,
0x5ab4ee5a, 0xa05bfba0, 0x52a4f652, 0x3b764d3b, 0xd6b761d6,
0xb37dceb3, 0x29527b29, 0xe3dd3ee3, 0x2f5e712f, 0x84139784,
0x53a6f553, 0xd1b968d1, 0x00000000, 0xedc12ced, 0x20406020,
0xfce31ffc, 0xb179c8b1, 0x5bb6ed5b, 0x6ad4be6a, 0xcb8d46cb,
0xbe67d9be, 0x39724b39, 0x4a94de4a, 0x4c98d44c, 0x58b0e858,
0xcf854acf, 0xd0bb6bd0, 0xefc52aef, 0xaa4fe5aa, 0xfbed16fb,
0x4386c543, 0x4d9ad74d, 0x33665533, 0x85119485, 0x458acf45,
0xf9e910f9, 0x02040602, 0x7ffe817f, 0x50a0f050, 0x3c78443c,
0x9f25ba9f, 0xa84be3a8, 0x51a2f351, 0xa35dfea3, 0x4080c040,
0x8f058a8f, 0x923fad92, 0x9d21bc9d, 0x38704838, 0xf5f104f5,
0xbc63dfbc, 0xb677c1b6, 0xdaaf75da, 0x21426321, 0x10203010,
0xffe51aff, 0xf3fd0ef3, 0xd2bf6dd2, 0xcd814ccd, 0x0c18140c,
0x13263513, 0xecc32fec, 0x5fbee15f, 0x9735a297, 0x4488cc44,
0x172e3917, 0xc49357c4, 0xa755f2a7, 0x7efc827e, 0x3d7a473d,
0x64c8ac64, 0x5dbae75d, 0x19322b19, 0x73e69573, 0x60c0a060,
0x81199881, 0x4f9ed14f, 0xdca37fdc, 0x22446622, 0x2a547e2a,
0x903bab90, 0x880b8388, 0x468cca46, 0xeec729ee, 0xb86bd3b8,
0x14283c14, 0xdea779de, 0x5ebce25e, 0x0b161d0b, 0xdbad76db,
0xe0db3be0, 0x32645632, 0x3a744e3a, 0x0a141e0a, 0x4992db49,
0x060c0a06, 0x24486c24, 0x5cb8e45c, 0xc29f5dc2, 0xd3bd6ed3,
0xac43efac, 0x62c4a662, 0x9139a891, 0x9531a495, 0xe4d337e4,
0x79f28b79, 0xe7d532e7, 0xc88b43c8, 0x376e5937, 0x6ddab76d,
0x8d018c8d, 0xd5b164d5, 0x4e9cd24e, 0xa949e0a9, 0x6cd8b46c,
0x56acfa56, 0xf4f307f4, 0xeacf25ea, 0x65caaf65, 0x7af48e7a,
0xae47e9ae, 0x08101808, 0xba6fd5ba, 0x78f08878, 0x254a6f25,
0x2e5c722e, 0x1c38241c, 0xa657f1a6, 0xb473c7b4, 0xc69751c6,
0xe8cb23e8, 0xdda17cdd, 0x74e89c74, 0x1f3e211f, 0x4b96dd4b,
0xbd61dcbd, 0x8b0d868b, 0x8a0f858a, 0x70e09070, 0x3e7c423e,
0xb571c4b5, 0x66ccaa66, 0x4890d848, 0x03060503, 0xf6f701f6,
0x0e1c120e, 0x61c2a361, 0x356a5f35, 0x57aef957, 0xb969d0b9,
0x86179186, 0xc19958c1, 0x1d3a271d, 0x9e27b99e, 0xe1d938e1,
0xf8eb13f8, 0x982bb398, 0x11223311, 0x69d2bb69, 0xd9a970d9,
0x8e07898e, 0x9433a794, 0x9b2db69b, 0x1e3c221e, 0x87159287,
0xe9c920e9, 0xce8749ce, 0x55aaff55, 0x28507828, 0xdfa57adf,
0x8c038f8c, 0xa159f8a1, 0x89098089, 0x0d1a170d, 0xbf65dabf,
0xe6d731e6, 0x4284c642, 0x68d0b868, 0x4182c341, 0x9929b099,
0x2d5a772d, 0x0f1e110f, 0xb07bcbb0, 0x54a8fc54, 0xbb6dd6bb,
0x162c3a16
};
private static readonly uint[] T3 =
{
0xc6a56363, 0xf8847c7c, 0xee997777, 0xf68d7b7b, 0xff0df2f2,
0xd6bd6b6b, 0xdeb16f6f, 0x9154c5c5, 0x60503030, 0x02030101,
0xcea96767, 0x567d2b2b, 0xe719fefe, 0xb562d7d7, 0x4de6abab,
0xec9a7676, 0x8f45caca, 0x1f9d8282, 0x8940c9c9, 0xfa877d7d,
0xef15fafa, 0xb2eb5959, 0x8ec94747, 0xfb0bf0f0, 0x41ecadad,
0xb367d4d4, 0x5ffda2a2, 0x45eaafaf, 0x23bf9c9c, 0x53f7a4a4,
0xe4967272, 0x9b5bc0c0, 0x75c2b7b7, 0xe11cfdfd, 0x3dae9393,
0x4c6a2626, 0x6c5a3636, 0x7e413f3f, 0xf502f7f7, 0x834fcccc,
0x685c3434, 0x51f4a5a5, 0xd134e5e5, 0xf908f1f1, 0xe2937171,
0xab73d8d8, 0x62533131, 0x2a3f1515, 0x080c0404, 0x9552c7c7,
0x46652323, 0x9d5ec3c3, 0x30281818, 0x37a19696, 0x0a0f0505,
0x2fb59a9a, 0x0e090707, 0x24361212, 0x1b9b8080, 0xdf3de2e2,
0xcd26ebeb, 0x4e692727, 0x7fcdb2b2, 0xea9f7575, 0x121b0909,
0x1d9e8383, 0x58742c2c, 0x342e1a1a, 0x362d1b1b, 0xdcb26e6e,
0xb4ee5a5a, 0x5bfba0a0, 0xa4f65252, 0x764d3b3b, 0xb761d6d6,
0x7dceb3b3, 0x527b2929, 0xdd3ee3e3, 0x5e712f2f, 0x13978484,
0xa6f55353, 0xb968d1d1, 0x00000000, 0xc12ceded, 0x40602020,
0xe31ffcfc, 0x79c8b1b1, 0xb6ed5b5b, 0xd4be6a6a, 0x8d46cbcb,
0x67d9bebe, 0x724b3939, 0x94de4a4a, 0x98d44c4c, 0xb0e85858,
0x854acfcf, 0xbb6bd0d0, 0xc52aefef, 0x4fe5aaaa, 0xed16fbfb,
0x86c54343, 0x9ad74d4d, 0x66553333, 0x11948585, 0x8acf4545,
0xe910f9f9, 0x04060202, 0xfe817f7f, 0xa0f05050, 0x78443c3c,
0x25ba9f9f, 0x4be3a8a8, 0xa2f35151, 0x5dfea3a3, 0x80c04040,
0x058a8f8f, 0x3fad9292, 0x21bc9d9d, 0x70483838, 0xf104f5f5,
0x63dfbcbc, 0x77c1b6b6, 0xaf75dada, 0x42632121, 0x20301010,
0xe51affff, 0xfd0ef3f3, 0xbf6dd2d2, 0x814ccdcd, 0x18140c0c,
0x26351313, 0xc32fecec, 0xbee15f5f, 0x35a29797, 0x88cc4444,
0x2e391717, 0x9357c4c4, 0x55f2a7a7, 0xfc827e7e, 0x7a473d3d,
0xc8ac6464, 0xbae75d5d, 0x322b1919, 0xe6957373, 0xc0a06060,
0x19988181, 0x9ed14f4f, 0xa37fdcdc, 0x44662222, 0x547e2a2a,
0x3bab9090, 0x0b838888, 0x8cca4646, 0xc729eeee, 0x6bd3b8b8,
0x283c1414, 0xa779dede, 0xbce25e5e, 0x161d0b0b, 0xad76dbdb,
0xdb3be0e0, 0x64563232, 0x744e3a3a, 0x141e0a0a, 0x92db4949,
0x0c0a0606, 0x486c2424, 0xb8e45c5c, 0x9f5dc2c2, 0xbd6ed3d3,
0x43efacac, 0xc4a66262, 0x39a89191, 0x31a49595, 0xd337e4e4,
0xf28b7979, 0xd532e7e7, 0x8b43c8c8, 0x6e593737, 0xdab76d6d,
0x018c8d8d, 0xb164d5d5, 0x9cd24e4e, 0x49e0a9a9, 0xd8b46c6c,
0xacfa5656, 0xf307f4f4, 0xcf25eaea, 0xcaaf6565, 0xf48e7a7a,
0x47e9aeae, 0x10180808, 0x6fd5baba, 0xf0887878, 0x4a6f2525,
0x5c722e2e, 0x38241c1c, 0x57f1a6a6, 0x73c7b4b4, 0x9751c6c6,
0xcb23e8e8, 0xa17cdddd, 0xe89c7474, 0x3e211f1f, 0x96dd4b4b,
0x61dcbdbd, 0x0d868b8b, 0x0f858a8a, 0xe0907070, 0x7c423e3e,
0x71c4b5b5, 0xccaa6666, 0x90d84848, 0x06050303, 0xf701f6f6,
0x1c120e0e, 0xc2a36161, 0x6a5f3535, 0xaef95757, 0x69d0b9b9,
0x17918686, 0x9958c1c1, 0x3a271d1d, 0x27b99e9e, 0xd938e1e1,
0xeb13f8f8, 0x2bb39898, 0x22331111, 0xd2bb6969, 0xa970d9d9,
0x07898e8e, 0x33a79494, 0x2db69b9b, 0x3c221e1e, 0x15928787,
0xc920e9e9, 0x8749cece, 0xaaff5555, 0x50782828, 0xa57adfdf,
0x038f8c8c, 0x59f8a1a1, 0x09808989, 0x1a170d0d, 0x65dabfbf,
0xd731e6e6, 0x84c64242, 0xd0b86868, 0x82c34141, 0x29b09999,
0x5a772d2d, 0x1e110f0f, 0x7bcbb0b0, 0xa8fc5454, 0x6dd6bbbb,
0x2c3a1616
};
private static readonly uint[] Tinv0 =
{
0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b,
0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad,
0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526,
0x8fa362b5, 0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d,
0x02752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03,
0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458,
0x2969e049, 0x44c8c98e, 0x6a89c275, 0x78798ef4, 0x6b3e5899,
0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d,
0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1,
0x84ae6bbb, 0x1ca081fe, 0x942b08f9, 0x58684870, 0x19fd458f,
0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3,
0x2aab5566, 0x0728ebb2, 0x03c2b52f, 0x9a7bc586, 0xa50837d3,
0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed, 0x2b1ccf8a,
0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506,
0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05,
0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x069f715e, 0x51106ebd,
0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491,
0x055dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6,
0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7,
0xdbeec879, 0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x00000000,
0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd,
0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68,
0xd1545b9b, 0x3a2e3624, 0xb1670a0c, 0x0fe75793, 0xd296eeb4,
0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c,
0x0aba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0x0b0d090e,
0xadc78bf2, 0xb9a8b62d, 0xc8a91e14, 0x8519f157, 0x4c0775af,
0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644,
0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8,
0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684, 0x7d244a85,
0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc,
0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411,
0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322,
0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6,
0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0x0d927850,
0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e,
0xf5afc382, 0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf,
0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x097826cd,
0xf418596e, 0x01b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa,
0x08cfbc21, 0xe6e815ef, 0xd99be7ba, 0xce366f4a, 0xd4099fea,
0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235,
0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1,
0xf7daec41, 0x0e50cd7f, 0x2ff69117, 0x8dd64d76, 0x4db0ef43,
0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1,
0x7f516546, 0x04ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb,
0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d, 0x8c61d79a,
0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7,
0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418,
0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478,
0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16,
0x0c25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08,
0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48,
0x4257b8d0
};
private static readonly uint[] Tinv1 =
{
0xa7f45150, 0x65417e53, 0xa4171ac3, 0x5e273a96, 0x6bab3bcb,
0x459d1ff1, 0x58faacab, 0x03e34b93, 0xfa302055, 0x6d76adf6,
0x76cc8891, 0x4c02f525, 0xd7e54ffc, 0xcb2ac5d7, 0x44352680,
0xa362b58f, 0x5ab1de49, 0x1bba2567, 0x0eea4598, 0xc0fe5de1,
0x752fc302, 0xf04c8112, 0x97468da3, 0xf9d36bc6, 0x5f8f03e7,
0x9c921595, 0x7a6dbfeb, 0x595295da, 0x83bed42d, 0x217458d3,
0x69e04929, 0xc8c98e44, 0x89c2756a, 0x798ef478, 0x3e58996b,
0x71b927dd, 0x4fe1beb6, 0xad88f017, 0xac20c966, 0x3ace7db4,
0x4adf6318, 0x311ae582, 0x33519760, 0x7f536245, 0x7764b1e0,
0xae6bbb84, 0xa081fe1c, 0x2b08f994, 0x68487058, 0xfd458f19,
0x6cde9487, 0xf87b52b7, 0xd373ab23, 0x024b72e2, 0x8f1fe357,
0xab55662a, 0x28ebb207, 0xc2b52f03, 0x7bc5869a, 0x0837d3a5,
0x872830f2, 0xa5bf23b2, 0x6a0302ba, 0x8216ed5c, 0x1ccf8a2b,
0xb479a792, 0xf207f3f0, 0xe2694ea1, 0xf4da65cd, 0xbe0506d5,
0x6234d11f, 0xfea6c48a, 0x532e349d, 0x55f3a2a0, 0xe18a0532,
0xebf6a475, 0xec830b39, 0xef6040aa, 0x9f715e06, 0x106ebd51,
0x8a213ef9, 0x06dd963d, 0x053eddae, 0xbde64d46, 0x8d5491b5,
0x5dc47105, 0xd406046f, 0x155060ff, 0xfb981924, 0xe9bdd697,
0x434089cc, 0x9ed96777, 0x42e8b0bd, 0x8b890788, 0x5b19e738,
0xeec879db, 0x0a7ca147, 0x0f427ce9, 0x1e84f8c9, 0x00000000,
0x86800983, 0xed2b3248, 0x70111eac, 0x725a6c4e, 0xff0efdfb,
0x38850f56, 0xd5ae3d1e, 0x392d3627, 0xd90f0a64, 0xa65c6821,
0x545b9bd1, 0x2e36243a, 0x670a0cb1, 0xe757930f, 0x96eeb4d2,
0x919b1b9e, 0xc5c0804f, 0x20dc61a2, 0x4b775a69, 0x1a121c16,
0xba93e20a, 0x2aa0c0e5, 0xe0223c43, 0x171b121d, 0x0d090e0b,
0xc78bf2ad, 0xa8b62db9, 0xa91e14c8, 0x19f15785, 0x0775af4c,
0xdd99eebb, 0x607fa3fd, 0x2601f79f, 0xf5725cbc, 0x3b6644c5,
0x7efb5b34, 0x29438b76, 0xc623cbdc, 0xfcedb668, 0xf1e4b863,
0xdc31d7ca, 0x85634210, 0x22971340, 0x11c68420, 0x244a857d,
0x3dbbd2f8, 0x32f9ae11, 0xa129c76d, 0x2f9e1d4b, 0x30b2dcf3,
0x52860dec, 0xe3c177d0, 0x16b32b6c, 0xb970a999, 0x489411fa,
0x64e94722, 0x8cfca8c4, 0x3ff0a01a, 0x2c7d56d8, 0x903322ef,
0x4e4987c7, 0xd138d9c1, 0xa2ca8cfe, 0x0bd49836, 0x81f5a6cf,
0xde7aa528, 0x8eb7da26, 0xbfad3fa4, 0x9d3a2ce4, 0x9278500d,
0xcc5f6a9b, 0x467e5462, 0x138df6c2, 0xb8d890e8, 0xf7392e5e,
0xafc382f5, 0x805d9fbe, 0x93d0697c, 0x2dd56fa9, 0x1225cfb3,
0x99acc83b, 0x7d1810a7, 0x639ce86e, 0xbb3bdb7b, 0x7826cd09,
0x18596ef4, 0xb79aec01, 0x9a4f83a8, 0x6e95e665, 0xe6ffaa7e,
0xcfbc2108, 0xe815efe6, 0x9be7bad9, 0x366f4ace, 0x099fead4,
0x7cb029d6, 0xb2a431af, 0x233f2a31, 0x94a5c630, 0x66a235c0,
0xbc4e7437, 0xca82fca6, 0xd090e0b0, 0xd8a73315, 0x9804f14a,
0xdaec41f7, 0x50cd7f0e, 0xf691172f, 0xd64d768d, 0xb0ef434d,
0x4daacc54, 0x0496e4df, 0xb5d19ee3, 0x886a4c1b, 0x1f2cc1b8,
0x5165467f, 0xea5e9d04, 0x358c015d, 0x7487fa73, 0x410bfb2e,
0x1d67b35a, 0xd2db9252, 0x5610e933, 0x47d66d13, 0x61d79a8c,
0x0ca1377a, 0x14f8598e, 0x3c13eb89, 0x27a9ceee, 0xc961b735,
0xe51ce1ed, 0xb1477a3c, 0xdfd29c59, 0x73f2553f, 0xce141879,
0x37c773bf, 0xcdf753ea, 0xaafd5f5b, 0x6f3ddf14, 0xdb447886,
0xf3afca81, 0xc468b93e, 0x3424382c, 0x40a3c25f, 0xc31d1672,
0x25e2bc0c, 0x493c288b, 0x950dff41, 0x01a83971, 0xb30c08de,
0xe4b4d89c, 0xc1566490, 0x84cb7b61, 0xb632d570, 0x5c6c4874,
0x57b8d042
};
private static readonly uint[] Tinv2 =
{
0xf45150a7, 0x417e5365, 0x171ac3a4, 0x273a965e, 0xab3bcb6b,
0x9d1ff145, 0xfaacab58, 0xe34b9303, 0x302055fa, 0x76adf66d,
0xcc889176, 0x02f5254c, 0xe54ffcd7, 0x2ac5d7cb, 0x35268044,
0x62b58fa3, 0xb1de495a, 0xba25671b, 0xea45980e, 0xfe5de1c0,
0x2fc30275, 0x4c8112f0, 0x468da397, 0xd36bc6f9, 0x8f03e75f,
0x9215959c, 0x6dbfeb7a, 0x5295da59, 0xbed42d83, 0x7458d321,
0xe0492969, 0xc98e44c8, 0xc2756a89, 0x8ef47879, 0x58996b3e,
0xb927dd71, 0xe1beb64f, 0x88f017ad, 0x20c966ac, 0xce7db43a,
0xdf63184a, 0x1ae58231, 0x51976033, 0x5362457f, 0x64b1e077,
0x6bbb84ae, 0x81fe1ca0, 0x08f9942b, 0x48705868, 0x458f19fd,
0xde94876c, 0x7b52b7f8, 0x73ab23d3, 0x4b72e202, 0x1fe3578f,
0x55662aab, 0xebb20728, 0xb52f03c2, 0xc5869a7b, 0x37d3a508,
0x2830f287, 0xbf23b2a5, 0x0302ba6a, 0x16ed5c82, 0xcf8a2b1c,
0x79a792b4, 0x07f3f0f2, 0x694ea1e2, 0xda65cdf4, 0x0506d5be,
0x34d11f62, 0xa6c48afe, 0x2e349d53, 0xf3a2a055, 0x8a0532e1,
0xf6a475eb, 0x830b39ec, 0x6040aaef, 0x715e069f, 0x6ebd5110,
0x213ef98a, 0xdd963d06, 0x3eddae05, 0xe64d46bd, 0x5491b58d,
0xc471055d, 0x06046fd4, 0x5060ff15, 0x981924fb, 0xbdd697e9,
0x4089cc43, 0xd967779e, 0xe8b0bd42, 0x8907888b, 0x19e7385b,
0xc879dbee, 0x7ca1470a, 0x427ce90f, 0x84f8c91e, 0x00000000,
0x80098386, 0x2b3248ed, 0x111eac70, 0x5a6c4e72, 0x0efdfbff,
0x850f5638, 0xae3d1ed5, 0x2d362739, 0x0f0a64d9, 0x5c6821a6,
0x5b9bd154, 0x36243a2e, 0x0a0cb167, 0x57930fe7, 0xeeb4d296,
0x9b1b9e91, 0xc0804fc5, 0xdc61a220, 0x775a694b, 0x121c161a,
0x93e20aba, 0xa0c0e52a, 0x223c43e0, 0x1b121d17, 0x090e0b0d,
0x8bf2adc7, 0xb62db9a8, 0x1e14c8a9, 0xf1578519, 0x75af4c07,
0x99eebbdd, 0x7fa3fd60, 0x01f79f26, 0x725cbcf5, 0x6644c53b,
0xfb5b347e, 0x438b7629, 0x23cbdcc6, 0xedb668fc, 0xe4b863f1,
0x31d7cadc, 0x63421085, 0x97134022, 0xc6842011, 0x4a857d24,
0xbbd2f83d, 0xf9ae1132, 0x29c76da1, 0x9e1d4b2f, 0xb2dcf330,
0x860dec52, 0xc177d0e3, 0xb32b6c16, 0x70a999b9, 0x9411fa48,
0xe9472264, 0xfca8c48c, 0xf0a01a3f, 0x7d56d82c, 0x3322ef90,
0x4987c74e, 0x38d9c1d1, 0xca8cfea2, 0xd498360b, 0xf5a6cf81,
0x7aa528de, 0xb7da268e, 0xad3fa4bf, 0x3a2ce49d, 0x78500d92,
0x5f6a9bcc, 0x7e546246, 0x8df6c213, 0xd890e8b8, 0x392e5ef7,
0xc382f5af, 0x5d9fbe80, 0xd0697c93, 0xd56fa92d, 0x25cfb312,
0xacc83b99, 0x1810a77d, 0x9ce86e63, 0x3bdb7bbb, 0x26cd0978,
0x596ef418, 0x9aec01b7, 0x4f83a89a, 0x95e6656e, 0xffaa7ee6,
0xbc2108cf, 0x15efe6e8, 0xe7bad99b, 0x6f4ace36, 0x9fead409,
0xb029d67c, 0xa431afb2, 0x3f2a3123, 0xa5c63094, 0xa235c066,
0x4e7437bc, 0x82fca6ca, 0x90e0b0d0, 0xa73315d8, 0x04f14a98,
0xec41f7da, 0xcd7f0e50, 0x91172ff6, 0x4d768dd6, 0xef434db0,
0xaacc544d, 0x96e4df04, 0xd19ee3b5, 0x6a4c1b88, 0x2cc1b81f,
0x65467f51, 0x5e9d04ea, 0x8c015d35, 0x87fa7374, 0x0bfb2e41,
0x67b35a1d, 0xdb9252d2, 0x10e93356, 0xd66d1347, 0xd79a8c61,
0xa1377a0c, 0xf8598e14, 0x13eb893c, 0xa9ceee27, 0x61b735c9,
0x1ce1ede5, 0x477a3cb1, 0xd29c59df, 0xf2553f73, 0x141879ce,
0xc773bf37, 0xf753eacd, 0xfd5f5baa, 0x3ddf146f, 0x447886db,
0xafca81f3, 0x68b93ec4, 0x24382c34, 0xa3c25f40, 0x1d1672c3,
0xe2bc0c25, 0x3c288b49, 0x0dff4195, 0xa8397101, 0x0c08deb3,
0xb4d89ce4, 0x566490c1, 0xcb7b6184, 0x32d570b6, 0x6c48745c,
0xb8d04257
};
private static readonly uint[] Tinv3 =
{
0x5150a7f4, 0x7e536541, 0x1ac3a417, 0x3a965e27, 0x3bcb6bab,
0x1ff1459d, 0xacab58fa, 0x4b9303e3, 0x2055fa30, 0xadf66d76,
0x889176cc, 0xf5254c02, 0x4ffcd7e5, 0xc5d7cb2a, 0x26804435,
0xb58fa362, 0xde495ab1, 0x25671bba, 0x45980eea, 0x5de1c0fe,
0xc302752f, 0x8112f04c, 0x8da39746, 0x6bc6f9d3, 0x03e75f8f,
0x15959c92, 0xbfeb7a6d, 0x95da5952, 0xd42d83be, 0x58d32174,
0x492969e0, 0x8e44c8c9, 0x756a89c2, 0xf478798e, 0x996b3e58,
0x27dd71b9, 0xbeb64fe1, 0xf017ad88, 0xc966ac20, 0x7db43ace,
0x63184adf, 0xe582311a, 0x97603351, 0x62457f53, 0xb1e07764,
0xbb84ae6b, 0xfe1ca081, 0xf9942b08, 0x70586848, 0x8f19fd45,
0x94876cde, 0x52b7f87b, 0xab23d373, 0x72e2024b, 0xe3578f1f,
0x662aab55, 0xb20728eb, 0x2f03c2b5, 0x869a7bc5, 0xd3a50837,
0x30f28728, 0x23b2a5bf, 0x02ba6a03, 0xed5c8216, 0x8a2b1ccf,
0xa792b479, 0xf3f0f207, 0x4ea1e269, 0x65cdf4da, 0x06d5be05,
0xd11f6234, 0xc48afea6, 0x349d532e, 0xa2a055f3, 0x0532e18a,
0xa475ebf6, 0x0b39ec83, 0x40aaef60, 0x5e069f71, 0xbd51106e,
0x3ef98a21, 0x963d06dd, 0xddae053e, 0x4d46bde6, 0x91b58d54,
0x71055dc4, 0x046fd406, 0x60ff1550, 0x1924fb98, 0xd697e9bd,
0x89cc4340, 0x67779ed9, 0xb0bd42e8, 0x07888b89, 0xe7385b19,
0x79dbeec8, 0xa1470a7c, 0x7ce90f42, 0xf8c91e84, 0x00000000,
0x09838680, 0x3248ed2b, 0x1eac7011, 0x6c4e725a, 0xfdfbff0e,
0x0f563885, 0x3d1ed5ae, 0x3627392d, 0x0a64d90f, 0x6821a65c,
0x9bd1545b, 0x243a2e36, 0x0cb1670a, 0x930fe757, 0xb4d296ee,
0x1b9e919b, 0x804fc5c0, 0x61a220dc, 0x5a694b77, 0x1c161a12,
0xe20aba93, 0xc0e52aa0, 0x3c43e022, 0x121d171b, 0x0e0b0d09,
0xf2adc78b, 0x2db9a8b6, 0x14c8a91e, 0x578519f1, 0xaf4c0775,
0xeebbdd99, 0xa3fd607f, 0xf79f2601, 0x5cbcf572, 0x44c53b66,
0x5b347efb, 0x8b762943, 0xcbdcc623, 0xb668fced, 0xb863f1e4,
0xd7cadc31, 0x42108563, 0x13402297, 0x842011c6, 0x857d244a,
0xd2f83dbb, 0xae1132f9, 0xc76da129, 0x1d4b2f9e, 0xdcf330b2,
0x0dec5286, 0x77d0e3c1, 0x2b6c16b3, 0xa999b970, 0x11fa4894,
0x472264e9, 0xa8c48cfc, 0xa01a3ff0, 0x56d82c7d, 0x22ef9033,
0x87c74e49, 0xd9c1d138, 0x8cfea2ca, 0x98360bd4, 0xa6cf81f5,
0xa528de7a, 0xda268eb7, 0x3fa4bfad, 0x2ce49d3a, 0x500d9278,
0x6a9bcc5f, 0x5462467e, 0xf6c2138d, 0x90e8b8d8, 0x2e5ef739,
0x82f5afc3, 0x9fbe805d, 0x697c93d0, 0x6fa92dd5, 0xcfb31225,
0xc83b99ac, 0x10a77d18, 0xe86e639c, 0xdb7bbb3b, 0xcd097826,
0x6ef41859, 0xec01b79a, 0x83a89a4f, 0xe6656e95, 0xaa7ee6ff,
0x2108cfbc, 0xefe6e815, 0xbad99be7, 0x4ace366f, 0xead4099f,
0x29d67cb0, 0x31afb2a4, 0x2a31233f, 0xc63094a5, 0x35c066a2,
0x7437bc4e, 0xfca6ca82, 0xe0b0d090, 0x3315d8a7, 0xf14a9804,
0x41f7daec, 0x7f0e50cd, 0x172ff691, 0x768dd64d, 0x434db0ef,
0xcc544daa, 0xe4df0496, 0x9ee3b5d1, 0x4c1b886a, 0xc1b81f2c,
0x467f5165, 0x9d04ea5e, 0x015d358c, 0xfa737487, 0xfb2e410b,
0xb35a1d67, 0x9252d2db, 0xe9335610, 0x6d1347d6, 0x9a8c61d7,
0x377a0ca1, 0x598e14f8, 0xeb893c13, 0xceee27a9, 0xb735c961,
0xe1ede51c, 0x7a3cb147, 0x9c59dfd2, 0x553f73f2, 0x1879ce14,
0x73bf37c7, 0x53eacdf7, 0x5f5baafd, 0xdf146f3d, 0x7886db44,
0xca81f3af, 0xb93ec468, 0x382c3424, 0xc25f40a3, 0x1672c31d,
0xbc0c25e2, 0x288b493c, 0xff41950d, 0x397101a8, 0x08deb30c,
0xd89ce4b4, 0x6490c156, 0x7b6184cb, 0xd570b632, 0x48745c6c,
0xd04257b8
};
private static uint Shift(uint r, int shift)
{
return (r >> shift) | (r << (32 - shift));
}
/* multiply four bytes in GF(2^8) by 'x' {02} in parallel */
private const uint m1 = 0x80808080;
private const uint m2 = 0x7f7f7f7f;
private const uint m3 = 0x0000001b;
private static uint FFmulX(uint x)
{
return ((x & m2) << 1) ^ (((x & m1) >> 7) * m3);
}
/*
The following defines provide alternative definitions of FFmulX that might
give improved performance if a fast 32-bit multiply is not available.
private int FFmulX(int x) { int u = x & m1; u |= (u >> 1); return ((x & m2) << 1) ^ ((u >>> 3) | (u >>> 6)); }
private static final int m4 = 0x1b1b1b1b;
private int FFmulX(int x) { int u = x & m1; return ((x & m2) << 1) ^ ((u - (u >>> 7)) & m4); }
*/
private static uint Inv_Mcol(uint x)
{
uint f2 = FFmulX(x);
uint f4 = FFmulX(f2);
uint f8 = FFmulX(f4);
uint f9 = x ^ f8;
return f2 ^ f4 ^ f8 ^ Shift(f2 ^ f9, 8) ^ Shift(f4 ^ f9, 16) ^ Shift(f9, 24);
}
private static uint SubWord(uint x)
{
return (uint)S[x&255]
| (((uint)S[(x>>8)&255]) << 8)
| (((uint)S[(x>>16)&255]) << 16)
| (((uint)S[(x>>24)&255]) << 24);
}
/**
* Calculate the necessary round keys
* The number of calculations depends on key size and block size
* AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits
* This code is written assuming those are the only possible values
*/
private uint[][] GenerateWorkingKey(
byte[] key,
bool forEncryption)
{
int KC = key.Length / 4; // key length in words
if (((KC != 4) && (KC != 6) && (KC != 8)) || ((KC * 4) != key.Length))
throw new ArgumentException("Key length not 128/192/256 bits.");
ROUNDS = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes
uint[][] W = new uint[ROUNDS + 1][]; // 4 words in a block
for (int i = 0; i <= ROUNDS; ++i)
{
W[i] = new uint[4];
}
//
// copy the key into the round key array
//
int t = 0;
for (int i = 0; i < key.Length; t++)
{
W[t >> 2][t & 3] = Pack.LE_To_UInt32(key, i);
i+=4;
}
//
// while not enough round key material calculated
// calculate new values
//
int k = (ROUNDS + 1) << 2;
for (int i = KC; (i < k); i++)
{
uint temp = W[(i-1)>>2][(i-1)&3];
if ((i % KC) == 0) {
temp = SubWord(Shift(temp, 8)) ^ rcon[(i / KC)-1];
} else if ((KC > 6) && ((i % KC) == 4)) {
temp = SubWord(temp);
}
W[i>>2][i&3] = W[(i - KC)>>2][(i-KC)&3] ^ temp;
}
if (!forEncryption)
{
for (int j = 1; j < ROUNDS; j++)
{
uint[] w = W[j];
for (int i = 0; i < 4; i++)
{
w[i] = Inv_Mcol(w[i]);
}
}
}
return W;
}
private int ROUNDS;
private uint[][] WorkingKey;
private uint C0, C1, C2, C3;
private bool forEncryption;
private const int BLOCK_SIZE = 16;
/**
* default constructor - 128 bit block size.
*/
public AesFastEngine()
{
}
/**
* initialise an AES cipher.
*
* @param forEncryption whether or not we are for encryption.
* @param parameters the parameters required to set up the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public virtual void Init(
bool forEncryption,
ICipherParameters parameters)
{
KeyParameter keyParameter = parameters as KeyParameter;
if (keyParameter == null)
throw new ArgumentException("invalid parameter passed to AES init - " + parameters.GetType().Name);
WorkingKey = GenerateWorkingKey(keyParameter.GetKey(), forEncryption);
this.forEncryption = forEncryption;
}
public virtual string AlgorithmName
{
get { return "AES"; }
}
public virtual bool IsPartialBlockOkay
{
get { return false; }
}
public virtual int GetBlockSize()
{
return BLOCK_SIZE;
}
public virtual int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
if (WorkingKey == null)
throw new InvalidOperationException("AES engine not initialised");
Check.DataLength(input, inOff, 16, "input buffer too short");
Check.OutputLength(output, outOff, 16, "output buffer too short");
UnPackBlock(input, inOff);
if (forEncryption)
{
EncryptBlock(WorkingKey);
}
else
{
DecryptBlock(WorkingKey);
}
PackBlock(output, outOff);
return BLOCK_SIZE;
}
public virtual void Reset()
{
}
private void UnPackBlock(
byte[] bytes,
int off)
{
C0 = Pack.LE_To_UInt32(bytes, off);
C1 = Pack.LE_To_UInt32(bytes, off + 4);
C2 = Pack.LE_To_UInt32(bytes, off + 8);
C3 = Pack.LE_To_UInt32(bytes, off + 12);
}
private void PackBlock(
byte[] bytes,
int off)
{
Pack.UInt32_To_LE(C0, bytes, off);
Pack.UInt32_To_LE(C1, bytes, off + 4);
Pack.UInt32_To_LE(C2, bytes, off + 8);
Pack.UInt32_To_LE(C3, bytes, off + 12);
}
private void EncryptBlock(uint[][] KW)
{
uint[] kw = KW[0];
uint t0 = this.C0 ^ kw[0];
uint t1 = this.C1 ^ kw[1];
uint t2 = this.C2 ^ kw[2];
uint r0, r1, r2, r3 = this.C3 ^ kw[3];
int r = 1;
while (r < ROUNDS - 1)
{
kw = KW[r++];
r0 = T0[t0 & 255] ^ T1[(t1 >> 8) & 255] ^ T2[(t2 >> 16) & 255] ^ T3[r3 >> 24] ^ kw[0];
r1 = T0[t1 & 255] ^ T1[(t2 >> 8) & 255] ^ T2[(r3 >> 16) & 255] ^ T3[t0 >> 24] ^ kw[1];
r2 = T0[t2 & 255] ^ T1[(r3 >> 8) & 255] ^ T2[(t0 >> 16) & 255] ^ T3[t1 >> 24] ^ kw[2];
r3 = T0[r3 & 255] ^ T1[(t0 >> 8) & 255] ^ T2[(t1 >> 16) & 255] ^ T3[t2 >> 24] ^ kw[3];
kw = KW[r++];
t0 = T0[r0 & 255] ^ T1[(r1 >> 8) & 255] ^ T2[(r2 >> 16) & 255] ^ T3[r3 >> 24] ^ kw[0];
t1 = T0[r1 & 255] ^ T1[(r2 >> 8) & 255] ^ T2[(r3 >> 16) & 255] ^ T3[r0 >> 24] ^ kw[1];
t2 = T0[r2 & 255] ^ T1[(r3 >> 8) & 255] ^ T2[(r0 >> 16) & 255] ^ T3[r1 >> 24] ^ kw[2];
r3 = T0[r3 & 255] ^ T1[(r0 >> 8) & 255] ^ T2[(r1 >> 16) & 255] ^ T3[r2 >> 24] ^ kw[3];
}
kw = KW[r++];
r0 = T0[t0 & 255] ^ T1[(t1 >> 8) & 255] ^ T2[(t2 >> 16) & 255] ^ T3[r3 >> 24] ^ kw[0];
r1 = T0[t1 & 255] ^ T1[(t2 >> 8) & 255] ^ T2[(r3 >> 16) & 255] ^ T3[t0 >> 24] ^ kw[1];
r2 = T0[t2 & 255] ^ T1[(r3 >> 8) & 255] ^ T2[(t0 >> 16) & 255] ^ T3[t1 >> 24] ^ kw[2];
r3 = T0[r3 & 255] ^ T1[(t0 >> 8) & 255] ^ T2[(t1 >> 16) & 255] ^ T3[t2 >> 24] ^ kw[3];
// the final round's table is a simple function of S so we don't use a whole other four tables for it
kw = KW[r];
this.C0 = (uint)S[r0 & 255] ^ (((uint)S[(r1 >> 8) & 255]) << 8) ^ (((uint)S[(r2 >> 16) & 255]) << 16) ^ (((uint)S[r3 >> 24]) << 24) ^ kw[0];
this.C1 = (uint)S[r1 & 255] ^ (((uint)S[(r2 >> 8) & 255]) << 8) ^ (((uint)S[(r3 >> 16) & 255]) << 16) ^ (((uint)S[r0 >> 24]) << 24) ^ kw[1];
this.C2 = (uint)S[r2 & 255] ^ (((uint)S[(r3 >> 8) & 255]) << 8) ^ (((uint)S[(r0 >> 16) & 255]) << 16) ^ (((uint)S[r1 >> 24]) << 24) ^ kw[2];
this.C3 = (uint)S[r3 & 255] ^ (((uint)S[(r0 >> 8) & 255]) << 8) ^ (((uint)S[(r1 >> 16) & 255]) << 16) ^ (((uint)S[r2 >> 24]) << 24) ^ kw[3];
}
private void DecryptBlock(uint[][] KW)
{
uint[] kw = KW[ROUNDS];
uint t0 = this.C0 ^ kw[0];
uint t1 = this.C1 ^ kw[1];
uint t2 = this.C2 ^ kw[2];
uint r0, r1, r2, r3 = this.C3 ^ kw[3];
int r = ROUNDS - 1;
while (r > 1)
{
kw = KW[r--];
r0 = Tinv0[t0 & 255] ^ Tinv1[(r3 >> 8) & 255] ^ Tinv2[(t2 >> 16) & 255] ^ Tinv3[t1 >> 24] ^ kw[0];
r1 = Tinv0[t1 & 255] ^ Tinv1[(t0 >> 8) & 255] ^ Tinv2[(r3 >> 16) & 255] ^ Tinv3[t2 >> 24] ^ kw[1];
r2 = Tinv0[t2 & 255] ^ Tinv1[(t1 >> 8) & 255] ^ Tinv2[(t0 >> 16) & 255] ^ Tinv3[r3 >> 24] ^ kw[2];
r3 = Tinv0[r3 & 255] ^ Tinv1[(t2 >> 8) & 255] ^ Tinv2[(t1 >> 16) & 255] ^ Tinv3[t0 >> 24] ^ kw[3];
kw = KW[r--];
t0 = Tinv0[r0 & 255] ^ Tinv1[(r3 >> 8) & 255] ^ Tinv2[(r2 >> 16) & 255] ^ Tinv3[r1 >> 24] ^ kw[0];
t1 = Tinv0[r1 & 255] ^ Tinv1[(r0 >> 8) & 255] ^ Tinv2[(r3 >> 16) & 255] ^ Tinv3[r2 >> 24] ^ kw[1];
t2 = Tinv0[r2 & 255] ^ Tinv1[(r1 >> 8) & 255] ^ Tinv2[(r0 >> 16) & 255] ^ Tinv3[r3 >> 24] ^ kw[2];
r3 = Tinv0[r3 & 255] ^ Tinv1[(r2 >> 8) & 255] ^ Tinv2[(r1 >> 16) & 255] ^ Tinv3[r0 >> 24] ^ kw[3];
}
kw = KW[1];
r0 = Tinv0[t0 & 255] ^ Tinv1[(r3 >> 8) & 255] ^ Tinv2[(t2 >> 16) & 255] ^ Tinv3[t1 >> 24] ^ kw[0];
r1 = Tinv0[t1 & 255] ^ Tinv1[(t0 >> 8) & 255] ^ Tinv2[(r3 >> 16) & 255] ^ Tinv3[t2 >> 24] ^ kw[1];
r2 = Tinv0[t2 & 255] ^ Tinv1[(t1 >> 8) & 255] ^ Tinv2[(t0 >> 16) & 255] ^ Tinv3[r3 >> 24] ^ kw[2];
r3 = Tinv0[r3 & 255] ^ Tinv1[(t2 >> 8) & 255] ^ Tinv2[(t1 >> 16) & 255] ^ Tinv3[t0 >> 24] ^ kw[3];
// the final round's table is a simple function of Si so we don't use a whole other four tables for it
kw = KW[0];
this.C0 = (uint)Si[r0 & 255] ^ (((uint)Si[(r3 >> 8) & 255]) << 8) ^ (((uint)Si[(r2 >> 16) & 255]) << 16) ^ (((uint)Si[r1 >> 24]) << 24) ^ kw[0];
this.C1 = (uint)Si[r1 & 255] ^ (((uint)Si[(r0 >> 8) & 255]) << 8) ^ (((uint)Si[(r3 >> 16) & 255]) << 16) ^ (((uint)Si[r2 >> 24]) << 24) ^ kw[1];
this.C2 = (uint)Si[r2 & 255] ^ (((uint)Si[(r1 >> 8) & 255]) << 8) ^ (((uint)Si[(r0 >> 16) & 255]) << 16) ^ (((uint)Si[r3 >> 24]) << 24) ^ kw[2];
this.C3 = (uint)Si[r3 & 255] ^ (((uint)Si[(r2 >> 8) & 255]) << 8) ^ (((uint)Si[(r1 >> 16) & 255]) << 16) ^ (((uint)Si[r0 >> 24]) << 24) ^ kw[3];
}
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Layouts;
/// <summary>
/// Sends log messages to the remote instance of NLog Viewer.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/NLogViewer-target">Documentation on NLog Wiki</seealso>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/NLogViewer/NLog.config" />
/// <p>
/// This assumes just one target and a single rule. More configuration
/// options are described <a href="config.html">here</a>.
/// </p>
/// <p>
/// To set up the log target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/NLogViewer/Simple/Example.cs" />
/// <p>
/// NOTE: If your receiver application is ever likely to be off-line, don't use TCP protocol
/// or you'll get TCP timeouts and your application will crawl.
/// Either switch to UDP transport or use <a href="target.AsyncWrapper.html">AsyncWrapper</a> target
/// so that your application threads will not be blocked by the timing-out connection attempts.
/// </p>
/// </example>
[Target("NLogViewer")]
public class NLogViewerTarget : NetworkTarget, IIncludeContext
{
private readonly Log4JXmlEventLayout _layout = new Log4JXmlEventLayout();
/// <summary>
/// Initializes a new instance of the <see cref="NLogViewerTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
public NLogViewerTarget()
{
Parameters = new List<NLogViewerParameterInfo>();
Renderer.Parameters = Parameters;
OnConnectionOverflow = NetworkTargetConnectionsOverflowAction.Block;
MaxConnections = 16;
NewLine = false;
}
/// <summary>
/// Initializes a new instance of the <see cref="NLogViewerTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
/// <param name="name">Name of the target.</param>
public NLogViewerTarget(string name) : this()
{
Name = name;
}
/// <summary>
/// Gets or sets a value indicating whether to include NLog-specific extensions to log4j schema.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool IncludeNLogData
{
get => Renderer.IncludeNLogData;
set => Renderer.IncludeNLogData = value;
}
/// <summary>
/// Gets or sets the AppInfo field. By default it's the friendly name of the current AppDomain.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public string AppInfo
{
get => Renderer.AppInfo;
set => Renderer.AppInfo = value;
}
/// <summary>
/// Gets or sets a value indicating whether to include call site (class and method name) in the information sent over the network.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool IncludeCallSite
{
get => Renderer.IncludeCallSite;
set => Renderer.IncludeCallSite = value;
}
#if !SILVERLIGHT
/// <summary>
/// Gets or sets a value indicating whether to include source info (file name and line number) in the information sent over the network.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool IncludeSourceInfo
{
get => Renderer.IncludeSourceInfo;
set => Renderer.IncludeSourceInfo = value;
}
#endif
/// <summary>
/// Gets or sets a value indicating whether to include <see cref="MappedDiagnosticsContext"/> dictionary contents.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool IncludeMdc
{
get => Renderer.IncludeMdc;
set => Renderer.IncludeMdc = value;
}
/// <summary>
/// Gets or sets a value indicating whether to include <see cref="NestedDiagnosticsContext"/> stack contents.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool IncludeNdc
{
get => Renderer.IncludeNdc;
set => Renderer.IncludeNdc = value;
}
#if !SILVERLIGHT
/// <summary>
/// Gets or sets a value indicating whether to include <see cref="MappedDiagnosticsLogicalContext"/> dictionary contents.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool IncludeMdlc
{
get => Renderer.IncludeMdlc;
set => Renderer.IncludeMdlc = value;
}
/// <summary>
/// Gets or sets a value indicating whether to include contents of the <see cref="NestedDiagnosticsLogicalContext"/> stack.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool IncludeNdlc
{
get => Renderer.IncludeNdlc;
set => Renderer.IncludeNdlc = value;
}
/// <summary>
/// Gets or sets the NDLC item separator.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public string NdlcItemSeparator
{
get => Renderer.NdlcItemSeparator;
set => Renderer.NdlcItemSeparator = value;
}
#endif
/// <summary>
/// Gets or sets the option to include all properties from the log events
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool IncludeAllProperties
{
get => Renderer.IncludeAllProperties;
set => Renderer.IncludeAllProperties = value;
}
/// <summary>
/// Gets or sets the NDC item separator.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public string NdcItemSeparator
{
get => Renderer.NdcItemSeparator;
set => Renderer.NdcItemSeparator = value;
}
/// <summary>
/// Gets or sets the renderer for log4j:event logger-xml-attribute (Default ${logger})
/// </summary>
/// <docgen category='Payload Options' order='10' />
public Layout LoggerName
{
get => Renderer.LoggerName;
set => Renderer.LoggerName = value;
}
/// <summary>
/// Gets the collection of parameters. Each parameter contains a mapping
/// between NLog layout and a named parameter.
/// </summary>
/// <docgen category='Payload Options' order='10' />
[ArrayParameter(typeof(NLogViewerParameterInfo), "parameter")]
public IList<NLogViewerParameterInfo> Parameters { get; private set; }
/// <summary>
/// Gets the layout renderer which produces Log4j-compatible XML events.
/// </summary>
public Log4JXmlEventLayoutRenderer Renderer => _layout.Renderer;
/// <summary>
/// Gets or sets the instance of <see cref="Log4JXmlEventLayout"/> that is used to format log messages.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public override Layout Layout
{
get
{
return _layout;
}
set
{
}
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft 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.Linq;
using System.Management.Automation;
using Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.Properties;
using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models;
namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery
{
/// <summary>
/// Retrieves Azure Site Recovery Protection Entity.
/// </summary>
[Cmdlet(
VerbsCommon.Set,
"AzureRmRecoveryServicesAsrReplicationProtectedItem",
DefaultParameterSetName = ASRParameterSets.ByObject,
SupportsShouldProcess = true)]
[Alias("Set-ASRReplicationProtectedItem")]
[OutputType(typeof(ASRJob))]
public class SetAzureRmRecoveryServicesAsrReplicationProtectedItem : SiteRecoveryCmdletBase
{
/// <summary>
/// Gets or sets ID of the Virtual Machine.
/// </summary>
[Parameter(
Mandatory = true,
ValueFromPipeline = true)]
[ValidateNotNullOrEmpty]
[Alias("ReplicationProtectedItem")]
public ASRReplicationProtectedItem InputObject { get; set; }
/// <summary>
/// Gets or sets Recovery Azure VM given name
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
/// <summary>
/// Gets or sets Recovery Azure VM size
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public string Size { get; set; }
/// <summary>
/// Gets or sets Selected Primary Network interface card Id
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public string PrimaryNic { get; set; }
/// <summary>
/// Gets or sets Recovery Azure Network Id
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public string RecoveryNetworkId { get; set; }
/// <summary>
/// Gets or sets Recovery Azure Network Id
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public string RecoveryNicSubnetName { get; set; }
/// <summary>
/// Gets or sets Recovery Nic Static IPAddress
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public string RecoveryNicStaticIPAddress { get; set; }
/// <summary>
/// Gets or sets Selection Type for Nic
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[ValidateSet(
Constants.NotSelected,
Constants.SelectedByUser)]
public string NicSelectionType { get; set; }
/// <summary>
/// Gets or sets Recovery Resource ID
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public string RecoveryResourceGroupId { get; set; }
/// <summary>
/// Gets or sets LicenseType for
/// HUB https://azure.microsoft.com/en-in/pricing/hybrid-use-benefit/
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[ValidateSet(
Constants.NoLicenseType,
Constants.LicenseTypeWindowsServer)]
public string LicenseType { get; set; }
/// <summary>
/// ProcessRecord of the command.
/// </summary>
public override void ExecuteSiteRecoveryCmdlet()
{
base.ExecuteSiteRecoveryCmdlet();
if (this.ShouldProcess(
this.InputObject.FriendlyName,
VerbsCommon.Set))
{
var replicationProtectedItemResponse = this.RecoveryServicesClient
.GetAzureSiteRecoveryReplicationProtectedItem(
Utilities.GetValueFromArmId(
this.InputObject.ID,
ARMResourceTypeConstants.ReplicationFabrics),
Utilities.GetValueFromArmId(
this.InputObject.ID,
ARMResourceTypeConstants.ReplicationProtectionContainers),
this.InputObject.Name);
var provider = replicationProtectedItemResponse.Properties.ProviderSpecificDetails;
// Check for Replication Provider type HyperVReplicaAzure/InMageAzureV2
if (!(provider is HyperVReplicaAzureReplicationDetails) &&
!(provider is InMageAzureV2ReplicationDetails))
{
this.WriteWarning(
Resources.UnsupportedReplicationProvidedForUpdateVmProperties);
return;
}
// Check for at least one option
if (string.IsNullOrEmpty(this.Name) &&
string.IsNullOrEmpty(this.Size) &&
string.IsNullOrEmpty(this.PrimaryNic) &&
string.IsNullOrEmpty(this.RecoveryNetworkId) &&
string.IsNullOrEmpty(this.RecoveryResourceGroupId) &&
string.IsNullOrEmpty(this.LicenseType))
{
this.WriteWarning(Resources.ArgumentsMissingForUpdateVmProperties);
return;
}
// Both primary & recovery inputs should be present
if (string.IsNullOrEmpty(this.PrimaryNic) ^
string.IsNullOrEmpty(this.RecoveryNetworkId))
{
this.WriteWarning(Resources.NetworkArgumentsMissingForUpdateVmProperties);
return;
}
var vmName = this.Name;
var vmSize = this.Size;
var vmRecoveryNetworkId = this.RecoveryNetworkId;
var licenseType = this.LicenseType;
var recoveryResourceGroupId = this.RecoveryResourceGroupId;
var vMNicInputDetailsList = new List<VMNicInputDetails>();
VMNicDetails vMNicDetailsToBeUpdated;
var providerSpecificInput = new UpdateReplicationProtectedItemProviderInput();
if (provider is HyperVReplicaAzureReplicationDetails)
{
var providerSpecificDetails =
(HyperVReplicaAzureReplicationDetails)replicationProtectedItemResponse
.Properties.ProviderSpecificDetails;
if (string.IsNullOrEmpty(this.RecoveryResourceGroupId))
{
recoveryResourceGroupId =
providerSpecificDetails.RecoveryAzureResourceGroupId;
}
var deploymentType = Utilities.GetValueFromArmId(
providerSpecificDetails.RecoveryAzureStorageAccount,
ARMResourceTypeConstants.Providers);
if (deploymentType.ToLower()
.Contains(Constants.Classic.ToLower()))
{
providerSpecificInput =
new HyperVReplicaAzureUpdateReplicationProtectedItemInput
{
RecoveryAzureV1ResourceGroupId = recoveryResourceGroupId,
RecoveryAzureV2ResourceGroupId = null
};
}
else
{
providerSpecificInput =
new HyperVReplicaAzureUpdateReplicationProtectedItemInput
{
RecoveryAzureV1ResourceGroupId = null,
RecoveryAzureV2ResourceGroupId = recoveryResourceGroupId
};
}
if (string.IsNullOrEmpty(this.Name))
{
vmName = providerSpecificDetails.RecoveryAzureVMName;
}
if (string.IsNullOrEmpty(this.Size))
{
vmSize = providerSpecificDetails.RecoveryAzureVMSize;
}
if (string.IsNullOrEmpty(this.RecoveryNetworkId))
{
vmRecoveryNetworkId = providerSpecificDetails
.SelectedRecoveryAzureNetworkId;
}
if (string.IsNullOrEmpty(this.LicenseType))
{
//licenseType = providerSpecificDetails.LicenseType;
}
if (!string.IsNullOrEmpty(this.PrimaryNic))
{
if (providerSpecificDetails.VmNics != null)
{
vMNicDetailsToBeUpdated =
providerSpecificDetails.VmNics.SingleOrDefault(
n => string.Compare(
n.NicId,
this.PrimaryNic,
StringComparison.OrdinalIgnoreCase) ==
0);
if (vMNicDetailsToBeUpdated != null)
{
var vMNicInputDetails = new VMNicInputDetails();
vMNicInputDetails.NicId = this.PrimaryNic;
vMNicInputDetails.RecoveryVMSubnetName = this.RecoveryNicSubnetName;
vMNicInputDetails.ReplicaNicStaticIPAddress =
this.RecoveryNicStaticIPAddress;
vMNicInputDetails.SelectionType =
string.IsNullOrEmpty(this.NicSelectionType)
? Constants.SelectedByUser : this.NicSelectionType;
vMNicInputDetailsList.Add(vMNicInputDetails);
var vMNicDetailsListRemaining =
providerSpecificDetails.VmNics.Where(
n => string.Compare(
n.NicId,
this.PrimaryNic,
StringComparison.OrdinalIgnoreCase) !=
0);
foreach (var nDetails in vMNicDetailsListRemaining)
{
vMNicInputDetails = new VMNicInputDetails();
vMNicInputDetails.NicId = nDetails.NicId;
vMNicInputDetails.RecoveryVMSubnetName =
nDetails.RecoveryVMSubnetName;
vMNicInputDetails.ReplicaNicStaticIPAddress =
nDetails.ReplicaNicStaticIPAddress;
vMNicInputDetails.SelectionType = nDetails.SelectionType;
vMNicInputDetailsList.Add(vMNicInputDetails);
}
}
else
{
throw new PSInvalidOperationException(
Resources.NicNotFoundInVMForUpdateVmProperties);
}
}
}
else
{
VMNicInputDetails vMNicInputDetails;
foreach (var nDetails in providerSpecificDetails.VmNics)
{
vMNicInputDetails = new VMNicInputDetails();
vMNicInputDetails.NicId = nDetails.NicId;
vMNicInputDetails.RecoveryVMSubnetName = nDetails.RecoveryVMSubnetName;
vMNicInputDetails.ReplicaNicStaticIPAddress =
nDetails.ReplicaNicStaticIPAddress;
vMNicInputDetails.SelectionType = nDetails.SelectionType;
vMNicInputDetailsList.Add(vMNicInputDetails);
}
}
}
else if (provider is InMageAzureV2ReplicationDetails)
{
var providerSpecificDetails =
(InMageAzureV2ReplicationDetails)replicationProtectedItemResponse.Properties
.ProviderSpecificDetails;
if (string.IsNullOrEmpty(this.RecoveryResourceGroupId))
{
recoveryResourceGroupId =
providerSpecificDetails.RecoveryAzureResourceGroupId;
}
var deploymentType = Utilities.GetValueFromArmId(
providerSpecificDetails.RecoveryAzureStorageAccount,
ARMResourceTypeConstants.Providers);
if (deploymentType.ToLower()
.Contains(Constants.Classic.ToLower()))
{
providerSpecificInput =
new InMageAzureV2UpdateReplicationProtectedItemInput
{
RecoveryAzureV1ResourceGroupId = recoveryResourceGroupId,
RecoveryAzureV2ResourceGroupId = null
};
}
else
{
providerSpecificInput =
new InMageAzureV2UpdateReplicationProtectedItemInput
{
RecoveryAzureV1ResourceGroupId = null,
RecoveryAzureV2ResourceGroupId = recoveryResourceGroupId
};
}
if (string.IsNullOrEmpty(this.Name))
{
vmName = providerSpecificDetails.RecoveryAzureVMName;
}
if (string.IsNullOrEmpty(this.Size))
{
vmSize = providerSpecificDetails.RecoveryAzureVMSize;
}
if (string.IsNullOrEmpty(this.RecoveryNetworkId))
{
vmRecoveryNetworkId = providerSpecificDetails
.SelectedRecoveryAzureNetworkId;
}
if (string.IsNullOrEmpty(this.LicenseType))
{
//licenseType = providerSpecificDetails.LicenseType;
}
if (!string.IsNullOrEmpty(this.PrimaryNic))
{
if (providerSpecificDetails.VmNics != null)
{
vMNicDetailsToBeUpdated =
providerSpecificDetails.VmNics.SingleOrDefault(
n => string.Compare(
n.NicId,
this.PrimaryNic,
StringComparison.OrdinalIgnoreCase) ==
0);
if (vMNicDetailsToBeUpdated != null)
{
var vMNicInputDetails = new VMNicInputDetails();
vMNicInputDetails.NicId = this.PrimaryNic;
vMNicInputDetails.RecoveryVMSubnetName = this.RecoveryNicSubnetName;
vMNicInputDetails.ReplicaNicStaticIPAddress =
this.RecoveryNicStaticIPAddress;
vMNicInputDetails.SelectionType =
string.IsNullOrEmpty(this.NicSelectionType)
? Constants.SelectedByUser : this.NicSelectionType;
vMNicInputDetailsList.Add(vMNicInputDetails);
var vMNicDetailsListRemaining =
providerSpecificDetails.VmNics.Where(
n => string.Compare(
n.NicId,
this.PrimaryNic,
StringComparison.OrdinalIgnoreCase) !=
0);
foreach (var nDetails in vMNicDetailsListRemaining)
{
vMNicInputDetails = new VMNicInputDetails();
vMNicInputDetails.NicId = nDetails.NicId;
vMNicInputDetails.RecoveryVMSubnetName =
nDetails.RecoveryVMSubnetName;
vMNicInputDetails.ReplicaNicStaticIPAddress =
nDetails.ReplicaNicStaticIPAddress;
vMNicInputDetails.SelectionType = nDetails.SelectionType;
vMNicInputDetailsList.Add(vMNicInputDetails);
}
}
else
{
throw new PSInvalidOperationException(
Resources.NicNotFoundInVMForUpdateVmProperties);
}
}
}
else
{
VMNicInputDetails vMNicInputDetails;
foreach (var nDetails in providerSpecificDetails.VmNics)
{
vMNicInputDetails = new VMNicInputDetails();
vMNicInputDetails.NicId = nDetails.NicId;
vMNicInputDetails.RecoveryVMSubnetName = nDetails.RecoveryVMSubnetName;
vMNicInputDetails.ReplicaNicStaticIPAddress =
nDetails.ReplicaNicStaticIPAddress;
vMNicInputDetails.SelectionType = nDetails.SelectionType;
vMNicInputDetailsList.Add(vMNicInputDetails);
}
}
}
var updateReplicationProtectedItemInputProperties =
new UpdateReplicationProtectedItemInputProperties
{
RecoveryAzureVMName = vmName,
RecoveryAzureVMSize = vmSize,
SelectedRecoveryAzureNetworkId = vmRecoveryNetworkId,
VmNics = vMNicInputDetailsList,
LicenseType =
licenseType ==
Management.RecoveryServices.SiteRecovery.Models.LicenseType
.NoLicenseType.ToString()
? Management.RecoveryServices.SiteRecovery.Models.LicenseType
.NoLicenseType
: Management.RecoveryServices.SiteRecovery.Models.LicenseType
.WindowsServer,
ProviderSpecificDetails = providerSpecificInput
};
var input = new UpdateReplicationProtectedItemInput
{
Properties = updateReplicationProtectedItemInputProperties
};
var response = this.RecoveryServicesClient.UpdateVmProperties(
Utilities.GetValueFromArmId(
this.InputObject.ID,
ARMResourceTypeConstants.ReplicationFabrics),
Utilities.GetValueFromArmId(
this.InputObject.ID,
ARMResourceTypeConstants.ReplicationProtectionContainers),
this.InputObject.Name,
input);
var jobResponse = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails(
PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location));
this.WriteObject(new ASRJob(jobResponse));
}
}
}
}
| |
// 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.Text;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
////////////////////////////////////////////////////////////////////////////
//
// Rules for the Hebrew calendar:
// - The Hebrew calendar is both a Lunar (months) and Solar (years)
// calendar, but allows for a week of seven days.
// - Days begin at sunset.
// - Leap Years occur in the 3, 6, 8, 11, 14, 17, & 19th years of a
// 19-year cycle. Year = leap iff ((7y+1) mod 19 < 7).
// - There are 12 months in a common year and 13 months in a leap year.
// - In a common year, the 6th month, Adar, has 29 days. In a leap
// year, the 6th month, Adar I, has 30 days and the leap month,
// Adar II, has 29 days.
// - Common years have 353-355 days. Leap years have 383-385 days.
// - The Hebrew new year (Rosh HaShanah) begins on the 1st of Tishri,
// the 7th month in the list below.
// - The new year may not begin on Sunday, Wednesday, or Friday.
// - If the new year would fall on a Tuesday and the conjunction of
// the following year were at midday or later, the new year is
// delayed until Thursday.
// - If the new year would fall on a Monday after a leap year, the
// new year is delayed until Tuesday.
// - The length of the 8th and 9th months vary from year to year,
// depending on the overall length of the year.
// - The length of a year is determined by the dates of the new
// years (Tishri 1) preceding and following the year in question.
// - The 2th month is long (30 days) if the year has 355 or 385 days.
// - The 3th month is short (29 days) if the year has 353 or 383 days.
// - The Hebrew months are:
// 1. Tishri (30 days)
// 2. Heshvan (29 or 30 days)
// 3. Kislev (29 or 30 days)
// 4. Teveth (29 days)
// 5. Shevat (30 days)
// 6. Adar I (30 days)
// 7. Adar {II} (29 days, this only exists if that year is a leap year)
// 8. Nisan (30 days)
// 9. Iyyar (29 days)
// 10. Sivan (30 days)
// 11. Tammuz (29 days)
// 12. Av (30 days)
// 13. Elul (29 days)
//
////////////////////////////////////////////////////////////////////////////
/*
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 1583/01/01 2239/09/29
** Hebrew 5343/04/07 5999/13/29
*/
// Includes CHebrew implemetation;i.e All the code necessary for converting
// Gregorian to Hebrew Lunar from 1583 to 2239.
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class HebrewCalendar : Calendar
{
public static readonly int HebrewEra = 1;
internal const int DatePartYear = 0;
internal const int DatePartDayOfYear = 1;
internal const int DatePartMonth = 2;
internal const int DatePartDay = 3;
internal const int DatePartDayOfWeek = 4;
//
// Hebrew Translation Table.
//
// This table is used to get the following Hebrew calendar information for a
// given Gregorian year:
// 1. The day of the Hebrew month corresponding to Gregorian January 1st
// for a given Gregorian year.
// 2. The month of the Hebrew month corresponding to Gregorian January 1st
// for a given Gregorian year.
// The information is not directly in the table. Instead, the info is decoded
// by special values (numbers above 29 and below 1).
// 3. The type of the Hebrew year for a given Gregorian year.
//
/*
More notes:
This table includes 2 numbers for each year.
The offset into the table determines the year. (offset 0 is Gregorian year 1500)
1st number determines the day of the Hebrew month coresponeds to January 1st.
2nd number determines the type of the Hebrew year. (the type determines how
many days are there in the year.)
normal years : 1 = 353 days 2 = 354 days 3 = 355 days.
Leap years : 4 = 383 5 384 6 = 385 days.
A 99 means the year is not supported for translation.
for convenience the table was defined for 750 year,
but only 640 years are supported. (from 1583 to 2239)
the years before 1582 (starting of Georgian calander)
and after 2239, are filled with 99.
Greogrian January 1st falls usually in Tevet (4th month). Tevet has always 29 days.
That's why, there no nead to specify the lunar month in the table.
There are exceptions, these are coded by giving numbers above 29 and below 1.
Actual decoding is takenig place whenever fetching information from the table.
The function for decoding is in GetLunarMonthDay().
Example:
The data for 2000 - 2005 A.D. is:
23,6,6,1,17,2,27,6,7,3, // 2000 - 2004
For year 2000, we know it has a Hebrew year type 6, which means it has 385 days.
And 1/1/2000 A.D. is Hebrew year 5760, 23rd day of 4th month.
*/
//
// Jewish Era in use today is dated from the supposed year of the
// Creation with its beginning in 3761 B.C.
//
// The Hebrew year of Gregorian 1st year AD.
// 0001/01/01 AD is Hebrew 3760/01/01
private const int HebrewYearOf1AD = 3760;
// The first Gregorian year in HebrewTable.
private const int FirstGregorianTableYear = 1583; // == Hebrew Year 5343
// The last Gregorian year in HebrewTable.
private const int LastGregorianTableYear = 2239; // == Hebrew Year 5999
private const int TABLESIZE = (LastGregorianTableYear - FirstGregorianTableYear);
private const int MinHebrewYear = HebrewYearOf1AD + FirstGregorianTableYear; // == 5343
private const int MaxHebrewYear = HebrewYearOf1AD + LastGregorianTableYear; // == 5999
private static readonly byte[] HebrewTable = {
7,3,17,3, // 1583-1584 (Hebrew year: 5343 - 5344)
0,4,11,2,21,6,1,3,13,2, // 1585-1589
25,4,5,3,16,2,27,6,9,1, // 1590-1594
20,2,0,6,11,3,23,4,4,2, // 1595-1599
14,3,27,4,8,2,18,3,28,6, // 1600
11,1,22,5,2,3,12,3,25,4, // 1605
6,2,16,3,26,6,8,2,20,1, // 1610
0,6,11,2,24,4,4,3,15,2, // 1615
25,6,8,1,19,2,29,6,9,3, // 1620
22,4,3,2,13,3,25,4,6,3, // 1625
17,2,27,6,7,3,19,2,31,4, // 1630
11,3,23,4,5,2,15,3,25,6, // 1635
6,2,19,1,29,6,10,2,22,4, // 1640
3,3,14,2,24,6,6,1,17,3, // 1645
28,5,8,3,20,1,32,5,12,3, // 1650
22,6,4,1,16,2,26,6,6,3, // 1655
17,2,0,4,10,3,22,4,3,2, // 1660
14,3,24,6,5,2,17,1,28,6, // 1665
9,2,19,3,31,4,13,2,23,6, // 1670
3,3,15,1,27,5,7,3,17,3, // 1675
29,4,11,2,21,6,3,1,14,2, // 1680
25,6,5,3,16,2,28,4,9,3, // 1685
20,2,0,6,12,1,23,6,4,2, // 1690
14,3,26,4,8,2,18,3,0,4, // 1695
10,3,21,5,1,3,13,1,24,5, // 1700
5,3,15,3,27,4,8,2,19,3, // 1705
29,6,10,2,22,4,3,3,14,2, // 1710
26,4,6,3,18,2,28,6,10,1, // 1715
20,6,2,2,12,3,24,4,5,2, // 1720
16,3,28,4,8,3,19,2,0,6, // 1725
12,1,23,5,3,3,14,3,26,4, // 1730
7,2,17,3,28,6,9,2,21,4, // 1735
1,3,13,2,25,4,5,3,16,2, // 1740
27,6,9,1,19,3,0,5,11,3, // 1745
23,4,4,2,14,3,25,6,7,1, // 1750
18,2,28,6,9,3,21,4,2,2, // 1755
12,3,25,4,6,2,16,3,26,6, // 1760
8,2,20,1,0,6,11,2,22,6, // 1765
4,1,15,2,25,6,6,3,18,1, // 1770
29,5,9,3,22,4,2,3,13,2, // 1775
23,6,4,3,15,2,27,4,7,3, // 1780
19,2,31,4,11,3,21,6,3,2, // 1785
15,1,25,6,6,2,17,3,29,4, // 1790
10,2,20,6,3,1,13,3,24,5, // 1795
4,3,16,1,27,5,7,3,17,3, // 1800
0,4,11,2,21,6,1,3,13,2, // 1805
25,4,5,3,16,2,29,4,9,3, // 1810
19,6,30,2,13,1,23,6,4,2, // 1815
14,3,27,4,8,2,18,3,0,4, // 1820
11,3,22,5,2,3,14,1,26,5, // 1825
6,3,16,3,28,4,10,2,20,6, // 1830
30,3,11,2,24,4,4,3,15,2, // 1835
25,6,8,1,19,2,29,6,9,3, // 1840
22,4,3,2,13,3,25,4,7,2, // 1845
17,3,27,6,9,1,21,5,1,3, // 1850
11,3,23,4,5,2,15,3,25,6, // 1855
6,2,19,1,29,6,10,2,22,4, // 1860
3,3,14,2,24,6,6,1,18,2, // 1865
28,6,8,3,20,4,2,2,12,3, // 1870
24,4,4,3,16,2,26,6,6,3, // 1875
17,2,0,4,10,3,22,4,3,2, // 1880
14,3,24,6,5,2,17,1,28,6, // 1885
9,2,21,4,1,3,13,2,23,6, // 1890
5,1,15,3,27,5,7,3,19,1, // 1895
0,5,10,3,22,4,2,3,13,2, // 1900
24,6,4,3,15,2,27,4,8,3, // 1905
20,4,1,2,11,3,22,6,3,2, // 1910
15,1,25,6,7,2,17,3,29,4, // 1915
10,2,21,6,1,3,13,1,24,5, // 1920
5,3,15,3,27,4,8,2,19,6, // 1925
1,1,12,2,22,6,3,3,14,2, // 1930
26,4,6,3,18,2,28,6,10,1, // 1935
20,6,2,2,12,3,24,4,5,2, // 1940
16,3,28,4,9,2,19,6,30,3, // 1945
12,1,23,5,3,3,14,3,26,4, // 1950
7,2,17,3,28,6,9,2,21,4, // 1955
1,3,13,2,25,4,5,3,16,2, // 1960
27,6,9,1,19,6,30,2,11,3, // 1965
23,4,4,2,14,3,27,4,7,3, // 1970
18,2,28,6,11,1,22,5,2,3, // 1975
12,3,25,4,6,2,16,3,26,6, // 1980
8,2,20,4,30,3,11,2,24,4, // 1985
4,3,15,2,25,6,8,1,18,3, // 1990
29,5,9,3,22,4,3,2,13,3, // 1995
23,6,6,1,17,2,27,6,7,3, // 2000 - 2004
20,4,1,2,11,3,23,4,5,2, // 2005 - 2009
15,3,25,6,6,2,19,1,29,6, // 2010
10,2,20,6,3,1,14,2,24,6, // 2015
4,3,17,1,28,5,8,3,20,4, // 2020
1,3,12,2,22,6,2,3,14,2, // 2025
26,4,6,3,17,2,0,4,10,3, // 2030
20,6,1,2,14,1,24,6,5,2, // 2035
15,3,28,4,9,2,19,6,1,1, // 2040
12,3,23,5,3,3,15,1,27,5, // 2045
7,3,17,3,29,4,11,2,21,6, // 2050
1,3,12,2,25,4,5,3,16,2, // 2055
28,4,9,3,19,6,30,2,12,1, // 2060
23,6,4,2,14,3,26,4,8,2, // 2065
18,3,0,4,10,3,22,5,2,3, // 2070
14,1,25,5,6,3,16,3,28,4, // 2075
9,2,20,6,30,3,11,2,23,4, // 2080
4,3,15,2,27,4,7,3,19,2, // 2085
29,6,11,1,21,6,3,2,13,3, // 2090
25,4,6,2,17,3,27,6,9,1, // 2095
20,5,30,3,10,3,22,4,3,2, // 2100
14,3,24,6,5,2,17,1,28,6, // 2105
9,2,21,4,1,3,13,2,23,6, // 2110
5,1,16,2,27,6,7,3,19,4, // 2115
30,2,11,3,23,4,3,3,14,2, // 2120
25,6,5,3,16,2,28,4,9,3, // 2125
21,4,2,2,12,3,23,6,4,2, // 2130
16,1,26,6,8,2,20,4,30,3, // 2135
11,2,22,6,4,1,14,3,25,5, // 2140
6,3,18,1,29,5,9,3,22,4, // 2145
2,3,13,2,23,6,4,3,15,2, // 2150
27,4,7,3,20,4,1,2,11,3, // 2155
21,6,3,2,15,1,25,6,6,2, // 2160
17,3,29,4,10,2,20,6,3,1, // 2165
13,3,24,5,4,3,17,1,28,5, // 2170
8,3,18,6,1,1,12,2,22,6, // 2175
2,3,14,2,26,4,6,3,17,2, // 2180
28,6,10,1,20,6,1,2,12,3, // 2185
24,4,5,2,15,3,28,4,9,2, // 2190
19,6,33,3,12,1,23,5,3,3, // 2195
13,3,25,4,6,2,16,3,26,6, // 2200
8,2,20,4,30,3,11,2,24,4, // 2205
4,3,15,2,25,6,8,1,18,6, // 2210
33,2,9,3,22,4,3,2,13,3, // 2215
25,4,6,3,17,2,27,6,9,1, // 2220
21,5,1,3,11,3,23,4,5,2, // 2225
15,3,25,6,6,2,19,4,33,3, // 2230
10,2,22,4,3,3,14,2,24,6, // 2235
6,1 // 2240 (Hebrew year: 6000)
};
const int MaxMonthPlusOne = 14;
//
// The lunar calendar has 6 different variations of month lengths
// within a year.
//
private static readonly byte[] LunarMonthLen = {
0,00,00,00,00,00,00,00,00,00,00,00,00,0,
0,30,29,29,29,30,29,30,29,30,29,30,29,0, // 3 common year variations
0,30,29,30,29,30,29,30,29,30,29,30,29,0,
0,30,30,30,29,30,29,30,29,30,29,30,29,0,
0,30,29,29,29,30,30,29,30,29,30,29,30,29, // 3 leap year variations
0,30,29,30,29,30,30,29,30,29,30,29,30,29,
0,30,30,30,29,30,30,29,30,29,30,29,30,29
};
//internal static Calendar m_defaultInstance;
internal static readonly DateTime calendarMinValue = new DateTime(1583, 1, 1);
// Gregorian 2239/9/29 = Hebrew 5999/13/29 (last day in Hebrew year 5999).
// We can only format/parse Hebrew numbers up to 999, so we limit the max range to Hebrew year 5999.
internal static readonly DateTime calendarMaxValue = new DateTime((new DateTime(2239, 9, 29, 23, 59, 59, 999)).Ticks + 9999);
public override DateTime MinSupportedDateTime
{
get
{
return (calendarMinValue);
}
}
public override DateTime MaxSupportedDateTime
{
get
{
return (calendarMaxValue);
}
}
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of HebrewCalendar. Used by NLS+ implementation
** and other calendars.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
/*
internal static Calendar GetDefaultInstance() {
if (m_defaultInstance == null) {
m_defaultInstance = new HebrewCalendar();
}
return (m_defaultInstance);
}
*/
// Construct an instance of gregorian calendar.
public HebrewCalendar()
{
}
internal override CalendarId ID
{
get
{
return (CalendarId.HEBREW);
}
}
/*=================================CheckHebrewYearValue==========================
**Action: Check if the Hebrew year value is supported in this class.
**Returns: None.
**Arguments: y Hebrew year value
** ear Hebrew era value
**Exceptions: ArgumentOutOfRange_Range if the year value is not supported.
**Note:
** We use a table for the Hebrew calendar calculation, so the year supported is limited.
============================================================================*/
static private void CheckHebrewYearValue(int y, int era, String varName)
{
CheckEraRange(era);
if (y > MaxHebrewYear || y < MinHebrewYear)
{
throw new ArgumentOutOfRangeException(
varName,
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
MinHebrewYear,
MaxHebrewYear));
}
}
/*=================================CheckHebrewMonthValue==========================
**Action: Check if the Hebrew month value is valid.
**Returns: None.
**Arguments: year Hebrew year value
** month Hebrew month value
**Exceptions: ArgumentOutOfRange_Range if the month value is not valid.
**Note:
** Call CheckHebrewYearValue() before calling this to verify the year value is supported.
============================================================================*/
private void CheckHebrewMonthValue(int year, int month, int era)
{
int monthsInYear = GetMonthsInYear(year, era);
if (month < 1 || month > monthsInYear)
{
throw new ArgumentOutOfRangeException(
"month",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
monthsInYear));
}
}
/*=================================CheckHebrewDayValue==========================
**Action: Check if the Hebrew day value is valid.
**Returns: None.
**Arguments: year Hebrew year value
** month Hebrew month value
** day Hebrew day value.
**Exceptions: ArgumentOutOfRange_Range if the day value is not valid.
**Note:
** Call CheckHebrewYearValue()/CheckHebrewMonthValue() before calling this to verify the year/month values are valid.
============================================================================*/
private void CheckHebrewDayValue(int year, int month, int day, int era)
{
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
"day",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
daysInMonth));
}
}
static internal void CheckEraRange(int era)
{
if (era != CurrentEra && era != HebrewEra)
{
throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue);
}
}
static private void CheckTicksRange(long ticks)
{
if (ticks < calendarMinValue.Ticks || ticks > calendarMaxValue.Ticks)
{
throw new ArgumentOutOfRangeException(
"time",
// Print out the date in Gregorian using InvariantCulture since the DateTime is based on GreograinCalendar.
String.Format(
CultureInfo.InvariantCulture,
SR.ArgumentOutOfRange_CalendarRange,
calendarMinValue,
calendarMaxValue));
}
}
static internal int GetResult(__DateBuffer result, int part)
{
switch (part)
{
case DatePartYear:
return (result.year);
case DatePartMonth:
return (result.month);
case DatePartDay:
return (result.day);
}
throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing);
}
/*=================================GetLunarMonthDay==========================
**Action: Using the Hebrew table (HebrewTable) to get the Hebrew month/day value for Gregorian January 1st
** in a given Gregorian year.
** Greogrian January 1st falls usually in Tevet (4th month). Tevet has always 29 days.
** That's why, there no nead to specify the lunar month in the table. There are exceptions, and these
** are coded by giving numbers above 29 and below 1.
** Actual decoding is takenig place in the switch statement below.
**Returns:
** The Hebrew year type. The value is from 1 to 6.
** normal years : 1 = 353 days 2 = 354 days 3 = 355 days.
** Leap years : 4 = 383 5 384 6 = 385 days.
**Arguments:
** gregorianYear The year value in Gregorian calendar. The value should be between 1500 and 2239.
** lunarDate Object to take the result of the Hebrew year/month/day.
**Exceptions:
============================================================================*/
static internal int GetLunarMonthDay(int gregorianYear, __DateBuffer lunarDate)
{
//
// Get the offset into the LunarMonthLen array and the lunar day
// for January 1st.
//
int index = gregorianYear - FirstGregorianTableYear;
if (index < 0 || index > TABLESIZE)
{
throw new ArgumentOutOfRangeException("gregorianYear");
}
index *= 2;
lunarDate.day = HebrewTable[index];
// Get the type of the year. The value is from 1 to 6
int LunarYearType = HebrewTable[index + 1];
//
// Get the Lunar Month.
//
switch (lunarDate.day)
{
case (0): // 1/1 is on Shvat 1
lunarDate.month = 5;
lunarDate.day = 1;
break;
case (30): // 1/1 is on Kislev 30
lunarDate.month = 3;
break;
case (31): // 1/1 is on Shvat 2
lunarDate.month = 5;
lunarDate.day = 2;
break;
case (32): // 1/1 is on Shvat 3
lunarDate.month = 5;
lunarDate.day = 3;
break;
case (33): // 1/1 is on Kislev 29
lunarDate.month = 3;
lunarDate.day = 29;
break;
default: // 1/1 is on Tevet (This is the general case)
lunarDate.month = 4;
break;
}
return (LunarYearType);
}
// Returns a given date part of this DateTime. This method is used
// to compute the year, day-of-year, month, or day part.
internal virtual int GetDatePart(long ticks, int part)
{
// The Gregorian year, month, day value for ticks.
int gregorianYear, gregorianMonth, gregorianDay;
int hebrewYearType; // lunar year type
long AbsoluteDate; // absolute date - absolute date 1/1/1600
//
// Make sure we have a valid Gregorian date that will fit into our
// Hebrew conversion limits.
//
CheckTicksRange(ticks);
DateTime time = new DateTime(ticks);
//
// Save the Gregorian date values.
//
gregorianYear = time.Year;
gregorianMonth = time.Month;
gregorianDay = time.Day;
__DateBuffer lunarDate = new __DateBuffer(); // lunar month and day for Jan 1
// From the table looking-up value of HebrewTable[index] (stored in lunarDate.day), we get the the
// lunar month and lunar day where the Gregorian date 1/1 falls.
lunarDate.year = gregorianYear + HebrewYearOf1AD;
hebrewYearType = GetLunarMonthDay(gregorianYear, lunarDate);
// This is the buffer used to store the result Hebrew date.
__DateBuffer result = new __DateBuffer();
//
// Store the values for the start of the new year - 1/1.
//
result.year = lunarDate.year;
result.month = lunarDate.month;
result.day = lunarDate.day;
//
// Get the absolute date from 1/1/1600.
//
AbsoluteDate = GregorianCalendar.GetAbsoluteDate(gregorianYear, gregorianMonth, gregorianDay);
//
// If the requested date was 1/1, then we're done.
//
if ((gregorianMonth == 1) && (gregorianDay == 1))
{
return (GetResult(result, part));
}
//
// Calculate the number of days between 1/1 and the requested date.
//
long NumDays; // number of days since 1/1
NumDays = AbsoluteDate - GregorianCalendar.GetAbsoluteDate(gregorianYear, 1, 1);
//
// If the requested date is within the current lunar month, then
// we're done.
//
if ((NumDays + (long)lunarDate.day) <= (long)(LunarMonthLen[hebrewYearType * MaxMonthPlusOne + lunarDate.month]))
{
result.day += (int)NumDays;
return (GetResult(result, part));
}
//
// Adjust for the current partial month.
//
result.month++;
result.day = 1;
//
// Adjust the Lunar Month and Year (if necessary) based on the number
// of days between 1/1 and the requested date.
//
// Assumes Jan 1 can never translate to the last Lunar month, which
// is true.
//
NumDays -= (long)(LunarMonthLen[hebrewYearType * MaxMonthPlusOne + lunarDate.month] - lunarDate.day);
Contract.Assert(NumDays >= 1, "NumDays >= 1");
// If NumDays is 1, then we are done. Otherwise, find the correct Hebrew month
// and day.
if (NumDays > 1)
{
//
// See if we're on the correct Lunar month.
//
while (NumDays > (long)(LunarMonthLen[hebrewYearType * MaxMonthPlusOne + result.month]))
{
//
// Adjust the number of days and move to the next month.
//
NumDays -= (long)(LunarMonthLen[hebrewYearType * MaxMonthPlusOne + result.month++]);
//
// See if we need to adjust the Year.
// Must handle both 12 and 13 month years.
//
if ((result.month > 13) || (LunarMonthLen[hebrewYearType * MaxMonthPlusOne + result.month] == 0))
{
//
// Adjust the Year.
//
result.year++;
hebrewYearType = HebrewTable[(gregorianYear + 1 - FirstGregorianTableYear) * 2 + 1];
//
// Adjust the Month.
//
result.month = 1;
}
}
//
// Found the right Lunar month.
//
result.day += (int)(NumDays - 1);
}
return (GetResult(result, part));
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public override DateTime AddMonths(DateTime time, int months)
{
try
{
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int monthsInYear;
int i;
if (months >= 0)
{
i = m + months;
while (i > (monthsInYear = GetMonthsInYear(y, CurrentEra)))
{
y++;
i -= monthsInYear;
}
}
else
{
if ((i = m + months) <= 0)
{
months = -months;
months -= m;
y--;
while (months > (monthsInYear = GetMonthsInYear(y, CurrentEra)))
{
y--;
months -= monthsInYear;
}
monthsInYear = GetMonthsInYear(y, CurrentEra);
i = monthsInYear - months;
}
}
int days = GetDaysInMonth(y, i);
if (d > days)
{
d = days;
}
return (new DateTime(ToDateTime(y, i, d, 0, 0, 0, 0).Ticks + (time.Ticks % TicksPerDay)));
}
// We expect ArgumentException and ArgumentOutOfRangeException (which is subclass of ArgumentException)
// If exception is thrown in the calls above, we are out of the supported range of this calendar.
catch (ArgumentException)
{
throw new ArgumentOutOfRangeException(
"months",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_AddValue));
}
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public override DateTime AddYears(DateTime time, int years)
{
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
y += years;
CheckHebrewYearValue(y, Calendar.CurrentEra, "years");
int months = GetMonthsInYear(y, CurrentEra);
if (m > months)
{
m = months;
}
int days = GetDaysInMonth(y, m);
if (d > days)
{
d = days;
}
long ticks = ToDateTime(y, m, d, 0, 0, 0, 0).Ticks + (time.Ticks % TicksPerDay);
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public override int GetDayOfMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDay));
}
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public override DayOfWeek GetDayOfWeek(DateTime time)
{
// If we calculate back, the Hebrew day of week for Gregorian 0001/1/1 is Monday (1).
// Therfore, the fomula is:
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
static internal int GetHebrewYearType(int year, int era)
{
CheckHebrewYearValue(year, era, "year");
// The HebrewTable is indexed by Gregorian year and starts from FirstGregorianYear.
// So we need to convert year (Hebrew year value) to Gregorian Year below.
return (HebrewTable[(year - HebrewYearOf1AD - FirstGregorianTableYear) * 2 + 1]);
}
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public override int GetDayOfYear(DateTime time)
{
// Get Hebrew year value of the specified time.
int year = GetYear(time);
DateTime beginOfYearDate;
if (year == 5343)
{
// Gregorian 1583/01/01 corresponds to Hebrew 5343/04/07 (MinSupportedDateTime)
// To figure out the Gregorian date associated with Hebrew 5343/01/01, we need to
// count the days from 5343/01/01 to 5343/04/07 and subtract that from Gregorian
// 1583/01/01.
// 1. Tishri (30 days)
// 2. Heshvan (30 days since 5343 has 355 days)
// 3. Kislev (30 days since 5343 has 355 days)
// 96 days to get from 5343/01/01 to 5343/04/07
// Gregorian 1583/01/01 - 96 days = 1582/9/27
// the beginning of Hebrew year 5343 corresponds to Gregorian September 27, 1582.
beginOfYearDate = new DateTime(1582, 9, 27);
}
else
{
// following line will fail when year is 5343 (first supported year)
beginOfYearDate = ToDateTime(year, 1, 1, 0, 0, 0, 0, CurrentEra);
}
return ((int)((time.Ticks - beginOfYearDate.Ticks) / TicksPerDay) + 1);
}
// Returns the number of days in the month given by the year and
// month arguments.
//
public override int GetDaysInMonth(int year, int month, int era)
{
CheckEraRange(era);
int hebrewYearType = GetHebrewYearType(year, era);
CheckHebrewMonthValue(year, month, era);
Contract.Assert(hebrewYearType >= 1 && hebrewYearType <= 6,
"hebrewYearType should be from 1 to 6, but now hebrewYearType = " + hebrewYearType + " for hebrew year " + year);
int monthDays = LunarMonthLen[hebrewYearType * MaxMonthPlusOne + month];
if (monthDays == 0)
{
throw new ArgumentOutOfRangeException("month", SR.ArgumentOutOfRange_Month);
}
return (monthDays);
}
// Returns the number of days in the year given by the year argument for the current era.
//
public override int GetDaysInYear(int year, int era)
{
CheckEraRange(era);
// normal years : 1 = 353 days 2 = 354 days 3 = 355 days.
// Leap years : 4 = 383 5 384 6 = 385 days.
// LunarYearType is from 1 to 6
int LunarYearType = GetHebrewYearType(year, era);
if (LunarYearType < 4)
{
// common year: LunarYearType = 1, 2, 3
return (352 + LunarYearType);
}
return (382 + (LunarYearType - 3));
}
// Returns the era for the specified DateTime value.
public override int GetEra(DateTime time)
{
return (HebrewEra);
}
public override int[] Eras
{
get
{
return (new int[] { HebrewEra });
}
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public override int GetMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartMonth));
}
// Returns the number of months in the specified year and era.
public override int GetMonthsInYear(int year, int era)
{
return (IsLeapYear(year, era) ? 13 : 12);
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and 9999.
//
public override int GetYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartYear));
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public override bool IsLeapDay(int year, int month, int day, int era)
{
if (IsLeapMonth(year, month, era))
{
// Every day in a leap month is a leap day.
CheckHebrewDayValue(year, month, day, era);
return (true);
}
else if (IsLeapYear(year, Calendar.CurrentEra))
{
// There is an additional day in the 6th month in the leap year (the extra day is the 30th day in the 6th month),
// so we should return true for 6/30 if that's in a leap year.
if (month == 6 && day == 30)
{
return (true);
}
}
CheckHebrewDayValue(year, month, day, era);
return (false);
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public override int GetLeapMonth(int year, int era)
{
// Year/era values are checked in IsLeapYear().
if (IsLeapYear(year, era))
{
// The 7th month in a leap year is a leap month.
return (7);
}
return (0);
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public override bool IsLeapMonth(int year, int month, int era)
{
// Year/era values are checked in IsLeapYear().
bool isLeapYear = IsLeapYear(year, era);
CheckHebrewMonthValue(year, month, era);
// The 7th month in a leap year is a leap month.
if (isLeapYear)
{
if (month == 7)
{
return (true);
}
}
return (false);
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public override bool IsLeapYear(int year, int era)
{
CheckHebrewYearValue(year, era, "year");
return (((7 * (long)year + 1) % 19) < 7);
}
// (month1, day1) - (month2, day2)
static int GetDayDifference(int lunarYearType, int month1, int day1, int month2, int day2)
{
if (month1 == month2)
{
return (day1 - day2);
}
// Make sure that (month1, day1) < (month2, day2)
bool swap = (month1 > month2);
if (swap)
{
// (month1, day1) < (month2, day2). Swap the values.
// The result will be a negative number.
int tempMonth, tempDay;
tempMonth = month1; tempDay = day1;
month1 = month2; day1 = day2;
month2 = tempMonth; day2 = tempDay;
}
// Get the number of days from (month1,day1) to (month1, end of month1)
int days = LunarMonthLen[lunarYearType * MaxMonthPlusOne + month1] - day1;
// Move to next month.
month1++;
// Add up the days.
while (month1 < month2)
{
days += LunarMonthLen[lunarYearType * MaxMonthPlusOne + month1++];
}
days += day2;
return (swap ? days : -days);
}
/*=================================HebrewToGregorian==========================
**Action: Convert Hebrew date to Gregorian date.
**Returns:
**Arguments:
**Exceptions:
** The algorithm is like this:
** The hebrew year has an offset to the Gregorian year, so we can guess the Gregorian year for
** the specified Hebrew year. That is, GreogrianYear = HebrewYear - FirstHebrewYearOf1AD.
**
** From the Gregorian year and HebrewTable, we can get the Hebrew month/day value
** of the Gregorian date January 1st. Let's call this month/day value [hebrewDateForJan1]
**
** If the requested Hebrew month/day is less than [hebrewDateForJan1], we know the result
** Gregorian date falls in previous year. So we decrease the Gregorian year value, and
** retrieve the Hebrew month/day value of the Gregorian date january 1st again.
**
** Now, we get the answer of the Gregorian year.
**
** The next step is to get the number of days between the requested Hebrew month/day
** and [hebrewDateForJan1]. When we get that, we can create the DateTime by adding/subtracting
** the ticks value of the number of days.
**
============================================================================*/
static DateTime HebrewToGregorian(int hebrewYear, int hebrewMonth, int hebrewDay, int hour, int minute, int second, int millisecond)
{
// Get the rough Gregorian year for the specified hebrewYear.
//
int gregorianYear = hebrewYear - HebrewYearOf1AD;
__DateBuffer hebrewDateOfJan1 = new __DateBuffer(); // year value is unused.
int lunarYearType = GetLunarMonthDay(gregorianYear, hebrewDateOfJan1);
if ((hebrewMonth == hebrewDateOfJan1.month) && (hebrewDay == hebrewDateOfJan1.day))
{
return (new DateTime(gregorianYear, 1, 1, hour, minute, second, millisecond));
}
int days = GetDayDifference(lunarYearType, hebrewMonth, hebrewDay, hebrewDateOfJan1.month, hebrewDateOfJan1.day);
DateTime gregorianNewYear = new DateTime(gregorianYear, 1, 1);
return (new DateTime(gregorianNewYear.Ticks + days * TicksPerDay
+ TimeToTicks(hour, minute, second, millisecond)));
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
CheckHebrewYearValue(year, era, "year");
CheckHebrewMonthValue(year, month, era);
CheckHebrewDayValue(year, month, day, era);
DateTime dt = HebrewToGregorian(year, month, day, hour, minute, second, millisecond);
CheckTicksRange(dt.Ticks);
return (dt);
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 5790;
public override int TwoDigitYearMax
{
get
{
if (twoDigitYearMax == -1)
{
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value == 99)
{
// Do nothing here. Year 99 is allowed so that TwoDitYearMax is disabled.
}
else
{
CheckHebrewYearValue(value, HebrewEra, "value");
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException("year",
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
if (year < 100)
{
return (base.ToFourDigitYear(year));
}
if (year > MaxHebrewYear || year < MinHebrewYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
MinHebrewYear,
MaxHebrewYear));
}
return (year);
}
internal class __DateBuffer
{
internal int year;
internal int month;
internal int day;
}
}
}
| |
//! \file ArcTCD3.cs
//! \date Thu Oct 08 13:14:57 2015
//! \brief TopCat data archives (TCD)
//
// Copyright (C) 2015 by morkt
//
// 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.ComponentModel.Composition;
using System.IO;
using System.Linq;
using GameRes.Utility;
namespace GameRes.Formats.TopCat
{
internal class TcdSection
{
public uint DataSize;
public uint IndexOffset;
public int DirCount;
public int DirNameLength;
public int FileCount;
public int FileNameLength;
}
internal struct TcdDirEntry
{
public int FileCount;
public int NamesOffset;
public int FirstIndex;
}
internal class TcdEntry : AutoEntry
{
public int Index;
public TcdEntry (int index, string name, ArcView file, long offset)
: base (name, () => DetectFileType (file, offset))
{
Index = index;
Offset = offset;
}
new private static IResource DetectFileType (ArcView file, long offset)
{
uint signature = file.View.ReadUInt32 (offset);
return FormatCatalog.Instance.LookupSignature (signature).FirstOrDefault();
}
}
internal class TcdArchive : ArcFile
{
public int? Key;
public TcdArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir)
: base (arc, impl, dir)
{
}
}
[Serializable]
public class TcdScheme : ResourceScheme
{
public Dictionary<string, int> KnownKeys;
}
[Export(typeof(ArchiveFormat))]
public class TcdOpener : ArchiveFormat
{
public override string Tag { get { return "TCD3"; } }
public override string Description { get { return "TopCat data archive"; } }
public override uint Signature { get { return 0x33444354; } } // 'TCD3'
public override bool IsHierarchic { get { return true; } }
public override bool CanCreate { get { return false; } }
public TcdOpener ()
{
Extensions = new string[] { "tcd" };
}
public static Dictionary<string, int> KnownKeys = new Dictionary<string, int>();
public override ResourceScheme Scheme
{
get { return new TcdScheme { KnownKeys = KnownKeys }; }
set { KnownKeys = ((TcdScheme)value).KnownKeys; }
}
public override ArcFile TryOpen (ArcView file)
{
int count = file.View.ReadInt32 (4);
if (!IsSaneCount (count))
return null;
uint current_offset = 8;
var sections = new List<TcdSection> (5);
for (int i = 0; i < 5; ++i, current_offset += 0x20)
{
uint index_offset = file.View.ReadUInt32 (current_offset+4);
if (0 == index_offset)
continue;
var section = new TcdSection
{
IndexOffset = index_offset,
DataSize = file.View.ReadUInt32 (current_offset),
DirCount = file.View.ReadInt32 (current_offset+8),
DirNameLength = file.View.ReadInt32 (current_offset+0x0C),
FileCount = file.View.ReadInt32 (current_offset+0x10),
FileNameLength = file.View.ReadInt32 (current_offset+0x14),
};
sections.Add (section);
}
var list = new List<Entry> (count);
foreach (var section in sections)
{
current_offset = section.IndexOffset;
uint dir_size = (uint)(section.DirCount * section.DirNameLength);
var dir_names = new byte[dir_size];
if (dir_size != file.View.Read (current_offset, dir_names, 0, dir_size))
return null;
current_offset += dir_size;
DecryptNames (dir_names, section.DirNameLength);
var dirs = new TcdDirEntry[section.DirCount];
for (int i = 0; i < dirs.Length; ++i)
{
dirs[i].FileCount = file.View.ReadInt32 (current_offset);
dirs[i].NamesOffset = file.View.ReadInt32 (current_offset+4);
dirs[i].FirstIndex = file.View.ReadInt32 (current_offset+8);
current_offset += 0x10;
}
uint entries_size = (uint)(section.FileCount * section.FileNameLength);
var file_names = new byte[entries_size];
if (entries_size != file.View.Read (current_offset, file_names, 0, entries_size))
return null;
current_offset += entries_size;
DecryptNames (file_names, section.FileNameLength);
var offsets = new uint[section.FileCount + 1];
for (int i = 0; i < offsets.Length; ++i)
{
offsets[i] = file.View.ReadUInt32 (current_offset);
current_offset += 4;
}
int dir_name_offset = 0;
foreach (var dir in dirs)
{
string dir_name = Binary.GetCString (dir_names, dir_name_offset, section.DirNameLength);
dir_name_offset += section.DirNameLength;
int index = dir.FirstIndex;
int name_offset = dir.NamesOffset;
for (int i = 0; i < dir.FileCount; ++i)
{
string name = Binary.GetCString (file_names, name_offset, section.FileNameLength);
name_offset += section.FileNameLength;
name = dir_name + '\\' + name;
var entry = new TcdEntry (index, name, file, offsets[index]);
entry.Size = offsets[index+1] - offsets[index];
++index;
list.Add (entry);
}
}
}
return new TcdArchive (file, this, list);
}
private void DecryptNames (byte[] buffer, int name_length)
{
byte key = buffer[name_length-1];
for (int i = 0; i < buffer.Length; ++i)
buffer[i] -= key;
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
var tcde = entry as TcdEntry;
var tcda = arc as TcdArchive;
if (null == tcde || null == tcda || entry.Size <= 0x14)
return arc.File.CreateStream (entry.Offset, entry.Size);
int signature = arc.File.View.ReadInt32 (entry.Offset);
if (0x43445053 == signature) // 'SPDC'
return arc.File.CreateStream (entry.Offset, entry.Size);
if (0x5367674F == signature) // 'OggS'
return DecryptOgg (arc, entry);
var header = new byte[0x14];
arc.File.View.Read (entry.Offset, header, 0, 0x14);
bool spdc_entry = false;
if (null == tcda.Key)
{
foreach (var key in KnownKeys.Values)
{
int first = signature + key * (tcde.Index + 3);
if (0x43445053 == first) // 'SPDC'
{
tcda.Key = key;
spdc_entry = true;
break;
}
}
}
else if (0x43445053 == signature + tcda.Key.Value * (tcde.Index + 3))
{
spdc_entry = true;
}
if (spdc_entry && 0 != tcda.Key.Value)
{
unsafe
{
fixed (byte* raw = header)
{
int* dw = (int*)raw;
for (int i = 0; i < 5; ++i)
dw[i] += tcda.Key.Value * (tcde.Index + 3 + i);
}
}
}
var rest = arc.File.CreateStream (entry.Offset+0x14, entry.Size-0x14);
return new PrefixStream (header, rest);
}
static Lazy<uint[]> OggCrcTable = new Lazy<uint[]> (InitOggCrcTable);
static uint[] InitOggCrcTable ()
{
var table = new uint[0x100];
for (uint i = 0; i < 0x100; ++i)
{
uint a = i << 24;
for (int j = 0; j < 8; ++j)
{
bool carry = 0 != (a & 0x80000000);
a <<= 1;
if (carry)
a ^= 0x04C11DB7;
}
table[i] = a;
}
return table;
}
Stream DecryptOgg (ArcFile arc, Entry entry)
{
var data = new byte[entry.Size];
arc.File.View.Read (entry.Offset, data, 0, entry.Size);
int remaining = data.Length;
int src = 0;
while (remaining > 0x1B && Binary.AsciiEqual (data, src, "OggS"))
{
int d = data[src+0x1A];
data[src+0x16] = 0;
data[src+0x17] = 0;
data[src+0x18] = 0;
data[src+0x19] = 0;
int dst = src + 0x1B;
int count = d + 0x1B;
if (d != 0)
{
if (remaining < count)
break;
for (int i = 0; i < d; ++i)
count += data[dst++];
}
remaining -= count;
if (remaining < 0)
break;
dst = src + 0x16;
uint crc = 0;
for (int i = 0; i < count; ++i)
{
uint x = (crc >> 24) ^ data[src++];
crc <<= 8;
crc ^= OggCrcTable.Value[x];
}
LittleEndian.Pack (crc, data, dst);
}
return new MemoryStream (data);
}
}
}
| |
//
// HyenaSqliteCommand.cs
//
// Authors:
// Aaron Bockover <[email protected]>
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2007-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Text;
using System.Threading;
namespace Hyena.Data.Sqlite
{
public class CommandExecutedArgs : EventArgs
{
public CommandExecutedArgs (string sql, int ms)
{
Sql = sql;
Ms = ms;
}
public string Sql;
public int Ms;
}
public class HyenaSqliteCommand
{
private object result = null;
private Exception execution_exception = null;
private bool finished = false;
private ManualResetEvent finished_event = new ManualResetEvent (true);
private string command;
private string command_format = null;
private string command_formatted = null;
private int parameter_count = 0;
private object [] current_values;
private int ticks;
public string Text {
get { return command; }
}
public bool ReaderDisposes { get; set; }
internal HyenaCommandType CommandType;
public HyenaSqliteCommand (string command)
{
this.command = command;
}
public HyenaSqliteCommand (string command, params object [] param_values)
{
this.command = command;
ApplyValues (param_values);
}
internal void Execute (HyenaSqliteConnection hconnection, Connection connection)
{
if (finished) {
throw new Exception ("Command is already set to finished; result needs to be claimed before command can be rerun");
}
execution_exception = null;
result = null;
int execution_ms = 0;
string command_text = null;
try {
command_text = CurrentSqlText;
ticks = System.Environment.TickCount;
switch (CommandType) {
case HyenaCommandType.Reader:
using (var reader = connection.Query (command_text)) {
result = new ArrayDataReader (reader, command_text);
}
break;
case HyenaCommandType.Scalar:
result = connection.Query<object> (command_text);
break;
case HyenaCommandType.Execute:
default:
connection.Execute (command_text);
result = connection.LastInsertRowId;
break;
}
execution_ms = System.Environment.TickCount - ticks;
if (log_all) {
Log.DebugFormat ("Executed in {0}ms {1}", execution_ms, command_text);
} else if (Log.Debugging && execution_ms > 500) {
Log.WarningFormat ("Executed in {0}ms {1}", execution_ms, command_text);
}
} catch (Exception e) {
Log.DebugFormat ("Exception executing command: {0}", command_text ?? command);
Log.Exception (e);
execution_exception = e;
}
// capture the text
string raise_text = null;
if (raise_command_executed && execution_ms >= raise_command_executed_threshold_ms) {
raise_text = Text;
}
finished_event.Reset ();
finished = true;
if (raise_command_executed && execution_ms >= raise_command_executed_threshold_ms) {
var handler = CommandExecuted;
if (handler != null) {
// Don't raise this on this thread; this thread is dedicated for use by the db connection
ThreadAssist.ProxyToMain (delegate {
handler (this, new CommandExecutedArgs (raise_text, execution_ms));
});
}
}
}
internal object WaitForResult (HyenaSqliteConnection conn)
{
while (!finished) {
conn.ResultReadySignal.WaitOne ();
}
// Reference the results since they could be overwritten
object ret = result;
var exception = execution_exception;
// Reset to false in case run again
finished = false;
conn.ClaimResult ();
finished_event.Set ();
if (exception != null) {
throw exception;
}
return ret;
}
internal void WaitIfNotFinished ()
{
finished_event.WaitOne ();
}
internal HyenaSqliteCommand ApplyValues (params object [] param_values)
{
if (command_format == null) {
CreateParameters ();
}
// Special case for if a single null values is the paramter array
if (parameter_count == 1 && param_values == null) {
current_values = new object [] { "NULL" };
command_formatted = null;
return this;
}
if (param_values.Length != parameter_count) {
throw new ArgumentException (String.Format (
"Command {2} has {0} parameters, but {1} values given.", parameter_count, param_values.Length, command
));
}
// Transform values as necessary - not needed for numerical types
for (int i = 0; i < parameter_count; i++) {
param_values[i] = SqlifyObject (param_values[i]);
}
current_values = param_values;
command_formatted = null;
return this;
}
public static object SqlifyObject (object o)
{
if (o is string) {
return String.Format ("'{0}'", (o as string).Replace ("'", "''"));
} else if (o is DateTime) {
return DateTimeUtil.FromDateTime ((DateTime) o);
} else if (o is bool) {
return ((bool)o) ? "1" : "0";
} else if (o == null) {
return "NULL";
} else if (o is byte[]) {
string hex = BitConverter.ToString (o as byte[]).Replace ("-", "");
return String.Format ("X'{0}'", hex);
} else if (o is Array) {
StringBuilder sb = new StringBuilder ();
bool first = true;
foreach (object i in (o as Array)) {
if (!first)
sb.Append (",");
else
first = false;
sb.Append (SqlifyObject (i));
}
return sb.ToString ();
} else {
return o;
}
}
private string CurrentSqlText {
get {
if (command_format == null) {
return command;
}
if (command_formatted == null) {
command_formatted = String.Format (System.Globalization.CultureInfo.InvariantCulture, command_format, current_values);
}
return command_formatted;
}
}
private void CreateParameters ()
{
StringBuilder sb = new StringBuilder ();
foreach (char c in command) {
if (c == '?') {
sb.Append ('{');
sb.Append (parameter_count++);
sb.Append ('}');
} else {
sb.Append (c);
}
}
command_format = sb.ToString ();
}
#region Static Debugging Facilities
private static bool log_all = false;
public static bool LogAll {
get { return log_all; }
set { log_all = value; }
}
public delegate void CommandExecutedHandler (object o, CommandExecutedArgs args);
public static event CommandExecutedHandler CommandExecuted;
private static bool raise_command_executed = false;
public static bool RaiseCommandExecuted {
get { return raise_command_executed; }
set { raise_command_executed = value; }
}
private static int raise_command_executed_threshold_ms = 400;
public static int RaiseCommandExecutedThresholdMs {
get { return raise_command_executed_threshold_ms; }
set { raise_command_executed_threshold_ms = value; }
}
#endregion
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using fyiReporting.RDL;
namespace fyiReporting.RDL
{
/// <summary>
/// Process a custom instance method request.
/// </summary>
[Serializable]
internal class FunctionCustomInstance : IExpr
{
string _Cls; // class name
string _Func; // function/operator
IExpr[] _Args; // arguments
ReportClass _Rc; // ReportClass
TypeCode _ReturnTypeCode; // the return type
Type[] _ArgTypes; // argument types
/// <summary>
/// passed ReportClass, function name, and args for evaluation
/// </summary>
public FunctionCustomInstance(ReportClass rc, string f, IExpr[] a, TypeCode type)
{
_Cls = null;
_Func = f;
_Args = a;
_Rc = rc;
_ReturnTypeCode = type;
_ArgTypes = new Type[a.Length];
int i=0;
foreach (IExpr ex in a)
{
_ArgTypes[i++] = XmlUtil.GetTypeFromTypeCode(ex.GetTypeCode());
}
}
public TypeCode GetTypeCode()
{
return _ReturnTypeCode;
}
public bool IsConstant()
{
return false; // Can't know what the function does
}
public IExpr ConstantOptimization()
{
// Do constant optimization on all the arguments
for (int i=0; i < _Args.GetLength(0); i++)
{
IExpr e = (IExpr)_Args[i];
_Args[i] = e.ConstantOptimization();
}
// Can't assume that the function doesn't vary
// based on something other than the args e.g. Now()
return this;
}
// Evaluate is for interpretation (and is relatively slow)
public object Evaluate(Report rpt, Row row)
{
// get the results
object[] argResults = new object[_Args.Length];
int i=0;
bool bUseArg=true;
bool bNull = false;
foreach(IExpr a in _Args)
{
argResults[i] = a.Evaluate(rpt, row);
if (argResults[i] == null)
bNull = true;
else if (argResults[i].GetType() != _ArgTypes[i])
bUseArg = false;
i++;
}
// we build the arguments based on the type
Type[] argTypes = bUseArg || bNull? _ArgTypes: Type.GetTypeArray(argResults);
// We can definitely optimize this by caching some info TODO
// Get ready to call the function
Object returnVal;
object inst = _Rc.Instance(rpt);
Type theClassType=inst.GetType();
MethodInfo mInfo = XmlUtil.GetMethod(theClassType, _Func, argTypes);
if (mInfo == null)
{
throw new Exception(string.Format("{0} method not found in class {1}", _Func, _Cls));
}
returnVal = mInfo.Invoke(inst, argResults);
return returnVal;
}
public double EvaluateDouble(Report rpt, Row row)
{
return Convert.ToDouble(Evaluate(rpt, row));
}
public decimal EvaluateDecimal(Report rpt, Row row)
{
return Convert.ToDecimal(Evaluate(rpt, row));
}
public int EvaluateInt32(Report rpt, Row row)
{
return Convert.ToInt32(Evaluate(rpt, row));
}
public string EvaluateString(Report rpt, Row row)
{
return Convert.ToString(Evaluate(rpt, row));
}
public DateTime EvaluateDateTime(Report rpt, Row row)
{
return Convert.ToDateTime(Evaluate(rpt, row));
}
public bool EvaluateBoolean(Report rpt, Row row)
{
return Convert.ToBoolean(Evaluate(rpt, row));
}
public string Cls
{
get { return _Cls; }
set { _Cls = value; }
}
public string Func
{
get { return _Func; }
set { _Func = value; }
}
public IExpr[] Args
{
get { return _Args; }
set { _Args = value; }
}
}
#if DEBUG
internal class TestFunction // for testing CodeModules, Classes, and the Function class
{
int counter=0;
public TestFunction()
{
counter=0;
}
public int count()
{
return counter++;
}
public int count(string s)
{
counter++;
return Convert.ToInt32(s) + counter;
}
static public double sqrt(double x)
{
return Math.Sqrt(x);
}
}
#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 OLEDB.Test.ModuleCore;
using System.IO;
using System.Text;
using XmlCoreTest.Common;
namespace System.Xml.Tests
{
[InheritRequired()]
public abstract partial class TCReadContentAsBase64 : TCXMLReaderBaseGeneral
{
public const string ST_ELEM_NAME1 = "ElemAll";
public const string ST_ELEM_NAME2 = "ElemEmpty";
public const string ST_ELEM_NAME3 = "ElemNum";
public const string ST_ELEM_NAME4 = "ElemText";
public const string ST_ELEM_NAME5 = "ElemNumText";
public const string ST_ELEM_NAME6 = "ElemLong";
public const string Base64Xml = "Base64.xml";
public const string strTextBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
public const string strNumBase64 = "0123456789+/";
public override int Init(object objParam)
{
int ret = base.Init(objParam);
CreateTestFile(EREADER_TYPE.BASE64_TEST);
return ret;
}
public override int Terminate(object objParam)
{
DataReader.Close();
return base.Terminate(objParam);
}
private bool VerifyInvalidReadBase64(int iBufferSize, int iIndex, int iCount, Type exceptionType)
{
bool bPassed = false;
byte[] buffer = new byte[iBufferSize];
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement(ST_ELEM_NAME1);
DataReader.Read();
if (CheckCanReadBinaryContent()) return true;
try
{
DataReader.ReadContentAsBase64(buffer, iIndex, iCount);
}
catch (Exception e)
{
CError.WriteLine("Actual exception:{0}", e.GetType().ToString());
CError.WriteLine("Expected exception:{0}", exceptionType.ToString());
bPassed = (e.GetType().ToString() == exceptionType.ToString());
}
return bPassed;
}
protected void TestOnInvalidNodeType(XmlNodeType nt)
{
ReloadSource();
PositionOnNodeType(nt);
if (CheckCanReadBinaryContent()) return;
try
{
byte[] buffer = new byte[1];
int nBytes = DataReader.ReadContentAsBase64(buffer, 0, 1);
}
catch (InvalidOperationException ioe)
{
if (ioe.ToString().IndexOf(nt.ToString()) < 0)
CError.Compare(false, "Call threw wrong invalid operation exception on " + nt);
else
return;
}
CError.Compare(false, "Call succeeded on " + nt);
}
protected void TestOnNopNodeType(XmlNodeType nt)
{
ReloadSource();
PositionOnNodeType(nt);
string name = DataReader.Name;
string value = DataReader.Value;
CError.WriteLine("Name=" + name);
CError.WriteLine("Value=" + value);
if (CheckCanReadBinaryContent()) return;
byte[] buffer = new byte[1];
int nBytes = DataReader.ReadContentAsBase64(buffer, 0, 1);
CError.Compare(nBytes, 0, "nBytes");
CError.Compare(DataReader.VerifyNode(nt, name, value), "vn");
CError.WriteLine("Succeeded:{0}", nt);
}
////////////////////////////////////////////////////////////////
// Variations
////////////////////////////////////////////////////////////////
[Variation("ReadBase64 Element with all valid value")]
public int TestReadBase64_1()
{
int base64len = 0;
byte[] base64 = new byte[1000];
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement(ST_ELEM_NAME1);
DataReader.Read();
if (CheckCanReadBinaryContent()) return TEST_PASS;
base64len = DataReader.ReadContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
CError.Compare(strActbase64, (strTextBase64 + strNumBase64), "Compare All Valid Base64");
return TEST_PASS;
}
[Variation("ReadBase64 Element with all valid Num value", Pri = 0)]
public int TestReadBase64_2()
{
int base64len = 0;
byte[] base64 = new byte[1000];
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement(ST_ELEM_NAME3);
DataReader.Read();
if (CheckCanReadBinaryContent()) return TEST_PASS;
base64len = DataReader.ReadContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
CError.Compare(strActbase64, strNumBase64, "Compare All Valid Base64");
return TEST_PASS;
}
[Variation("ReadBase64 Element with all valid Text value")]
public int TestReadBase64_3()
{
int base64len = 0;
byte[] base64 = new byte[1000];
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement(ST_ELEM_NAME4);
DataReader.Read();
if (CheckCanReadBinaryContent()) return TEST_PASS;
base64len = DataReader.ReadContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
CError.Compare(strActbase64, strTextBase64, "Compare All Valid Base64");
return TEST_PASS;
}
[Variation("ReadBase64 Element with all valid value (from concatenation), Pri=0")]
public int TestReadBase64_5()
{
int base64len = 0;
byte[] base64 = new byte[1000];
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement(ST_ELEM_NAME5);
DataReader.Read();
if (CheckCanReadBinaryContent()) return TEST_PASS;
base64len = DataReader.ReadContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
CError.Compare(strActbase64, (strTextBase64 + strNumBase64), "Compare All Valid Base64");
return TEST_PASS;
}
[Variation("ReadBase64 Element with Long valid value (from concatenation), Pri=0")]
public int TestReadBase64_6()
{
int base64len = 0;
byte[] base64 = new byte[2000];
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement(ST_ELEM_NAME6);
DataReader.Read();
if (CheckCanReadBinaryContent()) return TEST_PASS;
base64len = DataReader.ReadContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
string strExpbase64 = "";
for (int i = 0; i < 10; i++)
strExpbase64 += (strTextBase64 + strNumBase64);
CError.Compare(strActbase64, strExpbase64, "Compare All Valid Base64");
return TEST_PASS;
}
[Variation("ReadBase64 with count > buffer size")]
public int ReadBase64_7()
{
return BoolToLTMResult(VerifyInvalidReadBase64(5, 0, 6, typeof(ArgumentOutOfRangeException)));
}
[Variation("ReadBase64 with count < 0")]
public int ReadBase64_8()
{
return BoolToLTMResult(VerifyInvalidReadBase64(5, 2, -1, typeof(ArgumentOutOfRangeException)));
}
[Variation("ReadBase64 with index > buffer size")]
public int ReadBase64_9()
{
return BoolToLTMResult(VerifyInvalidReadBase64(5, 5, 1, typeof(ArgumentOutOfRangeException)));
}
[Variation("ReadBase64 with index < 0")]
public int ReadBase64_10()
{
return BoolToLTMResult(VerifyInvalidReadBase64(5, -1, 1, typeof(ArgumentOutOfRangeException)));
}
[Variation("ReadBase64 with index + count exceeds buffer")]
public int ReadBase64_11()
{
return BoolToLTMResult(VerifyInvalidReadBase64(5, 0, 10, typeof(ArgumentOutOfRangeException)));
}
[Variation("ReadBase64 index & count =0")]
public int ReadBase64_12()
{
byte[] buffer = new byte[5];
int iCount = 0;
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement(ST_ELEM_NAME1);
DataReader.Read();
if (CheckCanReadBinaryContent()) return TEST_PASS;
iCount = DataReader.ReadContentAsBase64(buffer, 0, 0);
CError.Compare(iCount, 0, "has to be zero");
return TEST_PASS;
}
[Variation("ReadBase64 Element multiple into same buffer (using offset), Pri=0")]
public int TestReadBase64_13()
{
int base64len = 20;
byte[] base64 = new byte[base64len];
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement(ST_ELEM_NAME4);
DataReader.Read();
if (CheckCanReadBinaryContent()) return TEST_PASS;
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
DataReader.ReadContentAsBase64(base64, i, 2);
strActbase64 = (System.BitConverter.ToChar(base64, i)).ToString();
CError.Compare(String.Compare(strActbase64, 0, strTextBase64, i / 2, 1), 0, "Compare All Valid Base64");
}
return TEST_PASS;
}
[Variation("ReadBase64 with buffer == null")]
public int TestReadBase64_14()
{
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement(ST_ELEM_NAME4);
DataReader.Read();
if (CheckCanReadBinaryContent()) return TEST_PASS;
try
{
DataReader.ReadContentAsBase64(null, 0, 0);
}
catch (ArgumentNullException)
{
return TEST_PASS;
}
return TEST_FAIL;
}
[Variation("ReadBase64 after failure")]
public int TestReadBase64_15()
{
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement("ElemErr");
DataReader.Read();
var line = ((IXmlLineInfo)DataReader.Internal).LinePosition;
if (CheckCanReadBinaryContent()) return TEST_PASS;
byte[] buffer = new byte[10];
int nRead = 0;
try
{
nRead = DataReader.ReadContentAsBase64(buffer, 0, 1);
return TEST_FAIL;
}
catch (XmlException e)
{
if (IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXPathNavigatorReader() || IsXmlValidatingReader() || IsCharCheckingReader())
CheckException("Xml_InvalidBase64Value", e);
else
{
CheckXmlException("Xml_UserException", e, 1, line);
}
}
return TEST_PASS;
}
[Variation("Read after partial ReadBase64", Pri = 0)]
public int TestReadBase64_16()
{
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement("ElemNum");
DataReader.Read();
if (CheckCanReadBinaryContent()) return TEST_PASS;
byte[] buffer = new byte[10];
int nRead = DataReader.ReadContentAsBase64(buffer, 0, 8);
CError.Compare(nRead, 8, "0");
DataReader.Read();
CError.Compare(DataReader.NodeType, XmlNodeType.Element, "1vn");
return TEST_PASS;
}
[Variation("Current node on multiple calls")]
public int TestReadBase64_17()
{
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement("ElemNum");
DataReader.Read();
if (CheckCanReadBinaryContent()) return TEST_PASS;
byte[] buffer = new byte[30];
int nRead = DataReader.ReadContentAsBase64(buffer, 0, 2);
CError.Compare(nRead, 2, "0");
nRead = DataReader.ReadContentAsBase64(buffer, 0, 23);
CError.Compare(nRead, 22, "1");
DataReader.Read();
CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Nodetype not end element");
CError.Compare(DataReader.Name, "ElemText", "Nodetype not end element");
return TEST_PASS;
}
[Variation("ReadBase64 with incomplete sequence")]
public int TestTextReadBase64_23()
{
byte[] expected = new byte[] { 0, 16, 131, 16, 81 };
byte[] buffer = new byte[10];
string strxml = "<r><ROOT>ABCDEFG</ROOT></r>";
ReloadSourceStr(strxml);
DataReader.PositionOnElement("ROOT");
DataReader.Read();
if (CheckCanReadBinaryContent()) return TEST_PASS;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadContentAsBase64(buffer, result, 1)) > 0)
result += nRead;
CError.Compare(result, expected.Length, "res");
for (int i = 0; i < result; i++)
CError.Compare(buffer[i], expected[i], "buffer[" + i + "]");
return TEST_PASS;
}
[Variation("ReadBase64 when end tag doesn't exist")]
public int TestTextReadBase64_24()
{
if (IsRoundTrippedReader())
return TEST_SKIPPED;
byte[] buffer = new byte[5000];
string strxml = "<B>" + new string('c', 5000);
ReloadSourceStr(strxml);
DataReader.PositionOnElement("B");
DataReader.Read();
if (CheckCanReadBinaryContent()) return TEST_PASS;
try
{
DataReader.ReadContentAsBase64(buffer, 0, 5000);
CError.WriteLine("Accepted incomplete element");
return TEST_FAIL;
}
catch (XmlException e)
{
CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004);
}
return TEST_PASS;
}
[Variation("ReadBase64 with whitespaces in the middle")]
public int TestTextReadBase64_26()
{
byte[] buffer = new byte[1];
string strxml = "<abc> AQID B B </abc>";
int nRead;
ReloadSourceStr(strxml);
DataReader.PositionOnElement("abc");
DataReader.Read();
if (CheckCanReadBinaryContent()) return TEST_PASS;
for (int i = 0; i < 4; i++)
{
nRead = DataReader.ReadContentAsBase64(buffer, 0, 1);
CError.Compare(nRead, 1, "res" + i);
CError.Compare(buffer[0], (byte)(i + 1), "buffer " + i);
}
nRead = DataReader.ReadContentAsBase64(buffer, 0, 1);
CError.Compare(nRead, 0, "nRead 0");
return TEST_PASS;
}
[Variation("ReadBase64 with = in the middle")]
public int TestTextReadBase64_27()
{
byte[] buffer = new byte[1];
string strxml = "<abc>AQI=ID</abc>";
int nRead;
ReloadSourceStr(strxml);
DataReader.PositionOnElement("abc");
DataReader.Read();
if (CheckCanReadBinaryContent()) return TEST_PASS;
for (int i = 0; i < 2; i++)
{
nRead = DataReader.ReadContentAsBase64(buffer, 0, 1);
CError.Compare(nRead, 1, "res" + i);
CError.Compare(buffer[0], (byte)(i + 1), "buffer " + i);
}
try
{
DataReader.ReadContentAsBase64(buffer, 0, 1);
CError.WriteLine("ReadBase64 with = in the middle succeeded");
return TEST_FAIL;
}
catch (XmlException e)
{
if (IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXPathNavigatorReader() || IsXmlValidatingReader() || IsCharCheckingReader())
CheckException("Xml_InvalidBase64Value", e);
else
CheckXmlException("Xml_UserException", e, 1, 6);
}
return TEST_PASS;
}
//[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "10000" })]
//[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "1000000" })]
//[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "10000000" })]
public int ReadBase64BufferOverflowWorksProperly()
{
int totalfilesize = Convert.ToInt32(CurVariation.Params[0].ToString());
CError.WriteLine(" totalfilesize = " + totalfilesize);
string ascii = new string('c', totalfilesize);
byte[] bits = Encoding.Unicode.GetBytes(ascii);
CError.WriteLineIgnore("Count = " + bits.Length);
string base64str = Convert.ToBase64String(bits);
string fileName = "bug105376_" + CurVariation.Params[0].ToString() + ".xml";
MemoryStream mems = new MemoryStream();
StreamWriter sw = new StreamWriter(mems);
{
sw.Write("<root><base64>");
sw.Write(base64str);
sw.Write("</base64></root>");
}
FilePathUtil.addStream(fileName, mems);
ReloadSource(fileName);
int SIZE = (totalfilesize - 30);
int SIZE64 = SIZE * 3 / 4;
DataReader.PositionOnElement("base64");
DataReader.Read();
if (CheckCanReadBinaryContent()) return TEST_PASS;
CError.WriteLine("ReadBase64 method... ");
CError.WriteLine(System.Int32.MaxValue);
byte[] base64 = new byte[SIZE64];
CError.WriteLine("SIZE64 = {0}", base64.Length);
int startPos = 0;
int readSize = 4096;
int currentSize = 0;
currentSize = DataReader.ReadContentAsBase64(base64, startPos, readSize);
CError.Compare(currentSize, readSize, "Read other than first chunk");
readSize = SIZE64 - readSize;
currentSize = DataReader.ReadContentAsBase64(base64, startPos, readSize);
CError.Compare(currentSize, readSize, "Read other than remaining Chunk Size");
readSize = 0;
currentSize = DataReader.ReadContentAsBase64(base64, startPos, readSize);
CError.Compare(currentSize, 0, "Read other than Zero Bytes");
DataReader.Close();
return TEST_PASS;
}
}
[InheritRequired()]
public abstract partial class TCReadElementContentAsBase64 : TCXMLReaderBaseGeneral
{
public const string ST_ELEM_NAME1 = "ElemAll";
public const string ST_ELEM_NAME2 = "ElemEmpty";
public const string ST_ELEM_NAME3 = "ElemNum";
public const string ST_ELEM_NAME4 = "ElemText";
public const string ST_ELEM_NAME5 = "ElemNumText";
public const string ST_ELEM_NAME6 = "ElemLong";
private const string Base64Xml = "Base64.xml";
public const string strTextBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
public const string strNumBase64 = "0123456789+/";
public override int Init(object objParam)
{
int ret = base.Init(objParam);
CreateTestFile(EREADER_TYPE.BASE64_TEST);
return ret;
}
public override int Terminate(object objParam)
{
DataReader.Close();
return base.Terminate(objParam);
}
private bool VerifyInvalidReadBase64(int iBufferSize, int iIndex, int iCount, Type exceptionType)
{
bool bPassed = false;
byte[] buffer = new byte[iBufferSize];
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement(ST_ELEM_NAME1);
if (CheckCanReadBinaryContent()) return true;
try
{
DataReader.ReadContentAsBase64(buffer, iIndex, iCount);
}
catch (Exception e)
{
CError.WriteLine("Actual exception:{0}", e.GetType().ToString());
CError.WriteLine("Expected exception:{0}", exceptionType.ToString());
bPassed = (e.GetType().ToString() == exceptionType.ToString());
}
return bPassed;
}
protected void TestOnInvalidNodeType(XmlNodeType nt)
{
ReloadSource();
PositionOnNodeType(nt);
if (CheckCanReadBinaryContent()) return;
try
{
byte[] buffer = new byte[1];
int nBytes = DataReader.ReadElementContentAsBase64(buffer, 0, 1);
}
catch (InvalidOperationException ioe)
{
if (ioe.ToString().IndexOf(nt.ToString()) < 0)
CError.Compare(false, "Call threw wrong invalid operation exception on " + nt);
else
return;
}
CError.Compare(false, "Call succeeded on " + nt);
}
////////////////////////////////////////////////////////////////
// Variations
////////////////////////////////////////////////////////////////
[Variation("ReadBase64 Element with all valid value")]
public int TestReadBase64_1()
{
int base64len = 0;
byte[] base64 = new byte[1000];
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement(ST_ELEM_NAME1);
if (CheckCanReadBinaryContent()) return TEST_PASS;
base64len = DataReader.ReadElementContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
CError.Compare(strActbase64, (strTextBase64 + strNumBase64), "Compare All Valid Base64");
return TEST_PASS;
}
[Variation("ReadBase64 Element with all valid Num value", Pri = 0)]
public int TestReadBase64_2()
{
int base64len = 0;
byte[] base64 = new byte[1000];
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement(ST_ELEM_NAME3);
if (CheckCanReadBinaryContent()) return TEST_PASS;
base64len = DataReader.ReadElementContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
CError.Compare(strActbase64, strNumBase64, "Compare All Valid Base64");
return TEST_PASS;
}
[Variation("ReadBase64 Element with all valid Text value")]
public int TestReadBase64_3()
{
int base64len = 0;
byte[] base64 = new byte[1000];
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement(ST_ELEM_NAME4);
if (CheckCanReadBinaryContent()) return TEST_PASS;
base64len = DataReader.ReadElementContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
CError.Compare(strActbase64, strTextBase64, "Compare All Valid Base64");
return TEST_PASS;
}
[Variation("ReadBase64 Element with all valid value (from concatenation), Pri=0")]
public int TestReadBase64_5()
{
int base64len = 0;
byte[] base64 = new byte[1000];
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement(ST_ELEM_NAME5);
if (CheckCanReadBinaryContent()) return TEST_PASS;
base64len = DataReader.ReadElementContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
CError.Compare(strActbase64, (strTextBase64 + strNumBase64), "Compare All Valid Base64");
return TEST_PASS;
}
[Variation("ReadBase64 Element with Long valid value (from concatenation), Pri=0")]
public int TestReadBase64_6()
{
int base64len = 0;
byte[] base64 = new byte[2000];
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement(ST_ELEM_NAME6);
if (CheckCanReadBinaryContent()) return TEST_PASS;
base64len = DataReader.ReadElementContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
string strExpbase64 = "";
for (int i = 0; i < 10; i++)
strExpbase64 += (strTextBase64 + strNumBase64);
CError.Compare(strActbase64, strExpbase64, "Compare All Valid Base64");
return TEST_PASS;
}
[Variation("ReadBase64 with count > buffer size")]
public int ReadBase64_7()
{
return BoolToLTMResult(VerifyInvalidReadBase64(5, 0, 6, typeof(ArgumentOutOfRangeException)));
}
[Variation("ReadBase64 with count < 0")]
public int ReadBase64_8()
{
return BoolToLTMResult(VerifyInvalidReadBase64(5, 2, -1, typeof(ArgumentOutOfRangeException)));
}
[Variation("ReadBase64 with index > buffer size")]
public int ReadBase64_9()
{
return BoolToLTMResult(VerifyInvalidReadBase64(5, 5, 1, typeof(ArgumentOutOfRangeException)));
}
[Variation("ReadBase64 with index < 0")]
public int ReadBase64_10()
{
return BoolToLTMResult(VerifyInvalidReadBase64(5, -1, 1, typeof(ArgumentOutOfRangeException)));
}
[Variation("ReadBase64 with index + count exceeds buffer")]
public int ReadBase64_11()
{
return BoolToLTMResult(VerifyInvalidReadBase64(5, 0, 10, typeof(ArgumentOutOfRangeException)));
}
[Variation("ReadBase64 index & count =0")]
public int ReadBase64_12()
{
byte[] buffer = new byte[5];
int iCount = 0;
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement(ST_ELEM_NAME1);
if (CheckCanReadBinaryContent()) return TEST_PASS;
iCount = DataReader.ReadElementContentAsBase64(buffer, 0, 0);
CError.Compare(iCount, 0, "has to be zero");
return TEST_PASS;
}
[Variation("ReadBase64 Element multiple into same buffer (using offset), Pri=0")]
public int TestReadBase64_13()
{
int base64len = 20;
byte[] base64 = new byte[base64len];
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement(ST_ELEM_NAME4);
if (CheckCanReadBinaryContent()) return TEST_PASS;
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
DataReader.ReadElementContentAsBase64(base64, i, 2);
strActbase64 = (System.BitConverter.ToChar(base64, i)).ToString();
CError.Compare(String.Compare(strActbase64, 0, strTextBase64, i / 2, 1), 0, "Compare All Valid Base64");
}
return TEST_PASS;
}
[Variation("ReadBase64 with buffer == null")]
public int TestReadBase64_14()
{
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement(ST_ELEM_NAME4);
if (CheckCanReadBinaryContent()) return TEST_PASS;
try
{
DataReader.ReadElementContentAsBase64(null, 0, 0);
}
catch (ArgumentNullException)
{
return TEST_PASS;
}
return TEST_FAIL;
}
[Variation("ReadBase64 after failure")]
public int TestReadBase64_15()
{
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement("ElemErr");
if (CheckCanReadBinaryContent()) return TEST_PASS;
var line = ((IXmlLineInfo)DataReader.Internal).LinePosition + "ElemErr".Length + 1;
byte[] buffer = new byte[10];
int nRead = 0;
try
{
nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 1);
return TEST_FAIL;
}
catch (XmlException e)
{
if (IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXPathNavigatorReader() || IsXmlValidatingReader() || IsCharCheckingReader())
CheckException("Xml_InvalidBase64Value", e);
else
CheckXmlException("Xml_UserException", e, 1, line);
}
return TEST_PASS;
}
[Variation("Read after partial ReadBase64", Pri = 0)]
public int TestReadBase64_16()
{
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement("ElemNum");
if (CheckCanReadBinaryContent()) return TEST_PASS;
byte[] buffer = new byte[10];
int nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 8);
CError.Compare(nRead, 8, "0");
DataReader.Read();
CError.Compare(DataReader.NodeType, XmlNodeType.Text, "1vn");
return TEST_PASS;
}
[Variation("Current node on multiple calls")]
public int TestReadBase64_17()
{
ReloadSource(EREADER_TYPE.BASE64_TEST);
DataReader.PositionOnElement("ElemNum");
if (CheckCanReadBinaryContent()) return TEST_PASS;
byte[] buffer = new byte[30];
int nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 2);
CError.Compare(nRead, 2, "0");
nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 23);
CError.Compare(nRead, 22, "1");
CError.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Nodetype not end element");
CError.Compare(DataReader.Name, "ElemNum", "Nodetype not end element");
return TEST_PASS;
}
[Variation("ReadBase64 with incomplete sequence")]
public int TestTextReadBase64_23()
{
byte[] expected = new byte[] { 0, 16, 131, 16, 81 };
byte[] buffer = new byte[10];
string strxml = "<r><ROOT>ABCDEFG</ROOT></r>";
ReloadSourceStr(strxml);
DataReader.PositionOnElement("ROOT");
if (CheckCanReadBinaryContent()) return TEST_PASS;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadElementContentAsBase64(buffer, result, 1)) > 0)
result += nRead;
CError.Compare(result, expected.Length, "res");
for (int i = 0; i < result; i++)
CError.Compare(buffer[i], expected[i], "buffer[" + i + "]");
return TEST_PASS;
}
[Variation("ReadBase64 when end tag doesn't exist")]
public int TestTextReadBase64_24()
{
if (IsRoundTrippedReader())
return TEST_SKIPPED;
byte[] buffer = new byte[5000];
string strxml = "<B>" + new string('c', 5000);
ReloadSourceStr(strxml);
DataReader.PositionOnElement("B");
if (CheckCanReadBinaryContent()) return TEST_PASS;
try
{
DataReader.ReadElementContentAsBase64(buffer, 0, 5000);
CError.WriteLine("Accepted incomplete element");
return TEST_FAIL;
}
catch (XmlException e)
{
CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004);
}
return TEST_PASS;
}
[Variation("ReadBase64 with whitespaces in the middle")]
public int TestTextReadBase64_26()
{
byte[] buffer = new byte[1];
string strxml = "<abc> AQID B B </abc>";
int nRead;
ReloadSourceStr(strxml);
DataReader.PositionOnElement("abc");
if (CheckCanReadBinaryContent()) return TEST_PASS;
for (int i = 0; i < 4; i++)
{
nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 1);
CError.Compare(nRead, 1, "res" + i);
CError.Compare(buffer[0], (byte)(i + 1), "buffer " + i);
}
nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 1);
CError.Compare(nRead, 0, "nRead 0");
return TEST_PASS;
}
[Variation("ReadBase64 with = in the middle")]
public int TestTextReadBase64_27()
{
byte[] buffer = new byte[1];
string strxml = "<abc>AQI=ID</abc>";
int nRead;
ReloadSourceStr(strxml);
DataReader.PositionOnElement("abc");
if (CheckCanReadBinaryContent()) return TEST_PASS;
for (int i = 0; i < 2; i++)
{
nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 1);
CError.Compare(nRead, 1, "res" + i);
CError.Compare(buffer[0], (byte)(i + 1), "buffer " + i);
}
try
{
DataReader.ReadElementContentAsBase64(buffer, 0, 1);
CError.WriteLine("ReadBase64 with = in the middle succeeded");
return TEST_FAIL;
}
catch (XmlException e)
{
if (IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXPathNavigatorReader() || IsXmlValidatingReader() || IsCharCheckingReader())
CheckException("Xml_InvalidBase64Value", e);
else
CheckXmlException("Xml_UserException", e, 1, 6);
}
return TEST_PASS;
}
//[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "10000" })]
//[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "1000000" })]
//[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "10000000" })]
public int ReadBase64RunsIntoOverflow()
{
if (CheckCanReadBinaryContent() || IsSubtreeReader() || IsCharCheckingReader() || IsWrappedReader())
return TEST_SKIPPED;
int totalfilesize = Convert.ToInt32(CurVariation.Params[0].ToString());
CError.WriteLine(" totalfilesize = " + totalfilesize);
string ascii = new string('c', totalfilesize);
byte[] bits = Encoding.Unicode.GetBytes(ascii);
CError.WriteLineIgnore("Count = " + bits.Length);
string base64str = Convert.ToBase64String(bits);
string fileName = "bug105376_" + CurVariation.Params[0].ToString() + ".xml";
MemoryStream mems = new MemoryStream();
StreamWriter sw = new StreamWriter(mems);
{
sw.Write("<root><base64>");
sw.Write(base64str);
sw.Write("</base64></root>");
}
FilePathUtil.addStream(fileName, mems);
ReloadSource(fileName);
int SIZE = (totalfilesize - 30);
int SIZE64 = SIZE * 3 / 4;
DataReader.PositionOnElement("base64");
CError.WriteLine("ReadBase64 method... ");
CError.WriteLine(System.Int32.MaxValue);
byte[] base64 = new byte[SIZE64];
CError.WriteLine("SIZE64 = {0}", base64.Length);
int startPos = 0;
int readSize = 4096;
int currentSize = 0;
currentSize = DataReader.ReadElementContentAsBase64(base64, startPos, readSize);
CError.Compare(currentSize, readSize, "Read other than first chunk");
readSize = SIZE64 - readSize;
currentSize = DataReader.ReadElementContentAsBase64(base64, startPos, readSize);
CError.Compare(currentSize, readSize, "Read other than remaining Chunk Size");
readSize = 0;
currentSize = DataReader.ReadElementContentAsBase64(base64, startPos, readSize);
CError.Compare(currentSize, 0, "Read other than Zero Bytes");
DataReader.Close();
return TEST_PASS;
}
[Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes")]
public int TestReadBase64ReadsTheContent()
{
string filename = Path.Combine(TestData, "Common", "Bug99148.xml");
ReloadSource(filename);
DataReader.MoveToContent();
if (CheckCanReadBinaryContent()) return TEST_PASS;
int bytes = -1;
StringBuilder output = new StringBuilder();
while (bytes != 0)
{
byte[] bbb = new byte[1024];
bytes = DataReader.ReadElementContentAsBase64(bbb, 0, bbb.Length);
for (int i = 0; i < bytes; i++)
{
CError.Write(bbb[i].ToString());
output.AppendFormat(bbb[i].ToString());
}
}
CError.WriteLine();
CError.WriteLine("Length of the output : " + output.ToString().Length);
CError.Compare(output.ToString().Length, 6072, "Expected Length : 6072");
return TEST_PASS;
}
[Variation("SubtreeReader inserted attributes don't work with ReadContentAsBase64")]
public int SubtreeReaderInsertedAttributesWorkWithReadContentAsBase64()
{
if (CheckCanReadBinaryContent()) return TEST_PASS;
string strxml1 = "<root xmlns='";
string strxml2 = "'><bar/></root>";
string[] binValue = new string[] { "AAECAwQFBgcI==", "0102030405060708090a0B0c" };
for (int i = 0; i < binValue.Length; i++)
{
string strxml = strxml1 + binValue[i] + strxml2;
ReloadSourceStr(strxml);
DataReader.Read();
DataReader.Read();
using (XmlReader sr = DataReader.ReadSubtree())
{
sr.Read();
sr.MoveToFirstAttribute();
sr.MoveToFirstAttribute();
byte[] bytes = new byte[4];
while ((sr.ReadContentAsBase64(bytes, 0, bytes.Length)) > 0) { }
}
}
return TEST_PASS;
}
[Variation("call ReadContentAsBase64 on two or more nodes")]
public int TestReadBase64_28()
{
string xml = "<elem0>123<elem1>123<elem2>123</elem2>123</elem1>123</elem0>";
ReloadSource(new StringReader(xml));
if (CheckCanReadBinaryContent()) return TEST_PASS;
byte[] buffer = new byte[3];
int startPos = 0;
int readSize = 3;
int currentSize = 0;
DataReader.Read();
while (DataReader.Read())
{
currentSize = DataReader.ReadContentAsBase64(buffer, startPos, readSize);
CError.Equals(currentSize, 2, "size");
CError.Equals(buffer[0], (byte)215, "buffer1");
CError.Equals(buffer[1], (byte)109, "buffer2");
if (!(IsXPathNavigatorReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc()))
{
CError.WriteLine("LineNumber" + DataReader.LineNumber);
CError.WriteLine("LinePosition" + DataReader.LinePosition);
}
}
DataReader.Close();
return TEST_PASS;
}
[Variation("read Base64 over invalid text node")]
public int TestReadBase64_29()
{
string xml = "<elem0>12%45<elem1>12%45<elem2>12%45</elem2>12%45</elem1>12%45</elem0>";
ReloadSource(new StringReader(xml));
if (CheckCanReadBinaryContent()) return TEST_PASS;
byte[] buffer = new byte[5];
int currentSize = 0;
while (DataReader.Read())
{
DataReader.Read();
try
{
currentSize = DataReader.ReadContentAsBase64(buffer, 0, 5);
if (!(IsCharCheckingReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXmlValidatingReader() || IsXPathNavigatorReader()))
return TEST_FAIL;
}
catch (XmlException)
{
CError.Compare(currentSize, 0, "size");
}
}
DataReader.Close();
return TEST_PASS;
}
[Variation("goto to text node, ask got.Value, readcontentasBase64")]
public int TestReadBase64_30()
{
string xml = "<elem0>123</elem0>";
ReloadSourceStr(xml);
if (CheckCanReadBinaryContent()) return TEST_PASS;
byte[] buffer = new byte[3];
DataReader.Read();
DataReader.Read();
CError.Compare(DataReader.Value, "123", "value");
CError.Compare(DataReader.ReadContentAsBase64(buffer, 0, 1), 1, "size");
DataReader.Close();
return TEST_PASS;
}
[Variation("goto to text node, readcontentasBase64, ask got.Value")]
public int TestReadBase64_31()
{
string xml = "<elem0>123</elem0>";
ReloadSourceStr(xml);
if (CheckCanReadBinaryContent()) return TEST_PASS;
byte[] buffer = new byte[3];
DataReader.Read();
DataReader.Read();
CError.Compare(DataReader.ReadContentAsBase64(buffer, 0, 1), 1, "size");
CError.Compare(DataReader.Value, (IsCharCheckingReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXmlValidatingReader() || IsXPathNavigatorReader()) ? "123" : "3", "value");
DataReader.Close();
return TEST_PASS;
}
[Variation("goto to huge text node, read several chars with ReadContentAsBase64 and Move forward with .Read()")]
public int TestReadBase64_32()
{
string xml = "<elem0>1234567 89 1234 123345 5676788 5567712 34567 89 1234 123345 5676788 55677</elem0>";
ReloadSource(new StringReader(xml));
byte[] buffer = new byte[5];
DataReader.Read();
DataReader.Read();
try
{
CError.Compare(DataReader.ReadContentAsBase64(buffer, 0, 5), 5, "size");
}
catch (NotSupportedException) { return TEST_PASS; }
DataReader.Read();
DataReader.Close();
return TEST_PASS;
}
[Variation("goto to huge text node with invalid chars, read several chars with ReadContentAsBase64 and Move forward with .Read()")]
public int TestReadBase64_33()
{
string xml = "<elem0>123 $^ 56789 abcdefg hij klmn opqrst 12345 uvw xy ^ z</elem0>";
ReloadSource(new StringReader(xml));
byte[] buffer = new byte[5];
DataReader.Read();
DataReader.Read();
try
{
CError.Compare(DataReader.ReadContentAsBase64(buffer, 0, 5), 5, "size");
DataReader.Read();
}
catch (XmlException) { return TEST_PASS; }
catch (NotSupportedException) { return TEST_PASS; }
finally
{
DataReader.Close();
}
return TEST_FAIL;
}
//[Variation("ReadContentAsBase64 on an xmlns attribute", Param = "<foo xmlns='default'> <bar id='1'/> </foo>")]
//[Variation("ReadContentAsBase64 on an xmlns:k attribute", Param = "<k:foo xmlns:k='default'> <k:bar id='1'/> </k:foo>")]
//[Variation("ReadContentAsBase64 on an xml:space attribute", Param = "<foo xml:space='default'> <bar id='1'/> </foo>")]
//[Variation("ReadContentAsBase64 on an xml:lang attribute", Param = "<foo xml:lang='default'> <bar id='1'/> </foo>")]
public int TestReadBase64_34()
{
string xml = (string)CurVariation.Param;
byte[] buffer = new byte[8];
try
{
ReloadSource(new StringReader(xml));
DataReader.Read();
if (IsBinaryReader()) DataReader.Read();
DataReader.MoveToAttribute(0);
CError.Compare(DataReader.Value, "default", "value");
CError.Equals(DataReader.ReadContentAsBase64(buffer, 0, 8), 5, "size");
}
catch (NotSupportedException) { }
DataReader.Close();
return TEST_PASS;
}
[Variation("call ReadContentAsBase64 on two or more nodes and whitespace")]
public int TestReadReadBase64_35()
{
string xml = @"<elem0> 123" + "\n" + @" <elem1>" + "\r" + @"123
<elem2>
123 </elem2>" + "\r\n" + @" 123</elem1> 123 </elem0>";
ReloadSource(new StringReader(xml));
if (CheckCanReadBinaryContent()) return TEST_PASS;
byte[] buffer = new byte[3];
int startPos = 0;
int readSize = 3;
int currentSize = 0;
DataReader.Read();
while (DataReader.Read())
{
currentSize = DataReader.ReadContentAsBase64(buffer, startPos, readSize);
CError.Equals(currentSize, 2, "size");
CError.Equals(buffer[0], (byte)215, "buffer1");
CError.Equals(buffer[1], (byte)109, "buffer2");
if (!(IsXPathNavigatorReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc()))
{
CError.WriteLine("LineNumber" + DataReader.LineNumber);
CError.WriteLine("LinePosition" + DataReader.LinePosition);
}
}
DataReader.Close();
return TEST_PASS;
}
[Variation("call ReadContentAsBase64 on two or more nodes and whitespace after call Value")]
public int TestReadReadBase64_36()
{
string xml = @"<elem0> 123" + "\n" + @" <elem1>" + "\r" + @"123
<elem2>
123 </elem2>" + "\r\n" + @" 123</elem1> 123 </elem0>";
ReloadSource(new StringReader(xml));
if (CheckCanReadBinaryContent()) return TEST_PASS;
byte[] buffer = new byte[3];
int startPos = 0;
int readSize = 3;
int currentSize = 0;
DataReader.Read();
while (DataReader.Read())
{
CError.Equals(DataReader.Value.Contains("123"), "Value");
currentSize = DataReader.ReadContentAsBase64(buffer, startPos, readSize);
CError.Equals(currentSize, 2, "size");
CError.Equals(buffer[0], (byte)215, "buffer1");
CError.Equals(buffer[1], (byte)109, "buffer2");
if (!(IsXPathNavigatorReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc()))
{
CError.WriteLine("LineNumber" + DataReader.LineNumber);
CError.WriteLine("LinePosition" + DataReader.LinePosition);
}
}
DataReader.Close();
return TEST_PASS;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Blade;
using Blade.Data;
using Maui.Data.Recognition;
using Maui.Data.Recognition.Core;
using Maui.Data.Recognition.Html;
using Maui.Tools.Studio.WebSpy.DatumLocationValidation;
using Maui.Data.Recognition.Spec;
namespace Maui.Tools.Studio.WebSpy
{
public partial class BrowserForm : UserControl, IBrowser
{
private MarkupDocument myMarkupDocument = null;
private LegacyDocumentBrowser myDocumentBrowser = null;
private bool myIsCapturing = false;
public BrowserForm()
{
InitializeComponent();
myDocumentBrowser = new LegacyDocumentBrowser( myBrowser );
myDocumentBrowser.Browser.Navigating += myBrowser_Navigating;
myDocumentBrowser.Browser.DocumentCompleted += myBrowser_DocumentCompleted;
// disable links
// TODO: we cannot use this, it disables navigation in general (Navigate() too)
//myBrowser.AllowNavigation = false;
// TODO: how to disable images in browser
myMarkupDocument = new MarkupDocument();
myMarkupDocument.ValidationChanged += SeriesName_ValidationChanged;
myDimension.DataSource = Enum.GetValues( typeof( CellDimension ) );
}
private void myGo_Click( object sender, EventArgs e )
{
if ( string.IsNullOrEmpty( myUrlTxt.Text ) )
{
return;
}
Navigate( myUrlTxt.Text );
}
private void myBrowser_Navigating( object sender, WebBrowserNavigatingEventArgs e )
{
if ( myIsCapturing )
{
myNavUrls.AppendText( new NavigatorUrl( UriType.Request, e.Url ).ToString() );
myNavUrls.AppendText( Environment.NewLine );
}
}
private void myBrowser_DocumentCompleted( object sender, WebBrowserDocumentCompletedEventArgs e )
{
myPath.Text = "";
myValue.Text = "";
if ( myMarkupDocument.Document != null )
{
myMarkupDocument.Document.Click -= HtmlDocument_Click;
}
myMarkupDocument.Document = myDocumentBrowser.Document;
myMarkupDocument.Document.Click += HtmlDocument_Click;
myUrlTxt.Text = myMarkupDocument.Document.Url.ToString();
if ( myIsCapturing )
{
myNavUrls.AppendText( new NavigatorUrl( UriType.Response, myDocumentBrowser.Browser.Document.Url ).ToString() );
myNavUrls.AppendText( Environment.NewLine );
}
}
private void HtmlDocument_Click( object sender, HtmlElementEventArgs e )
{
myPath.Text = myMarkupDocument.SelectedElement.GetPath().ToString();
myValue.Text = myMarkupDocument.SelectedElement.InnerText;
}
private void mySearchPath_Click( object sender, EventArgs e )
{
myMarkupDocument.Anchor = myPath.Text;
if ( myMarkupDocument.SelectedElement != null )
{
myValue.Text = myMarkupDocument.SelectedElement.InnerText;
}
}
protected override void OnHandleDestroyed( EventArgs e )
{
myMarkupDocument.Dispose();
myMarkupDocument = null;
myDocumentBrowser.Browser.DocumentCompleted -= myBrowser_DocumentCompleted;
myDocumentBrowser.Dispose();
myBrowser.Dispose();
myBrowser = null;
base.OnHandleDestroyed( e );
}
private void myDimension_SelectedIndexChanged( object sender, EventArgs e )
{
myMarkupDocument.Dimension = (CellDimension)myDimension.SelectedValue;
}
private void mySkipRows_TextChanged( object sender, EventArgs eventArgs )
{
SkipElements( mySkipRows, x => myMarkupDocument.SkipRows = x );
}
private void mySkipColumns_TextChanged( object sender, EventArgs eventArgs )
{
SkipElements( mySkipColumns, x => myMarkupDocument.SkipColumns = x );
}
private void myRowHeader_TextChanged( object sender, EventArgs e )
{
MarkHeader( myRowHeader, x => myMarkupDocument.RowHeader = x );
}
private void myColumnHeader_TextChanged( object sender, EventArgs e )
{
MarkHeader( myColumnHeader, x => myMarkupDocument.ColumnHeader = x );
}
private void mySeriesName_TextChanged( object sender, EventArgs eventArgs )
{
myMarkupDocument.SeriesName = mySeriesName.Text;
}
private void myReset_Click( object sender, EventArgs e )
{
myPath.Text = "";
myValue.Text = "";
myDimension.SelectedIndex = 0;
mySkipColumns.Text = "";
mySkipRows.Text = "";
myRowHeader.Text = "";
myColumnHeader.Text = "";
mySeriesName.Text = "";
myMarkupDocument.Reset();
}
private void SeriesName_ValidationChanged( bool isValid )
{
if ( isValid )
{
mySeriesName.BackColor = Color.White;
}
else
{
mySeriesName.BackColor = Color.Red;
}
}
private void MarkHeader( TextBox config, Action<int> UpdateTemplate )
{
string str = config.Text.TrimOrNull();
if ( string.IsNullOrEmpty( str ) )
{
UpdateTemplate( -1 );
return;
}
CellDimension dimension = (CellDimension)myDimension.SelectedValue;
try
{
UpdateTemplate( Convert.ToInt32( str ) );
}
catch
{
errorProvider1.SetError( config, "Must be: <number> [, <number> ]*" );
}
}
private void SkipElements( TextBox config, Action<int[]> UpdateTemplate )
{
if ( config.Text.IsNullOrTrimmedEmpty() )
{
UpdateTemplate( null );
return;
}
string[] tokens = config.Text.Split( ',' );
try
{
var positions = from t in tokens
where !t.IsNullOrTrimmedEmpty()
select Convert.ToInt32( t );
UpdateTemplate( positions.ToArray() );
}
catch
{
errorProvider1.SetError( config, "Must be: <number> [, <number> ]*" );
}
}
private void myCapture_Click( object sender, EventArgs e )
{
myIsCapturing = !myIsCapturing;
if ( myIsCapturing )
{
myCapture.Text = "Stop capturing";
}
else
{
myCapture.Text = "Start capturing";
}
myReplay.Enabled = !myIsCapturing;
}
private IList<NavigatorUrl> GetNavigationSteps()
{
var q = from token in myNavUrls.Text.Split( new string[] { Environment.NewLine }, StringSplitOptions.None )
where !token.IsNullOrTrimmedEmpty()
select NavigatorUrl.Parse( token );
// the last url must be a request
return (from navUrl in q
where !(navUrl == q.Last() && navUrl.UrlType == UriType.Response)
select navUrl).ToList();
}
private void myReplay_Click( object sender, EventArgs e )
{
var q = GetNavigationSteps();
Regex macroPattern = new Regex( @"(\$\{.*\})" );
List<NavigatorUrl> filtered = new List<NavigatorUrl>();
foreach ( NavigatorUrl navUrl in q )
{
Match md = macroPattern.Match( navUrl.UrlString );
if ( md.Success )
{
string macro = md.Groups[ 1 ].Value;
string value = InputForm.Show( "Enter macro value", "Enter value for macro " + macro );
if ( value != null )
{
filtered.Add( new NavigatorUrl( navUrl.UrlType, navUrl.UrlString.Replace( macro, value ) ) );
}
else
{
return;
}
}
else
{
filtered.Add( navUrl );
}
}
myDocumentBrowser.LoadDocument( filtered );
/*
Request: http://www.ariva.de/search/search.m?searchname=${stock.Symbol}&url=/quote/profile.m
Response: http://www.ariva.de/quote/profile.m?secu={(\d+)}
Request: http://www.ariva.de/statistics/facunda.m?secu={0}&page=-1
*/
}
private void myEditCapture_Click( object sender, EventArgs e )
{
EditCaptureForm form = new EditCaptureForm();
form.NavUrls = myNavUrls.Text;
DialogResult result = form.ShowDialog();
if ( result == DialogResult.OK )
{
myNavUrls.Text = form.NavUrls;
}
}
private void myValidateDatumLocatorsMenu_Click( object sender, EventArgs e )
{
var form = new ValidationForm( this );
form.Show();
}
public void Navigate( string url )
{
Cursor.Current = Cursors.WaitCursor;
myDocumentBrowser.Navigate( url );
Cursor.Current = Cursors.Default;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Helsenorge.Messaging.Abstractions;
using Helsenorge.Registries.Abstractions;
using Microsoft.Extensions.Logging;
using Helsenorge.Messaging.Http;
namespace Helsenorge.Messaging.ServiceBus
{
/// <summary>
/// Provides a number of functions used by both the Gateway (sending) and message listeners
/// </summary>
public class ServiceBusCore
{
/// <summary>
/// Label used when error message contains a SOAP fault
/// </summary>
public const string SoapFaultLabel = "AMQP_SOAP_FAULT";
/// <summary>
/// Header key for FromHerId
/// </summary>
public const string FromHerIdHeaderKey = "fromHerId";
/// <summary>
/// Header key for ToHerId
/// </summary>
public const string ToHerIdHeaderKey = "toHerId";
/// <summary>
/// Header key for CpaId
/// </summary>
public const string CpaIdHeaderKey = "cpaId";
/// <summary>
/// Header key for ApplicationTimestamp
/// </summary>
public const string ApplicationTimestampHeaderKey = "applicationTimeStamp";
private const string OriginalMessageIdHeaderKey = "originalMessageId";
private const string ReceiverTimestampHeaderKey = "receiverTimeStamp";
private const string ErrorConditionHeaderKey = "errorCondition";
private const string ErrorDescriptionHeaderKey = "errorDescription";
private const string ErrorConditionDataHeaderKey = "errorConditionData";
//convencience properties
internal ServiceBusSettings Settings => Core.Settings.ServiceBus;
internal IAddressRegistry AddressRegistry => Core.AddressRegistry;
internal ICollaborationProtocolRegistry CollaborationProtocolRegistry => Core.CollaborationProtocolRegistry;
internal ICertificateValidator DefaultCertificateValidator => Core.DefaultCertificateValidator;
internal IMessageProtection DefaultMessageProtection => Core.DefaultMessageProtection;
internal bool LogPayload => Core.Settings.LogPayload;
/// <summary>
/// Reference to the core messaging system
/// </summary>
private MessagingCore Core { get; }
internal IServiceBusFactoryPool FactoryPool { get; }
internal ServiceBusSenderPool SenderPool { get; }
internal ServiceBusReceiverPool ReceiverPool { get; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="core">A reference to the core messaging system</param>
/// <exception cref="ArgumentNullException"></exception>
internal ServiceBusCore(MessagingCore core)
{
if (core == null) throw new ArgumentNullException(nameof(core));
Core = core;
var connectionString = core.Settings.ServiceBus.ConnectionString;
if (connectionString == null)
{
throw new ArgumentNullException("connectionString");
}
if (connectionString.StartsWith("http://") || connectionString.StartsWith("https://"))
{
FactoryPool = new HttpServiceBusFactoryPool(core.Settings.ServiceBus);
}
else
{
FactoryPool = new ServiceBusFactoryPool(core.Settings.ServiceBus);
}
SenderPool = new ServiceBusSenderPool(core.Settings.ServiceBus, FactoryPool);
ReceiverPool = new ServiceBusReceiverPool(core.Settings.ServiceBus, FactoryPool);
}
/// <summary>
/// Sends an outgoing message
/// </summary>
/// <param name="logger"></param>
/// <param name="outgoingMessage">Information about the message to send</param>
/// <param name="queueType">The type of queue that should be used</param>
/// <param name="replyTo">An optional ReplyTo queue that should be used. Only relevant in synchronous messaging</param>
/// <param name="correlationId">The correlation id to use when sending the message. Only relevant in synchronous messaging</param>
/// <returns></returns>
internal async Task Send(ILogger logger, OutgoingMessage outgoingMessage, QueueType queueType, string replyTo = null, string correlationId = null)
{
if (outgoingMessage == null) throw new ArgumentNullException(nameof(outgoingMessage));
if (string.IsNullOrEmpty(outgoingMessage.MessageId)) throw new ArgumentNullException(nameof(outgoingMessage.MessageId));
if (outgoingMessage.Payload == null) throw new ArgumentNullException(nameof(outgoingMessage.Payload));
var hasAgreement = true;
// first we try and find an agreement
var profile = await CollaborationProtocolRegistry.FindAgreementForCounterpartyAsync(logger, outgoingMessage.ToHerId).ConfigureAwait(false);
if (profile == null)
{
hasAgreement = false; // if we don't have an agreement, we try to find the specific profile
profile = await CollaborationProtocolRegistry.FindProtocolForCounterpartyAsync(logger, outgoingMessage.ToHerId).ConfigureAwait(false);
}
var signature = Settings.SigningCertificate.Certificate;
var encryption = profile.EncryptionCertificate;
var validator = Core.DefaultCertificateValidator;
var encryptionStatus = validator.Validate(encryption, X509KeyUsageFlags.DataEncipherment);
var signatureStatus = validator.Validate(signature, X509KeyUsageFlags.NonRepudiation);
// this is the other parties certificate that may be out of date, not something we can fix
if (encryptionStatus != CertificateErrors.None)
{
if (Core.Settings.IgnoreCertificateErrorOnSend)
{
logger.LogError(EventIds.RemoteCertificate, $"Remote encryption certificate {encryption?.SerialNumber} for {outgoingMessage.ToHerId.ToString()} is not valid");
}
else
{
throw new MessagingException($"Remote encryption certificate {encryption?.SerialNumber} for {outgoingMessage.ToHerId.ToString()} is not valid")
{
EventId = EventIds.RemoteCertificate
};
}
}
// this is our certificate, something we can fix
if (signatureStatus != CertificateErrors.None)
{
if (Core.Settings.IgnoreCertificateErrorOnSend)
{
logger.LogError(EventIds.LocalCertificate, "Locally installed signing certificate is not valid");
}
else
{
throw new MessagingException("Locally installed signing certificate is not valid")
{
EventId = EventIds.LocalCertificate
};
}
}
var protection = Core.DefaultMessageProtection;
var stream = protection.Protect(outgoingMessage.Payload, encryption, signature);
var messagingMessage = FactoryPool.CreateMessage(logger, stream, outgoingMessage);
if (queueType != QueueType.SynchronousReply)
{
messagingMessage.ReplyTo =
replyTo ?? await ConstructQueueName(logger, Core.Settings.MyHerId, queueType).ConfigureAwait(false);
}
messagingMessage.ContentType = protection.ContentType;
messagingMessage.MessageId = outgoingMessage.MessageId;
// when we are replying to a synchronous message, we need to use the replyto of the original message
messagingMessage.To =
(queueType == QueueType.SynchronousReply) ?
replyTo :
await ConstructQueueName(logger, outgoingMessage.ToHerId, queueType).ConfigureAwait(false);
messagingMessage.MessageFunction = outgoingMessage.MessageFunction;
messagingMessage.CorrelationId = correlationId ?? outgoingMessage.MessageId;
messagingMessage.TimeToLive = (queueType == QueueType.Asynchronous)
? Settings.Asynchronous.TimeToLive
: Settings.Synchronous.TimeToLive;
messagingMessage.ScheduledEnqueueTimeUtc = outgoingMessage.ScheduledSendTimeUtc;
messagingMessage.FromHerId = Core.Settings.MyHerId;
messagingMessage.ToHerId = outgoingMessage.ToHerId;
messagingMessage.ApplicationTimestamp = DateTime.Now;
if (hasAgreement)
{
messagingMessage.CpaId = profile.CpaId.ToString("D");
}
await Send(logger, messagingMessage, queueType, outgoingMessage.PersonalId, (LogPayload) ? outgoingMessage.Payload : null).ConfigureAwait(false);
}
/// <summary>
/// Sends a prepared message
/// </summary>
/// <param name="logger"></param>
/// <param name="message">The prepared message</param>
/// <param name="queueType">The type of queue to use</param>
/// <param name="userId"></param>
/// <param name="xml">Optional xml content. This will be logged depending on the logging level.</param>
/// <returns></returns>
private async Task Send(ILogger logger, IMessagingMessage message, QueueType queueType, string userId = "99999999999", XDocument xml = null)
{
if (message == null) throw new ArgumentNullException(nameof(message));
logger.LogStartSend(queueType, message.MessageFunction, message.FromHerId, message.ToHerId, message.MessageId, userId, xml);
IMessagingSender messageSender = null;
try
{
messageSender = SenderPool.CreateCachedMessageSender(logger, message.To);
await messageSender.SendAsync(message).ConfigureAwait(false);
}
catch (Exception ex)
{
logger.LogException("Cannot send message to service bus. Invalid endpoint.", ex);
throw new MessagingException(ex.Message)
{
EventId = EventIds.Send
};
}
finally
{
if (messageSender != null)
{
SenderPool.ReleaseCachedMessageSender(logger, message.To);
}
}
logger.LogEndSend(queueType, message.MessageFunction, message.FromHerId, message.ToHerId, message.MessageId, userId);
}
/// <summary>
/// Sends an error message
/// </summary>
/// <param name="logger"></param>
/// <param name="originalMessage">The original message the error is in response to</param>
/// <param name="errorCode">The error code to report</param>
/// <param name="errorDescription">The error description to report</param>
/// <param name="additionalData">Additional information to include</param>
/// <returns></returns>
private async Task SendError(ILogger logger, IMessagingMessage originalMessage, string errorCode, string errorDescription, IEnumerable<string> additionalData) //TODO: Sjekk at SendError fungerer med Http-meldinger
{
if (originalMessage == null) throw new ArgumentNullException(nameof(originalMessage));
if (string.IsNullOrEmpty(errorCode)) throw new ArgumentNullException(nameof(errorCode));
if (string.IsNullOrEmpty(errorDescription)) throw new ArgumentNullException(nameof(errorDescription));
if (originalMessage.FromHerId <= 0)
{
logger.LogWarning(EventIds.MissingField, "FromHerId is missing. No idea where to send the error");
return;
}
// Clones original message, but leaves out the payload
var clonedMessage = originalMessage.Clone(false);
// update some properties on the cloned message
clonedMessage.To = await ConstructQueueName(logger, originalMessage.FromHerId, QueueType.Error).ConfigureAwait(false); // change target
clonedMessage.TimeToLive = Settings.Error.TimeToLive;
clonedMessage.FromHerId = originalMessage.ToHerId;
clonedMessage.ToHerId = originalMessage.FromHerId;
if (clonedMessage.Properties.ContainsKey(OriginalMessageIdHeaderKey) == false)
{
clonedMessage.Properties.Add(OriginalMessageIdHeaderKey, originalMessage.MessageId);
}
if (clonedMessage.Properties.ContainsKey(ReceiverTimestampHeaderKey) == false)
{
clonedMessage.Properties.Add(ReceiverTimestampHeaderKey, DateTime.Now.ToString(DateTimeFormatInfo.InvariantInfo));
}
if (clonedMessage.Properties.ContainsKey(ErrorConditionHeaderKey) == false)
{
clonedMessage.Properties.Add(ErrorConditionHeaderKey, errorCode);
}
if (clonedMessage.Properties.ContainsKey(ErrorDescriptionHeaderKey) == false)
{
clonedMessage.Properties.Add(ErrorDescriptionHeaderKey, errorDescription);
}
var additionDataValue = "None";
if (additionalData != null)
{
var sb = new StringBuilder();
foreach (var item in additionalData)
{
if (string.IsNullOrEmpty(item) == false)
{
sb.Append($"{item};");
}
}
additionDataValue = sb.ToString();
if (clonedMessage.Properties.ContainsKey(ErrorConditionDataHeaderKey) == false)
{
clonedMessage.Properties.Add(ErrorConditionDataHeaderKey, additionDataValue);
}
}
logger.LogWarning("Reporting error to sender. ErrorCode: {0} ErrorDescription: {1} AdditionalData: {2}", errorCode, errorDescription, additionDataValue);
await Send(logger, clonedMessage, QueueType.Error).ConfigureAwait(false);
}
/// <summary>
/// Gets the queue name that we can use on messages from a more extensive name
/// </summary>
/// <param name="queueAddress">The full name</param>
/// <returns>The short name</returns>
internal string ExtractQueueName(string queueAddress)
{
// the information stored in the address service includes the full address for the service
// sb.test.nhn.no/DigitalDialog/91468_async
// we only want the last part
if (string.IsNullOrEmpty(queueAddress)) throw new ArgumentNullException(nameof(queueAddress));
var i = queueAddress.LastIndexOf('/');
return queueAddress.Substring(i + 1);
}
private async Task<string> ConstructQueueName(ILogger logger, int herId, QueueType type)
{
var details = await Core.AddressRegistry.FindCommunicationPartyDetailsAsync(logger, herId).ConfigureAwait(false);
if (details == null)
{
throw new MessagingException("Could not find sender in address registry")
{
EventId = EventIds.SenderMissingInAddressRegistryEventId
};
}
switch (type)
{
case QueueType.Asynchronous:
return ExtractQueueName(details.AsynchronousQueueName);
case QueueType.Synchronous:
return ExtractQueueName(details.SynchronousQueueName);
case QueueType.Error:
return ExtractQueueName(details.ErrorQueueName);
default:
throw new InvalidOperationException("QueueType not supported");
}
}
/// <summary>
/// Sends a message to the remote sender with information about what is wrong.
/// Loggs information to our logs.
/// Removes message from processing queue since there is no point in processing it again.
/// </summary>
/// <param name="logger"></param>
/// <param name="id">The event id that error should be logged with</param>
/// <param name="originalMessage"></param>
/// <param name="errorCode"></param>
/// <param name="description"></param>
/// <param name="additionalData"></param>
/// <param name="ex"></param>
internal void ReportErrorToExternalSender(
ILogger logger,
EventId id,
IMessagingMessage originalMessage,
string errorCode,
string description,
IEnumerable<string> additionalData,
Exception ex = null)
{
logger.LogWarning(id, ex, description);
Task.WaitAll(SendError(logger, originalMessage, errorCode, description, additionalData));
RemoveMessageFromQueueAfterError(logger, originalMessage);
}
/// <summary>
/// Removes the message from the queue as part of an error.
/// </summary>
/// <param name="logger"></param>
/// <param name="message"></param>
internal static void RemoveMessageFromQueueAfterError(ILogger logger, IMessagingMessage message)
{
if (message == null) throw new ArgumentNullException(nameof(message));
logger.LogRemoveMessageFromQueueError(message.MessageId);
message.Complete();
}
/// <summary>
/// Removes the message from the queue as part of normal operation
/// </summary>
/// <param name="logger"></param>
/// <param name="message"></param>
internal static void RemoveProcessedMessageFromQueue(ILogger logger, IMessagingMessage message)
{
if (message == null) throw new ArgumentNullException(nameof(message));
logger.LogRemoveMessageFromQueueNormal(message.MessageId);
message.Complete();
}
/// <summary>
/// Registers an alternate messaging factory
/// </summary>
/// <param name="factory"></param>
public void RegisterAlternateMessagingFactory(IMessagingFactory factory) => FactoryPool.RegisterAlternateMessagingFactory(factory);
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CloudWatch.Model
{
/// <summary>
/// Container for the parameters to the DescribeAlarmsForMetric operation.
/// <para> Retrieves all alarms for a single metric. Specify a statistic, period, or unit to filter the set of alarms further. </para>
/// </summary>
/// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DescribeAlarmsForMetric"/>
public class DescribeAlarmsForMetricRequest : AmazonWebServiceRequest
{
private string metricName;
private string namespaceValue;
private string statistic;
private List<Dimension> dimensions = new List<Dimension>();
private int? period;
private string unit;
/// <summary>
/// The name of the metric.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 255</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string MetricName
{
get { return this.metricName; }
set { this.metricName = value; }
}
/// <summary>
/// Sets the MetricName property
/// </summary>
/// <param name="metricName">The value to set for the MetricName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeAlarmsForMetricRequest WithMetricName(string metricName)
{
this.metricName = metricName;
return this;
}
// Check to see if MetricName property is set
internal bool IsSetMetricName()
{
return this.metricName != null;
}
/// <summary>
/// The namespace of the metric.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 255</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[^:].*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Namespace
{
get { return this.namespaceValue; }
set { this.namespaceValue = value; }
}
/// <summary>
/// Sets the Namespace property
/// </summary>
/// <param name="namespaceValue">The value to set for the Namespace property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeAlarmsForMetricRequest WithNamespace(string namespaceValue)
{
this.namespaceValue = namespaceValue;
return this;
}
// Check to see if Namespace property is set
internal bool IsSetNamespace()
{
return this.namespaceValue != null;
}
/// <summary>
/// The statistic for the metric.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Allowed Values</term>
/// <description>SampleCount, Average, Sum, Minimum, Maximum</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Statistic
{
get { return this.statistic; }
set { this.statistic = value; }
}
/// <summary>
/// Sets the Statistic property
/// </summary>
/// <param name="statistic">The value to set for the Statistic property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeAlarmsForMetricRequest WithStatistic(string statistic)
{
this.statistic = statistic;
return this;
}
// Check to see if Statistic property is set
internal bool IsSetStatistic()
{
return this.statistic != null;
}
/// <summary>
/// The list of dimensions associated with the metric.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>0 - 10</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public List<Dimension> Dimensions
{
get { return this.dimensions; }
set { this.dimensions = value; }
}
/// <summary>
/// Adds elements to the Dimensions collection
/// </summary>
/// <param name="dimensions">The values to add to the Dimensions collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeAlarmsForMetricRequest WithDimensions(params Dimension[] dimensions)
{
foreach (Dimension element in dimensions)
{
this.dimensions.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the Dimensions collection
/// </summary>
/// <param name="dimensions">The values to add to the Dimensions collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeAlarmsForMetricRequest WithDimensions(IEnumerable<Dimension> dimensions)
{
foreach (Dimension element in dimensions)
{
this.dimensions.Add(element);
}
return this;
}
// Check to see if Dimensions property is set
internal bool IsSetDimensions()
{
return this.dimensions.Count > 0;
}
/// <summary>
/// The period in seconds over which the statistic is applied.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Range</term>
/// <description>60 - </description>
/// </item>
/// </list>
/// </para>
/// </summary>
public int Period
{
get { return this.period ?? default(int); }
set { this.period = value; }
}
/// <summary>
/// Sets the Period property
/// </summary>
/// <param name="period">The value to set for the Period property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeAlarmsForMetricRequest WithPeriod(int period)
{
this.period = period;
return this;
}
// Check to see if Period property is set
internal bool IsSetPeriod()
{
return this.period.HasValue;
}
/// <summary>
/// The unit for the metric.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Allowed Values</term>
/// <description>Seconds, Microseconds, Milliseconds, Bytes, Kilobytes, Megabytes, Gigabytes, Terabytes, Bits, Kilobits, Megabits, Gigabits, Terabits, Percent, Count, Bytes/Second, Kilobytes/Second, Megabytes/Second, Gigabytes/Second, Terabytes/Second, Bits/Second, Kilobits/Second, Megabits/Second, Gigabits/Second, Terabits/Second, Count/Second, None</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Unit
{
get { return this.unit; }
set { this.unit = value; }
}
/// <summary>
/// Sets the Unit property
/// </summary>
/// <param name="unit">The value to set for the Unit property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeAlarmsForMetricRequest WithUnit(string unit)
{
this.unit = unit;
return this;
}
// Check to see if Unit property is set
internal bool IsSetUnit()
{
return this.unit != null;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using ParatureSDK.Fields;
namespace ParatureSDK.Query.ModuleQuery
{
public abstract class ParaEntityQuery : ParaQuery
{
/// <summary>
/// If you set this property to "True", ParaConnect will perform a schema call, determine the custom fields, then will make a call including all the of the objects custom fields.
/// Caution: do not use the "IncludeCustomField" methods if you are setting this one to true, as the "IncludeCustomField" methods will be ignored.
/// </summary>
public bool IncludeAllCustomFields { get; set; }
public ParaEntityQuery()
{
IncludeAllCustomFields = false;
}
/// <summary>
/// Adds a custom field based filter to the query. Use this method for Custom Fields that are date based.
/// </summary>
/// <param name="customFieldId">
/// The id of the custom field you would like to filter your query on.
/// </param>
/// <param name="criteria">
/// The criteria you would like to apply to this custom field
/// </param>
/// <param name="value">
/// The Date you would like to base your filter off, converted to UTC.
/// NOTE: Custom fields are days, and do not include a time component. Data will look like: yyyy-MM-ddT00:00:00
/// The APIs do respect filtering relative to the full date/time provided, so if you want to use equals, zero the time component.
/// </param>
public void AddCustomFieldFilter(Int64 customFieldId, ParaEnums.QueryCriteria criteria, DateTime value)
{
QueryFilterAdd("FID" + customFieldId, criteria, value.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"));
}
/// <summary>
/// Adds a custom field based filter to the query. Use this method for Custom Fields that are NOT multi values.
/// </summary>
/// <param name="customFieldId">
/// The id of the custom field you would like to filter your query on.
/// </param>
/// <param name="criteria">
/// The criteria you would like to apply to this custom field
/// </param>
/// <param name="value">
/// The value you would like the custom field to have, for this filter.
/// </param>
public void AddCustomFieldFilter(Int64 customFieldId, ParaEnums.QueryCriteria criteria, string value)
{
QueryFilterAdd("FID" + customFieldId, criteria, ProcessEncoding(value));
}
/// <summary>
/// Add a custom field filter to the query for multiple values. Does not work for boolean field types. Query acts like a union of all provided values.
/// </summary>
/// <param name="customFieldId">The id of the custom field to query on</param>
/// <param name="criteria">The query criteria</param>
/// <param name="values">The list of possible values</param>
public void AddCustomFieldInListFilter(Int64 customFieldId, ParaEnums.QueryCriteria criteria,
IEnumerable<string> values)
{
var processedValues = values.Select(value => ProcessEncoding(value)).ToList();
QueryFilterAdd("FID" + customFieldId, criteria, string.Join(",", processedValues));
}
/// <summary>
/// Adds a custom field based filter to the query. Use this method for Custom Fields that are NOT multi values.
/// </summary>
/// <param name="customFieldId">
/// The id of the custom field you would like to filter your query on.
/// </param>
/// <param name="criteria">
/// The criteria you would like to apply to this custom field
/// </param>
/// <param name="value">
/// The value you would like the custom field to have, for this filter.
/// </param>
public void AddCustomFieldFilter(Int64 customFieldId, ParaEnums.QueryCriteria criteria, bool value)
{
var filter = value
? "1"
: "0";
QueryFilterAdd("FID" + customFieldId, criteria, filter);
}
/// <summary>
/// Adds a custom field based filter to the query. Use this method for Custom Fields that are multi values (dropdown, radio buttons, etc).
/// </summary>
/// <param name="customFieldId">
/// The id of the multi value custom field you would like to filter your query on.
/// </param>
/// <param name="criteria">
/// The criteria you would like to apply to this custom field
/// </param>
/// <param name="customFieldOptionId">
/// The list of all custom field options (for the customFieldID you specified) that need to be selected for an item to qualify to be returned when you run your query.
/// </param>
public void AddCustomFieldFilter(Int64 customFieldId, ParaEnums.QueryCriteria criteria, Int64[] customFieldOptionId)
{
if (customFieldOptionId.Length <= 0) return;
var filtering = "";
for (var i = 0; i < customFieldOptionId.Length; i++)
{
var separator = ",";
if (i == 0)
{
if (customFieldOptionId.Length > 1)
{
separator = "";
}
}
filtering = filtering + separator + customFieldOptionId[i];
}
QueryFilterAdd("FID" + customFieldId, criteria, filtering);
}
/// <summary>
/// Adds a custom field based filter to the query. Use this method for Custom Fields that are multi values (dropdown, radio buttons, etc).
/// </summary>
/// <param name="customFieldId">
/// The id of the multi value custom field you would like to filter your query on.
/// </param>
/// <param name="criteria">
/// The criteria you would like to apply to this custom field
/// </param>
/// <param name="customFieldOptionId">
/// The custom field option (for the customFieldID you specified) that need to be selected for an item to qualify to be returned when you run your query.
/// </param>
public void AddCustomFieldFilter(Int64 customFieldId, ParaEnums.QueryCriteria criteria, Int64 customFieldOptionId)
{
QueryFilterAdd("FID" + customFieldId, criteria, customFieldOptionId.ToString());
}
/// <summary>
/// Add a custom field filter for NULL or NOT NULL. Use with any custom fields
/// </summary>
/// <param name="customFieldId">
/// The id of the multi value custom field you would like to filter your query on.
/// </param>
/// <param name="fieldFilter">Null or Not Null filter</param>
public void AddCustomFieldFilter(Int64 customFieldId, ParaEnums.FieldValueFilter fieldFilter)
{
string filterValue = "";
switch (fieldFilter)
{
case ParaEnums.FieldValueFilter.IsNotNull:
filterValue = "_IS_NOT_NULL_";
break;
case ParaEnums.FieldValueFilter.IsNull:
filterValue = "_IS_NULL_";
break;
}
QueryFilterAdd("FID" + customFieldId, ParaEnums.QueryCriteria.Equal, filterValue);
}
/// <summary>
/// Add a custom field to the query returned returned
/// </summary>
public void IncludeCustomField(Int64 customFieldid)
{
IncludedFieldsCheckAndDeleteRecord(customFieldid.ToString());
_IncludedFields.Add(customFieldid.ToString());
}
/// <summary>
/// Include all the custom fields, included in the collection passed to this method,
/// to the api call. These custom fields will be returned with the objects receiveds from the APIs.
/// This is very useful if you have a schema objects and would like to query with all custom fields returned.
/// </summary>
public void IncludeCustomField(IEnumerable<CustomField> customFields)
{
foreach (var cf in customFields)
{
IncludeCustomField(cf.Id);
}
}
/// <summary>
/// Checking if a record exists in the _includedFields array, and delete it if it did.
/// </summary>
protected void IncludedFieldsCheckAndDeleteRecord(string nameValue)
{
ArrayCheckAndDeleteRecord(_IncludedFields, nameValue);
}
/// <summary>
/// Provides the string array of all dynamic filtering and fields to include that will be further processed
/// by the module specific object passed to the APIs, to include statis filtering.
/// </summary>
new internal ArrayList BuildQueryArguments()
{
// The following method is called here, instead of having all the logic in "BuildQueryArguments",
// it has been externalized so that it can be separately called from inherited classes. Certain
// inherited classes override buildQuaryArguments
_QueryFilters = new ArrayList();
BuildCustomFieldQueryArguments();
BuildParaQueryArguments();
if (this.GetActiveOrTrashed != null)
{
_QueryFilters.Add("_status_=" + this.GetActiveOrTrashed.ToString().ToLower());
}
return _QueryFilters;
}
/// <summary>
/// Build all related query arguments related to custom fields.
/// </summary>
private void BuildCustomFieldQueryArguments()
{
var dontAdd = false;
IncludeAllCustomFields = false;
if (TotalOnly == true
|| _IncludedFields == null
|| _IncludedFields.Count <= 0)
{
return;
}
var fieldsList = "_fields_=";
for (var j = 0; j < _IncludedFields.Count; j++)
{
if (j > 0)
{
fieldsList = fieldsList + ",";
}
fieldsList = fieldsList + _IncludedFields[j];
}
if (_QueryFilters.Cast<object>().Any(t => t.ToString() == fieldsList))
{
dontAdd = true;
}
if (dontAdd == false)
{
_QueryFilters.Add(fieldsList);
}
}
/// <summary>
/// Add a sort order to the Query, based on a custom field.
/// </summary>
/// <param name="customFieldId">The id of the custom field you would like to filter upon.</param>
/// <param name="sortDirection"></param>
public bool AddSortOrder(Int64 customFieldId, ParaEnums.QuerySortBy sortDirection)
{
if (_SortByFields.Count < 5)
{
_SortByFields.Add("FID" + customFieldId + "_" + sortDirection.ToString().ToLower() + "_");
return true;
}
else
{
return false;
}
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Novell.Directory.Ldap.LdapMessage.cs
//
// Author:
// Sunil Kumar ([email protected])
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
using System.Reflection;
using Novell.Directory.LDAP.VQ.Rfc2251;
using Novell.Directory.LDAP.VQ.Utilclass;
namespace Novell.Directory.LDAP.VQ
{
/// <summary> The base class for Ldap request and response messages.
///
/// Subclassed by response messages used in asynchronous operations.
///
///
/// </summary>
public class LdapMessage
{
/// <summary> Returns the LdapMessage request associated with this response</summary>
virtual internal LdapMessage RequestingMessage
{
/* package */
get
{
return message.RequestingMessage;
}
}
/// <summary> Returns any controls in the message.</summary>
virtual public LdapControl[] Controls
{
get
{
/* LdapControl[] controls = null;
RfcControls asn1Ctrls = message.Controls;
if (asn1Ctrls != null)
{
controls = new LdapControl[asn1Ctrls.size()];
for (int i = 0; i < asn1Ctrls.size(); i++)
{
RfcControl rfcCtl = (RfcControl) asn1Ctrls.get_Renamed(i);
string oid = rfcCtl.ControlType.stringValue();
sbyte[] value_Renamed = rfcCtl.ControlValue.byteValue();
bool critical = rfcCtl.Criticality.booleanValue();
controls[i] = controlFactory(oid, critical, value_Renamed);
}
}
return controls;
*/
LdapControl[] controls = null;
RfcControls asn1Ctrls = message.Controls;
// convert from RFC 2251 Controls to LDAPControl[].
if (asn1Ctrls != null)
{
controls = new LdapControl[asn1Ctrls.size()];
for (int i = 0; i < asn1Ctrls.size(); i++)
{
/*
* At this point we have an RfcControl which needs to be
* converted to the appropriate Response Control. This requires
* calling the constructor of a class that extends LDAPControl.
* The controlFactory method searches the list of registered
* controls and if a match is found calls the constructor
* for that child LDAPControl. Otherwise, it returns a regular
* LDAPControl object.
*
* Question: Why did we not call the controlFactory method when
* we were parsing the control. Answer: By the time the
* code realizes that we have a control it is already too late.
*/
RfcControl rfcCtl = (RfcControl)asn1Ctrls.get_Renamed(i);
string oid = rfcCtl.ControlType.stringValue();
sbyte[] value_Renamed = rfcCtl.ControlValue.byteValue();
bool critical = rfcCtl.Criticality.booleanValue();
/* Return from this call should return either an LDAPControl
* or a class extending LDAPControl that implements the
* appropriate registered response control
*/
controls[i] = controlFactory(oid, critical, value_Renamed);
}
}
return controls;
}
}
/// <summary> Returns the message ID. The message ID is an integer value
/// identifying the Ldap request and its response.
/// </summary>
virtual public int MessageID
{
get
{
if (imsgNum == -1)
{
imsgNum = message.MessageID;
}
return imsgNum;
}
}
/// <summary> Returns the Ldap operation type of the message.
///
/// The type is one of the following:
/// <ul>
/// <li>BIND_REQUEST = 0;</li>
/// <li>BIND_RESPONSE = 1;</li>
/// <li>UNBIND_REQUEST = 2;</li>
/// <li>SEARCH_REQUEST = 3;</li>
/// <li>SEARCH_RESPONSE = 4;</li>
/// <li>SEARCH_RESULT = 5;</li>
/// <li>MODIFY_REQUEST = 6;</li>
/// <li>MODIFY_RESPONSE = 7;</li>
/// <li>ADD_REQUEST = 8;</li>
/// <li>ADD_RESPONSE = 9;</li>
/// <li>DEL_REQUEST = 10;</li>
/// <li>DEL_RESPONSE = 11;</li>
/// <li>MODIFY_RDN_REQUEST = 12;</li>
/// <li>MODIFY_RDN_RESPONSE = 13;</li>
/// <li>COMPARE_REQUEST = 14;</li>
/// <li>COMPARE_RESPONSE = 15;</li>
/// <li>ABANDON_REQUEST = 16;</li>
/// <li>SEARCH_RESULT_REFERENCE = 19;</li>
/// <li>EXTENDED_REQUEST = 23;</li>
/// <li>EXTENDED_RESPONSE = 24;</li>
/// <li>INTERMEDIATE_RESPONSE = 25;</li>
/// </ul>
///
/// </summary>
/// <returns> The operation type of the message.
/// </returns>
virtual public int Type
{
get
{
if (messageType == -1)
{
messageType = message.Type;
}
return messageType;
}
}
/// <summary> Indicates whether the message is a request or a response
///
/// </summary>
/// <returns> true if the message is a request, false if it is a response,
/// a search result, or a search result reference.
/// </returns>
virtual public bool Request
{
get
{
return message.isRequest();
}
}
/// <summary> Returns the RFC 2251 LdapMessage composed in this object.</summary>
virtual internal RfcLdapMessage Asn1Object
{
/* package */
get
{
return message;
}
}
private string Name
{
get
{
string name;
switch (Type)
{
case SEARCH_RESPONSE:
name = "LdapSearchResponse";
break;
case SEARCH_RESULT:
name = "LdapSearchResult";
break;
case SEARCH_REQUEST:
name = "LdapSearchRequest";
break;
case MODIFY_REQUEST:
name = "LdapModifyRequest";
break;
case MODIFY_RESPONSE:
name = "LdapModifyResponse";
break;
case ADD_REQUEST:
name = "LdapAddRequest";
break;
case ADD_RESPONSE:
name = "LdapAddResponse";
break;
case DEL_REQUEST:
name = "LdapDelRequest";
break;
case DEL_RESPONSE:
name = "LdapDelResponse";
break;
case MODIFY_RDN_REQUEST:
name = "LdapModifyRDNRequest";
break;
case MODIFY_RDN_RESPONSE:
name = "LdapModifyRDNResponse";
break;
case COMPARE_REQUEST:
name = "LdapCompareRequest";
break;
case COMPARE_RESPONSE:
name = "LdapCompareResponse";
break;
case BIND_REQUEST:
name = "LdapBindRequest";
break;
case BIND_RESPONSE:
name = "LdapBindResponse";
break;
case UNBIND_REQUEST:
name = "LdapUnbindRequest";
break;
case ABANDON_REQUEST:
name = "LdapAbandonRequest";
break;
case SEARCH_RESULT_REFERENCE:
name = "LdapSearchResultReference";
break;
case EXTENDED_REQUEST:
name = "LdapExtendedRequest";
break;
case EXTENDED_RESPONSE:
name = "LdapExtendedResponse";
break;
case INTERMEDIATE_RESPONSE:
name = "LdapIntermediateResponse";
break;
default:
throw new Exception("LdapMessage: Unknown Type " + Type);
}
return name;
}
}
/// <summary> Retrieves the identifier tag for this message.
///
/// An identifier can be associated with a message with the
/// <code>setTag</code> method.
/// Tags are set by the application and not by the API or the server.
/// If a server response <code>isRequest() == false</code> has no tag,
/// the tag associated with the corresponding server request is used.
///
/// </summary>
/// <returns> the identifier associated with this message or <code>null</code>
/// if none.
///
/// </returns>
/// <summary> Sets a string identifier tag for this message.
///
/// This method allows an API to set a tag and later identify messages
/// by retrieving the tag associated with the message.
/// Tags are set by the application and not by the API or the server.
/// Message tags are not included with any message sent to or received
/// from the server.
///
/// Tags set on a request to the server
/// are automatically associated with the response messages when they are
/// received by the API and transferred to the application.
/// The application can explicitly set a different value in a
/// response message.
///
/// To set a value in a server request, for example an
/// {@link LdapSearchRequest}, you must create the object,
/// set the tag, and use the
/// {@link LdapConnection.SendRequest LdapConnection.sendRequest()}
/// method to send it to the server.
///
/// </summary>
/// <param name="stringTag"> the String assigned to identify this message.
///
/// </param>
virtual public string Tag
{
get
{
if (stringTag != null)
{
return stringTag;
}
if (Request)
{
return null;
}
LdapMessage m = RequestingMessage;
return m?.stringTag;
}
set
{
stringTag = value;
}
}
/// <summary> A bind request operation.
///
/// BIND_REQUEST = 0
/// </summary>
public const int BIND_REQUEST = 0;
/// <summary> A bind response operation.
///
/// BIND_RESPONSE = 1
/// </summary>
public const int BIND_RESPONSE = 1;
/// <summary> An unbind request operation.
///
/// UNBIND_REQUEST = 2
/// </summary>
public const int UNBIND_REQUEST = 2;
/// <summary> A search request operation.
///
/// SEARCH_REQUEST = 3
/// </summary>
public const int SEARCH_REQUEST = 3;
/// <summary> A search response containing data.
///
/// SEARCH_RESPONSE = 4
/// </summary>
public const int SEARCH_RESPONSE = 4;
/// <summary> A search result message - contains search status.
///
/// SEARCH_RESULT = 5
/// </summary>
public const int SEARCH_RESULT = 5;
/// <summary> A modify request operation.
///
/// MODIFY_REQUEST = 6
/// </summary>
public const int MODIFY_REQUEST = 6;
/// <summary> A modify response operation.
///
/// MODIFY_RESPONSE = 7
/// </summary>
public const int MODIFY_RESPONSE = 7;
/// <summary> An add request operation.
///
/// ADD_REQUEST = 8
/// </summary>
public const int ADD_REQUEST = 8;
/// <summary> An add response operation.
///
/// ADD_RESONSE = 9
/// </summary>
public const int ADD_RESPONSE = 9;
/// <summary> A delete request operation.
///
/// DEL_REQUEST = 10
/// </summary>
public const int DEL_REQUEST = 10;
/// <summary> A delete response operation.
///
/// DEL_RESONSE = 11
/// </summary>
public const int DEL_RESPONSE = 11;
/// <summary> A modify RDN request operation.
///
/// MODIFY_RDN_REQUEST = 12
/// </summary>
public const int MODIFY_RDN_REQUEST = 12;
/// <summary> A modify RDN response operation.
///
/// MODIFY_RDN_RESPONSE = 13
/// </summary>
public const int MODIFY_RDN_RESPONSE = 13;
/// <summary> A compare result operation.
///
/// COMPARE_REQUEST = 14
/// </summary>
public const int COMPARE_REQUEST = 14;
/// <summary> A compare response operation.
///
/// COMPARE_RESPONSE = 15
/// </summary>
public const int COMPARE_RESPONSE = 15;
/// <summary> An abandon request operation.
///
/// ABANDON_REQUEST = 16
/// </summary>
public const int ABANDON_REQUEST = 16;
/// <summary> A search result reference operation.
///
/// SEARCH_RESULT_REFERENCE = 19
/// </summary>
public const int SEARCH_RESULT_REFERENCE = 19;
/// <summary> An extended request operation.
///
/// EXTENDED_REQUEST = 23
/// </summary>
public const int EXTENDED_REQUEST = 23;
/// <summary> An extended response operation.
///
/// EXTENDED_RESONSE = 24
/// </summary>
public const int EXTENDED_RESPONSE = 24;
/// <summary> An intermediate response operation.
///
/// INTERMEDIATE_RESONSE = 25
/// </summary>
public const int INTERMEDIATE_RESPONSE = 25;
/// <summary> A request or response message for an asynchronous Ldap operation.</summary>
protected internal RfcLdapMessage message;
/// <summary> Lock object to protect counter for message numbers</summary>
/*
private static Object msgLock = new Object();
*/
/// <summary> Counters used to construct request message #'s, unique for each request
/// Will be enabled after ASN.1 conversion
/// </summary>
/*
private static int msgNum = 0; // Ldap Request counter
*/
private int imsgNum = -1; // This instance LdapMessage number
private int messageType = -1;
/* application defined tag to identify this message */
private string stringTag = null;
/// <summary> Dummy constuctor</summary>
/* package */
internal LdapMessage()
{
}
/// <summary> Creates an LdapMessage when sending a protocol operation and sends
/// some optional controls with the message.
///
/// </summary>
/// <param name="op">The operation type of message.
///
/// </param>
/// <param name="controls">The controls to use with the operation.
///
/// </param>
/// <seealso cref="Type">
/// </seealso>
/*package*/
internal LdapMessage(int type, RfcRequest op, LdapControl[] controls)
{
// Get a unique number for this request message
messageType = type;
RfcControls asn1Ctrls = null;
if (controls != null)
{
// Move LdapControls into an RFC 2251 Controls object.
asn1Ctrls = new RfcControls();
for (int i = 0; i < controls.Length; i++)
{
// asn1Ctrls.add(null);
asn1Ctrls.add(controls[i].Asn1Object);
}
}
// create RFC 2251 LdapMessage
message = new RfcLdapMessage(op, asn1Ctrls);
}
/// <summary> Creates an Rfc 2251 LdapMessage when the libraries receive a response
/// from a command.
///
/// </summary>
/// <param name="message">A response message.
/// </param>
protected internal LdapMessage(RfcLdapMessage message)
{
this.message = message;
}
/// <summary> Returns a mutated clone of this LdapMessage,
/// replacing base dn, filter.
///
/// </summary>
/// <param name="dn">the base dn
///
/// </param>
/// <param name="filter">the filter
///
/// </param>
/// <param name="reference">true if a search reference
///
/// </param>
/// <returns> the object representing the new message
/// </returns>
/* package */
internal LdapMessage Clone(string dn, string filter, bool reference)
{
return new LdapMessage((RfcLdapMessage)message.dupMessage(dn, filter, reference));
}
/// <summary> Instantiates an LdapControl. We search through our list of
/// registered controls. If we find a matchiing OID we instantiate
/// that control by calling its contructor. Otherwise we default to
/// returning a regular LdapControl object
///
/// </summary>
private LdapControl controlFactory(string oid, bool critical, sbyte[] value_Renamed)
{
// throw new NotImplementedException();
RespControlVector regControls = LdapControl.RegisteredControls;
try
{
/*
* search through the registered extension list to find the
* response control class
*/
Type respCtlClass = regControls.findResponseControl(oid);
// Did not find a match so return default LDAPControl
if (respCtlClass == null)
return new LdapControl(oid, critical, value_Renamed);
/* If found, get LDAPControl constructor */
Type[] argsClass = new Type[] { typeof(string), typeof(bool), typeof(sbyte[]) };
object[] args = new object[] { oid, critical, value_Renamed };
Exception ex = null;
try
{
ConstructorInfo ctlConstructor = respCtlClass.GetConstructor(argsClass);
try
{
/* Call the control constructor for a registered Class*/
object ctl = null;
// ctl = ctlConstructor.newInstance(args);
ctl = ctlConstructor.Invoke(args);
return (LdapControl)ctl;
}
catch (UnauthorizedAccessException e)
{
ex = e;
}
catch (TargetInvocationException e)
{
ex = e;
}
catch (Exception e)
{
// Could not create the ResponseControl object
// All possible exceptions are ignored. We fall through
// and create a default LDAPControl object
ex = e;
}
}
catch (MethodAccessException e)
{
// bad class was specified, fall through and return a
// default LDAPControl object
ex = e;
}
}
catch (FieldAccessException e)
{
// No match with the OID
// Do nothing. Fall through and construct a default LDAPControl object.
}
// If we get here we did not have a registered response control
// for this oid. Return a default LDAPControl object.
return new LdapControl(oid, critical, value_Renamed);
}
/// <summary> Creates a String representation of this object
///
/// </summary>
/// <returns> a String representation for this LdapMessage
/// </returns>
public override string ToString()
{
return Name + "(" + MessageID + "): " + message.ToString();
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// Copyright (c) Lead Pipe Software. All rights reserved. Licensed under the MIT License. Please see the LICENSE file in
// the project root for full license information. --------------------------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------
// Copyright (c) Lead Pipe Software. All rights reserved. Licensed under the MIT License. Please see the LICENSE file in
// the project root for full license information. --------------------------------------------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Diagnostics;
using LeadPipe.Net.Extensions;
namespace LeadPipe.Net
{
using System;
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// The abstract base persistable object.
/// </summary>
/// <typeparam name="TSurrogateIdentity">The type of the surrogate identity.</typeparam>
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass",
Justification = "Reviewed. Suppression is OK here because we're merely building off a base type.")]
public abstract class PersistableObject<TSurrogateIdentity> : IPersistable<TSurrogateIdentity, int>,
IEquatable<PersistableObject<TSurrogateIdentity>>
where TSurrogateIdentity : IComparable
{
/*
* Alas, persistence is a leaky abstraction. However, just because something is an entity doesn't mean that we
* have to clutter it up with persistence concerns. Here we're keeping the notion of entity and an object that
* is persistable separate for what I hope are obvious reasons.
*
* Many O/RM frameworks require a unique identifier for persistence purposes. Of course, you can use the domain
* identity for this purpose. However, it is often advisable to use a surrogate identity for this purpose. This
* identity has no meaning to the business, however, and effectively decouples what is ultimately just a
* persistence concern from the business concern and, therefore, shouldn't be leaked outside of the data layer.
*/
/// <summary>
/// Gets or sets the identity that created the object.
/// </summary>
public virtual string CreatedBy { get; set; }
/// <summary>
/// Gets or sets the date and time the instance was created.
/// </summary>
public virtual DateTime CreatedOn { get; set; }
/// <summary>
/// Gets a value indicating whether this instance is transient (no surrogate id has been set).
/// </summary>
/// <value><c>true</c> if this instance is transient; otherwise, <c>false</c>.</value>
public virtual bool IsTransient => this.Sid.IsNull() || Equals(this.Sid, default(TSurrogateIdentity));
/// <summary>
/// Gets or sets the persistence version.
/// </summary>
public virtual int PersistenceVersion { get; set; }
/// <summary>
/// Gets or sets the surrogate (persistence) id.
/// </summary>
/// <value>The surrogate id.</value>
public virtual TSurrogateIdentity Sid { get; set; }
/// <summary>
/// Gets or sets the identity that last updated the instance.
/// </summary>
public virtual string UpdatedBy { get; set; }
/// <summary>
/// Gets or sets the date and time the instance was last updated.
/// </summary>
public virtual DateTime? UpdatedOn { get; set; }
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="persistableObject1">The persistableObject1.</param>
/// <param name="persistableObject2">The persistableObject2.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(PersistableObject<TSurrogateIdentity> persistableObject1, PersistableObject<TSurrogateIdentity> persistableObject2)
{
return !(persistableObject1 == persistableObject2);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="persistableObject1">The persistableObject1.</param>
/// <param name="persistableObject2">The persistableObject2.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(PersistableObject<TSurrogateIdentity> persistableObject1, PersistableObject<TSurrogateIdentity> persistableObject2)
{
object obj1 = persistableObject1;
object obj2 = persistableObject2;
// If both objects are null then they are equal...
if (obj1 == null && obj2 == null)
{
return true;
}
// If one of the objects is null then they are not equal...
if (obj1 == null || obj2 == null)
{
return false;
}
// Try to compare by IKeyed...
var keyedObject1 = persistableObject1 as IKeyed;
var keyedObject2 = persistableObject2 as IKeyed;
if (keyedObject1 != null && keyedObject2 != null)
{
var compareResult = string.CompareOrdinal(keyedObject1.Key, keyedObject2.Key);
return compareResult == 0;
}
// If IKeyed didn't work out then if both objects are NOT transient then compare by the Sid (kinda icky)...
if (persistableObject1.IsTransient.IsFalse() && persistableObject2.IsTransient.IsFalse())
{
return persistableObject1.Sid.CompareTo(persistableObject2.Sid) == 0;
}
// If the objects are of different types then they are not equal...
/*
* NOTE: This code is below the IKeyed and Sid checks for a reason; proxies. If two persistable objects do
* not have keys and no sid has been assigned, but one is a proxy then all we can do is throw up our
* hands and say, "Nope, they're not the same".
*/
if (persistableObject1.GetType() != persistableObject2.GetType())
{
return false;
}
// I give up...
return obj1 == obj2;
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
public virtual bool Equals(PersistableObject<TSurrogateIdentity> other)
{
if (other == null)
{
return false;
}
return this == other;
}
/// <summary>
/// Compares two persistable objects for equality.
/// </summary>
/// <param name="persistableObject">The persistable object to compare against.</param>
/// <returns>True if the persistable objects are equal.</returns>
public override bool Equals(object persistableObject)
{
if (persistableObject == null || !(persistableObject is PersistableObject<TSurrogateIdentity>))
{
return false;
}
return this == (PersistableObject<TSurrogateIdentity>)persistableObject;
}
/// <summary>
/// Gets the hash code for the persistable object.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
// Cast ourselves as a keyed object...
var keyedObject = this as IKeyed;
// If we are keyed then return the key hash...
if (keyedObject != null && string.IsNullOrEmpty(keyedObject.Key) == false)
{
return keyedObject.Key.GetHashCode();
}
// If we're not transient then return the hash of our surrogate id...
if (IsTransient.IsFalse())
{
return Sid.GetHashCode();
}
return base.GetHashCode();
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public override string ToString()
{
// Cast ourselves as a keyed object...
var keyedObject = this as IKeyed;
// If we are keyed then return the key...
if (keyedObject != null)
{
return keyedObject.Key;
}
// If we have a surrogate id then return its hash otherwise return our base hash...
return this.Sid.Equals(default(TSurrogateIdentity)) == false
? this.Sid.ToString()
: base.ToString();
}
}
}
| |
//
// This file is part of the game Voxalia, created by FreneticXYZ.
// This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license.
// See README.md or LICENSE.txt for contents of the MIT license.
// If these are not available, see https://opensource.org/licenses/MIT
//
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections.Generic;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL4;
using Voxalia.Shared;
using Voxalia.ClientGame.CommandSystem;
using Voxalia.ClientGame.ClientMainSystem;
using FreneticScript;
namespace Voxalia.ClientGame.GraphicsSystems
{
public class TextureBlock
{
public Client TheClient;
public TextureEngine TEngine;
public List<AnimatedTexture> Anims;
public int TextureID = -1;
public int NormalTextureID = -1;
public int HelpTextureID = -1;
public int TWidth;
/// <summary>
/// TODO: Direct links, not lookup strings!
/// </summary>
public string[] IntTexs;
public void Generate(Client tclient, ClientCVar cvars, TextureEngine eng)
{
TheClient = tclient;
if (Anims != null)
{
for (int i = 0; i < Anims.Count; i++)
{
Anims[i].Destroy();
}
}
if (TextureID > -1)
{
GL.DeleteTexture(TextureID);
GL.DeleteTexture(NormalTextureID);
GL.DeleteTexture(HelpTextureID);
}
Anims = new List<AnimatedTexture>();
TEngine = eng;
TextureID = GL.GenTexture();
TWidth = cvars.r_blocktexturewidth.ValueI;
GL.BindTexture(TextureTarget.Texture2DArray, TextureID);
GL.TexStorage3D(TextureTarget3d.Texture2DArray, 1, SizedInternalFormat.Rgba8, TWidth, TWidth, MaterialHelpers.Textures.Length);
GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMinFilter, (int)(cvars.r_blocktexturelinear.ValueB ? TextureMinFilter.Linear: TextureMinFilter.Nearest));
GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMagFilter, (int)(cvars.r_blocktexturelinear.ValueB ? TextureMagFilter.Linear : TextureMagFilter.Nearest));
GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
HelpTextureID = GL.GenTexture();
GL.BindTexture(TextureTarget.Texture2DArray, HelpTextureID);
GL.TexStorage3D(TextureTarget3d.Texture2DArray, 1, SizedInternalFormat.Rgba8, TWidth, TWidth, MaterialHelpers.Textures.Length);
GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
NormalTextureID = GL.GenTexture();
GL.BindTexture(TextureTarget.Texture2DArray, NormalTextureID);
GL.TexStorage3D(TextureTarget3d.Texture2DArray, 1, SizedInternalFormat.Rgba8, TWidth, TWidth, MaterialHelpers.Textures.Length);
GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
// TODO: Use normal.a!
List<MaterialTextureInfo> texs = new List<MaterialTextureInfo>(MaterialHelpers.Textures.Length);
IntTexs = new string[MaterialHelpers.Textures.Length];
//float time = 0;
for (int ia = 0; ia < MaterialHelpers.Textures.Length; ia++)
{
int i = ia;
// TODO: Make this saner, and don't allow entering a game until it's done maybe?
//TheClient.Schedule.ScheduleSyncTask(() =>
{
MaterialTextureInfo tex = new MaterialTextureInfo();
tex.Mat = (Material)i;
string[] refrornot = MaterialHelpers.Textures[i].SplitFast('@');
if (refrornot.Length > 1)
{
string[] rorn = refrornot[1].SplitFast('%');
if (rorn.Length > 1)
{
tex.RefrRate = Utilities.StringToFloat(rorn[1]);
}
tex.RefractTextures = rorn[0].SplitFast(',');
}
string[] glowornot = refrornot[0].SplitFast('!');
if (glowornot.Length > 1)
{
tex.GlowingTextures = glowornot[1].SplitFast(',');
}
string[] reflornot = glowornot[0].SplitFast('*');
if (reflornot.Length > 1)
{
tex.ReflectTextures = reflornot[1].SplitFast(',');
}
string[] specularornot = reflornot[0].SplitFast('&');
if (specularornot.Length > 1)
{
tex.SpecularTextures = specularornot[1].SplitFast(',');
}
string[] normalornot = specularornot[0].SplitFast('$');
GL.BindTexture(TextureTarget.Texture2DArray, NormalTextureID);
if (normalornot.Length > 1)
{
string[] rorn = normalornot[1].SplitFast('%');
if (rorn.Length > 1)
{
tex.NormRate = Utilities.StringToFloat(rorn[1]);
}
tex.NormalTextures = rorn[0].SplitFast(',');
SetTexture((int)tex.Mat, tex.NormalTextures[0]);
if (tex.NormalTextures.Length > 1)
{
SetAnimated((int)tex.Mat, tex.NormRate, tex.NormalTextures, NormalTextureID);
}
}
else
{
SetTexture((int)tex.Mat, "normal_def");
}
string[] rateornot = normalornot[0].SplitFast('%');
if (rateornot.Length > 1)
{
tex.Rate = Utilities.StringToFloat(rateornot[1]);
}
tex.Textures = rateornot[0].SplitFast(',');
GL.BindTexture(TextureTarget.Texture2DArray, TextureID);
SetTexture((int)tex.Mat, tex.Textures[0]);
if (tex.Textures.Length > 1)
{
SetAnimated((int)tex.Mat, tex.Rate, tex.Textures, TextureID);
}
texs.Add(tex);
IntTexs[(int)tex.Mat] = tex.Textures[0];
}//, i * LoadRate);
//time = i * 0.1f;
}
for (int ia = 0; ia < texs.Count; ia++)
{
int i = ia;
//TheClient.Schedule.ScheduleSyncTask(() =>
{
GL.BindTexture(TextureTarget.Texture2DArray, HelpTextureID);
Bitmap combo = GetCombo(texs[i], 0);
TEngine.LockBitmapToTexture(combo, (int)texs[i].Mat);
if ((texs[i].SpecularTextures != null) && (texs[i].ReflectTextures != null) && (texs[i].RefractTextures != null) && (texs[i].GlowingTextures != null) && texs[i].SpecularTextures.Length > 1)
{
Bitmap[] bmps = new Bitmap[texs[i].SpecularTextures.Length];
bmps[0] = combo;
for (int x = 1; x < bmps.Length; x++)
{
bmps[x] = GetCombo(texs[i], x);
}
SetAnimated((int)texs[i].Mat, texs[i].RefrRate, bmps, HelpTextureID);
for (int x = 1; x < bmps.Length; x++)
{
bmps[x].Dispose();
}
}
combo.Dispose();
}//, time + i * LoadRate);
}
GL.BindTexture(TextureTarget.Texture2DArray, 0);
GL.BindTexture(TextureTarget.Texture2DArray, 0);
}
const float LoadRate = 0.1f;
public Bitmap GetCombo(MaterialTextureInfo tex, int coord)
{
string refract = (tex.RefractTextures != null && tex.RefractTextures.Length > coord) ? tex.RefractTextures[coord] : "black";
Texture trefr = TEngine.GetTexture(refract, TWidth);
Bitmap bmprefr = trefr.SaveToBMP();
string reflect = (tex.ReflectTextures != null && tex.ReflectTextures.Length > coord) ? tex.ReflectTextures[coord] : "black";
Texture trefl = TEngine.GetTexture(reflect, TWidth);
Bitmap bmprefl = trefl.SaveToBMP();
string specular = (tex.SpecularTextures != null && tex.SpecularTextures.Length > coord) ? tex.SpecularTextures[coord] : "black";
Texture tspec = TEngine.GetTexture(specular, TWidth);
Bitmap bmpspec = tspec.SaveToBMP();
string glowing = (tex.GlowingTextures != null && tex.GlowingTextures.Length > coord) ? tex.GlowingTextures[coord] : "black";
Texture tglow = TEngine.GetTexture(glowing, TWidth);
Bitmap bmpglow = tglow.SaveToBMP();
Bitmap combo = Combine(bmpspec, bmprefl, bmprefr, bmpglow);
bmprefr.Dispose();
bmprefl.Dispose();
bmpspec.Dispose();
bmpglow.Dispose();
return combo;
}
public Bitmap Combine(Bitmap one, Bitmap two, Bitmap three, Bitmap four)
{
Bitmap combined = new Bitmap(TWidth, TWidth);
// Surely there's a better way to do this!
unsafe
{
BitmapData bdat = combined.LockBits(new Rectangle(0, 0, combined.Width, combined.Height), ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
int stride = bdat.Stride;
byte* ptr = (byte*)bdat.Scan0;
BitmapData bdat1 = one.LockBits(new Rectangle(0, 0, one.Width, one.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
int stride1 = bdat1.Stride;
byte* ptr1 = (byte*)bdat1.Scan0;
BitmapData bdat2 = two.LockBits(new Rectangle(0, 0, two.Width, two.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
int stride2 = bdat2.Stride;
byte* ptr2 = (byte*)bdat2.Scan0;
BitmapData bdat3 = three.LockBits(new Rectangle(0, 0, three.Width, three.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
int stride3 = bdat3.Stride;
byte* ptr3 = (byte*)bdat3.Scan0;
BitmapData bdat4 = four.LockBits(new Rectangle(0, 0, four.Width, four.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
int stride4 = bdat4.Stride;
byte* ptr4 = (byte*)bdat4.Scan0;
for (int x = 0; x < TWidth; x++)
{
for (int y = 0; y < TWidth; y++)
{
ptr[(x * 4) + y * stride + 0] = ptr1[(x * 4) + y * stride];
ptr[(x * 4) + y * stride + 1] = ptr2[(x * 4) + y * stride];
ptr[(x * 4) + y * stride + 2] = ptr3[(x * 4) + y * stride];
ptr[(x * 4) + y * stride + 3] = ptr4[(x * 4) + y * stride];
}
}
combined.UnlockBits(bdat);
one.UnlockBits(bdat1);
two.UnlockBits(bdat2);
three.UnlockBits(bdat3);
four.UnlockBits(bdat4);
}
return combined;
}
public int Gray(Color col)
{
return (col.R + (int)col.G + col.B) / 3;
}
public void SetTexture(int ID, string texture)
{
TEngine.LoadTextureIntoArray(texture, ID, TWidth);
}
public void SetAnimated(int ID, double rate, Bitmap[] textures, int tid)
{
AnimatedTexture anim = new AnimatedTexture();
anim.Block = this;
anim.Level = ID;
anim.Time = 0;
anim.Rate = rate;
anim.Textures = new int[textures.Length];
anim.FBOs = new int[textures.Length];
anim.OwnsTheTextures = true;
for (int i = 0; i < textures.Length; i++)
{
anim.Textures[i] = GL.GenTexture();
GL.BindTexture(TextureTarget.Texture2D, anim.Textures[i]);
TEngine.LockBitmapToTexture(textures[i], false);
GL.BindTexture(TextureTarget.Texture2D, 0);
anim.FBOs[i] = GL.GenFramebuffer();
GL.BindFramebuffer(FramebufferTarget.Framebuffer, anim.FBOs[i]);
GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, anim.Textures[i], 0);
}
GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
anim.Current = 0;
anim.FBO = GL.GenFramebuffer();
GL.BindFramebuffer(FramebufferTarget.Framebuffer, anim.FBO);
GL.FramebufferTextureLayer(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, tid, 0, ID);
GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
Anims.Add(anim);
}
public void SetAnimated(int ID, double rate, string[] textures, int tid)
{
AnimatedTexture anim = new AnimatedTexture();
anim.Block = this;
anim.Level = ID;
anim.Time = 0;
anim.Rate = rate;
anim.Textures = new int[textures.Length];
anim.FBOs = new int[textures.Length];
anim.OwnsTheTextures = false;
for (int i = 0; i < textures.Length; i++)
{
anim.Textures[i] = TEngine.GetTexture(textures[i], TWidth).Original_InternalID;
anim.FBOs[i] = GL.GenFramebuffer();
GL.BindFramebuffer(FramebufferTarget.Framebuffer, anim.FBOs[i]);
GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, anim.Textures[i], 0);
}
GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
anim.Current = 0;
anim.FBO = GL.GenFramebuffer();
GL.BindFramebuffer(FramebufferTarget.Framebuffer, anim.FBO);
GL.FramebufferTextureLayer(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, tid, 0, ID);
GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
Anims.Add(anim);
}
public void Tick(double ttime)
{
for (int i = 0; i < Anims.Count; i++)
{
Anims[i].Tick(ttime);
}
GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, 0);
GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
}
}
public class MaterialTextureInfo
{
public Material Mat;
public string[] Textures;
public string[] NormalTextures;
public string[] RefractTextures;
public string[] ReflectTextures;
public string[] SpecularTextures;
public string[] GlowingTextures;
public double Rate = 1;
public double NormRate = 1;
public double RefrRate = 1;
}
public class AnimatedTexture
{
public TextureBlock Block;
public int Level;
public double Rate;
public double Time;
public int FBO;
public int[] FBOs;
public bool OwnsTheTextures;
public void Tick(double ttime)
{
Time += ttime;
bool changed = false;
while (Time > Rate)
{
Current++;
if (Current >= Textures.Length)
{
Current = 0;
}
Time -= Rate;
changed = true;
}
if (changed)
{
AnimateNext();
}
}
public int[] Textures;
public int Current = 0;
private void AnimateNext()
{
GL.BindFramebuffer(FramebufferTarget.Framebuffer, FBO);
GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, FBOs[Current]);
GL.BlitFramebuffer(0, 0, Block.TWidth, Block.TWidth, 0, 0, Block.TWidth, Block.TWidth, ClearBufferMask.ColorBufferBit, BlitFramebufferFilter.Nearest);
}
public void Destroy()
{
GL.DeleteFramebuffer(FBO);
for (int i = 0; i < FBOs.Length; i++)
{
GL.DeleteFramebuffer(FBOs[i]);
}
if (OwnsTheTextures)
{
for (int i = 0; i < Textures.Length; i++)
{
GL.DeleteTexture(Textures[i]);
}
}
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Runtime.InteropServices;
using AOT;
namespace UnityEngine.XR.iOS {
/// <summary>
/// A struct that allows us go from native Matrix4x4 to managed
/// </summary>
public struct UnityARMatrix4x4
{
public Vector4 column0;
public Vector4 column1;
public Vector4 column2;
public Vector4 column3;
public UnityARMatrix4x4(Vector4 c0, Vector4 c1, Vector4 c2, Vector4 c3)
{
column0 = c0; column1 = c1; column2 = c2; column3 = c3;
}
};
[Serializable]
public struct UnityVideoParams
{
public int yWidth;
public int yHeight;
public int screenOrientation;
public float texCoordScale;
public IntPtr cvPixelBufferPtr;
};
struct internal_UnityARCamera
{
public UnityARMatrix4x4 worldTransform;
public UnityARMatrix4x4 projectionMatrix;
public ARTrackingState trackingState;
public ARTrackingStateReason trackingReason;
public UnityVideoParams videoParams;
public UnityMarshalLightData lightData;
public UnityARMatrix4x4 displayTransform;
public uint getPointCloudData;
public uint getLightEstimation;
};
public struct UnityARCamera
{
public UnityARMatrix4x4 worldTransform;
public UnityARMatrix4x4 projectionMatrix;
public ARTrackingState trackingState;
public ARTrackingStateReason trackingReason;
public UnityVideoParams videoParams;
public UnityARLightData lightData;
public UnityARMatrix4x4 displayTransform;
public Vector3[] pointCloudData;
public UnityARCamera(UnityARMatrix4x4 wt, UnityARMatrix4x4 pm, ARTrackingState ats, ARTrackingStateReason atsr, UnityVideoParams uvp, UnityARLightData lightDat, UnityARMatrix4x4 dt, Vector3[] pointCloud)
{
worldTransform = wt;
projectionMatrix = pm;
trackingState = ats;
trackingReason = atsr;
videoParams = uvp;
lightData = lightDat;
displayTransform = dt;
pointCloudData = pointCloud;
}
};
public struct UnityARUserAnchorData
{
public IntPtr ptrIdentifier;
/**
The transformation matrix that defines the anchor's rotation, translation and scale in world coordinates.
*/
public UnityARMatrix4x4 transform;
public string identifierStr { get { return Marshal.PtrToStringAuto(this.ptrIdentifier); } }
public static UnityARUserAnchorData UnityARUserAnchorDataFromGameObject(GameObject go) {
// create an anchor data struct from a game object transform
Matrix4x4 matrix = Matrix4x4.TRS(go.transform.position, go.transform.rotation, go.transform.localScale);
UnityARUserAnchorData ad = new UnityARUserAnchorData();
ad.transform.column0 = matrix.GetColumn(0);
ad.transform.column1 = matrix.GetColumn(1);
ad.transform.column2 = matrix.GetColumn(2);
ad.transform.column3 = matrix.GetColumn(3);
return ad;
}
};
public struct UnityARHitTestResult
{
/**
The type of the hit-test result.
*/
public ARHitTestResultType type;
/**
The distance from the camera to the intersection in meters.
*/
public double distance;
/**
The transformation matrix that defines the intersection's rotation, translation and scale
relative to the anchor or nearest feature point.
*/
public Matrix4x4 localTransform;
/**
The transformation matrix that defines the intersection's rotation, translation and scale
relative to the world.
*/
public Matrix4x4 worldTransform;
/**
The anchor that the hit-test intersected.
*/
public IntPtr anchor;
/**
True if the test represents a valid hit test. Data is undefined otherwise.
*/
public bool isValid;
};
public enum UnityARAlignment
{
UnityARAlignmentGravity,
UnityARAlignmentGravityAndHeading,
UnityARAlignmentCamera
}
public enum UnityARPlaneDetection
{
None = 0,
Horizontal = (1 << 0),
Vertical = (1 << 1),
HorizontalAndVertical = (1 << 1) | (1 << 0)
}
public struct ARKitSessionConfiguration
{
public UnityARAlignment alignment;
public bool getPointCloudData;
public bool enableLightEstimation;
public bool IsSupported { get { return IsARKitSessionConfigurationSupported(); } private set {} }
public ARKitSessionConfiguration(UnityARAlignment alignment = UnityARAlignment.UnityARAlignmentGravity,
bool getPointCloudData = false,
bool enableLightEstimation = false)
{
this.getPointCloudData = getPointCloudData;
this.alignment = alignment;
this.enableLightEstimation = enableLightEstimation;
}
[DllImport("__Internal")]
private static extern bool IsARKitSessionConfigurationSupported();
}
public struct ARKitWorldTrackingSessionConfiguration
{
public UnityARAlignment alignment;
public UnityARPlaneDetection planeDetection;
public bool getPointCloudData;
public bool enableLightEstimation;
public bool enableAutoFocus;
public IntPtr videoFormat;
public string arResourceGroupName;
public bool IsSupported { get { return IsARKitWorldTrackingSessionConfigurationSupported(); } private set {} }
public ARKitWorldTrackingSessionConfiguration(UnityARAlignment alignment = UnityARAlignment.UnityARAlignmentGravity,
UnityARPlaneDetection planeDetection = UnityARPlaneDetection.Horizontal,
bool getPointCloudData = false,
bool enableLightEstimation = false,
bool enableAutoFocus = true,
IntPtr vidFormat = default(IntPtr),
string arResourceGroup = null)
{
this.getPointCloudData = getPointCloudData;
this.alignment = alignment;
this.planeDetection = planeDetection;
this.enableLightEstimation = enableLightEstimation;
this.enableAutoFocus = enableAutoFocus;
this.videoFormat = vidFormat;
this.arResourceGroupName = arResourceGroup;
}
#if UNITY_EDITOR
private bool IsARKitWorldTrackingSessionConfigurationSupported() {
return true;
}
#else
[DllImport("__Internal")]
private static extern bool IsARKitWorldTrackingSessionConfigurationSupported();
#endif
}
public struct ARKitFaceTrackingConfiguration
{
public UnityARAlignment alignment;
public bool enableLightEstimation;
public bool IsSupported { get { return IsARKitFaceTrackingConfigurationSupported(); } private set {} }
public ARKitFaceTrackingConfiguration(UnityARAlignment alignment = UnityARAlignment.UnityARAlignmentGravity,
bool enableLightEstimation = false)
{
this.alignment = alignment;
this.enableLightEstimation = enableLightEstimation;
}
#if UNITY_EDITOR
private bool IsARKitFaceTrackingConfigurationSupported() {
return true;
}
#else
[DllImport("__Internal")]
private static extern bool IsARKitFaceTrackingConfigurationSupported();
#endif
}
public enum UnityARSessionRunOption {
/** The session will reset tracking. */
ARSessionRunOptionResetTracking = (1 << 0),
/** The session will remove existing anchors. */
ARSessionRunOptionRemoveExistingAnchors = (1 << 1)
}
public class UnityARSessionNativeInterface {
// public delegate void ARFrameUpdate(UnityARMatrix4x4 cameraPos, UnityARMatrix4x4 projection);
// public static event ARFrameUpdate ARFrameUpdatedEvent;
// Plane Anchors
public delegate void ARFrameUpdate(UnityARCamera camera);
public static event ARFrameUpdate ARFrameUpdatedEvent;
public delegate void ARAnchorAdded(ARPlaneAnchor anchorData);
public static event ARAnchorAdded ARAnchorAddedEvent;
public delegate void ARAnchorUpdated(ARPlaneAnchor anchorData);
public static event ARAnchorUpdated ARAnchorUpdatedEvent;
public delegate void ARAnchorRemoved(ARPlaneAnchor anchorData);
public static event ARAnchorRemoved ARAnchorRemovedEvent;
// User Anchors
public delegate void ARUserAnchorAdded(ARUserAnchor anchorData);
public static event ARUserAnchorAdded ARUserAnchorAddedEvent;
public delegate void ARUserAnchorUpdated(ARUserAnchor anchorData);
public static event ARUserAnchorUpdated ARUserAnchorUpdatedEvent;
public delegate void ARUserAnchorRemoved(ARUserAnchor anchorData);
public static event ARUserAnchorRemoved ARUserAnchorRemovedEvent;
// Face Anchors
public delegate void ARFaceAnchorAdded(ARFaceAnchor anchorData);
public static event ARFaceAnchorAdded ARFaceAnchorAddedEvent;
public delegate void ARFaceAnchorUpdated(ARFaceAnchor anchorData);
public static event ARFaceAnchorUpdated ARFaceAnchorUpdatedEvent;
public delegate void ARFaceAnchorRemoved(ARFaceAnchor anchorData);
public static event ARFaceAnchorRemoved ARFaceAnchorRemovedEvent;
// Image Anchors
public delegate void ARImageAnchorAdded(ARImageAnchor anchorData);
public static event ARImageAnchorAdded ARImageAnchorAddedEvent;
public delegate void ARImageAnchorUpdated(ARImageAnchor anchorData);
public static event ARImageAnchorUpdated ARImageAnchorUpdatedEvent;
public delegate void ARImageAnchorRemoved(ARImageAnchor anchorData);
public static event ARImageAnchorRemoved ARImageAnchorRemovedEvent;
public delegate void ARSessionFailed(string error);
public static event ARSessionFailed ARSessionFailedEvent;
public delegate void ARSessionCallback();
public delegate bool ARSessionLocalizeCallback();
public static event ARSessionCallback ARSessionInterruptedEvent;
public static event ARSessionCallback ARSessioninterruptionEndedEvent;
public delegate void ARSessionTrackingChanged(UnityARCamera camera);
public static event ARSessionTrackingChanged ARSessionTrackingChangedEvent;
public static bool ARSessionShouldAttemptRelocalization { get; set; }
delegate void internal_ARFrameUpdate(internal_UnityARCamera camera);
public delegate void internal_ARAnchorAdded(UnityARAnchorData anchorData);
public delegate void internal_ARAnchorUpdated(UnityARAnchorData anchorData);
public delegate void internal_ARAnchorRemoved(UnityARAnchorData anchorData);
public delegate void internal_ARUserAnchorAdded(UnityARUserAnchorData anchorData);
public delegate void internal_ARUserAnchorUpdated(UnityARUserAnchorData anchorData);
public delegate void internal_ARUserAnchorRemoved(UnityARUserAnchorData anchorData);
public delegate void internal_ARFaceAnchorAdded(UnityARFaceAnchorData anchorData);
public delegate void internal_ARFaceAnchorUpdated(UnityARFaceAnchorData anchorData);
public delegate void internal_ARFaceAnchorRemoved(UnityARFaceAnchorData anchorData);
public delegate void internal_ARImageAnchorAdded(UnityARImageAnchorData anchorData);
public delegate void internal_ARImageAnchorUpdated(UnityARImageAnchorData anchorData);
public delegate void internal_ARImageAnchorRemoved(UnityARImageAnchorData anchorData);
delegate void internal_ARSessionTrackingChanged(internal_UnityARCamera camera);
#if !UNITY_EDITOR
private IntPtr m_NativeARSession;
#endif
private static UnityARCamera s_Camera;
[DllImport("__Internal")]
private static extern IntPtr unity_CreateNativeARSession();
[DllImport("__Internal")]
private static extern void session_SetSessionCallbacks(IntPtr nativeSession, internal_ARFrameUpdate frameCallback,
ARSessionFailed sessionFailed,
ARSessionCallback sessionInterrupted,
ARSessionCallback sessionInterruptionEnded,
ARSessionLocalizeCallback sessionShouldRelocalize,
internal_ARSessionTrackingChanged trackingChanged);
[DllImport("__Internal")]
private static extern void session_SetPlaneAnchorCallbacks(IntPtr nativeSession, internal_ARAnchorAdded anchorAddedCallback,
internal_ARAnchorUpdated anchorUpdatedCallback,
internal_ARAnchorRemoved anchorRemovedCallback);
[DllImport("__Internal")]
private static extern void session_SetUserAnchorCallbacks(IntPtr nativeSession, internal_ARUserAnchorAdded userAnchorAddedCallback,
internal_ARUserAnchorUpdated userAnchorUpdatedCallback,
internal_ARUserAnchorRemoved userAnchorRemovedCallback);
[DllImport("__Internal")]
private static extern void session_SetImageAnchorCallbacks(IntPtr nativeSession, internal_ARImageAnchorAdded imageAnchorAddedCallback,
internal_ARImageAnchorUpdated imageAnchorUpdatedCallback,
internal_ARImageAnchorRemoved imageAnchorRemovedCallback);
[DllImport("__Internal")]
private static extern void session_SetFaceAnchorCallbacks(IntPtr nativeSession, internal_ARFaceAnchorAdded faceAnchorAddedCallback,
internal_ARFaceAnchorUpdated faceAnchorUpdatedCallback,
internal_ARFaceAnchorRemoved faceAnchorRemovedCallback);
[DllImport("__Internal")]
private static extern void StartWorldTrackingSession(IntPtr nativeSession, ARKitWorldTrackingSessionConfiguration configuration);
[DllImport("__Internal")]
private static extern void StartWorldTrackingSessionWithOptions(IntPtr nativeSession, ARKitWorldTrackingSessionConfiguration configuration, UnityARSessionRunOption runOptions);
[DllImport("__Internal")]
private static extern void StartSession(IntPtr nativeSession, ARKitSessionConfiguration configuration);
[DllImport("__Internal")]
private static extern void StartSessionWithOptions(IntPtr nativeSession, ARKitSessionConfiguration configuration, UnityARSessionRunOption runOptions);
[DllImport("__Internal")]
private static extern void StartFaceTrackingSession(IntPtr nativeSession, ARKitFaceTrackingConfiguration configuration);
[DllImport("__Internal")]
private static extern void StartFaceTrackingSessionWithOptions(IntPtr nativeSession, ARKitFaceTrackingConfiguration configuration, UnityARSessionRunOption runOptions);
[DllImport("__Internal")]
private static extern void PauseSession(IntPtr nativeSession);
[DllImport("__Internal")]
private static extern int HitTest(IntPtr nativeSession, ARPoint point, ARHitTestResultType types);
[DllImport("__Internal")]
private static extern UnityARHitTestResult GetLastHitTestResult(int index);
[DllImport("__Internal")]
private static extern ARTextureHandles GetVideoTextureHandles();
[DllImport("__Internal")]
private static extern float GetAmbientIntensity();
[DllImport("__Internal")]
private static extern int GetTrackingQuality();
[DllImport("__Internal")]
private static extern bool GetARPointCloud (ref IntPtr verts, ref uint vertLength);
[DllImport("__Internal")]
private static extern void SetCameraNearFar (float nearZ, float farZ);
[DllImport("__Internal")]
private static extern void CapturePixelData (int enable, IntPtr pYPixelBytes, IntPtr pUVPixelBytes);
[DllImport("__Internal")]
private static extern UnityARUserAnchorData SessionAddUserAnchor (IntPtr nativeSession, UnityARUserAnchorData anchorData);
[DllImport("__Internal")]
private static extern void SessionRemoveUserAnchor (IntPtr nativeSession, [MarshalAs(UnmanagedType.LPStr)] string anchorIdentifier);
[DllImport("__Internal")]
private static extern void SessionSetWorldOrigin (IntPtr nativeSession, Matrix4x4 worldMatrix);
public UnityARSessionNativeInterface()
{
#if !UNITY_EDITOR
m_NativeARSession = unity_CreateNativeARSession();
session_SetSessionCallbacks(m_NativeARSession, _frame_update, _ar_session_failed, _ar_session_interrupted,
_ar_session_interruption_ended, _ar_session_should_relocalize, _ar_tracking_changed);
session_SetPlaneAnchorCallbacks(m_NativeARSession, _anchor_added, _anchor_updated, _anchor_removed);
session_SetUserAnchorCallbacks(m_NativeARSession, _user_anchor_added, _user_anchor_updated, _user_anchor_removed);
session_SetFaceAnchorCallbacks(m_NativeARSession, _face_anchor_added, _face_anchor_updated, _face_anchor_removed);
session_SetImageAnchorCallbacks(m_NativeARSession, _image_anchor_added, _image_anchor_updated, _image_anchor_removed);
#endif
}
static UnityARSessionNativeInterface s_UnityARSessionNativeInterface = null;
public static UnityARSessionNativeInterface GetARSessionNativeInterface()
{
if (s_UnityARSessionNativeInterface == null) {
s_UnityARSessionNativeInterface = new UnityARSessionNativeInterface ();
}
return s_UnityARSessionNativeInterface;
}
#if UNITY_EDITOR
public static void SetStaticCamera(UnityARCamera scamera)
{
s_Camera = scamera;
}
public static void RunFrameUpdateCallbacks()
{
if (ARFrameUpdatedEvent != null)
{
ARFrameUpdatedEvent(s_Camera);
}
}
public static void RunAddAnchorCallbacks(ARPlaneAnchor arPlaneAnchor)
{
if (ARAnchorAddedEvent != null)
{
ARAnchorAddedEvent(arPlaneAnchor);
}
}
public static void RunUpdateAnchorCallbacks(ARPlaneAnchor arPlaneAnchor)
{
if (ARAnchorUpdatedEvent != null)
{
ARAnchorUpdatedEvent(arPlaneAnchor);
}
}
public static void RunRemoveAnchorCallbacks(ARPlaneAnchor arPlaneAnchor)
{
if (ARAnchorRemovedEvent != null)
{
ARAnchorRemovedEvent(arPlaneAnchor);
}
}
public static void RunAddAnchorCallbacks(ARFaceAnchor arFaceAnchor)
{
if (ARFaceAnchorAddedEvent != null)
{
ARFaceAnchorAddedEvent(arFaceAnchor);
}
}
public static void RunUpdateAnchorCallbacks(ARFaceAnchor arFaceAnchor)
{
if (ARFaceAnchorUpdatedEvent != null)
{
ARFaceAnchorUpdatedEvent(arFaceAnchor);
}
}
public static void RunRemoveAnchorCallbacks(ARFaceAnchor arFaceAnchor)
{
if (ARFaceAnchorRemovedEvent != null)
{
ARFaceAnchorRemovedEvent(arFaceAnchor);
}
}
private static void CreateRemoteFaceTrackingConnection(ARKitFaceTrackingConfiguration config, UnityARSessionRunOption runOptions)
{
GameObject go = new GameObject ("ARKitFaceTrackingRemoteConnection");
ARKitFaceTrackingRemoteConnection addComp = go.AddComponent<ARKitFaceTrackingRemoteConnection> ();
addComp.enableLightEstimation = config.enableLightEstimation;
addComp.resetTracking = (runOptions & UnityARSessionRunOption.ARSessionRunOptionResetTracking) != 0;
addComp.removeExistingAnchors = (runOptions & UnityARSessionRunOption.ARSessionRunOptionRemoveExistingAnchors) != 0;
}
private static void CreateRemoteWorldTrackingConnection(ARKitWorldTrackingSessionConfiguration config, UnityARSessionRunOption runOptions)
{
GameObject go = new GameObject ("ARKitWorldTrackingRemoteConnection");
ARKitRemoteConnection addComp = go.AddComponent<ARKitRemoteConnection> ();
addComp.planeDetection = config.planeDetection;
addComp.startAlignment = config.alignment;
addComp.getPointCloud = config.getPointCloudData;
addComp.enableLightEstimation = config.enableLightEstimation;
addComp.resetTracking = (runOptions & UnityARSessionRunOption.ARSessionRunOptionResetTracking) != 0;
addComp.removeExistingAnchors = (runOptions & UnityARSessionRunOption.ARSessionRunOptionRemoveExistingAnchors) != 0;
}
#endif
public Matrix4x4 GetCameraPose()
{
Matrix4x4 matrix = new Matrix4x4();
matrix.SetColumn(0, s_Camera.worldTransform.column0);
matrix.SetColumn(1, s_Camera.worldTransform.column1);
matrix.SetColumn(2, s_Camera.worldTransform.column2);
matrix.SetColumn(3, s_Camera.worldTransform.column3);
return matrix;
}
public Matrix4x4 GetCameraProjection()
{
Matrix4x4 matrix = new Matrix4x4();
matrix.SetColumn(0, s_Camera.projectionMatrix.column0);
matrix.SetColumn(1, s_Camera.projectionMatrix.column1);
matrix.SetColumn(2, s_Camera.projectionMatrix.column2);
matrix.SetColumn(3, s_Camera.projectionMatrix.column3);
return matrix;
}
public void SetCameraClipPlanes(float nearZ, float farZ)
{
#if !UNITY_EDITOR
SetCameraNearFar (nearZ, farZ);
#endif
}
public void SetCapturePixelData(bool enable, IntPtr pYByteArray, IntPtr pUVByteArray)
{
#if !UNITY_EDITOR
int iEnable = enable ? 1 : 0;
CapturePixelData (iEnable,pYByteArray, pUVByteArray);
#endif
}
[MonoPInvokeCallback(typeof(internal_ARFrameUpdate))]
static void _frame_update(internal_UnityARCamera camera)
{
UnityARCamera pubCamera = new UnityARCamera();
pubCamera.projectionMatrix = camera.projectionMatrix;
pubCamera.worldTransform = camera.worldTransform;
pubCamera.trackingState = camera.trackingState;
pubCamera.trackingReason = camera.trackingReason;
pubCamera.videoParams = camera.videoParams;
if (camera.getLightEstimation == 1)
{
pubCamera.lightData = camera.lightData;
}
pubCamera.displayTransform = camera.displayTransform;
s_Camera = pubCamera;
if (camera.getPointCloudData == 1)
{
UpdatePointCloudData (ref s_Camera);
}
if (ARFrameUpdatedEvent != null)
{
ARFrameUpdatedEvent(s_Camera);
}
}
[MonoPInvokeCallback(typeof(internal_ARSessionTrackingChanged))]
static void _ar_tracking_changed(internal_UnityARCamera camera)
{
// we only update the current camera's tracking state since that's all
// this cllback is for
s_Camera.trackingState = camera.trackingState;
s_Camera.trackingReason = camera.trackingReason;
if (ARSessionTrackingChangedEvent != null)
{
ARSessionTrackingChangedEvent(s_Camera);
}
}
static void UpdatePointCloudData(ref UnityARCamera camera)
{
IntPtr ptrResultVerts = IntPtr.Zero;
uint resultVertLength = 0;
bool success = GetARPointCloud (ref ptrResultVerts, ref resultVertLength);
float[] resultVertices = null;
if (success) {
// Load the results into a managed array.
resultVertices = new float[resultVertLength];
Marshal.Copy (ptrResultVerts, resultVertices, 0, (int)resultVertLength);
Vector3[] verts = new Vector3[(resultVertLength / 4)];
for (int count = 0; count < resultVertLength; count++)
{
verts [count / 4].x = resultVertices[count++];
verts [count / 4].y = resultVertices[count++];
verts [count / 4].z = -resultVertices[count++];
}
camera.pointCloudData = verts;
}
}
static ARUserAnchor GetUserAnchorFromAnchorData(UnityARUserAnchorData anchor)
{
//get the identifier for this anchor from the pointer
ARUserAnchor arUserAnchor = new ARUserAnchor ();
arUserAnchor.identifier = Marshal.PtrToStringAuto(anchor.ptrIdentifier);
Matrix4x4 matrix = new Matrix4x4 ();
matrix.SetColumn(0, anchor.transform.column0);
matrix.SetColumn(1, anchor.transform.column1);
matrix.SetColumn(2, anchor.transform.column2);
matrix.SetColumn(3, anchor.transform.column3);
arUserAnchor.transform = matrix;
return arUserAnchor;
}
static ARHitTestResult GetHitTestResultFromResultData(UnityARHitTestResult resultData)
{
ARHitTestResult arHitTestResult = new ARHitTestResult ();
arHitTestResult.type = resultData.type;
arHitTestResult.distance = resultData.distance;
arHitTestResult.localTransform = resultData.localTransform;
arHitTestResult.worldTransform = resultData.worldTransform;
arHitTestResult.isValid = resultData.isValid;
if (resultData.anchor != IntPtr.Zero) {
arHitTestResult.anchorIdentifier = Marshal.PtrToStringAuto (resultData.anchor);
}
return arHitTestResult;
}
#region Plane Anchors
#if !UNITY_EDITOR
[MonoPInvokeCallback(typeof(internal_ARAnchorAdded))]
static void _anchor_added(UnityARAnchorData anchor)
{
if (ARAnchorAddedEvent != null)
{
ARPlaneAnchor arPlaneAnchor = new ARPlaneAnchor(anchor);
ARAnchorAddedEvent(arPlaneAnchor);
}
}
[MonoPInvokeCallback(typeof(internal_ARAnchorUpdated))]
static void _anchor_updated(UnityARAnchorData anchor)
{
if (ARAnchorUpdatedEvent != null)
{
ARPlaneAnchor arPlaneAnchor = new ARPlaneAnchor(anchor);
ARAnchorUpdatedEvent(arPlaneAnchor);
}
}
[MonoPInvokeCallback(typeof(internal_ARAnchorRemoved))]
static void _anchor_removed(UnityARAnchorData anchor)
{
if (ARAnchorRemovedEvent != null)
{
ARPlaneAnchor arPlaneAnchor = new ARPlaneAnchor(anchor);
ARAnchorRemovedEvent(arPlaneAnchor);
}
}
#endif
#endregion
#region User Anchors
[MonoPInvokeCallback(typeof(internal_ARUserAnchorAdded))]
static void _user_anchor_added(UnityARUserAnchorData anchor)
{
if (ARUserAnchorAddedEvent != null)
{
ARUserAnchor arUserAnchor = GetUserAnchorFromAnchorData(anchor);
ARUserAnchorAddedEvent(arUserAnchor);
}
}
[MonoPInvokeCallback(typeof(internal_ARUserAnchorUpdated))]
static void _user_anchor_updated(UnityARUserAnchorData anchor)
{
if (ARUserAnchorUpdatedEvent != null)
{
ARUserAnchor arUserAnchor = GetUserAnchorFromAnchorData(anchor);
ARUserAnchorUpdatedEvent(arUserAnchor); }
}
[MonoPInvokeCallback(typeof(internal_ARUserAnchorRemoved))]
static void _user_anchor_removed(UnityARUserAnchorData anchor)
{
if (ARUserAnchorRemovedEvent != null)
{
ARUserAnchor arUserAnchor = GetUserAnchorFromAnchorData(anchor);
ARUserAnchorRemovedEvent(arUserAnchor);
}
}
#endregion
#region Face Anchors
#if !UNITY_EDITOR
[MonoPInvokeCallback(typeof(internal_ARFaceAnchorAdded))]
static void _face_anchor_added(UnityARFaceAnchorData anchor)
{
if (ARFaceAnchorAddedEvent != null)
{
ARFaceAnchor arFaceAnchor = new ARFaceAnchor(anchor);
ARFaceAnchorAddedEvent(arFaceAnchor);
}
}
[MonoPInvokeCallback(typeof(internal_ARFaceAnchorUpdated))]
static void _face_anchor_updated(UnityARFaceAnchorData anchor)
{
if (ARFaceAnchorUpdatedEvent != null)
{
ARFaceAnchor arFaceAnchor = new ARFaceAnchor(anchor);
ARFaceAnchorUpdatedEvent(arFaceAnchor); }
}
[MonoPInvokeCallback(typeof(internal_ARFaceAnchorRemoved))]
static void _face_anchor_removed(UnityARFaceAnchorData anchor)
{
if (ARFaceAnchorRemovedEvent != null)
{
ARFaceAnchor arFaceAnchor = new ARFaceAnchor(anchor);
ARFaceAnchorRemovedEvent(arFaceAnchor);
}
}
#endif
#endregion
#region Image Anchors
[MonoPInvokeCallback(typeof(internal_ARImageAnchorAdded))]
static void _image_anchor_added(UnityARImageAnchorData anchor)
{
if (ARImageAnchorAddedEvent != null)
{
ARImageAnchor arImageAnchor = new ARImageAnchor(anchor);
ARImageAnchorAddedEvent(arImageAnchor);
}
}
[MonoPInvokeCallback(typeof(internal_ARImageAnchorUpdated))]
static void _image_anchor_updated(UnityARImageAnchorData anchor)
{
if (ARImageAnchorUpdatedEvent != null)
{
ARImageAnchor arImageAnchor = new ARImageAnchor(anchor);
ARImageAnchorUpdatedEvent(arImageAnchor);
}
}
[MonoPInvokeCallback(typeof(internal_ARImageAnchorRemoved))]
static void _image_anchor_removed(UnityARImageAnchorData anchor)
{
if (ARImageAnchorRemovedEvent != null)
{
ARImageAnchor arImageAnchor = new ARImageAnchor(anchor);
ARImageAnchorRemovedEvent(arImageAnchor);
}
}
#endregion
[MonoPInvokeCallback(typeof(ARSessionFailed))]
static void _ar_session_failed(string error)
{
if (ARSessionFailedEvent != null)
{
ARSessionFailedEvent(error);
}
}
[MonoPInvokeCallback(typeof(ARSessionCallback))]
static void _ar_session_interrupted()
{
Debug.Log("ar_session_interrupted");
if (ARSessionInterruptedEvent != null)
{
ARSessionInterruptedEvent();
}
}
[MonoPInvokeCallback(typeof(ARSessionCallback))]
static void _ar_session_interruption_ended()
{
Debug.Log("ar_session_interruption_ended");
if (ARSessioninterruptionEndedEvent != null)
{
ARSessioninterruptionEndedEvent();
}
}
[MonoPInvokeCallback(typeof(ARSessionLocalizeCallback))]
static bool _ar_session_should_relocalize()
{
Debug.Log("_ar_session_should_relocalize");
return ARSessionShouldAttemptRelocalization;
}
public void RunWithConfigAndOptions(ARKitWorldTrackingSessionConfiguration config, UnityARSessionRunOption runOptions)
{
#if !UNITY_EDITOR
StartWorldTrackingSessionWithOptions (m_NativeARSession, config, runOptions);
#else
CreateRemoteWorldTrackingConnection(config, runOptions);
#endif
}
public void RunWithConfig(ARKitWorldTrackingSessionConfiguration config)
{
#if !UNITY_EDITOR
StartWorldTrackingSession(m_NativeARSession, config);
#else
UnityARSessionRunOption runOptions = UnityARSessionRunOption.ARSessionRunOptionRemoveExistingAnchors | UnityARSessionRunOption.ARSessionRunOptionResetTracking;
CreateRemoteWorldTrackingConnection(config, runOptions);
#endif
}
public void Run()
{
RunWithConfig(new ARKitWorldTrackingSessionConfiguration(UnityARAlignment.UnityARAlignmentGravity, UnityARPlaneDetection.Horizontal));
}
public void RunWithConfigAndOptions(ARKitSessionConfiguration config, UnityARSessionRunOption runOptions)
{
#if !UNITY_EDITOR
StartSessionWithOptions (m_NativeARSession, config, runOptions);
#endif
}
public void RunWithConfig(ARKitSessionConfiguration config)
{
#if !UNITY_EDITOR
StartSession(m_NativeARSession, config);
#endif
}
public void RunWithConfigAndOptions(ARKitFaceTrackingConfiguration config, UnityARSessionRunOption runOptions)
{
#if !UNITY_EDITOR
StartFaceTrackingSessionWithOptions (m_NativeARSession, config, runOptions);
#else
CreateRemoteFaceTrackingConnection(config, runOptions);
#endif
}
public void RunWithConfig(ARKitFaceTrackingConfiguration config)
{
#if !UNITY_EDITOR
StartFaceTrackingSession(m_NativeARSession, config);
#else
UnityARSessionRunOption runOptions = UnityARSessionRunOption.ARSessionRunOptionRemoveExistingAnchors | UnityARSessionRunOption.ARSessionRunOptionResetTracking;
CreateRemoteFaceTrackingConnection(config, runOptions);
#endif
}
public void Pause()
{
#if !UNITY_EDITOR
PauseSession(m_NativeARSession);
#endif
}
public List<ARHitTestResult> HitTest(ARPoint point, ARHitTestResultType types)
{
#if !UNITY_EDITOR
int numResults = HitTest(m_NativeARSession, point, types);
List<ARHitTestResult> results = new List<ARHitTestResult>();
for (int i = 0; i < numResults; ++i)
{
var result = GetLastHitTestResult(i);
results.Add(GetHitTestResultFromResultData(result));
}
return results;
#else
return new List<ARHitTestResult>();
#endif
}
public ARTextureHandles GetARVideoTextureHandles()
{
return GetVideoTextureHandles ();
}
[Obsolete("Hook ARFrameUpdatedEvent instead and get UnityARCamera.ambientIntensity")]
public float GetARAmbientIntensity()
{
return GetAmbientIntensity ();
}
[Obsolete("Hook ARFrameUpdatedEvent instead and get UnityARCamera.trackingState")]
public int GetARTrackingQuality()
{
return GetTrackingQuality();
}
public UnityARUserAnchorData AddUserAnchor(UnityARUserAnchorData anchorData)
{
#if !UNITY_EDITOR
return SessionAddUserAnchor(m_NativeARSession, anchorData);
#else
return new UnityARUserAnchorData();
#endif
}
public UnityARUserAnchorData AddUserAnchorFromGameObject(GameObject go) {
#if !UNITY_EDITOR
UnityARUserAnchorData data = AddUserAnchor(UnityARUserAnchorData.UnityARUserAnchorDataFromGameObject(go));
return data;
#else
return new UnityARUserAnchorData();
#endif
}
public void RemoveUserAnchor(string anchorIdentifier)
{
#if !UNITY_EDITOR
SessionRemoveUserAnchor(m_NativeARSession, anchorIdentifier);
#endif
}
public void SetWorldOrigin(Transform worldTransform)
{
#if !UNITY_EDITOR
//convert from Unity coord system to ARKit
Matrix4x4 worldMatrix = UnityARMatrixOps.UnityToARKitCoordChange(worldTransform.position, worldTransform.rotation);
SessionSetWorldOrigin (m_NativeARSession, worldMatrix);
#endif
}
}
}
| |
namespace MonoRpg.Engine.GameStates {
using global::System;
using global::System.Collections.Generic;
using global::System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using MonoRpg.Engine.RenderEngine;
using MonoRpg.Engine.UI;
public class FrontMenu : BaseStateObject {
public InGameMenu Parent { get; set; }
public StateMachine StateMachine { get; private set; }
public Layout Layout { get; private set; }
public Selection<string> Selections { get; set; }
public List<Panel> Panels { get; set; }
public string TopBarText { get; set; }
public Selection<ActorSummary> PartyMenu { get; set; }
public string PrevTopBarText { get; set; }
public bool InPartyMenu { get; set; }
public FrontMenu(InGameMenu parent) : base(parent.Stack) {
var layout = new Layout()
.Contract("screen", 118, 40)
.SplitHorizontal("screen", "top", "bottom", 0.12f, 2)
.SplitVertical("bottom", "left", "party", 0.726f, 2)
.SplitHorizontal("left", "menu", "gold", 0.7f, 2);
Parent = parent;
StateMachine = parent.StateMachine;
Layout = layout;
Selections = new Selection<string>(System.Renderer,
new SelectionArgs<string>("Items", "Status") {
SpacingY = 32,
OnSelection = (i, s) => OnMenuClick(i)
}
);
Panels = new List<Panel> {
layout.CreatePanel("gold"),
layout.CreatePanel("top"),
layout.CreatePanel("party"),
layout.CreatePanel("menu")
};
TopBarText = "Current Map Name";
PartyMenu = new Selection<ActorSummary>(System.Renderer, new SelectionArgs<ActorSummary>(CreatePartySummaries()) {
SpacingY = 90,
Columns = 1,
Rows = 3,
OnSelection = OnPartyMemberChosen,
RenderItem = (renderer, x, y, item) => {
item.SetPosition(x, y + 35);
item.Render(renderer);
}
});
PartyMenu.HideCursor();
TopBarText = "Empty Room";
InPartyMenu = false;
}
private void OnMenuClick(int index) {
var items = 0;
if (index == items) {
StateMachine.Change("items");
return;
}
InPartyMenu = true;
Selections.HideCursor();
PartyMenu.ShowCursor();
PrevTopBarText = TopBarText;
TopBarText = "Chose a party member";
}
public override bool Update(float dt) {
return false;
}
public override void Render(Renderer renderer) {
foreach (var panel in Panels) {
panel.Render(renderer);
}
renderer.AlignText(TextAlignment.Left, TextAlignment.Center);
var menuX = Layout.Left("menu") + 16;
var menuY = Layout.Top("menu") - 24;
Selections.TextScale = Parent.TitleSize;
Selections.Position = new Vector2(menuX, menuY);
Selections.Render(renderer);
var nameX = Layout.CenterX("top");
var nameY = Layout.CenterY("top");
renderer.AlignText(TextAlignment.Center, TextAlignment.Center);
renderer.DrawText2D(nameX, nameY, TopBarText);
var goldX = Layout.CenterX("gold") - 22;
var goldY = Layout.CenterY("gold") + 22;
renderer.AlignText(TextAlignment.Right, TextAlignment.Top);
var scale = Parent.LabelSize;
renderer.DrawText2D(goldX, goldY, "GP:", Color.White, scale);
renderer.DrawText2D(goldX, goldY - 25, "TIME:", Color.White, scale);
renderer.AlignText(TextAlignment.Left, TextAlignment.Top);
renderer.DrawText2D(goldX + 10, goldY, World.Instance.Gold.ToString(), Color.White, scale);
renderer.DrawText2D(goldX + 10, goldY - 25, World.Instance.TimeString, Color.White, scale);
var partyX = Layout.Left("party") - 16;
var partyY = Layout.Top("party") - 45;
PartyMenu.Position = new Vector2(partyX, partyY);
PartyMenu.Render(renderer);
}
public override void HandleInput(float dt) {
if (InPartyMenu) {
PartyMenu.HandleInput();
if (System.Keys.WasPressed(Keys.Back) || System.Keys.WasPressed(Keys.Escape)) {
InPartyMenu = false;
TopBarText = PrevTopBarText;
Selections.ShowCursor();
PartyMenu.HideCursor();
}
} else {
Selections.HandleInput();
if (System.Keys.WasPressed(Keys.Back) || System.Keys.WasPressed(Keys.Escape)) {
Stack.Pop();
}
}
}
public List<ActorSummary> CreatePartySummaries() {
var members = World.Instance.Party.Members;
return members.Select(kv => new ActorSummary(kv.Value, new ActorSummaryArgs { ShowXP = true })).ToList();
}
private void OnPartyMemberChosen(int actorIndex, ActorSummary actorSummary) {
var indexToStateId = new Dictionary<int, string> {
[1] = "status"
};
var actor = actorSummary.Actor;
var index = Selections.GetIndex();
var stateId = indexToStateId[index];
StateMachine.Change(stateId, new StatusArgs{Actor = actor});
}
}
public class ActorSummary {
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public Actor Actor { get; set; }
public ProgressBar HPBar { get; set; }
public ProgressBar MPBar { get; set; }
public int AvatarTextPad { get; set; }
public int LabelRightPad { get; set; }
public int LabelValuePad { get; set; }
public int VerticalPad { get; set; }
public bool ShowXP { get; set; }
public ProgressBar XPBar { get; set; }
public ActorSummary(Actor actor, ActorSummaryArgs args) {
X = 0;
Y = 0;
Width = 340;
Actor = actor;
HPBar = new ProgressBar(new ProgressBarArgs {
Value = actor.Stats.GetStat(Stats.HitPoints).Value,
Maximum = actor.Stats.GetStat(Stats.MaxHitPoints).Value,
Background = System.Content.FindTexture("hpbackground.png"),
Foreground = System.Content.FindTexture("hpforeground.png")
});
HPBar.Foreground.PixelArt = true;
HPBar.Background.PixelArt = true;
MPBar = new ProgressBar(new ProgressBarArgs {
Value = actor.Stats.GetStat(Stats.MagicPoints).Value,
Maximum = actor.Stats.GetStat(Stats.MaxMagicPoints).Value,
Background = System.Content.FindTexture("mpbackground.png"),
Foreground = System.Content.FindTexture("mpforeground.png")
});
MPBar.Foreground.PixelArt = true;
MPBar.Background.PixelArt = true;
AvatarTextPad = 14;
LabelRightPad = 15;
LabelValuePad = 8;
VerticalPad = 18;
ShowXP = args.ShowXP;
if (ShowXP) {
XPBar = new ProgressBar(new ProgressBarArgs {
Value = actor.XP,
Maximum = actor.NextLevelXP,
Background = System.Content.FindTexture("xpbackground.png"),
Foreground = System.Content.FindTexture("xpforeground.png")
});
}
SetPosition(X, Y);
}
public void SetPosition(int x, int y) {
X = x;
Y = y;
int barX;
if (ShowXP) {
var boxRight = X + Width;
barX = boxRight - XPBar.HalfWidth;
var barY = Y - 44;
XPBar.Position = new Vector2(barX, barY);
}
var avatarW = Actor.PortraitTexture.Width;
barX = X + avatarW + AvatarTextPad;
barX += LabelRightPad + LabelValuePad;
barX += MPBar.HalfWidth;
MPBar.Position = new Vector2(barX, Y - 72);
HPBar.Position = new Vector2(barX, Y - 54);
}
public Vector2 GetCursorPosition() {
return new Vector2(X, Y - 40);
}
public void Render(Renderer renderer) {
var avatarW = Actor.PortraitTexture.Width;
var avatarH = Actor.PortraitTexture.Height;
var avatarX = X + avatarW / 2;
var avatarY = Y - avatarH / 2;
Actor.Portrait.Position = new Vector2(avatarX, avatarY);
renderer.DrawSprite(Actor.Portrait);
renderer.AlignText(TextAlignment.Left, TextAlignment.Top);
var textPadY = 2;
var textX = avatarX + avatarW / 2 + AvatarTextPad;
var textY = Y - textPadY;
renderer.DrawText2D(textX, textY, Actor.Name, Color.White, 1.2f );
renderer.AlignText(TextAlignment.Right, TextAlignment.Top);
textX += LabelRightPad;
textY -= 20;
var startStatsY = textY;
var scale = 1.0f;
renderer.DrawText2D(textX, textY, "LV", Color.White, scale);
textY -= VerticalPad;
renderer.DrawText2D(textX, textY, "HP", Color.White, scale);
textY -= VerticalPad;
renderer.DrawText2D(textX, textY, "MP", Color.White, scale);
textY = startStatsY;
textX += LabelValuePad;
renderer.AlignText(TextAlignment.Left, TextAlignment.Top);
var level = Actor.Level;
var hp = Actor.Stats.GetStat(Stats.HitPoints).Value;
var maxHp = Actor.Stats.GetStat(Stats.MaxHitPoints).Value;
var mp = Actor.Stats.GetStat(Stats.MaxMagicPoints).Value;
var maxMp = Actor.Stats.GetStat(Stats.MaxMagicPoints).Value;
var counter = "{0}/{1}";
renderer.DrawText2D(textX, textY, level.ToString(), Color.White, scale);
textY -= VerticalPad;
renderer.DrawText2D(textX, textY, string.Format(counter, hp, maxHp), Color.White, scale);
textY -= VerticalPad;
renderer.DrawText2D(textX, textY, string.Format(counter, mp, maxMp), Color.White, scale);
if (ShowXP) {
renderer.AlignText(TextAlignment.Left, TextAlignment.Top);
var boxRight = X + Width;
textY = startStatsY;
var left = boxRight - XPBar.HalfWidth*2;
renderer.DrawText2D(left, textY, "Next Level", Color.White, scale);
XPBar.Render(renderer);
}
HPBar.Render(renderer);
MPBar.Render(renderer);
}
}
public class ActorSummaryArgs {
public bool ShowXP { get; set; }
}
public class StatusArgs : EnterArgs {
public Actor Actor { get; set; }
}
}
| |
using TQVaultAE.GUI.Components;
namespace TQVaultAE.GUI
{
/// <summary>
/// Form designer class for ItemSeedDialog
/// </summary>
internal partial class CharacterEditDialog
{
/// <summary>
/// OK button control
/// </summary>
private ScalingButton ok;
/// <summary>
/// Cancel button
/// </summary>
private ScalingButton cancel;
/// <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 && (this.components != null))
{
this.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(CharacterEditDialog));
this.ok = new TQVaultAE.GUI.Components.ScalingButton();
this.cancel = new TQVaultAE.GUI.Components.ScalingButton();
this.strengthLabel = new TQVaultAE.GUI.Components.ScalingLabel();
this.dexterityLabel = new TQVaultAE.GUI.Components.ScalingLabel();
this.IntelligenceLabel = new TQVaultAE.GUI.Components.ScalingLabel();
this.healthLabel = new TQVaultAE.GUI.Components.ScalingLabel();
this.manaLabel = new TQVaultAE.GUI.Components.ScalingLabel();
this.attribGroupBox = new System.Windows.Forms.GroupBox();
this.manacUpDown = new System.Windows.Forms.NumericUpDown();
this.healthUpDown = new System.Windows.Forms.NumericUpDown();
this.intelligenceUpDown = new System.Windows.Forms.NumericUpDown();
this.dexterityUpDown = new System.Windows.Forms.NumericUpDown();
this.strengthUpDown = new System.Windows.Forms.NumericUpDown();
this.levelingGroupBox = new System.Windows.Forms.GroupBox();
this.levelingCheckBox = new TQVaultAE.GUI.Components.ScalingCheckBox();
this.difficultyLabel = new TQVaultAE.GUI.Components.ScalingLabel();
this.difficultlyComboBox = new System.Windows.Forms.ComboBox();
this.skillPointsNumericUpDown = new System.Windows.Forms.NumericUpDown();
this.skillPointsLabel = new TQVaultAE.GUI.Components.ScalingLabel();
this.attributeNumericUpDown = new System.Windows.Forms.NumericUpDown();
this.attributeLabel = new TQVaultAE.GUI.Components.ScalingLabel();
this.xpTextBox = new System.Windows.Forms.TextBox();
this.xpLabel = new TQVaultAE.GUI.Components.ScalingLabel();
this.levelNumericUpDown = new System.Windows.Forms.NumericUpDown();
this.levelLabel = new TQVaultAE.GUI.Components.ScalingLabel();
this.ResetMasteriesScalingButton = new TQVaultAE.GUI.Components.ScalingButton();
this.MasteriesGroupBox = new System.Windows.Forms.GroupBox();
this.Mastery2ValueScalingLabel = new TQVaultAE.GUI.Components.ScalingLabel();
this.Mastery1ValueScalingLabel = new TQVaultAE.GUI.Components.ScalingLabel();
this.Mastery2NameScalingLabel = new TQVaultAE.GUI.Components.ScalingLabel();
this.Mastery1NameScalingLabel = new TQVaultAE.GUI.Components.ScalingLabel();
this.ResetAttributesScalingButton = new TQVaultAE.GUI.Components.ScalingButton();
this.attribGroupBox.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.manacUpDown)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.healthUpDown)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.intelligenceUpDown)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dexterityUpDown)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.strengthUpDown)).BeginInit();
this.levelingGroupBox.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.skillPointsNumericUpDown)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.attributeNumericUpDown)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.levelNumericUpDown)).BeginInit();
this.MasteriesGroupBox.SuspendLayout();
this.SuspendLayout();
//
// ok
//
this.ok.BackColor = System.Drawing.Color.Transparent;
this.ok.DownBitmap = ((System.Drawing.Bitmap)(resources.GetObject("ok.DownBitmap")));
this.ok.FlatAppearance.BorderSize = 0;
this.ok.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.ok.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.ok.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.ok.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F);
this.ok.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.ok.Image = ((System.Drawing.Image)(resources.GetObject("ok.Image")));
this.ok.Location = new System.Drawing.Point(540, 438);
this.ok.Margin = new System.Windows.Forms.Padding(4);
this.ok.Name = "ok";
this.ok.OverBitmap = ((System.Drawing.Bitmap)(resources.GetObject("ok.OverBitmap")));
this.ok.Size = new System.Drawing.Size(171, 38);
this.ok.SizeToGraphic = false;
this.ok.TabIndex = 13;
this.ok.Text = "OK";
this.ok.UpBitmap = ((System.Drawing.Bitmap)(resources.GetObject("ok.UpBitmap")));
this.ok.UseCustomGraphic = true;
this.ok.UseVisualStyleBackColor = false;
this.ok.Click += new System.EventHandler(this.OKButton_Click);
//
// cancel
//
this.cancel.BackColor = System.Drawing.Color.Transparent;
this.cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancel.DownBitmap = ((System.Drawing.Bitmap)(resources.GetObject("cancel.DownBitmap")));
this.cancel.FlatAppearance.BorderSize = 0;
this.cancel.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.cancel.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.cancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cancel.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F);
this.cancel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.cancel.Image = ((System.Drawing.Image)(resources.GetObject("cancel.Image")));
this.cancel.Location = new System.Drawing.Point(722, 438);
this.cancel.Margin = new System.Windows.Forms.Padding(4);
this.cancel.Name = "cancel";
this.cancel.OverBitmap = ((System.Drawing.Bitmap)(resources.GetObject("cancel.OverBitmap")));
this.cancel.Size = new System.Drawing.Size(171, 38);
this.cancel.SizeToGraphic = false;
this.cancel.TabIndex = 14;
this.cancel.Text = "Cancel";
this.cancel.UpBitmap = ((System.Drawing.Bitmap)(resources.GetObject("cancel.UpBitmap")));
this.cancel.UseCustomGraphic = true;
this.cancel.UseVisualStyleBackColor = false;
this.cancel.Click += new System.EventHandler(this.CancelButton_Click);
//
// strengthLabel
//
this.strengthLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F);
this.strengthLabel.Location = new System.Drawing.Point(8, 41);
this.strengthLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.strengthLabel.Name = "strengthLabel";
this.strengthLabel.Size = new System.Drawing.Size(128, 22);
this.strengthLabel.TabIndex = 5;
this.strengthLabel.Text = "Strength";
this.strengthLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// dexterityLabel
//
this.dexterityLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F);
this.dexterityLabel.Location = new System.Drawing.Point(11, 79);
this.dexterityLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.dexterityLabel.Name = "dexterityLabel";
this.dexterityLabel.Size = new System.Drawing.Size(124, 22);
this.dexterityLabel.TabIndex = 7;
this.dexterityLabel.Text = "Dexterity";
this.dexterityLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// IntelligenceLabel
//
this.IntelligenceLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F);
this.IntelligenceLabel.Location = new System.Drawing.Point(15, 116);
this.IntelligenceLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.IntelligenceLabel.Name = "IntelligenceLabel";
this.IntelligenceLabel.Size = new System.Drawing.Size(120, 22);
this.IntelligenceLabel.TabIndex = 9;
this.IntelligenceLabel.Text = "Intelligence";
this.IntelligenceLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// healthLabel
//
this.healthLabel.CausesValidation = false;
this.healthLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F);
this.healthLabel.Location = new System.Drawing.Point(11, 154);
this.healthLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.healthLabel.Name = "healthLabel";
this.healthLabel.Size = new System.Drawing.Size(124, 22);
this.healthLabel.TabIndex = 11;
this.healthLabel.Text = "Health";
this.healthLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// manaLabel
//
this.manaLabel.CausesValidation = false;
this.manaLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F);
this.manaLabel.Location = new System.Drawing.Point(15, 191);
this.manaLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.manaLabel.Name = "manaLabel";
this.manaLabel.Size = new System.Drawing.Size(120, 22);
this.manaLabel.TabIndex = 13;
this.manaLabel.Text = "Mana";
this.manaLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// attribGroupBox
//
this.attribGroupBox.BackColor = System.Drawing.Color.Transparent;
this.attribGroupBox.Controls.Add(this.manacUpDown);
this.attribGroupBox.Controls.Add(this.healthUpDown);
this.attribGroupBox.Controls.Add(this.intelligenceUpDown);
this.attribGroupBox.Controls.Add(this.dexterityUpDown);
this.attribGroupBox.Controls.Add(this.strengthUpDown);
this.attribGroupBox.Controls.Add(this.manaLabel);
this.attribGroupBox.Controls.Add(this.healthLabel);
this.attribGroupBox.Controls.Add(this.IntelligenceLabel);
this.attribGroupBox.Controls.Add(this.dexterityLabel);
this.attribGroupBox.Controls.Add(this.strengthLabel);
this.attribGroupBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.attribGroupBox.ForeColor = System.Drawing.Color.Gold;
this.attribGroupBox.Location = new System.Drawing.Point(39, 35);
this.attribGroupBox.Margin = new System.Windows.Forms.Padding(4);
this.attribGroupBox.Name = "attribGroupBox";
this.attribGroupBox.Padding = new System.Windows.Forms.Padding(4);
this.attribGroupBox.Size = new System.Drawing.Size(339, 265);
this.attribGroupBox.TabIndex = 14;
this.attribGroupBox.TabStop = false;
this.attribGroupBox.Text = "Base Attributes";
//
// manacUpDown
//
this.manacUpDown.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.manacUpDown.Increment = new decimal(new int[] {
40,
0,
0,
0});
this.manacUpDown.Location = new System.Drawing.Point(142, 189);
this.manacUpDown.Margin = new System.Windows.Forms.Padding(4);
this.manacUpDown.Maximum = new decimal(new int[] {
9996,
0,
0,
0});
this.manacUpDown.Minimum = new decimal(new int[] {
300,
0,
0,
0});
this.manacUpDown.Name = "manacUpDown";
this.manacUpDown.ReadOnly = true;
this.manacUpDown.Size = new System.Drawing.Size(81, 28);
this.manacUpDown.TabIndex = 5;
this.manacUpDown.Value = new decimal(new int[] {
300,
0,
0,
0});
this.manacUpDown.ValueChanged += new System.EventHandler(this.StatsUpDown_ValueChanged);
//
// healthUpDown
//
this.healthUpDown.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.healthUpDown.Increment = new decimal(new int[] {
40,
0,
0,
0});
this.healthUpDown.Location = new System.Drawing.Point(142, 151);
this.healthUpDown.Margin = new System.Windows.Forms.Padding(4);
this.healthUpDown.Maximum = new decimal(new int[] {
9996,
0,
0,
0});
this.healthUpDown.Minimum = new decimal(new int[] {
300,
0,
0,
0});
this.healthUpDown.Name = "healthUpDown";
this.healthUpDown.ReadOnly = true;
this.healthUpDown.Size = new System.Drawing.Size(81, 28);
this.healthUpDown.TabIndex = 4;
this.healthUpDown.Value = new decimal(new int[] {
300,
0,
0,
0});
this.healthUpDown.ValueChanged += new System.EventHandler(this.StatsUpDown_ValueChanged);
//
// intelligenceUpDown
//
this.intelligenceUpDown.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.intelligenceUpDown.Increment = new decimal(new int[] {
4,
0,
0,
0});
this.intelligenceUpDown.Location = new System.Drawing.Point(142, 114);
this.intelligenceUpDown.Margin = new System.Windows.Forms.Padding(4);
this.intelligenceUpDown.Maximum = new decimal(new int[] {
996,
0,
0,
0});
this.intelligenceUpDown.Minimum = new decimal(new int[] {
50,
0,
0,
0});
this.intelligenceUpDown.Name = "intelligenceUpDown";
this.intelligenceUpDown.ReadOnly = true;
this.intelligenceUpDown.Size = new System.Drawing.Size(81, 28);
this.intelligenceUpDown.TabIndex = 3;
this.intelligenceUpDown.Value = new decimal(new int[] {
50,
0,
0,
0});
this.intelligenceUpDown.ValueChanged += new System.EventHandler(this.StatsUpDown_ValueChanged);
//
// dexterityUpDown
//
this.dexterityUpDown.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.dexterityUpDown.Increment = new decimal(new int[] {
4,
0,
0,
0});
this.dexterityUpDown.Location = new System.Drawing.Point(142, 76);
this.dexterityUpDown.Margin = new System.Windows.Forms.Padding(4);
this.dexterityUpDown.Maximum = new decimal(new int[] {
996,
0,
0,
0});
this.dexterityUpDown.Minimum = new decimal(new int[] {
50,
0,
0,
0});
this.dexterityUpDown.Name = "dexterityUpDown";
this.dexterityUpDown.ReadOnly = true;
this.dexterityUpDown.Size = new System.Drawing.Size(81, 28);
this.dexterityUpDown.TabIndex = 2;
this.dexterityUpDown.Value = new decimal(new int[] {
50,
0,
0,
0});
this.dexterityUpDown.ValueChanged += new System.EventHandler(this.StatsUpDown_ValueChanged);
//
// strengthUpDown
//
this.strengthUpDown.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.strengthUpDown.Increment = new decimal(new int[] {
4,
0,
0,
0});
this.strengthUpDown.Location = new System.Drawing.Point(142, 39);
this.strengthUpDown.Margin = new System.Windows.Forms.Padding(4);
this.strengthUpDown.Maximum = new decimal(new int[] {
996,
0,
0,
0});
this.strengthUpDown.Minimum = new decimal(new int[] {
50,
0,
0,
0});
this.strengthUpDown.Name = "strengthUpDown";
this.strengthUpDown.ReadOnly = true;
this.strengthUpDown.Size = new System.Drawing.Size(81, 28);
this.strengthUpDown.TabIndex = 1;
this.strengthUpDown.Value = new decimal(new int[] {
50,
0,
0,
0});
this.strengthUpDown.ValueChanged += new System.EventHandler(this.StatsUpDown_ValueChanged);
//
// levelingGroupBox
//
this.levelingGroupBox.BackColor = System.Drawing.Color.Transparent;
this.levelingGroupBox.Controls.Add(this.levelingCheckBox);
this.levelingGroupBox.Controls.Add(this.difficultyLabel);
this.levelingGroupBox.Controls.Add(this.difficultlyComboBox);
this.levelingGroupBox.Controls.Add(this.skillPointsNumericUpDown);
this.levelingGroupBox.Controls.Add(this.skillPointsLabel);
this.levelingGroupBox.Controls.Add(this.attributeNumericUpDown);
this.levelingGroupBox.Controls.Add(this.attributeLabel);
this.levelingGroupBox.Controls.Add(this.xpTextBox);
this.levelingGroupBox.Controls.Add(this.xpLabel);
this.levelingGroupBox.Controls.Add(this.levelNumericUpDown);
this.levelingGroupBox.Controls.Add(this.levelLabel);
this.levelingGroupBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.levelingGroupBox.ForeColor = System.Drawing.Color.Gold;
this.levelingGroupBox.Location = new System.Drawing.Point(411, 35);
this.levelingGroupBox.Margin = new System.Windows.Forms.Padding(4);
this.levelingGroupBox.Name = "levelingGroupBox";
this.levelingGroupBox.Padding = new System.Windows.Forms.Padding(4);
this.levelingGroupBox.Size = new System.Drawing.Size(482, 265);
this.levelingGroupBox.TabIndex = 15;
this.levelingGroupBox.TabStop = false;
this.levelingGroupBox.Text = "Leveling";
//
// levelingCheckBox
//
this.levelingCheckBox.AutoSize = true;
this.levelingCheckBox.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this.levelingCheckBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F);
this.levelingCheckBox.Location = new System.Drawing.Point(86, 224);
this.levelingCheckBox.Margin = new System.Windows.Forms.Padding(4);
this.levelingCheckBox.Name = "levelingCheckBox";
this.levelingCheckBox.Size = new System.Drawing.Size(168, 28);
this.levelingCheckBox.TabIndex = 12;
this.levelingCheckBox.Text = "Enable Leveling";
this.levelingCheckBox.UseVisualStyleBackColor = true;
this.levelingCheckBox.CheckedChanged += new System.EventHandler(this.LevelingCheckBox_CheckedChanged);
//
// difficultyLabel
//
this.difficultyLabel.BackColor = System.Drawing.Color.Transparent;
this.difficultyLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F);
this.difficultyLabel.Location = new System.Drawing.Point(19, 188);
this.difficultyLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.difficultyLabel.Name = "difficultyLabel";
this.difficultyLabel.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.difficultyLabel.Size = new System.Drawing.Size(204, 22);
this.difficultyLabel.TabIndex = 15;
this.difficultyLabel.Text = "Difficultly";
this.difficultyLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// difficultlyComboBox
//
this.difficultlyComboBox.Enabled = false;
this.difficultlyComboBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.difficultlyComboBox.FormattingEnabled = true;
this.difficultlyComboBox.Location = new System.Drawing.Point(230, 184);
this.difficultlyComboBox.Margin = new System.Windows.Forms.Padding(4);
this.difficultlyComboBox.Name = "difficultlyComboBox";
this.difficultlyComboBox.Size = new System.Drawing.Size(199, 30);
this.difficultlyComboBox.TabIndex = 11;
//
// skillPointsNumericUpDown
//
this.skillPointsNumericUpDown.Enabled = false;
this.skillPointsNumericUpDown.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.skillPointsNumericUpDown.Location = new System.Drawing.Point(230, 146);
this.skillPointsNumericUpDown.Margin = new System.Windows.Forms.Padding(4);
this.skillPointsNumericUpDown.Maximum = new decimal(new int[] {
286,
0,
0,
0});
this.skillPointsNumericUpDown.Name = "skillPointsNumericUpDown";
this.skillPointsNumericUpDown.ReadOnly = true;
this.skillPointsNumericUpDown.Size = new System.Drawing.Size(200, 28);
this.skillPointsNumericUpDown.TabIndex = 10;
//
// skillPointsLabel
//
this.skillPointsLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F);
this.skillPointsLabel.Location = new System.Drawing.Point(19, 149);
this.skillPointsLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.skillPointsLabel.Name = "skillPointsLabel";
this.skillPointsLabel.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.skillPointsLabel.Size = new System.Drawing.Size(208, 22);
this.skillPointsLabel.TabIndex = 12;
this.skillPointsLabel.Text = "Skill Points";
this.skillPointsLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// attributeNumericUpDown
//
this.attributeNumericUpDown.Enabled = false;
this.attributeNumericUpDown.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.attributeNumericUpDown.Location = new System.Drawing.Point(230, 109);
this.attributeNumericUpDown.Margin = new System.Windows.Forms.Padding(4);
this.attributeNumericUpDown.Maximum = new decimal(new int[] {
186,
0,
0,
0});
this.attributeNumericUpDown.Name = "attributeNumericUpDown";
this.attributeNumericUpDown.ReadOnly = true;
this.attributeNumericUpDown.Size = new System.Drawing.Size(200, 28);
this.attributeNumericUpDown.TabIndex = 9;
//
// attributeLabel
//
this.attributeLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F);
this.attributeLabel.Location = new System.Drawing.Point(19, 111);
this.attributeLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.attributeLabel.Name = "attributeLabel";
this.attributeLabel.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.attributeLabel.Size = new System.Drawing.Size(208, 22);
this.attributeLabel.TabIndex = 10;
this.attributeLabel.Text = "Attribute Points";
this.attributeLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// xpTextBox
//
this.xpTextBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.xpTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.xpTextBox.Location = new System.Drawing.Point(230, 71);
this.xpTextBox.Margin = new System.Windows.Forms.Padding(4);
this.xpTextBox.Name = "xpTextBox";
this.xpTextBox.ReadOnly = true;
this.xpTextBox.Size = new System.Drawing.Size(200, 28);
this.xpTextBox.TabIndex = 8;
this.xpTextBox.WordWrap = false;
//
// xpLabel
//
this.xpLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F);
this.xpLabel.Location = new System.Drawing.Point(19, 74);
this.xpLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.xpLabel.Name = "xpLabel";
this.xpLabel.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.xpLabel.Size = new System.Drawing.Size(208, 22);
this.xpLabel.TabIndex = 8;
this.xpLabel.Text = "XP";
this.xpLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// levelNumericUpDown
//
this.levelNumericUpDown.Enabled = false;
this.levelNumericUpDown.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.levelNumericUpDown.Location = new System.Drawing.Point(230, 34);
this.levelNumericUpDown.Margin = new System.Windows.Forms.Padding(4);
this.levelNumericUpDown.Maximum = new decimal(new int[] {
84,
0,
0,
0});
this.levelNumericUpDown.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.levelNumericUpDown.Name = "levelNumericUpDown";
this.levelNumericUpDown.ReadOnly = true;
this.levelNumericUpDown.Size = new System.Drawing.Size(70, 28);
this.levelNumericUpDown.TabIndex = 7;
this.levelNumericUpDown.Value = new decimal(new int[] {
1,
0,
0,
0});
this.levelNumericUpDown.ValueChanged += new System.EventHandler(this.LevelNumericUpDown_ValueChanged);
//
// levelLabel
//
this.levelLabel.BackColor = System.Drawing.Color.Transparent;
this.levelLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F);
this.levelLabel.Location = new System.Drawing.Point(19, 36);
this.levelLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.levelLabel.Name = "levelLabel";
this.levelLabel.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.levelLabel.Size = new System.Drawing.Size(208, 22);
this.levelLabel.TabIndex = 6;
this.levelLabel.Text = "Level";
this.levelLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// ResetMasteriesScalingButton
//
this.ResetMasteriesScalingButton.BackColor = System.Drawing.Color.Transparent;
this.ResetMasteriesScalingButton.DownBitmap = ((System.Drawing.Bitmap)(resources.GetObject("ResetMasteriesScalingButton.DownBitmap")));
this.ResetMasteriesScalingButton.FlatAppearance.BorderSize = 0;
this.ResetMasteriesScalingButton.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.ResetMasteriesScalingButton.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.ResetMasteriesScalingButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.ResetMasteriesScalingButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F);
this.ResetMasteriesScalingButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.ResetMasteriesScalingButton.Image = ((System.Drawing.Image)(resources.GetObject("ResetMasteriesScalingButton.Image")));
this.ResetMasteriesScalingButton.Location = new System.Drawing.Point(39, 438);
this.ResetMasteriesScalingButton.Margin = new System.Windows.Forms.Padding(4);
this.ResetMasteriesScalingButton.Name = "ResetMasteriesScalingButton";
this.ResetMasteriesScalingButton.OverBitmap = ((System.Drawing.Bitmap)(resources.GetObject("ResetMasteriesScalingButton.OverBitmap")));
this.ResetMasteriesScalingButton.Size = new System.Drawing.Size(171, 38);
this.ResetMasteriesScalingButton.SizeToGraphic = false;
this.ResetMasteriesScalingButton.TabIndex = 16;
this.ResetMasteriesScalingButton.Text = "Reset Masteries";
this.ResetMasteriesScalingButton.UpBitmap = ((System.Drawing.Bitmap)(resources.GetObject("ResetMasteriesScalingButton.UpBitmap")));
this.ResetMasteriesScalingButton.UseCustomGraphic = true;
this.ResetMasteriesScalingButton.UseVisualStyleBackColor = false;
this.ResetMasteriesScalingButton.Click += new System.EventHandler(this.ResetMasteriesScalingButton_Click);
//
// MasteriesGroupBox
//
this.MasteriesGroupBox.BackColor = System.Drawing.Color.Transparent;
this.MasteriesGroupBox.Controls.Add(this.Mastery2ValueScalingLabel);
this.MasteriesGroupBox.Controls.Add(this.Mastery1ValueScalingLabel);
this.MasteriesGroupBox.Controls.Add(this.Mastery2NameScalingLabel);
this.MasteriesGroupBox.Controls.Add(this.Mastery1NameScalingLabel);
this.MasteriesGroupBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.MasteriesGroupBox.ForeColor = System.Drawing.Color.Gold;
this.MasteriesGroupBox.Location = new System.Drawing.Point(39, 308);
this.MasteriesGroupBox.Margin = new System.Windows.Forms.Padding(4);
this.MasteriesGroupBox.Name = "MasteriesGroupBox";
this.MasteriesGroupBox.Padding = new System.Windows.Forms.Padding(4);
this.MasteriesGroupBox.Size = new System.Drawing.Size(855, 110);
this.MasteriesGroupBox.TabIndex = 17;
this.MasteriesGroupBox.TabStop = false;
this.MasteriesGroupBox.Text = "Masteries";
//
// Mastery2ValueScalingLabel
//
this.Mastery2ValueScalingLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F);
this.Mastery2ValueScalingLabel.Location = new System.Drawing.Point(258, 69);
this.Mastery2ValueScalingLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.Mastery2ValueScalingLabel.Name = "Mastery2ValueScalingLabel";
this.Mastery2ValueScalingLabel.Size = new System.Drawing.Size(545, 22);
this.Mastery2ValueScalingLabel.TabIndex = 21;
this.Mastery2ValueScalingLabel.Tag = "{0} skills, {1} points";
this.Mastery2ValueScalingLabel.Text = "{0} skills, {1} points";
this.Mastery2ValueScalingLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// Mastery1ValueScalingLabel
//
this.Mastery1ValueScalingLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F);
this.Mastery1ValueScalingLabel.Location = new System.Drawing.Point(258, 31);
this.Mastery1ValueScalingLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.Mastery1ValueScalingLabel.Name = "Mastery1ValueScalingLabel";
this.Mastery1ValueScalingLabel.Size = new System.Drawing.Size(545, 22);
this.Mastery1ValueScalingLabel.TabIndex = 20;
this.Mastery1ValueScalingLabel.Tag = "{0} skills, {1} points";
this.Mastery1ValueScalingLabel.Text = "{0} skills, {1} points";
this.Mastery1ValueScalingLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// Mastery2NameScalingLabel
//
this.Mastery2NameScalingLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F);
this.Mastery2NameScalingLabel.Location = new System.Drawing.Point(8, 69);
this.Mastery2NameScalingLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.Mastery2NameScalingLabel.Name = "Mastery2NameScalingLabel";
this.Mastery2NameScalingLabel.Size = new System.Drawing.Size(242, 22);
this.Mastery2NameScalingLabel.TabIndex = 19;
this.Mastery2NameScalingLabel.Tag = "{0} :";
this.Mastery2NameScalingLabel.Text = "Defense :";
this.Mastery2NameScalingLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// Mastery1NameScalingLabel
//
this.Mastery1NameScalingLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F);
this.Mastery1NameScalingLabel.Location = new System.Drawing.Point(8, 31);
this.Mastery1NameScalingLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.Mastery1NameScalingLabel.Name = "Mastery1NameScalingLabel";
this.Mastery1NameScalingLabel.Size = new System.Drawing.Size(242, 22);
this.Mastery1NameScalingLabel.TabIndex = 7;
this.Mastery1NameScalingLabel.Tag = "{0} :";
this.Mastery1NameScalingLabel.Text = "Warfare :";
this.Mastery1NameScalingLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// ResetAttributesScalingButton
//
this.ResetAttributesScalingButton.BackColor = System.Drawing.Color.Transparent;
this.ResetAttributesScalingButton.DownBitmap = ((System.Drawing.Bitmap)(resources.GetObject("ResetAttributesScalingButton.DownBitmap")));
this.ResetAttributesScalingButton.FlatAppearance.BorderSize = 0;
this.ResetAttributesScalingButton.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.ResetAttributesScalingButton.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.ResetAttributesScalingButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.ResetAttributesScalingButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F);
this.ResetAttributesScalingButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.ResetAttributesScalingButton.Image = ((System.Drawing.Image)(resources.GetObject("ResetAttributesScalingButton.Image")));
this.ResetAttributesScalingButton.Location = new System.Drawing.Point(236, 438);
this.ResetAttributesScalingButton.Margin = new System.Windows.Forms.Padding(4);
this.ResetAttributesScalingButton.Name = "ResetAttributesScalingButton";
this.ResetAttributesScalingButton.OverBitmap = ((System.Drawing.Bitmap)(resources.GetObject("ResetAttributesScalingButton.OverBitmap")));
this.ResetAttributesScalingButton.Size = new System.Drawing.Size(171, 38);
this.ResetAttributesScalingButton.SizeToGraphic = false;
this.ResetAttributesScalingButton.TabIndex = 18;
this.ResetAttributesScalingButton.Text = "Reset Attributes";
this.ResetAttributesScalingButton.UpBitmap = ((System.Drawing.Bitmap)(resources.GetObject("ResetAttributesScalingButton.UpBitmap")));
this.ResetAttributesScalingButton.UseCustomGraphic = true;
this.ResetAttributesScalingButton.UseVisualStyleBackColor = false;
this.ResetAttributesScalingButton.Click += new System.EventHandler(this.ResetAttributesScalingButton_Click);
//
// CharacterEditDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(120F, 120F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(46)))), ((int)(((byte)(31)))), ((int)(((byte)(21)))));
this.ClientSize = new System.Drawing.Size(932, 504);
this.Controls.Add(this.ResetAttributesScalingButton);
this.Controls.Add(this.MasteriesGroupBox);
this.Controls.Add(this.ResetMasteriesScalingButton);
this.Controls.Add(this.levelingGroupBox);
this.Controls.Add(this.attribGroupBox);
this.Controls.Add(this.cancel);
this.Controls.Add(this.ok);
this.DrawCustomBorder = true;
this.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ForeColor = System.Drawing.Color.White;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Margin = new System.Windows.Forms.Padding(5);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "CharacterEditDialog";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Character Editor";
this.TopMost = true;
this.Load += new System.EventHandler(this.CharacterEditDlg_Load);
this.Controls.SetChildIndex(this.ok, 0);
this.Controls.SetChildIndex(this.cancel, 0);
this.Controls.SetChildIndex(this.attribGroupBox, 0);
this.Controls.SetChildIndex(this.levelingGroupBox, 0);
this.Controls.SetChildIndex(this.ResetMasteriesScalingButton, 0);
this.Controls.SetChildIndex(this.MasteriesGroupBox, 0);
this.Controls.SetChildIndex(this.ResetAttributesScalingButton, 0);
this.attribGroupBox.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.manacUpDown)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.healthUpDown)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.intelligenceUpDown)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dexterityUpDown)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.strengthUpDown)).EndInit();
this.levelingGroupBox.ResumeLayout(false);
this.levelingGroupBox.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.skillPointsNumericUpDown)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.attributeNumericUpDown)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.levelNumericUpDown)).EndInit();
this.MasteriesGroupBox.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private ScalingLabel strengthLabel;
private ScalingLabel dexterityLabel;
private ScalingLabel IntelligenceLabel;
private ScalingLabel healthLabel;
private ScalingLabel manaLabel;
private System.Windows.Forms.GroupBox attribGroupBox;
private System.Windows.Forms.NumericUpDown manacUpDown;
private System.Windows.Forms.NumericUpDown healthUpDown;
private System.Windows.Forms.NumericUpDown intelligenceUpDown;
private System.Windows.Forms.NumericUpDown dexterityUpDown;
private System.Windows.Forms.NumericUpDown strengthUpDown;
private System.Windows.Forms.GroupBox levelingGroupBox;
private System.Windows.Forms.TextBox xpTextBox;
private ScalingLabel xpLabel;
private System.Windows.Forms.NumericUpDown levelNumericUpDown;
private ScalingLabel levelLabel;
private System.Windows.Forms.NumericUpDown attributeNumericUpDown;
private ScalingLabel attributeLabel;
private System.Windows.Forms.NumericUpDown skillPointsNumericUpDown;
private ScalingLabel skillPointsLabel;
private ScalingLabel difficultyLabel;
private System.Windows.Forms.ComboBox difficultlyComboBox;
private ScalingCheckBox levelingCheckBox;
private ScalingButton ResetMasteriesScalingButton;
private System.Windows.Forms.GroupBox MasteriesGroupBox;
private ScalingLabel Mastery2ValueScalingLabel;
private ScalingLabel Mastery1ValueScalingLabel;
private ScalingLabel Mastery2NameScalingLabel;
private ScalingLabel Mastery1NameScalingLabel;
private ScalingButton ResetAttributesScalingButton;
}
}
| |
// ***********************************************************************
// Copyright (c) 2015 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
#if ASYNC
using System;
using System.Threading.Tasks;
using NUnit.Framework;
#if NET_4_0
using Task = System.Threading.Tasks.TaskEx;
#endif
namespace NUnit.TestData
{
public class AsyncRealFixture
{
[Test]
public async void AsyncVoid()
{
var result = await ReturnOne();
Assert.AreEqual(1, result);
}
#region async Task
[Test]
public async System.Threading.Tasks.Task AsyncTaskSuccess()
{
var result = await ReturnOne();
Assert.AreEqual(1, result);
}
[Test]
public async System.Threading.Tasks.Task AsyncTaskFailure()
{
var result = await ReturnOne();
Assert.AreEqual(2, result);
}
[Test]
public async System.Threading.Tasks.Task AsyncTaskError()
{
await ThrowException();
Assert.Fail("Should never get here");
}
[Test]
public async System.Threading.Tasks.Task ThrowAsyncOperationCanceledException()
{
await Task.Yield();
throw new OperationCanceledException();
}
#endregion
#region non-async Task
[Test]
public System.Threading.Tasks.Task TaskSuccess()
{
return Task.Run(() => Assert.AreEqual(1, 1));
}
[Test]
public System.Threading.Tasks.Task TaskFailure()
{
return Task.Run(() => Assert.AreEqual(1, 2));
}
[Test]
public System.Threading.Tasks.Task TaskError()
{
throw new InvalidOperationException();
}
#endregion
[Test]
public async Task<int> AsyncTaskResult()
{
return await ReturnOne();
}
[Test]
public Task<int> TaskResult()
{
return ReturnOne();
}
#region async Task<T>
[TestCase(ExpectedResult = 1)]
public async Task<int> AsyncTaskResultCheckSuccess()
{
return await ReturnOne();
}
[TestCase(ExpectedResult = 2)]
public async Task<int> AsyncTaskResultCheckFailure()
{
return await ReturnOne();
}
[TestCase(ExpectedResult = 0)]
public async Task<int> AsyncTaskResultCheckError()
{
return await ThrowException();
}
#endregion
#region non-async Task<T>
[TestCase(ExpectedResult = 1)]
public Task<int> TaskResultCheckSuccess()
{
return ReturnOne();
}
[TestCase(ExpectedResult = 2)]
public Task<int> TaskResultCheckFailure()
{
return ReturnOne();
}
[TestCase(ExpectedResult = 0)]
public Task<int> TaskResultCheckError()
{
return ThrowException();
}
#endregion
[TestCase(1, 2)]
public async System.Threading.Tasks.Task AsyncTaskTestCaseWithParametersSuccess(int a, int b)
{
Assert.AreEqual(await ReturnOne(), b - a);
}
[TestCase(ExpectedResult = null)]
public async Task<object> AsyncTaskResultCheckSuccessReturningNull()
{
return await Task.Run(() => (object)null);
}
[TestCase(ExpectedResult = null)]
public Task<object> TaskResultCheckSuccessReturningNull()
{
return Task.Run(() => (object)null);
}
[Test]
public async System.Threading.Tasks.Task NestedAsyncTaskSuccess()
{
var result = await Task.Run(async () => await ReturnOne());
Assert.AreEqual(1, result);
}
[Test]
public async System.Threading.Tasks.Task NestedAsyncTaskFailure()
{
var result = await Task.Run(async () => await ReturnOne());
Assert.AreEqual(2, result);
}
[Test]
public async System.Threading.Tasks.Task NestedAsyncTaskError()
{
await Task.Run(async () => await ThrowException());
Assert.Fail("Should never get here");
}
[Test]
public async System.Threading.Tasks.Task AsyncTaskMultipleSuccess()
{
var result = await ReturnOne();
Assert.AreEqual(await ReturnOne(), result);
}
[Test]
public async System.Threading.Tasks.Task AsyncTaskMultipleFailure()
{
var result = await ReturnOne();
Assert.AreEqual(await ReturnOne() + 1, result);
}
[Test]
public async System.Threading.Tasks.Task AsyncTaskMultipleError()
{
await ThrowException();
Assert.Fail("Should never get here");
}
[Test]
public async System.Threading.Tasks.Task TaskCheckTestContextAcrossTasks()
{
var testName = await GetTestNameFromContext();
Assert.IsNotNull(testName);
Assert.AreEqual(testName, TestContext.CurrentContext.Test.Name);
}
[Test]
public async System.Threading.Tasks.Task TaskCheckTestContextWithinTestBody()
{
var testName = TestContext.CurrentContext.Test.Name;
await ReturnOne();
Assert.IsNotNull(testName);
Assert.AreEqual(testName, TestContext.CurrentContext.Test.Name);
}
private static Task<string> GetTestNameFromContext()
{
return Task.Run(() => TestContext.CurrentContext.Test.Name);
}
private static Task<int> ReturnOne()
{
return Task.Run(() => 1);
}
private static Task<int> ThrowException()
{
Func<int> throws = () => { throw new InvalidOperationException(); };
return Task.Run( throws );
}
}
}
#endif
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input.Events;
using osu.Framework.Logging;
using osu.Framework.Screens;
using osu.Framework.Threading;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Input.Bindings;
using osu.Game.Overlays;
using osu.Game.Overlays.Mods;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Menu;
using osu.Game.Screens.Select.Options;
using osuTK;
using osuTK.Graphics;
using osuTK.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using osu.Framework.Audio.Track;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Bindings;
using osu.Game.Collections;
using osu.Game.Graphics.UserInterface;
using System.Diagnostics;
using osu.Game.Screens.Play;
using osu.Game.Database;
namespace osu.Game.Screens.Select
{
public abstract class SongSelect : ScreenWithBeatmapBackground, IKeyBindingHandler<GlobalAction>
{
public static readonly float WEDGE_HEIGHT = 245;
protected const float BACKGROUND_BLUR = 20;
private const float left_area_padding = 20;
public FilterControl FilterControl { get; private set; }
protected virtual bool ShowFooter => true;
protected virtual bool DisplayStableImportPrompt => legacyImportManager?.SupportsImportFromStable == true;
public override bool? AllowTrackAdjustments => true;
/// <summary>
/// Can be null if <see cref="ShowFooter"/> is false.
/// </summary>
protected BeatmapOptionsOverlay BeatmapOptions { get; private set; }
/// <summary>
/// Can be null if <see cref="ShowFooter"/> is false.
/// </summary>
protected Footer Footer { get; private set; }
/// <summary>
/// Contains any panel which is triggered by a footer button.
/// Helps keep them located beneath the footer itself.
/// </summary>
protected Container FooterPanels { get; private set; }
/// <summary>
/// Whether entering editor mode should be allowed.
/// </summary>
public virtual bool AllowEditing => true;
public bool BeatmapSetsLoaded => IsLoaded && Carousel?.BeatmapSetsLoaded == true;
[Resolved]
private Bindable<IReadOnlyList<Mod>> selectedMods { get; set; }
protected BeatmapCarousel Carousel { get; private set; }
protected Container LeftArea { get; private set; }
private BeatmapInfoWedge beatmapInfoWedge;
private DialogOverlay dialogOverlay;
[Resolved]
private BeatmapManager beatmaps { get; set; }
[Resolved(CanBeNull = true)]
private LegacyImportManager legacyImportManager { get; set; }
protected ModSelectOverlay ModSelect { get; private set; }
protected Sample SampleConfirm { get; private set; }
private Sample sampleChangeDifficulty;
private Sample sampleChangeBeatmap;
private Container carouselContainer;
protected BeatmapDetailArea BeatmapDetails { get; private set; }
private readonly Bindable<RulesetInfo> decoupledRuleset = new Bindable<RulesetInfo>();
private double audioFeedbackLastPlaybackTime;
[Resolved]
private MusicController music { get; set; }
[BackgroundDependencyLoader(true)]
private void load(AudioManager audio, DialogOverlay dialog, OsuColour colours, ManageCollectionsDialog manageCollectionsDialog, DifficultyRecommender recommender)
{
// initial value transfer is required for FilterControl (it uses our re-cached bindables in its async load for the initial filter).
transferRulesetValue();
LoadComponentAsync(Carousel = new BeatmapCarousel
{
AllowSelection = false, // delay any selection until our bindables are ready to make a good choice.
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight,
RelativeSizeAxes = Axes.Both,
BleedTop = FilterControl.HEIGHT,
BleedBottom = Footer.HEIGHT,
SelectionChanged = updateSelectedBeatmap,
BeatmapSetsChanged = carouselBeatmapsLoaded,
GetRecommendedBeatmap = s => recommender?.GetRecommendedBeatmap(s),
}, c => carouselContainer.Child = c);
AddRangeInternal(new Drawable[]
{
new ResetScrollContainer(() => Carousel.ScrollToSelected())
{
RelativeSizeAxes = Axes.Y,
Width = 250,
},
new VerticalMaskingContainer
{
Children = new Drawable[]
{
new GridContainer // used for max width implementation
{
RelativeSizeAxes = Axes.Both,
ColumnDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.Relative, 0.5f, maxSize: 850),
},
Content = new[]
{
new Drawable[]
{
new ParallaxContainer
{
ParallaxAmount = 0.005f,
RelativeSizeAxes = Axes.Both,
Child = new WedgeBackground
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Right = -150 },
},
},
carouselContainer = new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding
{
Top = FilterControl.HEIGHT,
Bottom = Footer.HEIGHT
},
Child = new LoadingSpinner(true) { State = { Value = Visibility.Visible } }
}
},
}
},
FilterControl = new FilterControl
{
RelativeSizeAxes = Axes.X,
Height = FilterControl.HEIGHT,
FilterChanged = ApplyFilterToCarousel,
},
new GridContainer // used for max width implementation
{
RelativeSizeAxes = Axes.Both,
ColumnDimensions = new[]
{
new Dimension(GridSizeMode.Relative, 0.5f, maxSize: 650),
},
Content = new[]
{
new Drawable[]
{
LeftArea = new Container
{
Origin = Anchor.BottomLeft,
Anchor = Anchor.BottomLeft,
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Top = left_area_padding },
Children = new Drawable[]
{
beatmapInfoWedge = new BeatmapInfoWedge
{
Height = WEDGE_HEIGHT,
RelativeSizeAxes = Axes.X,
Margin = new MarginPadding
{
Right = left_area_padding,
Left = -BeatmapInfoWedge.BORDER_THICKNESS, // Hide the left border
},
},
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding
{
Bottom = Footer.HEIGHT,
Top = WEDGE_HEIGHT,
Left = left_area_padding,
Right = left_area_padding * 2,
},
Child = BeatmapDetails = CreateBeatmapDetailArea().With(d =>
{
d.RelativeSizeAxes = Axes.Both;
d.Padding = new MarginPadding { Top = 10, Right = 5 };
})
},
}
},
},
}
}
}
},
});
if (ShowFooter)
{
AddRangeInternal(new Drawable[]
{
new GridContainer // used for max height implementation
{
RelativeSizeAxes = Axes.Both,
RowDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.Relative, 1f, maxSize: ModSelectOverlay.HEIGHT + Footer.HEIGHT),
},
Content = new[]
{
null,
new Drawable[]
{
FooterPanels = new Container
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Bottom = Footer.HEIGHT },
Children = new Drawable[]
{
BeatmapOptions = new BeatmapOptionsOverlay(),
ModSelect = CreateModSelectOverlay()
}
}
}
}
},
Footer = new Footer()
});
}
if (Footer != null)
{
foreach (var (button, overlay) in CreateFooterButtons())
Footer.AddButton(button, overlay);
BeatmapOptions.AddButton(@"Manage", @"collections", FontAwesome.Solid.Book, colours.Green, () => manageCollectionsDialog?.Show());
BeatmapOptions.AddButton(@"Delete", @"all difficulties", FontAwesome.Solid.Trash, colours.Pink, () => delete(Beatmap.Value.BeatmapSetInfo));
BeatmapOptions.AddButton(@"Remove", @"from unplayed", FontAwesome.Regular.TimesCircle, colours.Purple, null);
BeatmapOptions.AddButton(@"Clear", @"local scores", FontAwesome.Solid.Eraser, colours.Purple, () => clearScores(Beatmap.Value.BeatmapInfo));
}
dialogOverlay = dialog;
sampleChangeDifficulty = audio.Samples.Get(@"SongSelect/select-difficulty");
sampleChangeBeatmap = audio.Samples.Get(@"SongSelect/select-expand");
SampleConfirm = audio.Samples.Get(@"SongSelect/confirm-selection");
if (dialogOverlay != null)
{
Schedule(() =>
{
// if we have no beatmaps, let's prompt the user to import from over a stable install if he has one.
if (beatmaps.QueryBeatmapSet(s => !s.Protected && !s.DeletePending) == null && DisplayStableImportPrompt)
{
dialogOverlay.Push(new ImportFromStablePopup(() =>
{
Task.Run(() => legacyImportManager.ImportFromStableAsync(StableContent.All));
}));
}
});
}
}
/// <summary>
/// Creates the buttons to be displayed in the footer.
/// </summary>
/// <returns>A set of <see cref="FooterButton"/> and an optional <see cref="OverlayContainer"/> which the button opens when pressed.</returns>
protected virtual IEnumerable<(FooterButton, OverlayContainer)> CreateFooterButtons() => new (FooterButton, OverlayContainer)[]
{
(new FooterButtonMods { Current = Mods }, ModSelect),
(new FooterButtonRandom
{
NextRandom = () => Carousel.SelectNextRandom(),
PreviousRandom = Carousel.SelectPreviousRandom
}, null),
(new FooterButtonOptions(), BeatmapOptions)
};
protected virtual ModSelectOverlay CreateModSelectOverlay() => new UserModSelectOverlay();
protected virtual void ApplyFilterToCarousel(FilterCriteria criteria)
{
// if not the current screen, we want to get carousel in a good presentation state before displaying (resume or enter).
bool shouldDebounce = this.IsCurrentScreen();
Carousel.Filter(criteria, shouldDebounce);
}
private DependencyContainer dependencies;
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
{
dependencies = new DependencyContainer(base.CreateChildDependencies(parent));
dependencies.CacheAs(this);
dependencies.CacheAs(decoupledRuleset);
dependencies.CacheAs<IBindable<RulesetInfo>>(decoupledRuleset);
return dependencies;
}
/// <summary>
/// Creates the beatmap details to be displayed underneath the wedge.
/// </summary>
protected abstract BeatmapDetailArea CreateBeatmapDetailArea();
public void Edit(BeatmapInfo beatmapInfo = null)
{
if (!AllowEditing)
throw new InvalidOperationException($"Attempted to edit when {nameof(AllowEditing)} is disabled");
Beatmap.Value = beatmaps.GetWorkingBeatmap(beatmapInfo ?? beatmapInfoNoDebounce);
this.Push(new EditorLoader());
}
/// <summary>
/// Call to make a selection and perform the default action for this SongSelect.
/// </summary>
/// <param name="beatmapInfo">An optional beatmap to override the current carousel selection.</param>
/// <param name="ruleset">An optional ruleset to override the current carousel selection.</param>
/// <param name="customStartAction">An optional custom action to perform instead of <see cref="OnStart"/>.</param>
public void FinaliseSelection(BeatmapInfo beatmapInfo = null, RulesetInfo ruleset = null, Action customStartAction = null)
{
// This is very important as we have not yet bound to screen-level bindables before the carousel load is completed.
if (!Carousel.BeatmapSetsLoaded)
return;
if (ruleset != null)
Ruleset.Value = ruleset;
transferRulesetValue();
// while transferRulesetValue will flush, it only does so if the ruleset changes.
// the user could have changed a filter, and we want to ensure we are 100% up-to-date and consistent here.
Carousel.FlushPendingFilterOperations();
// avoid attempting to continue before a selection has been obtained.
// this could happen via a user interaction while the carousel is still in a loading state.
if (Carousel.SelectedBeatmapInfo == null) return;
if (beatmapInfo != null)
Carousel.SelectBeatmap(beatmapInfo);
if (selectionChangedDebounce?.Completed == false)
{
selectionChangedDebounce.RunTask();
selectionChangedDebounce?.Cancel(); // cancel the already scheduled task.
selectionChangedDebounce = null;
}
if (customStartAction != null)
{
customStartAction();
Carousel.AllowSelection = false;
}
else if (OnStart())
Carousel.AllowSelection = false;
}
/// <summary>
/// Called when a selection is made.
/// </summary>
/// <returns>If a resultant action occurred that takes the user away from SongSelect.</returns>
protected abstract bool OnStart();
private ScheduledDelegate selectionChangedDebounce;
private void workingBeatmapChanged(ValueChangedEvent<WorkingBeatmap> e)
{
if (e.NewValue is DummyWorkingBeatmap || !this.IsCurrentScreen()) return;
Logger.Log($"Song select working beatmap updated to {e.NewValue}");
if (!Carousel.SelectBeatmap(e.NewValue.BeatmapInfo, false))
{
// A selection may not have been possible with filters applied.
// There was possibly a ruleset mismatch. This is a case we can help things along by updating the game-wide ruleset to match.
if (!e.NewValue.BeatmapInfo.Ruleset.Equals(decoupledRuleset.Value))
{
Ruleset.Value = e.NewValue.BeatmapInfo.Ruleset;
transferRulesetValue();
}
// Even if a ruleset mismatch was not the cause (ie. a text filter is applied),
// we still want to temporarily show the new beatmap, bypassing filters.
// This will be undone the next time the user changes the filter.
var criteria = FilterControl.CreateCriteria();
criteria.SelectedBeatmapSet = e.NewValue.BeatmapInfo.BeatmapSet;
Carousel.Filter(criteria);
Carousel.SelectBeatmap(e.NewValue.BeatmapInfo);
}
}
// We need to keep track of the last selected beatmap ignoring debounce to play the correct selection sounds.
private BeatmapInfo beatmapInfoPrevious;
private BeatmapInfo beatmapInfoNoDebounce;
private RulesetInfo rulesetNoDebounce;
private void updateSelectedBeatmap(BeatmapInfo beatmapInfo)
{
if (beatmapInfo == null && beatmapInfoNoDebounce == null)
return;
if (beatmapInfo?.Equals(beatmapInfoNoDebounce) == true)
return;
beatmapInfoNoDebounce = beatmapInfo;
performUpdateSelected();
}
private void updateSelectedRuleset(RulesetInfo ruleset)
{
if (ruleset == null && rulesetNoDebounce == null)
return;
if (ruleset?.Equals(rulesetNoDebounce) == true)
return;
rulesetNoDebounce = ruleset;
performUpdateSelected();
}
/// <summary>
/// Selection has been changed as the result of a user interaction.
/// </summary>
private void performUpdateSelected()
{
var beatmap = beatmapInfoNoDebounce;
var ruleset = rulesetNoDebounce;
selectionChangedDebounce?.Cancel();
if (beatmapInfoNoDebounce == null)
run();
else
selectionChangedDebounce = Scheduler.AddDelayed(run, 200);
if (beatmap?.Equals(beatmapInfoPrevious) != true)
{
if (beatmap != null && beatmapInfoPrevious != null && Time.Current - audioFeedbackLastPlaybackTime >= 50)
{
if (beatmap.BeatmapSet?.ID == beatmapInfoPrevious.BeatmapSet?.ID)
sampleChangeDifficulty.Play();
else
sampleChangeBeatmap.Play();
audioFeedbackLastPlaybackTime = Time.Current;
}
beatmapInfoPrevious = beatmap;
}
void run()
{
// clear pending task immediately to track any potential nested debounce operation.
selectionChangedDebounce = null;
Logger.Log($"updating selection with beatmap:{beatmap?.ID.ToString() ?? "null"} ruleset:{ruleset?.ShortName ?? "null"}");
if (transferRulesetValue())
{
Mods.Value = Array.Empty<Mod>();
// transferRulesetValue() may trigger a re-filter. If the current selection does not match the new ruleset, we want to switch away from it.
// The default logic on WorkingBeatmap change is to switch to a matching ruleset (see workingBeatmapChanged()), but we don't want that here.
// We perform an early selection attempt and clear out the beatmap selection to avoid a second ruleset change (revert).
if (beatmap != null && !Carousel.SelectBeatmap(beatmap, false))
beatmap = null;
}
if (selectionChangedDebounce != null)
{
// a new nested operation was started; switch to it for further selection.
// this avoids having two separate debounces trigger from the same source.
selectionChangedDebounce.RunTask();
return;
}
// We may be arriving here due to another component changing the bindable Beatmap.
// In these cases, the other component has already loaded the beatmap, so we don't need to do so again.
if (!EqualityComparer<BeatmapInfo>.Default.Equals(beatmap, Beatmap.Value.BeatmapInfo))
{
Logger.Log($"beatmap changed from \"{Beatmap.Value.BeatmapInfo}\" to \"{beatmap}\"");
Beatmap.Value = beatmaps.GetWorkingBeatmap(beatmap);
}
if (this.IsCurrentScreen())
ensurePlayingSelected();
updateComponentFromBeatmap(Beatmap.Value);
}
}
public override void OnEntering(IScreen last)
{
base.OnEntering(last);
this.FadeInFromZero(250);
FilterControl.Activate();
ModSelect.SelectedMods.BindTo(selectedMods);
beginLooping();
}
private const double logo_transition = 250;
protected override void LogoArriving(OsuLogo logo, bool resuming)
{
base.LogoArriving(logo, resuming);
Vector2 position = new Vector2(0.95f, 0.96f);
if (logo.Alpha > 0.8f)
{
logo.MoveTo(position, 500, Easing.OutQuint);
}
else
{
logo.Hide();
logo.ScaleTo(0.2f);
logo.MoveTo(position);
}
logo.FadeIn(logo_transition, Easing.OutQuint);
logo.ScaleTo(0.4f, logo_transition, Easing.OutQuint);
logo.Action = () =>
{
FinaliseSelection();
return false;
};
}
protected override void LogoExiting(OsuLogo logo)
{
base.LogoExiting(logo);
logo.ScaleTo(0.2f, logo_transition / 2, Easing.Out);
logo.FadeOut(logo_transition / 2, Easing.Out);
}
public override void OnResuming(IScreen last)
{
base.OnResuming(last);
// required due to https://github.com/ppy/osu-framework/issues/3218
ModSelect.SelectedMods.Disabled = false;
ModSelect.SelectedMods.BindTo(selectedMods);
Carousel.AllowSelection = true;
BeatmapDetails.Refresh();
beginLooping();
music.ResetTrackAdjustments();
if (Beatmap != null && !Beatmap.Value.BeatmapSetInfo.DeletePending)
{
updateComponentFromBeatmap(Beatmap.Value);
// restart playback on returning to song select, regardless.
// not sure this should be a permanent thing (we may want to leave a user pause paused even on returning)
music.Play(requestedByUser: true);
}
this.FadeIn(250);
this.ScaleTo(1, 250, Easing.OutSine);
FilterControl.Activate();
}
public override void OnSuspending(IScreen next)
{
// Handle the case where FinaliseSelection is never called (ie. when a screen is pushed externally).
// Without this, it's possible for a transfer to happen while we are not the current screen.
transferRulesetValue();
ModSelect.SelectedMods.UnbindFrom(selectedMods);
ModSelect.Hide();
BeatmapOptions.Hide();
endLooping();
this.ScaleTo(1.1f, 250, Easing.InSine);
this.FadeOut(250);
FilterControl.Deactivate();
base.OnSuspending(next);
}
public override bool OnExiting(IScreen next)
{
if (base.OnExiting(next))
return true;
beatmapInfoWedge.Hide();
this.FadeOut(100);
FilterControl.Deactivate();
endLooping();
return false;
}
private bool isHandlingLooping;
private void beginLooping()
{
Debug.Assert(!isHandlingLooping);
isHandlingLooping = true;
ensureTrackLooping(Beatmap.Value, TrackChangeDirection.None);
music.TrackChanged += ensureTrackLooping;
}
private void endLooping()
{
// may be called multiple times during screen exit process.
if (!isHandlingLooping)
return;
music.CurrentTrack.Looping = isHandlingLooping = false;
music.TrackChanged -= ensureTrackLooping;
}
private void ensureTrackLooping(IWorkingBeatmap beatmap, TrackChangeDirection changeDirection)
=> beatmap.PrepareTrackForPreviewLooping();
public override bool OnBackButton()
{
if (ModSelect.State.Value == Visibility.Visible)
{
ModSelect.Hide();
return true;
}
return false;
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
decoupledRuleset.UnbindAll();
if (music != null)
music.TrackChanged -= ensureTrackLooping;
}
/// <summary>
/// Allow components in SongSelect to update their loaded beatmap details.
/// This is a debounced call (unlike directly binding to WorkingBeatmap.ValueChanged).
/// </summary>
/// <param name="beatmap">The working beatmap.</param>
private void updateComponentFromBeatmap(WorkingBeatmap beatmap)
{
ApplyToBackground(backgroundModeBeatmap =>
{
backgroundModeBeatmap.Beatmap = beatmap;
backgroundModeBeatmap.BlurAmount.Value = BACKGROUND_BLUR;
backgroundModeBeatmap.FadeColour(Color4.White, 250);
});
beatmapInfoWedge.Beatmap = beatmap;
BeatmapDetails.Beatmap = beatmap;
}
private readonly WeakReference<ITrack> lastTrack = new WeakReference<ITrack>(null);
/// <summary>
/// Ensures some music is playing for the current track.
/// Will resume playback from a manual user pause if the track has changed.
/// </summary>
private void ensurePlayingSelected()
{
ITrack track = music.CurrentTrack;
bool isNewTrack = !lastTrack.TryGetTarget(out var last) || last != track;
if (!track.IsRunning && (music.UserPauseRequested != true || isNewTrack))
music.Play(true);
lastTrack.SetTarget(track);
}
private void carouselBeatmapsLoaded()
{
bindBindables();
Carousel.AllowSelection = true;
// If a selection was already obtained, do not attempt to update the selected beatmap.
if (Carousel.SelectedBeatmapSet != null)
return;
// Attempt to select the current beatmap on the carousel, if it is valid to be selected.
if (!Beatmap.IsDefault && Beatmap.Value.BeatmapSetInfo?.DeletePending == false && Beatmap.Value.BeatmapSetInfo?.Protected == false)
{
if (Carousel.SelectBeatmap(Beatmap.Value.BeatmapInfo, false))
return;
// prefer not changing ruleset at this point, so look for another difficulty in the currently playing beatmap
var found = Beatmap.Value.BeatmapSetInfo.Beatmaps.FirstOrDefault(b => b.Ruleset.Equals(decoupledRuleset.Value));
if (found != null && Carousel.SelectBeatmap(found, false))
return;
}
// If the current active beatmap could not be selected, select a new random beatmap.
if (!Carousel.SelectNextRandom())
{
// in the case random selection failed, we want to trigger selectionChanged
// to show the dummy beatmap (we have nothing else to display).
performUpdateSelected();
}
}
private bool boundLocalBindables;
private void bindBindables()
{
if (boundLocalBindables)
return;
// manual binding to parent ruleset to allow for delayed load in the incoming direction.
transferRulesetValue();
Ruleset.ValueChanged += r => updateSelectedRuleset(r.NewValue);
decoupledRuleset.ValueChanged += r => Ruleset.Value = r.NewValue;
decoupledRuleset.DisabledChanged += r => Ruleset.Disabled = r;
Beatmap.BindValueChanged(workingBeatmapChanged);
boundLocalBindables = true;
}
/// <summary>
/// Transfer the game-wide ruleset to the local decoupled ruleset.
/// Will immediately run filter operations if required.
/// </summary>
/// <returns>Whether a transfer occurred.</returns>
private bool transferRulesetValue()
{
if (decoupledRuleset.Value?.Equals(Ruleset.Value) == true)
return false;
Logger.Log($"decoupled ruleset transferred (\"{decoupledRuleset.Value}\" -> \"{Ruleset.Value}\")");
rulesetNoDebounce = decoupledRuleset.Value = Ruleset.Value;
// if we have a pending filter operation, we want to run it now.
// it could change selection (ie. if the ruleset has been changed).
Carousel?.FlushPendingFilterOperations();
return true;
}
private void delete(BeatmapSetInfo beatmap)
{
if (beatmap == null) return;
dialogOverlay?.Push(new BeatmapDeleteDialog(beatmap));
}
private void clearScores(BeatmapInfo beatmapInfo)
{
if (beatmapInfo == null) return;
dialogOverlay?.Push(new BeatmapClearScoresDialog(beatmapInfo, () =>
// schedule done here rather than inside the dialog as the dialog may fade out and never callback.
Schedule(() => BeatmapDetails.Refresh())));
}
public virtual bool OnPressed(KeyBindingPressEvent<GlobalAction> e)
{
if (e.Repeat)
return false;
if (!this.IsCurrentScreen()) return false;
switch (e.Action)
{
case GlobalAction.Select:
FinaliseSelection();
return true;
}
return false;
}
public void OnReleased(KeyBindingReleaseEvent<GlobalAction> e)
{
}
protected override bool OnKeyDown(KeyDownEvent e)
{
if (e.Repeat) return false;
switch (e.Key)
{
case Key.Delete:
if (e.ShiftPressed)
{
if (!Beatmap.IsDefault)
delete(Beatmap.Value.BeatmapSetInfo);
return true;
}
break;
}
return base.OnKeyDown(e);
}
private class VerticalMaskingContainer : Container
{
private const float panel_overflow = 1.2f;
protected override Container<Drawable> Content { get; }
public VerticalMaskingContainer()
{
RelativeSizeAxes = Axes.Both;
Masking = true;
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
Width = panel_overflow; // avoid horizontal masking so the panels don't clip when screen stack is pushed.
InternalChild = Content = new Container
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Width = 1 / panel_overflow,
};
}
}
private class ResetScrollContainer : Container
{
private readonly Action onHoverAction;
public ResetScrollContainer(Action onHoverAction)
{
this.onHoverAction = onHoverAction;
}
protected override bool OnHover(HoverEvent e)
{
onHoverAction?.Invoke();
return base.OnHover(e);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Threading;
namespace System.Data.SqlClient
{
// This is a singleton instance per AppDomain that acts as the notification dispatcher for
// that AppDomain. It receives calls from the SqlDependencyProcessDispatcher with an ID or a server name
// to invalidate matching dependencies in the given AppDomain.
internal partial class SqlDependencyPerAppDomainDispatcher : MarshalByRefObject
{
// Instance members
internal static readonly SqlDependencyPerAppDomainDispatcher
SingletonInstance = new SqlDependencyPerAppDomainDispatcher(); // singleton object
internal object _instanceLock = new object();
// Dependency ID -> Dependency hashtable. 1 -> 1 mapping.
// 1) Used for ASP.NET to map from ID to dependency.
// 2) Used to enumerate dependencies to invalidate based on server.
private readonly Dictionary<string, SqlDependency> _dependencyIdToDependencyHash;
// holds dependencies list per notification and the command hash from which this notification was generated
// command hash is needed to remove its entry from _commandHashToNotificationId when the notification is removed
private sealed class DependencyList : List<SqlDependency>
{
public readonly string CommandHash;
internal DependencyList(string commandHash)
{
CommandHash = commandHash;
}
}
// notificationId -> Dependencies hashtable: 1 -> N mapping. notificationId == appDomainKey + commandHash.
// More than one dependency can be using the same command hash values resulting in a hash to the same value.
// We use this to cache mapping between command to dependencies such that we may reduce the notification
// resource effect on SQL Server. The Guid identifier is sent to the server during notification enlistment,
// and returned during the notification event. Dependencies look up existing Guids, if one exists, to ensure
// they are re-using notification ids.
private readonly Dictionary<string, DependencyList> _notificationIdToDependenciesHash;
// CommandHash value -> notificationId associated with it: 1->1 mapping. This map is used to quickly find if we need to create
// new notification or hookup into existing one.
// CommandHash is built from connection string, command text and parameters
private readonly Dictionary<string, string> _commandHashToNotificationId;
// TIMEOUT LOGIC DESCRIPTION
//
// Every time we add a dependency we compute the next, earlier timeout.
//
// We setup a timer to get a callback every 15 seconds. In the call back:
// - If there are no active dependencies, we just return.
// - If there are dependencies but none of them timed-out (compared to the "next timeout"),
// we just return.
// - Otherwise we Invalidate() those that timed-out.
//
// So the client-generated timeouts have a granularity of 15 seconds. This allows
// for a simple and low-resource-consumption implementation.
//
// LOCKS: don't update _nextTimeout outside of the _dependencyHash.SyncRoot lock.
private bool _sqlDependencyTimeOutTimerStarted = false;
// Next timeout for any of the dependencies in the dependency table.
private DateTime _nextTimeout;
// Timer to periodically check the dependencies in the table and see if anyone needs
// a timeout. We'll enable this only on demand.
private readonly Timer _timeoutTimer;
private SqlDependencyPerAppDomainDispatcher()
{
_dependencyIdToDependencyHash = new Dictionary<string, SqlDependency>();
_notificationIdToDependenciesHash = new Dictionary<string, DependencyList>();
_commandHashToNotificationId = new Dictionary<string, string>();
_timeoutTimer = ADP.UnsafeCreateTimer(
new TimerCallback(TimeoutTimerCallback),
null,
Timeout.Infinite,
Timeout.Infinite);
SubscribeToAppDomainUnload();
}
// When remoted across appdomains, MarshalByRefObject links by default time out if there is no activity
// within a few minutes. Add this override to prevent marshaled links from timing out.
public override object InitializeLifetimeService()
{
return null;
}
// Methods for dependency hash manipulation and firing.
// This method is called upon SqlDependency constructor.
internal void AddDependencyEntry(SqlDependency dep)
{
lock (_instanceLock)
{
_dependencyIdToDependencyHash.Add(dep.Id, dep);
}
}
// This method is called upon Execute of a command associated with a SqlDependency object.
internal string AddCommandEntry(string commandHash, SqlDependency dep)
{
string notificationId = string.Empty;
lock (_instanceLock)
{
if (_dependencyIdToDependencyHash.ContainsKey(dep.Id))
{
// check if we already have notification associated with given command hash
if (_commandHashToNotificationId.TryGetValue(commandHash, out notificationId))
{
// we have one or more SqlDependency instances with same command hash
DependencyList dependencyList = null;
if (!_notificationIdToDependenciesHash.TryGetValue(notificationId, out dependencyList))
{
// this should not happen since _commandHashToNotificationId and _notificationIdToDependenciesHash are always
// updated together
Debug.Fail("_commandHashToNotificationId has entries that were removed from _notificationIdToDependenciesHash. Remember to keep them in sync");
throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyCommandHashIsNotAssociatedWithNotification);
}
// join the new dependency to the list
if (!dependencyList.Contains(dep))
{
dependencyList.Add(dep);
}
}
else
{
// we did not find notification ID with the same app domain and command hash, create a new one
// use unique guid to avoid duplicate IDs
// prepend app domain ID to the key - SqlConnectionContainer::ProcessNotificationResults (SqlDependencyListener.cs)
// uses this app domain ID to route the message back to the app domain in which this SqlDependency was created
notificationId = string.Format(System.Globalization.CultureInfo.InvariantCulture,
"{0};{1}",
SqlDependency.AppDomainKey, // must be first
Guid.NewGuid().ToString("D", System.Globalization.CultureInfo.InvariantCulture)
);
DependencyList dependencyList = new DependencyList(commandHash);
dependencyList.Add(dep);
// map command hash to notification we just created to reuse it for the next client
_commandHashToNotificationId.Add(commandHash, notificationId);
_notificationIdToDependenciesHash.Add(notificationId, dependencyList);
}
Debug.Assert(_notificationIdToDependenciesHash.Count == _commandHashToNotificationId.Count, "always keep these maps in sync!");
}
}
return notificationId;
}
// This method is called by the ProcessDispatcher upon a notification for this AppDomain.
internal void InvalidateCommandID(SqlNotification sqlNotification)
{
List<SqlDependency> dependencyList = null;
lock (_instanceLock)
{
dependencyList = LookupCommandEntryWithRemove(sqlNotification.Key);
if (null != dependencyList)
{
foreach (SqlDependency dependency in dependencyList)
{
// Ensure we remove from process static app domain hash for dependency initiated invalidates.
LookupDependencyEntryWithRemove(dependency.Id);
// Completely remove Dependency from commandToDependenciesHash.
RemoveDependencyFromCommandToDependenciesHash(dependency);
}
}
}
if (null != dependencyList)
{
// After removal from hashtables, invalidate.
foreach (SqlDependency dependency in dependencyList)
{
try
{
dependency.Invalidate(sqlNotification.Type, sqlNotification.Info, sqlNotification.Source);
}
catch (Exception e)
{
// Since we are looping over dependencies, do not allow one Invalidate
// that results in a throw prevent us from invalidating all dependencies
// related to this server.
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e);
}
}
}
}
// This method is called when a connection goes down or other unknown error occurs in the ProcessDispatcher.
internal void InvalidateServer(string server, SqlNotification sqlNotification)
{
List<SqlDependency> dependencies = new List<SqlDependency>();
lock (_instanceLock)
{ // Copy inside of lock, but invalidate outside of lock.
foreach (KeyValuePair<string, SqlDependency> entry in _dependencyIdToDependencyHash)
{
SqlDependency dependency = entry.Value;
if (dependency.ContainsServer(server))
{
dependencies.Add(dependency);
}
}
foreach (SqlDependency dependency in dependencies)
{ // Iterate over resulting list removing from our hashes.
// Ensure we remove from process static app domain hash for dependency initiated invalidates.
LookupDependencyEntryWithRemove(dependency.Id);
// Completely remove Dependency from commandToDependenciesHash.
RemoveDependencyFromCommandToDependenciesHash(dependency);
}
}
foreach (SqlDependency dependency in dependencies)
{ // Iterate and invalidate.
try
{
dependency.Invalidate(sqlNotification.Type, sqlNotification.Info, sqlNotification.Source);
}
catch (Exception e)
{
// Since we are looping over dependencies, do not allow one Invalidate
// that results in a throw prevent us from invalidating all dependencies
// related to this server.
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e);
}
}
}
// This method is called by SqlCommand to enable ASP.NET scenarios - map from ID to Dependency.
internal SqlDependency LookupDependencyEntry(string id)
{
if (null == id)
{
throw ADP.ArgumentNull(nameof(id));
}
if (string.IsNullOrEmpty(id))
{
throw SQL.SqlDependencyIdMismatch();
}
SqlDependency entry = null;
lock (_instanceLock)
{
if (_dependencyIdToDependencyHash.ContainsKey(id))
{
entry = _dependencyIdToDependencyHash[id];
}
}
return entry;
}
// Remove the dependency from the hashtable with the passed id.
private void LookupDependencyEntryWithRemove(string id)
{
lock (_instanceLock)
{
if (_dependencyIdToDependencyHash.ContainsKey(id))
{
_dependencyIdToDependencyHash.Remove(id);
// if there are no more dependencies then we can dispose the timer.
if (0 == _dependencyIdToDependencyHash.Count)
{
_timeoutTimer.Change(Timeout.Infinite, Timeout.Infinite);
_sqlDependencyTimeOutTimerStarted = false;
}
}
}
}
// Find and return arraylist, and remove passed hash value.
private List<SqlDependency> LookupCommandEntryWithRemove(string notificationId)
{
DependencyList entry = null;
lock (_instanceLock)
{
if (_notificationIdToDependenciesHash.TryGetValue(notificationId, out entry))
{
// update the tables
_notificationIdToDependenciesHash.Remove(notificationId);
// Cleanup the map between the command hash and associated notification ID
_commandHashToNotificationId.Remove(entry.CommandHash);
}
Debug.Assert(_notificationIdToDependenciesHash.Count == _commandHashToNotificationId.Count, "always keep these maps in sync!");
}
return entry; // DependencyList inherits from List<SqlDependency>
}
// Remove from commandToDependenciesHash all references to the passed dependency.
private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency dependency)
{
lock (_instanceLock)
{
List<string> notificationIdsToRemove = new List<string>();
List<string> commandHashesToRemove = new List<string>();
foreach (KeyValuePair<string, DependencyList> entry in _notificationIdToDependenciesHash)
{
DependencyList dependencies = entry.Value;
if (dependencies.Remove(dependency))
{
if (dependencies.Count == 0)
{
// this dependency was the last associated with this notification ID, remove the entry
// note: cannot do it inside foreach over dictionary
notificationIdsToRemove.Add(entry.Key);
commandHashesToRemove.Add(entry.Value.CommandHash);
}
}
// same SqlDependency can be associated with more than one command, so we have to continue till the end...
}
Debug.Assert(commandHashesToRemove.Count == notificationIdsToRemove.Count, "maps should be kept in sync");
for (int i = 0; i < notificationIdsToRemove.Count; i++)
{
// cleanup the entry outside of foreach
_notificationIdToDependenciesHash.Remove(notificationIdsToRemove[i]);
// Cleanup the map between the command hash and associated notification ID
_commandHashToNotificationId.Remove(commandHashesToRemove[i]);
}
Debug.Assert(_notificationIdToDependenciesHash.Count == _commandHashToNotificationId.Count, "always keep these maps in sync!");
}
}
// Methods for Timer maintenance and firing.
internal void StartTimer(SqlDependency dep)
{
// If this dependency expires sooner than the current next timeout, change
// the timeout and enable timer callback as needed. Note that we change _nextTimeout
// only inside the hashtable syncroot.
lock (_instanceLock)
{
// Enable the timer if needed (disable when empty, enable on the first addition).
if (!_sqlDependencyTimeOutTimerStarted)
{
_timeoutTimer.Change(15000 /* 15 secs */, 15000 /* 15 secs */);
// Save this as the earlier timeout to come.
_nextTimeout = dep.ExpirationTime;
_sqlDependencyTimeOutTimerStarted = true;
}
else if (_nextTimeout > dep.ExpirationTime)
{
// Save this as the earlier timeout to come.
_nextTimeout = dep.ExpirationTime;
}
}
}
private static void TimeoutTimerCallback(object state)
{
SqlDependency[] dependencies;
// Only take the lock for checking whether there is work to do
// if we do have work, we'll copy the hashtable and scan it after releasing
// the lock.
lock (SingletonInstance._instanceLock)
{
if (0 == SingletonInstance._dependencyIdToDependencyHash.Count)
{
// Nothing to check.
return;
}
if (SingletonInstance._nextTimeout > DateTime.UtcNow)
{
// No dependency timed-out yet.
return;
}
// If at least one dependency timed-out do a scan of the table.
// NOTE: we could keep a shadow table sorted by expiration time, but
// given the number of typical simultaneously alive dependencies it's
// probably not worth the optimization.
dependencies = new SqlDependency[SingletonInstance._dependencyIdToDependencyHash.Count];
SingletonInstance._dependencyIdToDependencyHash.Values.CopyTo(dependencies, 0);
}
// Scan the active dependencies if needed.
DateTime now = DateTime.UtcNow;
DateTime newNextTimeout = DateTime.MaxValue;
for (int i = 0; i < dependencies.Length; i++)
{
// If expired fire the change notification.
if (dependencies[i].ExpirationTime <= now)
{
try
{
// This invokes user-code which may throw exceptions.
// NOTE: this is intentionally outside of the lock, we don't want
// to invoke user-code while holding an internal lock.
dependencies[i].Invalidate(SqlNotificationType.Change, SqlNotificationInfo.Error, SqlNotificationSource.Timeout);
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
// This is an exception in user code, and we're in a thread-pool thread
// without user's code up in the stack, no much we can do other than
// eating the exception.
ADP.TraceExceptionWithoutRethrow(e);
}
}
else
{
if (dependencies[i].ExpirationTime < newNextTimeout)
{
newNextTimeout = dependencies[i].ExpirationTime; // Track the next earlier timeout.
}
dependencies[i] = null; // Null means "don't remove it from the hashtable" in the loop below.
}
}
// Remove timed-out dependencies from the hashtable.
lock (SingletonInstance._instanceLock)
{
for (int i = 0; i < dependencies.Length; i++)
{
if (null != dependencies[i])
{
SingletonInstance._dependencyIdToDependencyHash.Remove(dependencies[i].Id);
}
}
if (newNextTimeout < SingletonInstance._nextTimeout)
{
SingletonInstance._nextTimeout = newNextTimeout; // We're inside the lock so ok to update.
}
}
}
}
// Simple class used to encapsulate all data in a notification.
internal class SqlNotification : MarshalByRefObject
{
// This class could be Serializable rather than MBR...
private readonly SqlNotificationInfo _info;
private readonly SqlNotificationSource _source;
private readonly SqlNotificationType _type;
private readonly string _key;
internal SqlNotification(SqlNotificationInfo info, SqlNotificationSource source, SqlNotificationType type, string key)
{
_info = info;
_source = source;
_type = type;
_key = key;
}
internal SqlNotificationInfo Info => _info;
internal string Key => _key;
internal SqlNotificationSource Source => _source;
internal SqlNotificationType Type => _type;
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Gaming.V1Beta.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedRealmsServiceClientSnippets
{
/// <summary>Snippet for ListRealms</summary>
public void ListRealmsRequestObject()
{
// Snippet: ListRealms(ListRealmsRequest, CallSettings)
// Create client
RealmsServiceClient realmsServiceClient = RealmsServiceClient.Create();
// Initialize request argument(s)
ListRealmsRequest request = new ListRealmsRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Filter = "",
OrderBy = "",
};
// Make the request
PagedEnumerable<ListRealmsResponse, Realm> response = realmsServiceClient.ListRealms(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Realm item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListRealmsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Realm item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Realm> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Realm item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListRealmsAsync</summary>
public async Task ListRealmsRequestObjectAsync()
{
// Snippet: ListRealmsAsync(ListRealmsRequest, CallSettings)
// Create client
RealmsServiceClient realmsServiceClient = await RealmsServiceClient.CreateAsync();
// Initialize request argument(s)
ListRealmsRequest request = new ListRealmsRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Filter = "",
OrderBy = "",
};
// Make the request
PagedAsyncEnumerable<ListRealmsResponse, Realm> response = realmsServiceClient.ListRealmsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Realm item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListRealmsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Realm item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Realm> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Realm item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListRealms</summary>
public void ListRealms()
{
// Snippet: ListRealms(string, string, int?, CallSettings)
// Create client
RealmsServiceClient realmsServiceClient = RealmsServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedEnumerable<ListRealmsResponse, Realm> response = realmsServiceClient.ListRealms(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Realm item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListRealmsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Realm item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Realm> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Realm item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListRealmsAsync</summary>
public async Task ListRealmsAsync()
{
// Snippet: ListRealmsAsync(string, string, int?, CallSettings)
// Create client
RealmsServiceClient realmsServiceClient = await RealmsServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedAsyncEnumerable<ListRealmsResponse, Realm> response = realmsServiceClient.ListRealmsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Realm item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListRealmsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Realm item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Realm> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Realm item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListRealms</summary>
public void ListRealmsResourceNames()
{
// Snippet: ListRealms(LocationName, string, int?, CallSettings)
// Create client
RealmsServiceClient realmsServiceClient = RealmsServiceClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedEnumerable<ListRealmsResponse, Realm> response = realmsServiceClient.ListRealms(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Realm item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListRealmsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Realm item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Realm> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Realm item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListRealmsAsync</summary>
public async Task ListRealmsResourceNamesAsync()
{
// Snippet: ListRealmsAsync(LocationName, string, int?, CallSettings)
// Create client
RealmsServiceClient realmsServiceClient = await RealmsServiceClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedAsyncEnumerable<ListRealmsResponse, Realm> response = realmsServiceClient.ListRealmsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Realm item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListRealmsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Realm item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Realm> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Realm item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetRealm</summary>
public void GetRealmRequestObject()
{
// Snippet: GetRealm(GetRealmRequest, CallSettings)
// Create client
RealmsServiceClient realmsServiceClient = RealmsServiceClient.Create();
// Initialize request argument(s)
GetRealmRequest request = new GetRealmRequest
{
RealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
};
// Make the request
Realm response = realmsServiceClient.GetRealm(request);
// End snippet
}
/// <summary>Snippet for GetRealmAsync</summary>
public async Task GetRealmRequestObjectAsync()
{
// Snippet: GetRealmAsync(GetRealmRequest, CallSettings)
// Additional: GetRealmAsync(GetRealmRequest, CancellationToken)
// Create client
RealmsServiceClient realmsServiceClient = await RealmsServiceClient.CreateAsync();
// Initialize request argument(s)
GetRealmRequest request = new GetRealmRequest
{
RealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
};
// Make the request
Realm response = await realmsServiceClient.GetRealmAsync(request);
// End snippet
}
/// <summary>Snippet for GetRealm</summary>
public void GetRealm()
{
// Snippet: GetRealm(string, CallSettings)
// Create client
RealmsServiceClient realmsServiceClient = RealmsServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/realms/[REALM]";
// Make the request
Realm response = realmsServiceClient.GetRealm(name);
// End snippet
}
/// <summary>Snippet for GetRealmAsync</summary>
public async Task GetRealmAsync()
{
// Snippet: GetRealmAsync(string, CallSettings)
// Additional: GetRealmAsync(string, CancellationToken)
// Create client
RealmsServiceClient realmsServiceClient = await RealmsServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/realms/[REALM]";
// Make the request
Realm response = await realmsServiceClient.GetRealmAsync(name);
// End snippet
}
/// <summary>Snippet for GetRealm</summary>
public void GetRealmResourceNames()
{
// Snippet: GetRealm(RealmName, CallSettings)
// Create client
RealmsServiceClient realmsServiceClient = RealmsServiceClient.Create();
// Initialize request argument(s)
RealmName name = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]");
// Make the request
Realm response = realmsServiceClient.GetRealm(name);
// End snippet
}
/// <summary>Snippet for GetRealmAsync</summary>
public async Task GetRealmResourceNamesAsync()
{
// Snippet: GetRealmAsync(RealmName, CallSettings)
// Additional: GetRealmAsync(RealmName, CancellationToken)
// Create client
RealmsServiceClient realmsServiceClient = await RealmsServiceClient.CreateAsync();
// Initialize request argument(s)
RealmName name = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]");
// Make the request
Realm response = await realmsServiceClient.GetRealmAsync(name);
// End snippet
}
/// <summary>Snippet for CreateRealm</summary>
public void CreateRealmRequestObject()
{
// Snippet: CreateRealm(CreateRealmRequest, CallSettings)
// Create client
RealmsServiceClient realmsServiceClient = RealmsServiceClient.Create();
// Initialize request argument(s)
CreateRealmRequest request = new CreateRealmRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
RealmId = "",
Realm = new Realm(),
};
// Make the request
Operation<Realm, OperationMetadata> response = realmsServiceClient.CreateRealm(request);
// Poll until the returned long-running operation is complete
Operation<Realm, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Realm result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Realm, OperationMetadata> retrievedResponse = realmsServiceClient.PollOnceCreateRealm(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Realm retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateRealmAsync</summary>
public async Task CreateRealmRequestObjectAsync()
{
// Snippet: CreateRealmAsync(CreateRealmRequest, CallSettings)
// Additional: CreateRealmAsync(CreateRealmRequest, CancellationToken)
// Create client
RealmsServiceClient realmsServiceClient = await RealmsServiceClient.CreateAsync();
// Initialize request argument(s)
CreateRealmRequest request = new CreateRealmRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
RealmId = "",
Realm = new Realm(),
};
// Make the request
Operation<Realm, OperationMetadata> response = await realmsServiceClient.CreateRealmAsync(request);
// Poll until the returned long-running operation is complete
Operation<Realm, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Realm result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Realm, OperationMetadata> retrievedResponse = await realmsServiceClient.PollOnceCreateRealmAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Realm retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateRealm</summary>
public void CreateRealm()
{
// Snippet: CreateRealm(string, Realm, string, CallSettings)
// Create client
RealmsServiceClient realmsServiceClient = RealmsServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
Realm realm = new Realm();
string realmId = "";
// Make the request
Operation<Realm, OperationMetadata> response = realmsServiceClient.CreateRealm(parent, realm, realmId);
// Poll until the returned long-running operation is complete
Operation<Realm, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Realm result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Realm, OperationMetadata> retrievedResponse = realmsServiceClient.PollOnceCreateRealm(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Realm retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateRealmAsync</summary>
public async Task CreateRealmAsync()
{
// Snippet: CreateRealmAsync(string, Realm, string, CallSettings)
// Additional: CreateRealmAsync(string, Realm, string, CancellationToken)
// Create client
RealmsServiceClient realmsServiceClient = await RealmsServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
Realm realm = new Realm();
string realmId = "";
// Make the request
Operation<Realm, OperationMetadata> response = await realmsServiceClient.CreateRealmAsync(parent, realm, realmId);
// Poll until the returned long-running operation is complete
Operation<Realm, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Realm result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Realm, OperationMetadata> retrievedResponse = await realmsServiceClient.PollOnceCreateRealmAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Realm retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateRealm</summary>
public void CreateRealmResourceNames()
{
// Snippet: CreateRealm(LocationName, Realm, string, CallSettings)
// Create client
RealmsServiceClient realmsServiceClient = RealmsServiceClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
Realm realm = new Realm();
string realmId = "";
// Make the request
Operation<Realm, OperationMetadata> response = realmsServiceClient.CreateRealm(parent, realm, realmId);
// Poll until the returned long-running operation is complete
Operation<Realm, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Realm result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Realm, OperationMetadata> retrievedResponse = realmsServiceClient.PollOnceCreateRealm(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Realm retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateRealmAsync</summary>
public async Task CreateRealmResourceNamesAsync()
{
// Snippet: CreateRealmAsync(LocationName, Realm, string, CallSettings)
// Additional: CreateRealmAsync(LocationName, Realm, string, CancellationToken)
// Create client
RealmsServiceClient realmsServiceClient = await RealmsServiceClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
Realm realm = new Realm();
string realmId = "";
// Make the request
Operation<Realm, OperationMetadata> response = await realmsServiceClient.CreateRealmAsync(parent, realm, realmId);
// Poll until the returned long-running operation is complete
Operation<Realm, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Realm result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Realm, OperationMetadata> retrievedResponse = await realmsServiceClient.PollOnceCreateRealmAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Realm retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteRealm</summary>
public void DeleteRealmRequestObject()
{
// Snippet: DeleteRealm(DeleteRealmRequest, CallSettings)
// Create client
RealmsServiceClient realmsServiceClient = RealmsServiceClient.Create();
// Initialize request argument(s)
DeleteRealmRequest request = new DeleteRealmRequest
{
RealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
};
// Make the request
Operation<Empty, OperationMetadata> response = realmsServiceClient.DeleteRealm(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = realmsServiceClient.PollOnceDeleteRealm(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteRealmAsync</summary>
public async Task DeleteRealmRequestObjectAsync()
{
// Snippet: DeleteRealmAsync(DeleteRealmRequest, CallSettings)
// Additional: DeleteRealmAsync(DeleteRealmRequest, CancellationToken)
// Create client
RealmsServiceClient realmsServiceClient = await RealmsServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteRealmRequest request = new DeleteRealmRequest
{
RealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
};
// Make the request
Operation<Empty, OperationMetadata> response = await realmsServiceClient.DeleteRealmAsync(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await realmsServiceClient.PollOnceDeleteRealmAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteRealm</summary>
public void DeleteRealm()
{
// Snippet: DeleteRealm(string, CallSettings)
// Create client
RealmsServiceClient realmsServiceClient = RealmsServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/realms/[REALM]";
// Make the request
Operation<Empty, OperationMetadata> response = realmsServiceClient.DeleteRealm(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = realmsServiceClient.PollOnceDeleteRealm(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteRealmAsync</summary>
public async Task DeleteRealmAsync()
{
// Snippet: DeleteRealmAsync(string, CallSettings)
// Additional: DeleteRealmAsync(string, CancellationToken)
// Create client
RealmsServiceClient realmsServiceClient = await RealmsServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/realms/[REALM]";
// Make the request
Operation<Empty, OperationMetadata> response = await realmsServiceClient.DeleteRealmAsync(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await realmsServiceClient.PollOnceDeleteRealmAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteRealm</summary>
public void DeleteRealmResourceNames()
{
// Snippet: DeleteRealm(RealmName, CallSettings)
// Create client
RealmsServiceClient realmsServiceClient = RealmsServiceClient.Create();
// Initialize request argument(s)
RealmName name = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]");
// Make the request
Operation<Empty, OperationMetadata> response = realmsServiceClient.DeleteRealm(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = realmsServiceClient.PollOnceDeleteRealm(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteRealmAsync</summary>
public async Task DeleteRealmResourceNamesAsync()
{
// Snippet: DeleteRealmAsync(RealmName, CallSettings)
// Additional: DeleteRealmAsync(RealmName, CancellationToken)
// Create client
RealmsServiceClient realmsServiceClient = await RealmsServiceClient.CreateAsync();
// Initialize request argument(s)
RealmName name = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]");
// Make the request
Operation<Empty, OperationMetadata> response = await realmsServiceClient.DeleteRealmAsync(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await realmsServiceClient.PollOnceDeleteRealmAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateRealm</summary>
public void UpdateRealmRequestObject()
{
// Snippet: UpdateRealm(UpdateRealmRequest, CallSettings)
// Create client
RealmsServiceClient realmsServiceClient = RealmsServiceClient.Create();
// Initialize request argument(s)
UpdateRealmRequest request = new UpdateRealmRequest
{
Realm = new Realm(),
UpdateMask = new FieldMask(),
};
// Make the request
Operation<Realm, OperationMetadata> response = realmsServiceClient.UpdateRealm(request);
// Poll until the returned long-running operation is complete
Operation<Realm, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Realm result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Realm, OperationMetadata> retrievedResponse = realmsServiceClient.PollOnceUpdateRealm(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Realm retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateRealmAsync</summary>
public async Task UpdateRealmRequestObjectAsync()
{
// Snippet: UpdateRealmAsync(UpdateRealmRequest, CallSettings)
// Additional: UpdateRealmAsync(UpdateRealmRequest, CancellationToken)
// Create client
RealmsServiceClient realmsServiceClient = await RealmsServiceClient.CreateAsync();
// Initialize request argument(s)
UpdateRealmRequest request = new UpdateRealmRequest
{
Realm = new Realm(),
UpdateMask = new FieldMask(),
};
// Make the request
Operation<Realm, OperationMetadata> response = await realmsServiceClient.UpdateRealmAsync(request);
// Poll until the returned long-running operation is complete
Operation<Realm, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Realm result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Realm, OperationMetadata> retrievedResponse = await realmsServiceClient.PollOnceUpdateRealmAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Realm retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateRealm</summary>
public void UpdateRealm()
{
// Snippet: UpdateRealm(Realm, FieldMask, CallSettings)
// Create client
RealmsServiceClient realmsServiceClient = RealmsServiceClient.Create();
// Initialize request argument(s)
Realm realm = new Realm();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<Realm, OperationMetadata> response = realmsServiceClient.UpdateRealm(realm, updateMask);
// Poll until the returned long-running operation is complete
Operation<Realm, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Realm result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Realm, OperationMetadata> retrievedResponse = realmsServiceClient.PollOnceUpdateRealm(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Realm retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateRealmAsync</summary>
public async Task UpdateRealmAsync()
{
// Snippet: UpdateRealmAsync(Realm, FieldMask, CallSettings)
// Additional: UpdateRealmAsync(Realm, FieldMask, CancellationToken)
// Create client
RealmsServiceClient realmsServiceClient = await RealmsServiceClient.CreateAsync();
// Initialize request argument(s)
Realm realm = new Realm();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<Realm, OperationMetadata> response = await realmsServiceClient.UpdateRealmAsync(realm, updateMask);
// Poll until the returned long-running operation is complete
Operation<Realm, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Realm result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Realm, OperationMetadata> retrievedResponse = await realmsServiceClient.PollOnceUpdateRealmAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Realm retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PreviewRealmUpdate</summary>
public void PreviewRealmUpdateRequestObject()
{
// Snippet: PreviewRealmUpdate(PreviewRealmUpdateRequest, CallSettings)
// Create client
RealmsServiceClient realmsServiceClient = RealmsServiceClient.Create();
// Initialize request argument(s)
PreviewRealmUpdateRequest request = new PreviewRealmUpdateRequest
{
Realm = new Realm(),
UpdateMask = new FieldMask(),
PreviewTime = new Timestamp(),
};
// Make the request
PreviewRealmUpdateResponse response = realmsServiceClient.PreviewRealmUpdate(request);
// End snippet
}
/// <summary>Snippet for PreviewRealmUpdateAsync</summary>
public async Task PreviewRealmUpdateRequestObjectAsync()
{
// Snippet: PreviewRealmUpdateAsync(PreviewRealmUpdateRequest, CallSettings)
// Additional: PreviewRealmUpdateAsync(PreviewRealmUpdateRequest, CancellationToken)
// Create client
RealmsServiceClient realmsServiceClient = await RealmsServiceClient.CreateAsync();
// Initialize request argument(s)
PreviewRealmUpdateRequest request = new PreviewRealmUpdateRequest
{
Realm = new Realm(),
UpdateMask = new FieldMask(),
PreviewTime = new Timestamp(),
};
// Make the request
PreviewRealmUpdateResponse response = await realmsServiceClient.PreviewRealmUpdateAsync(request);
// End snippet
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Xml;
namespace System.Runtime.Serialization.Json
{
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime;
using System.Security;
using System.Xml;
internal delegate object JsonFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString[] memberNames);
internal delegate object JsonFormatCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString itemName, CollectionDataContract collectionContract);
internal delegate void JsonFormatGetOnlyCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString itemName, CollectionDataContract collectionContract);
internal sealed class JsonFormatReaderGenerator
{
private CriticalHelper _helper;
public JsonFormatReaderGenerator()
{
_helper = new CriticalHelper();
}
public JsonFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract)
{
return _helper.GenerateClassReader(classContract);
}
public JsonFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract)
{
return _helper.GenerateCollectionReader(collectionContract);
}
public JsonFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract)
{
return _helper.GenerateGetOnlyCollectionReader(collectionContract);
}
private class CriticalHelper
{
private CodeGenerator _ilg;
private LocalBuilder _objectLocal;
private Type _objectType;
private ArgBuilder _xmlReaderArg;
private ArgBuilder _contextArg;
private ArgBuilder _memberNamesArg;
private ArgBuilder _collectionContractArg;
private ArgBuilder _emptyDictionaryStringArg;
public JsonFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract)
{
_ilg = new CodeGenerator();
bool memberAccessFlag = classContract.RequiresMemberAccessForRead(null);
try
{
BeginMethod(_ilg, "Read" + DataContract.SanitizeTypeName(classContract.StableName.Name) + "FromJson", typeof(JsonFormatClassReaderDelegate), memberAccessFlag);
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
classContract.RequiresMemberAccessForRead(securityException);
}
else
{
throw;
}
}
InitArgs();
CreateObject(classContract);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal);
InvokeOnDeserializing(classContract);
if (classContract.IsISerializable)
ReadISerializable(classContract);
else
ReadClass(classContract);
if (Globals.TypeOfIDeserializationCallback.IsAssignableFrom(classContract.UnderlyingType))
{
_ilg.Call(_objectLocal, JsonFormatGeneratorStatics.OnDeserializationMethod, null);
}
InvokeOnDeserialized(classContract);
if (!InvokeFactoryMethod(classContract))
{
_ilg.Load(_objectLocal);
// Do a conversion back from DateTimeOffsetAdapter to DateTimeOffset after deserialization.
// DateTimeOffsetAdapter is used here for deserialization purposes to bypass the ISerializable implementation
// on DateTimeOffset; which does not work in partial trust.
if (classContract.UnderlyingType == Globals.TypeOfDateTimeOffsetAdapter)
{
_ilg.ConvertValue(_objectLocal.LocalType, Globals.TypeOfDateTimeOffsetAdapter);
_ilg.Call(XmlFormatGeneratorStatics.GetDateTimeOffsetMethod);
_ilg.ConvertValue(Globals.TypeOfDateTimeOffset, _ilg.CurrentMethod.ReturnType);
}
//Copy the KeyValuePairAdapter<K,T> to a KeyValuePair<K,T>.
else if (classContract.IsKeyValuePairAdapter)
{
_ilg.Call(classContract.GetKeyValuePairMethodInfo);
_ilg.ConvertValue(Globals.TypeOfKeyValuePair.MakeGenericType(classContract.KeyValuePairGenericArguments), _ilg.CurrentMethod.ReturnType);
}
else
{
_ilg.ConvertValue(_objectLocal.LocalType, _ilg.CurrentMethod.ReturnType);
}
}
return (JsonFormatClassReaderDelegate)_ilg.EndMethod();
}
public JsonFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract)
{
_ilg = GenerateCollectionReaderHelper(collectionContract, false /*isGetOnlyCollection*/);
ReadCollection(collectionContract);
_ilg.Load(_objectLocal);
_ilg.ConvertValue(_objectLocal.LocalType, _ilg.CurrentMethod.ReturnType);
return (JsonFormatCollectionReaderDelegate)_ilg.EndMethod();
}
public JsonFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract)
{
_ilg = GenerateCollectionReaderHelper(collectionContract, true /*isGetOnlyCollection*/);
ReadGetOnlyCollection(collectionContract);
return (JsonFormatGetOnlyCollectionReaderDelegate)_ilg.EndMethod();
}
private CodeGenerator GenerateCollectionReaderHelper(CollectionDataContract collectionContract, bool isGetOnlyCollection)
{
_ilg = new CodeGenerator();
bool memberAccessFlag = collectionContract.RequiresMemberAccessForRead(null);
try
{
if (isGetOnlyCollection)
{
BeginMethod(_ilg, "Read" + DataContract.SanitizeTypeName(collectionContract.StableName.Name) + "FromJson" + "IsGetOnly", typeof(JsonFormatGetOnlyCollectionReaderDelegate), memberAccessFlag);
}
else
{
BeginMethod(_ilg, "Read" + DataContract.SanitizeTypeName(collectionContract.StableName.Name) + "FromJson", typeof(JsonFormatCollectionReaderDelegate), memberAccessFlag);
}
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
collectionContract.RequiresMemberAccessForRead(securityException);
}
else
{
throw;
}
}
InitArgs();
_collectionContractArg = _ilg.GetArg(4);
return _ilg;
}
private void BeginMethod(CodeGenerator ilg, string methodName, Type delegateType, bool allowPrivateMemberAccess)
{
#if USE_REFEMIT
ilg.BeginMethod(methodName, delegateType, allowPrivateMemberAccess);
#else
MethodInfo signature = delegateType.GetMethod("Invoke");
ParameterInfo[] parameters = signature.GetParameters();
Type[] paramTypes = new Type[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
paramTypes[i] = parameters[i].ParameterType;
DynamicMethod dynamicMethod = new DynamicMethod(methodName, signature.ReturnType, paramTypes, typeof(JsonFormatReaderGenerator).Module, allowPrivateMemberAccess);
ilg.BeginMethod(dynamicMethod, delegateType, methodName, paramTypes, allowPrivateMemberAccess);
#endif
}
private void InitArgs()
{
_xmlReaderArg = _ilg.GetArg(0);
_contextArg = _ilg.GetArg(1);
_emptyDictionaryStringArg = _ilg.GetArg(2);
_memberNamesArg = _ilg.GetArg(3);
}
private void CreateObject(ClassDataContract classContract)
{
_objectType = classContract.UnderlyingType;
Type type = classContract.ObjectType;
_objectLocal = _ilg.DeclareLocal(type, "objectDeserialized");
if (classContract.UnderlyingType == Globals.TypeOfDBNull)
{
_ilg.LoadMember(Globals.TypeOfDBNull.GetField("Value"));
_ilg.Stloc(_objectLocal);
}
else if (classContract.IsNonAttributedType)
{
if (type.IsValueType)
{
_ilg.Ldloca(_objectLocal);
_ilg.InitObj(type);
}
else
{
_ilg.New(classContract.GetNonAttributedTypeConstructor());
_ilg.Stloc(_objectLocal);
}
}
else
{
_ilg.Call(null, JsonFormatGeneratorStatics.GetUninitializedObjectMethod, classContract.TypeForInitialization);
_ilg.ConvertValue(Globals.TypeOfObject, type);
_ilg.Stloc(_objectLocal);
}
}
private void InvokeOnDeserializing(ClassDataContract classContract)
{
if (classContract.BaseContract != null)
InvokeOnDeserializing(classContract.BaseContract);
if (classContract.OnDeserializing != null)
{
_ilg.LoadAddress(_objectLocal);
_ilg.ConvertAddress(_objectLocal.LocalType, _objectType);
_ilg.Load(_contextArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod);
_ilg.Call(classContract.OnDeserializing);
}
}
private void InvokeOnDeserialized(ClassDataContract classContract)
{
if (classContract.BaseContract != null)
InvokeOnDeserialized(classContract.BaseContract);
if (classContract.OnDeserialized != null)
{
_ilg.LoadAddress(_objectLocal);
_ilg.ConvertAddress(_objectLocal.LocalType, _objectType);
_ilg.Load(_contextArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod);
_ilg.Call(classContract.OnDeserialized);
}
}
bool HasFactoryMethod(ClassDataContract classContract)
{
return Globals.TypeOfIObjectReference.IsAssignableFrom(classContract.UnderlyingType);
}
private bool InvokeFactoryMethod(ClassDataContract classContract)
{
if (HasFactoryMethod(classContract))
{
_ilg.Load(_contextArg);
_ilg.LoadAddress(_objectLocal);
_ilg.ConvertAddress(_objectLocal.LocalType, Globals.TypeOfIObjectReference);
_ilg.Load(Globals.NewObjectId);
_ilg.Call(XmlFormatGeneratorStatics.GetRealObjectMethod);
_ilg.ConvertValue(Globals.TypeOfObject, _ilg.CurrentMethod.ReturnType);
return true;
}
return false;
}
private void ReadClass(ClassDataContract classContract)
{
if (classContract.HasExtensionData)
{
LocalBuilder extensionDataLocal = _ilg.DeclareLocal(Globals.TypeOfExtensionDataObject, "extensionData");
_ilg.New(JsonFormatGeneratorStatics.ExtensionDataObjectCtor);
_ilg.Store(extensionDataLocal);
ReadMembers(classContract, extensionDataLocal);
ClassDataContract currentContract = classContract;
while (currentContract != null)
{
MethodInfo extensionDataSetMethod = currentContract.ExtensionDataSetMethod;
if (extensionDataSetMethod != null)
_ilg.Call(_objectLocal, extensionDataSetMethod, extensionDataLocal);
currentContract = currentContract.BaseContract;
}
}
else
{
ReadMembers(classContract, null /*extensionDataLocal*/);
}
}
private void ReadMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal)
{
int memberCount = classContract.MemberNames.Length;
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, memberCount);
BitFlagsGenerator expectedElements = new BitFlagsGenerator(memberCount, _ilg, classContract.UnderlyingType.Name + "_ExpectedElements");
byte[] requiredElements = new byte[expectedElements.GetLocalCount()];
SetRequiredElements(classContract, requiredElements);
SetExpectedElements(expectedElements, 0 /*startIndex*/);
LocalBuilder memberIndexLocal = _ilg.DeclareLocal(Globals.TypeOfInt, "memberIndex", -1);
Label throwDuplicateMemberLabel = _ilg.DefineLabel();
Label throwMissingRequiredMembersLabel = _ilg.DefineLabel();
object forReadElements = _ilg.For(null, null, null);
_ilg.Call(null, XmlFormatGeneratorStatics.MoveToNextElementMethod, _xmlReaderArg);
_ilg.IfFalseBreak(forReadElements);
_ilg.Call(_contextArg, JsonFormatGeneratorStatics.GetJsonMemberIndexMethod, _xmlReaderArg, _memberNamesArg, memberIndexLocal, extensionDataLocal);
if (memberCount > 0)
{
Label[] memberLabels = _ilg.Switch(memberCount);
ReadMembers(classContract, expectedElements, memberLabels, throwDuplicateMemberLabel, memberIndexLocal);
_ilg.EndSwitch();
}
else
{
_ilg.Pop();
}
_ilg.EndFor();
CheckRequiredElements(expectedElements, requiredElements, throwMissingRequiredMembersLabel);
Label endOfTypeLabel = _ilg.DefineLabel();
_ilg.Br(endOfTypeLabel);
_ilg.MarkLabel(throwDuplicateMemberLabel);
_ilg.Call(null, JsonFormatGeneratorStatics.ThrowDuplicateMemberExceptionMethod, _objectLocal, _memberNamesArg, memberIndexLocal);
_ilg.MarkLabel(throwMissingRequiredMembersLabel);
_ilg.Load(_objectLocal);
_ilg.ConvertValue(_objectLocal.LocalType, Globals.TypeOfObject);
_ilg.Load(_memberNamesArg);
expectedElements.LoadArray();
LoadArray(requiredElements, "requiredElements");
_ilg.Call(JsonFormatGeneratorStatics.ThrowMissingRequiredMembersMethod);
_ilg.MarkLabel(endOfTypeLabel);
}
private int ReadMembers(ClassDataContract classContract, BitFlagsGenerator expectedElements,
Label[] memberLabels, Label throwDuplicateMemberLabel, LocalBuilder memberIndexLocal)
{
int memberCount = (classContract.BaseContract == null) ? 0 :
ReadMembers(classContract.BaseContract, expectedElements, memberLabels, throwDuplicateMemberLabel, memberIndexLocal);
for (int i = 0; i < classContract.Members.Count; i++, memberCount++)
{
DataMember dataMember = classContract.Members[i];
Type memberType = dataMember.MemberType;
_ilg.Case(memberLabels[memberCount], dataMember.Name);
_ilg.Set(memberIndexLocal, memberCount);
expectedElements.Load(memberCount);
_ilg.Brfalse(throwDuplicateMemberLabel);
LocalBuilder value = null;
if (dataMember.IsGetOnlyCollection)
{
_ilg.LoadAddress(_objectLocal);
_ilg.LoadMember(dataMember.MemberInfo);
value = _ilg.DeclareLocal(memberType, dataMember.Name + "Value");
_ilg.Stloc(value);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.StoreCollectionMemberInfoMethod, value);
ReadValue(memberType, dataMember.Name);
}
else
{
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.ResetCollectionMemberInfoMethod);
value = ReadValue(memberType, dataMember.Name);
_ilg.LoadAddress(_objectLocal);
_ilg.ConvertAddress(_objectLocal.LocalType, _objectType);
_ilg.Ldloc(value);
_ilg.StoreMember(dataMember.MemberInfo);
}
ResetExpectedElements(expectedElements, memberCount);
_ilg.EndCase();
}
return memberCount;
}
private void CheckRequiredElements(BitFlagsGenerator expectedElements, byte[] requiredElements, Label throwMissingRequiredMembersLabel)
{
for (int i = 0; i < requiredElements.Length; i++)
{
_ilg.Load(expectedElements.GetLocal(i));
_ilg.Load(requiredElements[i]);
_ilg.And();
_ilg.Load(0);
_ilg.Ceq();
_ilg.Brfalse(throwMissingRequiredMembersLabel);
}
}
private void LoadArray(byte[] array, string name)
{
LocalBuilder localArray = _ilg.DeclareLocal(Globals.TypeOfByteArray, name);
_ilg.NewArray(typeof(byte), array.Length);
_ilg.Store(localArray);
for (int i = 0; i < array.Length; i++)
{
_ilg.StoreArrayElement(localArray, i, array[i]);
}
_ilg.Load(localArray);
}
private int SetRequiredElements(ClassDataContract contract, byte[] requiredElements)
{
int memberCount = (contract.BaseContract == null) ? 0 :
SetRequiredElements(contract.BaseContract, requiredElements);
List<DataMember> members = contract.Members;
for (int i = 0; i < members.Count; i++, memberCount++)
{
if (members[i].IsRequired)
{
BitFlagsGenerator.SetBit(requiredElements, memberCount);
}
}
return memberCount;
}
private void SetExpectedElements(BitFlagsGenerator expectedElements, int startIndex)
{
int memberCount = expectedElements.GetBitCount();
for (int i = startIndex; i < memberCount; i++)
{
expectedElements.Store(i, true);
}
}
private void ResetExpectedElements(BitFlagsGenerator expectedElements, int index)
{
expectedElements.Store(index, false);
}
private void ReadISerializable(ClassDataContract classContract)
{
ConstructorInfo ctor = classContract.UnderlyingType.GetConstructor(Globals.ScanAllMembers, null, JsonFormatGeneratorStatics.SerInfoCtorArgs, null);
if (ctor == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.SerializationInfo_ConstructorNotFound, DataContract.GetClrTypeFullName(classContract.UnderlyingType))));
_ilg.LoadAddress(_objectLocal);
_ilg.ConvertAddress(_objectLocal.LocalType, _objectType);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadSerializationInfoMethod, _xmlReaderArg, classContract.UnderlyingType);
_ilg.Load(_contextArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod);
_ilg.Call(ctor);
}
private LocalBuilder ReadValue(Type type, string name)
{
LocalBuilder value = _ilg.DeclareLocal(type, "valueRead");
LocalBuilder nullableValue = null;
int nullables = 0;
while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable)
{
nullables++;
type = type.GetGenericArguments()[0];
}
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType)
{
LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead");
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadAttributesMethod, _xmlReaderArg);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadIfNullOrRefMethod, _xmlReaderArg, type, DataContract.IsTypeSerializable(type));
_ilg.Stloc(objectId);
// Deserialize null
_ilg.If(objectId, Cmp.EqualTo, Globals.NullObjectId);
if (nullables != 0)
{
_ilg.LoadAddress(value);
_ilg.InitObj(value.LocalType);
}
else if (type.IsValueType)
ThrowSerializationException(SR.Format(SR.ValueTypeCannotBeNull, DataContract.GetClrTypeFullName(type)));
else
{
_ilg.Load(null);
_ilg.Stloc(value);
}
// Deserialize value
// Compare against Globals.NewObjectId, which is set to string.Empty
_ilg.ElseIfIsEmptyString(objectId);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod);
_ilg.Stloc(objectId);
if (type.IsValueType)
{
_ilg.IfNotIsEmptyString(objectId);
ThrowSerializationException(SR.Format(SR.ValueTypeCannotHaveId, DataContract.GetClrTypeFullName(type)));
_ilg.EndIf();
}
if (nullables != 0)
{
nullableValue = value;
value = _ilg.DeclareLocal(type, "innerValueRead");
}
if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject)
{
_ilg.Call(_xmlReaderArg, primitiveContract.XmlFormatReaderMethod);
_ilg.Stloc(value);
if (!type.IsValueType)
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, value);
}
else
{
InternalDeserialize(value, type, name);
}
// Deserialize ref
_ilg.Else();
if (type.IsValueType)
ThrowSerializationException(SR.Format(SR.ValueTypeCannotHaveRef, DataContract.GetClrTypeFullName(type)));
else
{
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetExistingObjectMethod, objectId, type, name, string.Empty);
_ilg.ConvertValue(Globals.TypeOfObject, type);
_ilg.Stloc(value);
}
_ilg.EndIf();
if (nullableValue != null)
{
_ilg.If(objectId, Cmp.NotEqualTo, Globals.NullObjectId);
WrapNullableObject(value, nullableValue, nullables);
_ilg.EndIf();
value = nullableValue;
}
}
else
{
InternalDeserialize(value, type, name);
}
return value;
}
private void InternalDeserialize(LocalBuilder value, Type type, string name)
{
_ilg.Load(_contextArg);
_ilg.Load(_xmlReaderArg);
Type declaredType = type;
_ilg.Load(DataContract.GetId(declaredType.TypeHandle));
_ilg.Ldtoken(declaredType);
_ilg.Load(name);
// Empty namespace
_ilg.Load(string.Empty);
_ilg.Call(XmlFormatGeneratorStatics.InternalDeserializeMethod);
_ilg.ConvertValue(Globals.TypeOfObject, type);
_ilg.Stloc(value);
}
private void WrapNullableObject(LocalBuilder innerValue, LocalBuilder outerValue, int nullables)
{
Type innerType = innerValue.LocalType, outerType = outerValue.LocalType;
_ilg.LoadAddress(outerValue);
_ilg.Load(innerValue);
for (int i = 1; i < nullables; i++)
{
Type type = Globals.TypeOfNullable.MakeGenericType(innerType);
_ilg.New(type.GetConstructor(new Type[] { innerType }));
innerType = type;
}
_ilg.Call(outerType.GetConstructor(new Type[] { innerType }));
}
private void ReadCollection(CollectionDataContract collectionContract)
{
Type type = collectionContract.UnderlyingType;
Type itemType = collectionContract.ItemType;
bool isArray = (collectionContract.Kind == CollectionKind.Array);
ConstructorInfo constructor = collectionContract.Constructor;
if (type.IsInterface)
{
switch (collectionContract.Kind)
{
case CollectionKind.GenericDictionary:
type = Globals.TypeOfDictionaryGeneric.MakeGenericType(itemType.GetGenericArguments());
constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Array.Empty<Type>());
break;
case CollectionKind.Dictionary:
type = Globals.TypeOfHashtable;
constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Array.Empty<Type>());
break;
case CollectionKind.Collection:
case CollectionKind.GenericCollection:
case CollectionKind.Enumerable:
case CollectionKind.GenericEnumerable:
case CollectionKind.List:
case CollectionKind.GenericList:
type = itemType.MakeArrayType();
isArray = true;
break;
}
}
_objectLocal = _ilg.DeclareLocal(type, "objectDeserialized");
if (!isArray)
{
if (type.IsValueType)
{
_ilg.Ldloca(_objectLocal);
_ilg.InitObj(type);
}
else
{
_ilg.New(constructor);
_ilg.Stloc(_objectLocal);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal);
}
}
bool canReadSimpleDictionary = collectionContract.Kind == CollectionKind.Dictionary ||
collectionContract.Kind == CollectionKind.GenericDictionary;
if (canReadSimpleDictionary)
{
_ilg.Load(_contextArg);
_ilg.LoadMember(JsonFormatGeneratorStatics.UseSimpleDictionaryFormatReadProperty);
_ilg.If();
ReadSimpleDictionary(collectionContract, itemType);
_ilg.Else();
}
LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead");
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod);
_ilg.Stloc(objectId);
bool canReadPrimitiveArray = false;
if (isArray && TryReadPrimitiveArray(itemType))
{
canReadPrimitiveArray = true;
_ilg.IfNot();
}
LocalBuilder growingCollection = null;
if (isArray)
{
growingCollection = _ilg.DeclareLocal(type, "growingCollection");
_ilg.NewArray(itemType, 32);
_ilg.Stloc(growingCollection);
}
LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i");
object forLoop = _ilg.For(i, 0, int.MaxValue);
// Empty namespace
IsStartElement(_memberNamesArg, _emptyDictionaryStringArg);
_ilg.If();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1);
LocalBuilder value = ReadCollectionItem(collectionContract, itemType);
if (isArray)
{
MethodInfo ensureArraySizeMethod = XmlFormatGeneratorStatics.EnsureArraySizeMethod.MakeGenericMethod(itemType);
_ilg.Call(null, ensureArraySizeMethod, growingCollection, i);
_ilg.Stloc(growingCollection);
_ilg.StoreArrayElement(growingCollection, i, value);
}
else
StoreCollectionValue(_objectLocal, value, collectionContract);
_ilg.Else();
IsEndElement();
_ilg.If();
_ilg.Break(forLoop);
_ilg.Else();
HandleUnexpectedItemInCollection(i);
_ilg.EndIf();
_ilg.EndIf();
_ilg.EndFor();
if (isArray)
{
MethodInfo trimArraySizeMethod = XmlFormatGeneratorStatics.TrimArraySizeMethod.MakeGenericMethod(itemType);
_ilg.Call(null, trimArraySizeMethod, growingCollection, i);
_ilg.Stloc(_objectLocal);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectWithIdMethod, objectId, _objectLocal);
}
if (canReadPrimitiveArray)
{
_ilg.Else();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectWithIdMethod, objectId, _objectLocal);
_ilg.EndIf();
}
if (canReadSimpleDictionary)
{
_ilg.EndIf();
}
}
private void ReadSimpleDictionary(CollectionDataContract collectionContract, Type keyValueType)
{
Type[] keyValueTypes = keyValueType.GetGenericArguments();
Type keyType = keyValueTypes[0];
Type valueType = keyValueTypes[1];
int keyTypeNullableDepth = 0;
Type keyTypeOriginal = keyType;
while (keyType.IsGenericType && keyType.GetGenericTypeDefinition() == Globals.TypeOfNullable)
{
keyTypeNullableDepth++;
keyType = keyType.GetGenericArguments()[0];
}
ClassDataContract keyValueDataContract = (ClassDataContract)collectionContract.ItemContract;
DataContract keyDataContract = keyValueDataContract.Members[0].MemberTypeContract;
KeyParseMode keyParseMode = KeyParseMode.Fail;
if (keyType == Globals.TypeOfString || keyType == Globals.TypeOfObject)
{
keyParseMode = KeyParseMode.AsString;
}
else if (keyType.IsEnum)
{
keyParseMode = KeyParseMode.UsingParseEnum;
}
else if (keyDataContract.ParseMethod != null)
{
keyParseMode = KeyParseMode.UsingCustomParse;
}
if (keyParseMode == KeyParseMode.Fail)
{
ThrowSerializationException(
SR.Format(
SR.KeyTypeCannotBeParsedInSimpleDictionary,
DataContract.GetClrTypeFullName(collectionContract.UnderlyingType),
DataContract.GetClrTypeFullName(keyType)));
}
else
{
LocalBuilder nodeType = _ilg.DeclareLocal(typeof(XmlNodeType), "nodeType");
_ilg.BeginWhileCondition();
_ilg.Call(_xmlReaderArg, JsonFormatGeneratorStatics.MoveToContentMethod);
_ilg.Stloc(nodeType);
_ilg.Load(nodeType);
_ilg.Load(XmlNodeType.EndElement);
_ilg.BeginWhileBody(Cmp.NotEqualTo);
_ilg.Load(nodeType);
_ilg.Load(XmlNodeType.Element);
_ilg.If(Cmp.NotEqualTo);
ThrowUnexpectedStateException(XmlNodeType.Element);
_ilg.EndIf();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1);
if (keyParseMode == KeyParseMode.UsingParseEnum)
{
_ilg.Load(keyType);
}
_ilg.Load(_xmlReaderArg);
_ilg.Call(JsonFormatGeneratorStatics.GetJsonMemberNameMethod);
if (keyParseMode == KeyParseMode.UsingParseEnum)
{
_ilg.Call(JsonFormatGeneratorStatics.ParseEnumMethod);
_ilg.ConvertValue(Globals.TypeOfObject, keyType);
}
else if (keyParseMode == KeyParseMode.UsingCustomParse)
{
_ilg.Call(keyDataContract.ParseMethod);
}
LocalBuilder pairKey = _ilg.DeclareLocal(keyType, "key");
_ilg.Stloc(pairKey);
if (keyTypeNullableDepth > 0)
{
LocalBuilder pairKeyNullable = _ilg.DeclareLocal(keyTypeOriginal, "keyOriginal");
WrapNullableObject(pairKey, pairKeyNullable, keyTypeNullableDepth);
pairKey = pairKeyNullable;
}
LocalBuilder pairValue = ReadValue(valueType, string.Empty);
StoreKeyValuePair(_objectLocal, collectionContract, pairKey, pairValue);
_ilg.EndWhile();
}
}
private void ReadGetOnlyCollection(CollectionDataContract collectionContract)
{
Type type = collectionContract.UnderlyingType;
Type itemType = collectionContract.ItemType;
bool isArray = (collectionContract.Kind == CollectionKind.Array);
LocalBuilder size = _ilg.DeclareLocal(Globals.TypeOfInt, "arraySize");
_objectLocal = _ilg.DeclareLocal(type, "objectDeserialized");
_ilg.Load(_contextArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.GetCollectionMemberMethod);
_ilg.ConvertValue(Globals.TypeOfObject, type);
_ilg.Stloc(_objectLocal);
bool canReadSimpleDictionary = collectionContract.Kind == CollectionKind.Dictionary ||
collectionContract.Kind == CollectionKind.GenericDictionary;
if (canReadSimpleDictionary)
{
_ilg.Load(_contextArg);
_ilg.LoadMember(JsonFormatGeneratorStatics.UseSimpleDictionaryFormatReadProperty);
_ilg.If();
if (!type.IsValueType)
{
_ilg.If(_objectLocal, Cmp.EqualTo, null);
_ilg.Call(null, XmlFormatGeneratorStatics.ThrowNullValueReturnedForGetOnlyCollectionExceptionMethod, type);
_ilg.EndIf();
}
ReadSimpleDictionary(collectionContract, itemType);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.CheckEndOfArrayMethod, _xmlReaderArg, size, _memberNamesArg, _emptyDictionaryStringArg);
_ilg.Else();
}
//check that items are actually going to be deserialized into the collection
IsStartElement(_memberNamesArg, _emptyDictionaryStringArg);
_ilg.If();
if (!type.IsValueType)
{
_ilg.If(_objectLocal, Cmp.EqualTo, null);
_ilg.Call(null, XmlFormatGeneratorStatics.ThrowNullValueReturnedForGetOnlyCollectionExceptionMethod, type);
_ilg.EndIf();
}
if (isArray)
{
_ilg.Load(_objectLocal);
_ilg.Call(XmlFormatGeneratorStatics.GetArrayLengthMethod);
_ilg.Stloc(size);
}
LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i");
object forLoop = _ilg.For(i, 0, int.MaxValue);
IsStartElement(_memberNamesArg, _emptyDictionaryStringArg);
_ilg.If();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1);
LocalBuilder value = ReadCollectionItem(collectionContract, itemType);
if (isArray)
{
_ilg.If(size, Cmp.EqualTo, i);
_ilg.Call(null, XmlFormatGeneratorStatics.ThrowArrayExceededSizeExceptionMethod, size, type);
_ilg.Else();
_ilg.StoreArrayElement(_objectLocal, i, value);
_ilg.EndIf();
}
else
StoreCollectionValue(_objectLocal, value, collectionContract);
_ilg.Else();
IsEndElement();
_ilg.If();
_ilg.Break(forLoop);
_ilg.Else();
HandleUnexpectedItemInCollection(i);
_ilg.EndIf();
_ilg.EndIf();
_ilg.EndFor();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.CheckEndOfArrayMethod, _xmlReaderArg, size, _memberNamesArg, _emptyDictionaryStringArg);
_ilg.EndIf();
if (canReadSimpleDictionary)
{
_ilg.EndIf();
}
}
private bool TryReadPrimitiveArray(Type itemType)
{
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
if (primitiveContract == null)
return false;
string readArrayMethod = null;
switch (itemType.GetTypeCode())
{
case TypeCode.Boolean:
readArrayMethod = "TryReadBooleanArray";
break;
case TypeCode.Decimal:
readArrayMethod = "TryReadDecimalArray";
break;
case TypeCode.Int32:
readArrayMethod = "TryReadInt32Array";
break;
case TypeCode.Int64:
readArrayMethod = "TryReadInt64Array";
break;
case TypeCode.Single:
readArrayMethod = "TryReadSingleArray";
break;
case TypeCode.Double:
readArrayMethod = "TryReadDoubleArray";
break;
case TypeCode.DateTime:
readArrayMethod = "TryReadJsonDateTimeArray";
break;
default:
break;
}
if (readArrayMethod != null)
{
_ilg.Load(_xmlReaderArg);
_ilg.ConvertValue(typeof(XmlReaderDelegator), typeof(JsonReaderDelegator));
_ilg.Load(_contextArg);
_ilg.Load(_memberNamesArg);
// Empty namespace
_ilg.Load(_emptyDictionaryStringArg);
// -1 Array Size
_ilg.Load(-1);
_ilg.Ldloca(_objectLocal);
_ilg.Call(typeof(JsonReaderDelegator).GetMethod(readArrayMethod, Globals.ScanAllMembers));
return true;
}
return false;
}
private LocalBuilder ReadCollectionItem(CollectionDataContract collectionContract, Type itemType)
{
if (collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary)
{
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.ResetAttributesMethod);
LocalBuilder value = _ilg.DeclareLocal(itemType, "valueRead");
_ilg.Load(_collectionContractArg);
_ilg.Call(JsonFormatGeneratorStatics.GetItemContractMethod);
_ilg.Call(JsonFormatGeneratorStatics.GetRevisedItemContractMethod);
_ilg.Load(_xmlReaderArg);
_ilg.Load(_contextArg);
_ilg.Call(JsonFormatGeneratorStatics.ReadJsonValueMethod);
_ilg.ConvertValue(Globals.TypeOfObject, itemType);
_ilg.Stloc(value);
return value;
}
else
{
return ReadValue(itemType, JsonGlobals.itemString);
}
}
private void StoreCollectionValue(LocalBuilder collection, LocalBuilder value, CollectionDataContract collectionContract)
{
if (collectionContract.Kind == CollectionKind.GenericDictionary || collectionContract.Kind == CollectionKind.Dictionary)
{
ClassDataContract keyValuePairContract = DataContract.GetDataContract(value.LocalType) as ClassDataContract;
if (keyValuePairContract == null)
{
Fx.Assert("Failed to create contract for KeyValuePair type");
}
DataMember keyMember = keyValuePairContract.Members[0];
DataMember valueMember = keyValuePairContract.Members[1];
LocalBuilder pairKey = _ilg.DeclareLocal(keyMember.MemberType, keyMember.Name);
LocalBuilder pairValue = _ilg.DeclareLocal(valueMember.MemberType, valueMember.Name);
_ilg.LoadAddress(value);
_ilg.LoadMember(keyMember.MemberInfo);
_ilg.Stloc(pairKey);
_ilg.LoadAddress(value);
_ilg.LoadMember(valueMember.MemberInfo);
_ilg.Stloc(pairValue);
StoreKeyValuePair(collection, collectionContract, pairKey, pairValue);
}
else
{
_ilg.Call(collection, collectionContract.AddMethod, value);
if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid)
_ilg.Pop();
}
}
private void StoreKeyValuePair(LocalBuilder collection, CollectionDataContract collectionContract, LocalBuilder pairKey, LocalBuilder pairValue)
{
_ilg.Call(collection, collectionContract.AddMethod, pairKey, pairValue);
if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid)
_ilg.Pop();
}
private void HandleUnexpectedItemInCollection(LocalBuilder iterator)
{
IsStartElement();
_ilg.If();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.SkipUnknownElementMethod, _xmlReaderArg);
_ilg.Dec(iterator);
_ilg.Else();
ThrowUnexpectedStateException(XmlNodeType.Element);
_ilg.EndIf();
}
private void IsStartElement(ArgBuilder nameArg, ArgBuilder nsArg)
{
_ilg.Call(_xmlReaderArg, JsonFormatGeneratorStatics.IsStartElementMethod2, nameArg, nsArg);
}
private void IsStartElement()
{
_ilg.Call(_xmlReaderArg, JsonFormatGeneratorStatics.IsStartElementMethod0);
}
private void IsEndElement()
{
_ilg.Load(_xmlReaderArg);
_ilg.LoadMember(JsonFormatGeneratorStatics.NodeTypeProperty);
_ilg.Load(XmlNodeType.EndElement);
_ilg.Ceq();
}
private void ThrowUnexpectedStateException(XmlNodeType expectedState)
{
_ilg.Call(null, XmlFormatGeneratorStatics.CreateUnexpectedStateExceptionMethod, expectedState, _xmlReaderArg);
_ilg.Throw();
}
private void ThrowSerializationException(string msg, params object[] values)
{
if (values != null && values.Length > 0)
_ilg.CallStringFormat(msg, values);
else
_ilg.Load(msg);
ThrowSerializationException();
}
private void ThrowSerializationException()
{
_ilg.New(JsonFormatGeneratorStatics.SerializationExceptionCtor);
_ilg.Throw();
}
private enum KeyParseMode
{
Fail,
AsString,
UsingParseEnum,
UsingCustomParse
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Linq;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public static class CollectionImportTests
{
[Fact]
public static void ImportNull()
{
X509Certificate2Collection cc2 = new X509Certificate2Collection();
Assert.Throws<ArgumentNullException>(() => cc2.Import((byte[])null));
Assert.Throws<ArgumentNullException>(() => cc2.Import((string)null));
}
[Fact]
public static void ImportEmpty_Pkcs12()
{
var collection = new X509Certificate2Collection();
collection.Import(TestData.EmptyPfx);
Assert.Equal(0, collection.Count);
}
[Fact]
public static void ImportX509DerBytes()
{
var collection = new X509Certificate2Collection();
collection.Import(TestData.MsCertificate);
Assert.Equal(1, collection.Count);
}
[Fact]
public static void ImportX509PemBytes()
{
var collection = new X509Certificate2Collection();
collection.Import(TestData.MsCertificatePemBytes);
Assert.Equal(1, collection.Count);
}
[Fact]
public static void ImportX509DerFile()
{
var collection = new X509Certificate2Collection();
collection.Import(Path.Combine("TestData", "MS.cer"));
Assert.Equal(1, collection.Count);
}
[Fact]
public static void ImportX509PemFile()
{
var collection = new X509Certificate2Collection();
collection.Import(Path.Combine("TestData", "MS.pem"));
Assert.Equal(1, collection.Count);
}
[Fact]
public static void ImportPkcs7DerBytes_Empty()
{
var collection = new X509Certificate2Collection();
collection.Import(TestData.Pkcs7EmptyDerBytes);
Assert.Equal(0, collection.Count);
}
[Fact]
public static void ImportPkcs7PemBytes_Empty()
{
var collection = new X509Certificate2Collection();
collection.Import(TestData.Pkcs7EmptyPemBytes);
Assert.Equal(0, collection.Count);
}
[Fact]
public static void ImportPkcs7DerFile_Empty()
{
var collection = new X509Certificate2Collection();
collection.Import(Path.Combine("TestData", "empty.p7b"));
Assert.Equal(0, collection.Count);
}
[Fact]
public static void ImportPkcs7PemFile_Empty()
{
var collection = new X509Certificate2Collection();
collection.Import(Path.Combine("TestData", "empty.p7c"));
Assert.Equal(0, collection.Count);
}
[Fact]
public static void ImportPkcs7DerBytes_Single()
{
var collection = new X509Certificate2Collection();
collection.Import(TestData.Pkcs7SingleDerBytes);
Assert.Equal(1, collection.Count);
}
[Fact]
public static void ImportPkcs7PemBytes_Single()
{
var collection = new X509Certificate2Collection();
collection.Import(TestData.Pkcs7SinglePemBytes);
Assert.Equal(1, collection.Count);
}
[Fact]
public static void ImportPkcs7DerFile_Single()
{
var collection = new X509Certificate2Collection();
collection.Import(Path.Combine("TestData", "singlecert.p7b"));
Assert.Equal(1, collection.Count);
}
[Fact]
public static void ImportPkcs7PemFile_Single()
{
var collection = new X509Certificate2Collection();
collection.Import(Path.Combine("TestData", "singlecert.p7c"));
Assert.Equal(1, collection.Count);
}
[Fact]
public static void ImportPkcs7DerBytes_Chain()
{
var collection = new X509Certificate2Collection();
collection.Import(TestData.Pkcs7ChainDerBytes);
Assert.Equal(3, collection.Count);
}
[Fact]
public static void ImportPkcs7PemBytes_Chain()
{
var collection = new X509Certificate2Collection();
collection.Import(TestData.Pkcs7ChainPemBytes);
Assert.Equal(3, collection.Count);
}
[Fact]
public static void ImportPkcs7DerFile_Chain()
{
var collection = new X509Certificate2Collection();
collection.Import(Path.Combine("TestData", "certchain.p7b"));
Assert.Equal(3, collection.Count);
}
[Fact]
public static void ImportPkcs7PemFile_Chain()
{
var collection = new X509Certificate2Collection();
collection.Import(Path.Combine("TestData", "certchain.p7c"));
Assert.Equal(3, collection.Count);
}
[Fact]
public static void ImportPkcs12Bytes_Single()
{
X509Certificate2Collection cc2 = new X509Certificate2Collection();
cc2.Import(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.DefaultKeySet);
int count = cc2.Count;
Assert.Equal(1, count);
}
[Fact]
public static void ImportPkcs12Bytes_Single_VerifyContents()
{
using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
{
X509Certificate2Collection cc2 = new X509Certificate2Collection();
cc2.Import(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.DefaultKeySet);
int count = cc2.Count;
Assert.Equal(1, count);
using (X509Certificate2 c = cc2[0])
{
// pfxCer was loaded directly, cc2[0] was Imported, two distinct copies.
Assert.NotSame(pfxCer, c);
Assert.Equal(pfxCer, c);
Assert.Equal(pfxCer.Thumbprint, c.Thumbprint);
}
}
}
[Fact]
public static void ImportPkcs12File_Single()
{
X509Certificate2Collection cc2 = new X509Certificate2Collection();
cc2.Import(Path.Combine("TestData", "My.pfx"), TestData.PfxDataPassword, X509KeyStorageFlags.DefaultKeySet);
int count = cc2.Count;
Assert.Equal(1, count);
}
[Fact]
public static void ImportPkcs12Bytes_Chain()
{
X509Certificate2Collection certs = new X509Certificate2Collection();
certs.Import(TestData.ChainPfxBytes, TestData.ChainPfxPassword, X509KeyStorageFlags.DefaultKeySet);
int count = certs.Count;
Assert.Equal(3, count);
}
[Fact]
public static void ImportPkcs12File_Chain()
{
X509Certificate2Collection certs = new X509Certificate2Collection();
certs.Import(Path.Combine("TestData", "test.pfx"), TestData.ChainPfxPassword, X509KeyStorageFlags.DefaultKeySet);
int count = certs.Count;
Assert.Equal(3, count);
}
[Fact]
public static void ImportPkcs12File_Chain_VerifyContents()
{
X509Certificate2Collection certs = new X509Certificate2Collection();
certs.Import(Path.Combine("TestData", "test.pfx"), TestData.ChainPfxPassword, X509KeyStorageFlags.DefaultKeySet);
int count = certs.Count;
Assert.Equal(3, count);
// Verify that the read ordering is consistent across the platforms
string[] expectedSubjects =
{
"MS Passport Test Sub CA",
"MS Passport Test Root CA",
"test.local",
};
string[] actualSubjects = certs.OfType<X509Certificate2>().
Select(cert => cert.GetNameInfo(X509NameType.SimpleName, false)).
ToArray();
Assert.Equal(expectedSubjects, actualSubjects);
// And verify that we have private keys when we expect them
bool[] expectedHasPrivateKeys =
{
false,
false,
true,
};
bool[] actualHasPrivateKeys = certs.OfType<X509Certificate2>().
Select(cert => cert.HasPrivateKey).
ToArray();
Assert.Equal(expectedHasPrivateKeys, actualHasPrivateKeys);
}
}
}
| |
namespace Zutatensuppe.DiabloInterface.Gui.Controls
{
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using Zutatensuppe.D2Reader;
using Zutatensuppe.D2Reader.Models;
using Zutatensuppe.DiabloInterface.Lib;
using Zutatensuppe.DiabloInterface.Lib.Extensions;
using Zutatensuppe.DiabloInterface.Lib.Services;
class Def
{
public string name;
public string maxString;
public Func<ApplicationConfig, Tuple<bool, Color, int>> settings;
public Label[] labels;
public Dictionary<Label, string> defaults;
public bool enabled;
public Def(string name, string maxString, Func<ApplicationConfig, Tuple<bool, Color, int>> settings, string[] labels)
{
this.name = name;
this.maxString = maxString;
this.settings = settings;
this.labels = (from n in labels select new Label() { Text = n }).ToArray();
this.defaults = new Dictionary<Label, string>();
this.enabled = false;
foreach (Label l in this.labels)
{
this.defaults.Add(l, l.Text);
}
}
}
abstract class AbstractLayout : UserControl
{
static readonly Lib.ILogger Logger = Lib.Logging.CreateLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected IDiabloInterface di;
protected Dictionary<string, Def> def = new Dictionary<string, Def>();
protected bool realFrwIas;
GameDifficulty? activeDifficulty;
CharacterClass? activeCharacterClass;
protected IEnumerable<FlowLayoutPanel> RunePanels { get; set; }
protected abstract Panel RuneLayoutPanel { get; }
protected void Add(
string nam,
string maxStr,
Func<ApplicationConfig, Tuple<bool, Color, int>> s,
params string[] names
)
{
def.Add(nam, new Def(nam, maxStr, s, names));
}
protected Font CreateFont(string name, int size)
{
try
{
return new Font(name, size);
}
catch
{
return new Font(DefaultFont.FontFamily.Name, size);
}
}
public static string ReplaceFirst(string text, string search, string replace)
{
int pos = text.IndexOf(search);
if (pos < 0)
return text;
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}
protected void UpdateLabel(string nam, string[] values, bool visible = true)
{
if (!def[nam].enabled)
return;
foreach (Label l in def[nam].labels)
{
l.Visible = visible;
var text = def[nam].defaults[l];
foreach (var value in values)
{
text = ReplaceFirst(text, "{}", value);
}
l.Text = text;
}
}
protected void UpdateLabel(string nam, string value, bool visible = true)
{
if (!def[nam].enabled)
return;
foreach (Label l in def[nam].labels)
{
l.Visible = visible;
l.Text = def[nam].defaults[l].Replace("{}", value);
}
}
protected void UpdateLabel(string nam, int value, bool visible = true)
{
UpdateLabel(nam, "" + value, visible);
}
protected void UpdateLabel(string nam, uint value, bool visible = true)
{
UpdateLabel(nam, "" + value, visible);
}
protected void RegisterServiceEventHandlers()
{
di.configService.Changed += SettingsServiceOnSettingsChanged;
di.game.DataRead += GameServiceOnDataRead;
}
protected void UnregisterServiceEventHandlers()
{
di.configService.Changed -= SettingsServiceOnSettingsChanged;
di.game.DataRead -= GameServiceOnDataRead;
}
void SettingsServiceOnSettingsChanged(object sender, ApplicationConfigEventArgs e)
{
if (InvokeRequired)
{
Invoke((Action)(() => SettingsServiceOnSettingsChanged(sender, e)));
return;
}
activeCharacterClass = null;
UpdateConfig(e.Config);
}
string lastGuid;
void GameServiceOnDataRead(object sender, DataReadEventArgs e)
{
if (InvokeRequired)
{
Invoke((Action)(() => GameServiceOnDataRead(sender, e)));
return;
}
if (lastGuid != e.Character.Guid)
{
Reset();
lastGuid = e.Character.Guid;
}
UpdateLabels(e.Character, e.Quests, e.Game);
UpdateClassRuneList(e.Character.CharClass);
UpdateRuneDisplay(e.Character.InventoryItemIds);
}
public void Reset()
{
foreach (FlowLayoutPanel fp in RunePanels)
{
if (fp.Controls.Count <= 0)
continue;
foreach (RuneDisplayElement c in fp.Controls)
{
c.SetHaveRune(false);
}
}
foreach (KeyValuePair<string, Def> pair in def)
{
foreach (Label l in pair.Value.labels)
{
l.Text = pair.Value.defaults[l];
}
}
}
abstract protected void UpdateConfig(ApplicationConfig config);
abstract protected void UpdateLabels(Character player, Quests quests, Game game);
void UpdateClassRuneList(CharacterClass characterClass)
{
var config = di.configService.CurrentConfig;
if (!config.DisplayRunes) return;
var targetDifficulty = di.game.TargetDifficulty;
var isCharacterClassChanged = activeCharacterClass == null || activeCharacterClass != characterClass;
var isGameDifficultyChanged = activeDifficulty != targetDifficulty;
if (!isCharacterClassChanged && !isGameDifficultyChanged)
return;
Logger.Info("Loading rune list.");
var runeSettings = GetMostSpecificRuneSettings(characterClass, targetDifficulty);
UpdateRuneList(config, runeSettings?.Runes?.ToList());
activeDifficulty = targetDifficulty;
activeCharacterClass = characterClass;
}
void UpdateRuneList(ApplicationConfig config, IReadOnlyList<Rune> runes)
{
var panel = RuneLayoutPanel;
if (panel == null) return;
panel.Controls.ClearAndDispose();
panel.Visible = runes?.Count > 0;
runes?.ForEach(rune => panel.Controls.Add(
new RuneDisplayElement(rune, config.DisplayRunesHighContrast, false, false)));
}
/// <summary>
/// Gets the most specific rune settings in the order:
/// Class+Difficulty > Class > Difficulty > None
/// </summary>
/// <param name="characterClass">Active character class.</param>
/// <param name="targetDifficulty">Manual difficulty selection.</param>
/// <returns>The rune settings.</returns>
IClassRuneSettings GetMostSpecificRuneSettings(CharacterClass characterClass, GameDifficulty targetDifficulty)
{
IEnumerable<IClassRuneSettings> runeClassSettings = di.configService.CurrentConfig.ClassRunes.ToList();
return runeClassSettings.FirstOrDefault(rs => rs.Class == characterClass && rs.Difficulty == targetDifficulty)
?? runeClassSettings.FirstOrDefault(rs => rs.Class == characterClass && rs.Difficulty == null)
?? runeClassSettings.FirstOrDefault(rs => rs.Class == null && rs.Difficulty == targetDifficulty)
?? runeClassSettings.FirstOrDefault(rs => rs.Class == null && rs.Difficulty == null);
}
void UpdateRuneDisplay(IEnumerable<int> itemIds)
{
var panel = RuneLayoutPanel;
if (panel == null) return;
// Count number of items of each type.
Dictionary<int, int> itemClassCounts = itemIds
.GroupBy(id => id)
.ToDictionary(g => g.Key, g => g.Count());
foreach (RuneDisplayElement runeElement in panel.Controls)
{
var itemClassId = (int)runeElement.Rune + 610;
if (itemClassCounts.ContainsKey(itemClassId) && itemClassCounts[itemClassId] > 0)
{
itemClassCounts[itemClassId]--;
runeElement.SetHaveRune(true);
}
}
}
protected Size MeasureText(string str, Control control)
{
return TextRenderer.MeasureText(str, control.Font, Size.Empty, TextFormatFlags.SingleLine);
}
}
}
| |
namespace DotNetXri.Client.Resolve {
using System.Text;
using DotNetXri.Client.Xml;
using System.Collections;
using System;
using DotNetXri.Syntax;
using DotNetXri.Loggers;
public class SEPSelector {
private static ILog log = Logger.Create(typeof(Service));
public static List select(List seps, string inType, string inMediaType, string inPath, ResolverFlags flags) {
int n = seps.Count;
ArrayList sepOut = new ArrayList();
ArrayList defaultSepOut = new ArrayList(n);
bool noDefaultType = flags.isNoDefaultT();
bool noDefaultPath = flags.isNoDefaultP();
bool noDefaultMediaType = flags.isNoDefaultM();
// every SEP has each of the flags
bool[] positiveType = new bool[n];
bool[] positivePath = new bool[n];
bool[] positiveMediaType = new bool[n];
bool[] defaultType = new bool[n];
bool[] defaultPath = new bool[n];
bool[] defaultMediaType = new bool[n];
bool[] presentType = new bool[n];
bool[] presentPath = new bool[n];
bool[] presentMediaType = new bool[n];
log.Info("select type='" + inType + "' mtype='" + inMediaType + "' path='" + inPath + "' len(SEPs)=" + n);
for (int i = 0; i < n; i++) {
ArrayList sels;
IEnumerator it;
Service sep = (Service)seps[i];
defaultSepOut.Add(null); // occupy the slot by setting to null
log.Info("SEPSelector.select SEP[" + i + "] = " + sep);
// flag to continue main loop from SEL loop
bool sepDone = false;
/// do Type SELs
sepDone = false;
sels = sep.getTypes();
for (it = sels.GetEnumerator(); it.MoveNext(); ) {
SEPType typeSEL = (SEPType)it.Current;
presentType[i] = true;
if (matchSEL(typeSEL, inType)) {
if (typeSEL.getSelect()) {
log.Info("SEPSelector.select SEP[" + i + "] Type is selected.");
sepOut.Add(sep);
sepDone = true;
break; // next sep
} else {
log.Info("SEPSelector.select SEP[" + i + "] Type is a positive match.");
positiveType[i] = true;
}
} else if (!noDefaultType && !positiveType[i] && isDefaultMatch(typeSEL)) {
log.Info("SEPSelector.select SEP[" + i + "] Type is a default match.");
defaultType[i] = true;
}
} // end-foreach type-sel
if (sepDone)
continue;
if (!presentType[i] && !noDefaultType) {
log.Info("SEPSelector.select SEP[" + i + "] Type is a default match (no Type element found).");
defaultType[i] = true;
}
/// do Path SELs
sepDone = false;
sels = sep.getPaths();
for (it = sels.GetEnumerator(); it.MoveNext(); ) {
SEPPath pathSEL = (SEPPath)it.Current;
presentPath[i] = true;
if (matchSEL(pathSEL, inPath)) {
if (pathSEL.getSelect()) {
log.Info("SEPSelector.select SEP[" + i + "] Path is selected.");
sepOut.Add(sep);
sepDone = true;
break; // next sep
} else {
log.Info("SEPSelector.select SEP[" + i + "] Path is a positive match.");
positivePath[i] = true;
}
} else if (!noDefaultPath && !positivePath[i] && isDefaultMatch(pathSEL)) {
log.Info("SEPSelector.select SEP[" + i + "] Path is a default match.");
defaultPath[i] = true;
}
} // end-foreach path-sel
if (sepDone)
continue;
if (!presentPath[i] && !noDefaultPath) {
log.Info("SEPSelector.select SEP[" + i + "] Path is a default match (no Path element found).");
defaultPath[i] = true;
}
/// do MediaType SELs
sepDone = false;
sels = sep.getMediaTypes();
for (it = sels.GetEnumerator(); it.MoveNext(); ) {
SEPMediaType mediaTypeSEL = (SEPMediaType)it.Current;
presentMediaType[i] = true;
if (matchSEL(mediaTypeSEL, inMediaType)) {
if (mediaTypeSEL.getSelect()) {
log.Info("SEPSelector.select SEP[" + i + "] MediaType is selected.");
sepOut.Add(sep);
sepDone = true;
break; // next sep
} else {
log.Info("SEPSelector.select SEP[" + i + "] MediaType is a positive match.");
positiveMediaType[i] = true;
}
} else if (!noDefaultMediaType && !positiveMediaType[i] && isDefaultMatch(mediaTypeSEL)) {
log.Info("SEPSelector.select SEP[" + i + "] MediaType is a default match.");
defaultMediaType[i] = true;
}
} // end-foreach mediatype-sel
if (sepDone)
continue;
if (!presentMediaType[i] && !noDefaultMediaType) {
log.Info("SEPSelector.select SEP[" + i + "] MediaType is a default match (no MediaType element found).");
defaultMediaType[i] = true;
}
if (positiveType[i] && positivePath[i] && positiveMediaType[i]) {
log.Info("SEPSelector.select SEP[" + i + "] is an ALL positive match.");
sepOut.Add(sep);
// next sep
} else if (sepOut.Count == 0 && (
(positiveType[i] || defaultType[i]) &&
(positivePath[i] || defaultPath[i]) &&
(positiveMediaType[i] || defaultMediaType[i]))
) {
log.Info("SEPSelector.select SEP[" + i + "] is a default match.");
defaultSepOut[i] = sep; // instead of using add(), override the null at this index pos
}
} // end-foreach sep
if (sepOut.Count == 0) {
int[] numMatches = new int[n];
for (int i = 0; i < n; i++) {
object sep = defaultSepOut[i];
if (sep == null)
continue;
if (positiveType[i])
numMatches[i]++;
if (positivePath[i])
numMatches[i]++;
if (positiveMediaType[i])
numMatches[i]++;
}
/// add the seps with default match and has 2 positive matches
for (int i = 0; i < n; i++) {
if (numMatches[i] >= 2) {
log.Info("SEPSelector.select Phase 2 - SEP[" + i + "] is selected for having 2 positive matches.");
sepOut.Add(seps[i]);
}
}
/// still empty, add those seps with default match and has 1 positive match
if (sepOut.Count == 0) {
for (int i = 0; i < n; i++) {
if (numMatches[i] == 1) {
log.Info("SEPSelector.select Phase 2 - SEP[" + i + "] is selected for having 1 positive match.");
sepOut.Add(seps[i]);
}
}
}
/// still empty? add the default seps
if (sepOut.Count == 0) {
for (int i = 0; i < n; i++) {
object sep = defaultSepOut[i];
if (sep != null) {
log.Info("SEPSelector.select Phase 2 - SEP[" + i + "] is selected for being a default match.");
sepOut.Add(sep);
}
}
}
}
return sepOut;
}
public static bool isDefaultMatch(SEPElement sel) {
string m = sel.getMatch();
return (m != null && m.Equals(SEPElement.MATCH_ATTR_DEFAULT));
}
/* This method is used to match the element of the service */
private static bool matchSEL(SEPElement element, string inValue) {
string matchAttr = element.getMatch();
string selVal = element.getValue();
if (matchAttr != null) {
if (matchAttr.Equals(SEPElement.MATCH_ATTR_ANY))
return true;
else if (matchAttr.Equals(SEPElement.MATCH_ATTR_NON_NULL)) {
return (inValue != null && inValue.Length > 0);
} else if (matchAttr.Equals(SEPElement.MATCH_ATTR_NULL)) {
return (inValue == null || inValue.Length == 0);
}
/*
else if (elementMatch.Equals(SEPElement.MATCH_ATTR_NONE)) {
return false;
}
*/
// fall through
}
// In CD02 if "match" attribute is absent, we match content
if (matchAttr == null || matchAttr.Equals(SEPElement.MATCH_ATTR_CONTENT)) {
// special case: input value is null (against e.g. <Path />)
if (inValue == null || inValue.Length == 0)
return (selVal.Length == 0);
if (element is SEPType)
return matchType(selVal, inValue);
else if (element is SEPPath)
return matchPath(selVal, inValue);
else if (element is SEPMediaType)
return matchMediaType(selVal, inValue);
else
throw new RuntimeException("Unsupported SEL");
}
// MATCH_ATTR_DEFAULT is not considered here because it is checked elsewhere
return false;
}
public static bool matchType(string selType, string inType) {
return inType.Equals(selType);
}
public static bool matchPath(string selPath, string inPath) {
// XXX use Unicode caseless matching
if (inPath.Equals(selPath, StringComparison.OrdinalIgnoreCase))
return true;
log.Info("xrdPath = '" + selPath + "'");
log.Info("inputPath = '" + inPath + "'");
if (selPath.Length > 0 && selPath[0] != '/')
selPath = '/' + selPath; // prepend leading slash
try {
XRIAbsolutePath xrdAbsPath = new XRIAbsolutePath(selPath);
XRIAbsolutePath inputAbsPath = new XRIAbsolutePath(inPath);
return xrdAbsPath.isPrefixOf(inputAbsPath);
} catch (XRIParseException e) {
log.Error("matchPath(selPath='" + selPath + "', inPath='" + inPath + "' - XRIParseException caught: " + e.getMessage());
return false;
}
}
public static bool matchMediaType(string selMediaType, string inMediaType) {
MimeType candidateMimeType = MimeType.parse(inMediaType);
MimeType critMimeType = MimeType.parse(selMediaType);
return critMimeType.Equals(candidateMimeType);
}
private ArrayList seps = null;
private string matchTypeValue = null;
private string matchMediaTypeValue = null;
private string matchPathValue = null;
private bool matchedNonDefaultType = false;
private bool matchedNonDefaultMediaType = false;
private bool matchedNonDefaultPath = false;
// cloned copies of seps, these are changed for, why cloned
// because in the phase 1 of matching of classes asumes the
// some default values of match attribute, that are required
// for select rules, otherwise requires to check default values
// of match attributes in phase2 (select) + also keep the indexes remove all later
private ArrayList matchedPhase1List = null;
// by the end of phase2 will have finally selected indexs (pointers to seps list)
private ArrayList indexes = new ArrayList();
public SEPSelector(ArrayList pSeps) {
seps = pSeps;
}
public void reset() {
seps = null;
}
public ArrayList getSelectedSEPs(string type, string mediaType, string path) {
this.matchTypeValue = type;
this.matchMediaTypeValue = mediaType;
this.matchPathValue = path;
this.matchedNonDefaultType = false;
this.matchedNonDefaultMediaType = false;
this.matchedNonDefaultPath = false;
matchedPhase1List = new ArrayList();
applyMatchingRules();
removeMatchDefaults();
applySelectionRules();
ArrayList returnList = new ArrayList();
for (int i = 0; i < seps.Count; i++) {
// eliminate all the elements that must be removed using indexes list
int inx = i;
if (!indexes.Contains(inx)) {
returnList.Add(seps[i]);
}
}
matchedPhase1List.Clear();
indexes.Clear();
return returnList;
}
private bool applyMatchingRules() {
try {
for (int i = 0; i < seps.Count; i++) {
Service service = (Service)seps[i];
service = (Service)service.clone();
ArrayList types = service.getTypes();
ArrayList mtypes = service.getMediaTypes();
ArrayList paths = service.getPaths();
ArrayList elements = new ArrayList();
/* rule 1 is applied after 2, 3, 4 for processing optimization
* if SEP element is omited consider <element match="default" />
* according specs this would resort if matching elements found */
if (types.Count == 0) {
SEPType type = new SEPType(null, SEPElement.MATCH_ATTR_DEFAULT, false);
service.addType(type);
types = service.getTypes();
}
if (mtypes.Count == 0) {
SEPMediaType mtype = new SEPMediaType(null, SEPElement.MATCH_ATTR_DEFAULT, false);
service.addMediaType(mtype);
mtypes = service.getMediaTypes();
}
if (paths.Count == 0) {
SEPPath path = new SEPPath(null, SEPElement.MATCH_ATTR_DEFAULT, false);
service.addPath(path);
paths = service.getPaths();
}
/* Rule 2 follows the naturally the element value is null */
/* Rule 3 if element present but match attribute omitted or null
* examples: <Type /> or <Type>xxxx</Type> or
* <Type match="" /> or <Type match="">yyyy</Type>
* Then set match="content"
*/
elements.AddRange(service.getTypes());
elements.AddRange(service.getMediaTypes());
elements.AddRange(service.getPaths());
// anytime we find an element that has match="none", we will
// skip the service entirely.
// Should be optimized and merged into one of the loops below
bool foundMatchNone = false;
for (int j = 0; j < elements.Count; j++) {
SEPElement element = (SEPElement)elements[j];
if (element.getMatch() != null && element.getMatch().Equals(SEPElement.MATCH_ATTR_NONE)) {
foundMatchNone = true;
}
}
if (foundMatchNone) {
// skip this service by adding a null reference so
// our index is not screwed... UGLY!!!
matchedPhase1List.Add(null);
continue;
}
// set the default match attribute, should be optimized by merging with
// one of the loops below
for (int j = 0; j < elements.Count; j++) {
SEPElement element = (SEPElement)elements[j];
if (element.getMatch() == null || element.getMatch().Equals("")) {
element.setMatch(SEPElement.MATCH_ATTR_CONTENT);
}
}
ArrayList output = new ArrayList();
/* Rule 4 use table 20 (XRI specs march 2006 wd10 ) to match rules */
for (int j = 0; j < types.Count; j++) {
SEPElement element = (SEPElement)types[j];
if (element.getMatch().Equals(SEPElement.MATCH_ATTR_DEFAULT)) {
// retain match="default"
output.Add(element);
} else if (match(element)) {
matchedNonDefaultType = true;
output.Add(element);
}
}
types = output;
service.setTypes(types);
output = new ArrayList();
for (int j = 0; j < mtypes.Count; j++) {
SEPElement element = (SEPElement)mtypes[j];
if (element.getMatch().Equals(SEPElement.MATCH_ATTR_DEFAULT)) {
output.Add(element);
} else if (match(element)) {
matchedNonDefaultMediaType = true;
output.Add(element);
}
}
mtypes = output;
service.setMediaTypes(mtypes);
output = new ArrayList();
for (int j = 0; j < paths.Count; j++) {
SEPElement element = (SEPElement)paths[j];
if (element.getMatch().Equals(SEPElement.MATCH_ATTR_DEFAULT)) {
output.Add(element);
} else if (match(element)) {
matchedNonDefaultPath = true;
output.Add(element);
}
}
paths = output;
service.setPaths(paths);
matchedPhase1List.Add(service);
}
} catch (CloneNotSupportedException cnse) {
log.Error("This should not happen as we implemented Service.clone() - the only clone call we make here");
throw new RuntimeException("Internal error: " + cnse.getMessage());
}
return true;
}
private bool removeMatchDefaults() {
for (int i = 0; i < matchedPhase1List.Count; i++) {
Service sep = (Service)matchedPhase1List[i];
if (sep == null) continue; // inactive service
// earlier we found a non-default match for Type element,
// remove all the match="default" elements
if (matchedNonDefaultType) {
ArrayList newTypes = new ArrayList();
for (int j = 0; j < sep.getTypes().Count; j++) {
SEPElement element = (SEPElement)sep.getTypes()[j];
if (!element.getMatch().Equals(SEPElement.MATCH_ATTR_DEFAULT)) {
newTypes.Add(element);
} else log.Info("removeMatchDefaults - removing Type[" + j + "] from Service[" + i + "]");
}
sep.setTypes(newTypes);
}
if (matchedNonDefaultPath) {
ArrayList newPaths = new ArrayList();
for (int j = 0; j < sep.getPaths().Count; j++) {
SEPElement element = (SEPElement)sep.getPaths()[j];
if (!element.getMatch().Equals(SEPElement.MATCH_ATTR_DEFAULT)) {
newPaths.Add(element);
} else log.Info("removeMatchDefaults - removing Path[" + j + "] from Service[" + i + "]");
}
sep.setPaths(newPaths);
}
if (matchedNonDefaultMediaType) {
ArrayList newMediaTypes = new ArrayList();
for (int j = 0; j < sep.getMediaTypes().Count; j++) {
SEPElement element = (SEPElement)sep.getMediaTypes()[j];
if (!element.getMatch().Equals(SEPElement.MATCH_ATTR_DEFAULT)) {
newMediaTypes.Add(element);
} else log.Info("removeMatchDefaults - removing MediaType[" + j + "] from Service[" + i + "]");
}
sep.setMediaTypes(newMediaTypes);
}
}
return true;
}
private bool applySelectionRules() {
for (int i = 0; i < matchedPhase1List.Count; i++) {
Service sep = (Service)matchedPhase1List[i];
if (sep == null) {
log.Debug("applySelectionRules - service[" + i + "] is inactive");
// inactive service
} else if (!canBeSelected(sep)) {
log.Debug("applySelectionRules - service[" + i + "] will not be selected");
indexes.Add(i);
} else {
log.Debug("applySelectionRules - service[" + i + "] is good to go");
}
}
return true;
}
/* The input service elements contain all matched elements of service
* We assume all the service elements met the criteria and filtered
* as per the matching rules applied before applying select criteria
*/
private bool canBeSelected(Service service) {
ArrayList elements = new ArrayList();
elements.AddRange(service.getTypes());
elements.AddRange(service.getMediaTypes());
elements.AddRange(service.getPaths());
/*
* Section 8.3
* Rule 1 - if any of the elements has a match attribute value of 'none', do not select the service
* (shouldn't this be done in the matching phase?)
* Rule 2 - OR operation any element of service matches then select this service
* Rule 3 - case when select is false
* ie.e AND operation => at least one matchTypeValue, mediatype & matchPathValue must match
*/
bool typeMatched = false;
bool mediaTypeMatched = false;
bool pathMatched = false;
bool selectService = false;
for (int i = 0; i < elements.Count; i++) {
SEPElement element = (SEPElement)elements[i];
if (element.getMatch().Equals(SEPElement.MATCH_ATTR_NONE))
// rule 1 - do not select this service when any element has match="none"
return false;
if (element.getSelect())
selectService = true;
if (element is SEPType) {
typeMatched = true;
} else if (element is SEPMediaType) {
mediaTypeMatched = true;
} else if (element is SEPPath) {
pathMatched = true;
}
}
if (selectService || (typeMatched && mediaTypeMatched && pathMatched)) {
return true;
}
return false;
}
/* This method is used to match the element of the service */
private bool match(SEPElement element) {
string elementMatch = element.getMatch();
string elementValue = element.getValue();
string matchElementValue = null;
if (element is SEPType) {
matchElementValue = this.matchTypeValue;
} else if (element is SEPMediaType) {
matchElementValue = this.matchMediaTypeValue;
} else if (element is SEPPath) {
matchElementValue = this.matchPathValue;
}
if (elementMatch.Equals(SEPElement.MATCH_ATTR_CONTENT)) {
if (matchElementValue == null && elementValue == null) return true;
if (matchElementValue != null && elementValue == null) return false;
if (matchElementValue == null && elementValue != null) return false;
return matchContent(element);
}
if (elementMatch.Equals(SEPElement.MATCH_ATTR_ANY)) {
return true;
}
if (elementMatch.Equals(SEPElement.MATCH_ATTR_NON_NULL)) {
if (matchElementValue != null && matchElementValue.Length != 0)
return true;
return false;
}
if (elementMatch.Equals(SEPElement.MATCH_ATTR_NULL)) {
if (matchElementValue == null || matchElementValue.Length == 0)
return true;
return false;
}
if (elementMatch.Equals(SEPElement.MATCH_ATTR_NONE)) {
return false;
}
// MATCH_ATTR_DEFAULT is not considered here because it should always stay
// (whether internally added or already present in the original XRDS)
// during the matching phase, and only removed if other non-default
// elements are matched.
return false;
}
public bool matchContent(SEPElement candidate) {
if (candidate is SEPType) {
return matchContent((SEPType)candidate);
} else if (candidate is SEPPath) {
return matchContent((SEPPath)candidate);
} else if (candidate is SEPMediaType) {
return matchContent((SEPMediaType)candidate);
}
return false;
}
public bool matchContent(SEPType type) {
return this.matchTypeValue.Equals(type.getValue());
}
public bool matchContent(SEPPath path) {
string xrdPath = trimPath(path.getValue());
string inputPath = trimPath(this.matchPathValue);
// try verbatim match (caseless)
if (inputPath.Equals(xrdPath, StringComparison.OrdinalIgnoreCase))
return true;
log.Info("xrdPath = '" + xrdPath + "'");
log.Info("inputPath = '" + inputPath + "'");
XRIAbsolutePath xrdAbsPath = new XRIAbsolutePath("/" + xrdPath);
XRIAbsolutePath inputAbsPath = new XRIAbsolutePath("/" + inputPath);
return xrdAbsPath.isPrefixOf(inputAbsPath);
}
public bool matchContent(SEPMediaType mtype) {
MimeType candidateMimeType = MimeType.parse(mtype.getValue());
MimeType critMimeType = MimeType.parse(this.matchMediaTypeValue);
return critMimeType.Equals(candidateMimeType);
}
/**
* Removes trailing delimiters '/', '*' or '!'
* @param path
* @return
*/
private string trimPath(string path) {
StringBuilder sb = new StringBuilder(path.Trim());
while (sb.Length > 0) {
char last = sb[sb.Length - 1];
if (last == '/' || last == '*' || last == '!')
sb.Remove(sb.Length - 1, 1);
else
break;
}
return sb.ToString();
}
}
}
| |
#region Header
/*
* The authors disclaim copyright to this source code.
* For more details, see the COPYING file included with this distribution.
*/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace LitJson {
internal class FsmContext {
public Lexer L;
public bool Return;
public int NextState, StateStack;
}
/// <summary>
/// JSON lexer implementation based on a finite state machine.
/// </summary>
internal class Lexer {
private delegate bool StateHandler (FsmContext ctx);
private static int[] returnTable;
private static StateHandler[] handlerTable;
private int inputBuffer, inputChar, state, unichar;
private FsmContext context;
private TextReader reader;
private StringBuilder stringBuffer;
public bool AllowComments { get; set; }
public bool AllowSingleQuotedStrings { get; set; }
public bool EndOfInput { get; private set; }
public int Token { get; private set; }
public string StringValue { get; private set; }
static Lexer() {
PopulateFsmTables();
}
public Lexer(TextReader reader) {
AllowComments = true;
AllowSingleQuotedStrings = true;
inputBuffer = 0;
stringBuffer = new StringBuilder(128);
state = 1;
EndOfInput = false;
this.reader = reader;
context = new FsmContext();
context.L = this;
}
private static int HexValue(int digit) {
switch (digit) {
case 'a':
case 'A':
return 10;
case 'b':
case 'B':
return 11;
case 'c':
case 'C':
return 12;
case 'd':
case 'D':
return 13;
case 'e':
case 'E':
return 14;
case 'f':
case 'F':
return 15;
default:
return digit - '0';
}
}
private static void PopulateFsmTables() {
// See section A.1. of the manual for details of the finite state machine.
handlerTable = new StateHandler[28] {
State1,
State2,
State3,
State4,
State5,
State6,
State7,
State8,
State9,
State10,
State11,
State12,
State13,
State14,
State15,
State16,
State17,
State18,
State19,
State20,
State21,
State22,
State23,
State24,
State25,
State26,
State27,
State28
};
returnTable = new int[28] {
(int)ParserToken.Char,
0,
(int)ParserToken.Number,
(int)ParserToken.Number,
0,
(int)ParserToken.Number,
0,
(int)ParserToken.Number,
0,
0,
(int)ParserToken.True,
0,
0,
0,
(int)ParserToken.False,
0,
0,
(int)ParserToken.Null,
(int)ParserToken.CharSeq,
(int)ParserToken.Char,
0,
0,
(int)ParserToken.CharSeq,
(int)ParserToken.Char,
0,
0,
0,
0
};
}
private static char ProcessEscChar (int escChar) {
switch (escChar) {
case '"':
case '\'':
case '\\':
case '/':
return Convert.ToChar(escChar);
case 'n':
return '\n';
case 't':
return '\t';
case 'r':
return '\r';
case 'b':
return '\b';
case 'f':
return '\f';
default:
// Unreachable
return '?';
}
}
private static bool State1(FsmContext ctx) {
while (ctx.L.GetChar()) {
if (ctx.L.inputChar == ' ' ||
ctx.L.inputChar >= '\t' && ctx.L.inputChar <= '\r') {
continue;
}
if (ctx.L.inputChar >= '1' && ctx.L.inputChar <= '9') {
ctx.L.stringBuffer.Append ((char) ctx.L.inputChar);
ctx.NextState = 3;
return true;
}
switch (ctx.L.inputChar) {
case '"':
ctx.NextState = 19;
ctx.Return = true;
return true;
case ',':
case ':':
case '[':
case ']':
case '{':
case '}':
ctx.NextState = 1;
ctx.Return = true;
return true;
case '-':
ctx.L.stringBuffer.Append ((char) ctx.L.inputChar);
ctx.NextState = 2;
return true;
case '0':
ctx.L.stringBuffer.Append ((char) ctx.L.inputChar);
ctx.NextState = 4;
return true;
case 'f':
ctx.NextState = 12;
return true;
case 'n':
ctx.NextState = 16;
return true;
case 't':
ctx.NextState = 9;
return true;
case '\'':
if (!ctx.L.AllowSingleQuotedStrings) {
return false;
}
ctx.L.inputChar = '"';
ctx.NextState = 23;
ctx.Return = true;
return true;
case '/':
if (!ctx.L.AllowComments) {
return false;
}
ctx.NextState = 25;
return true;
default:
return false;
}
}
return true;
}
private static bool State2(FsmContext ctx) {
ctx.L.GetChar();
if (ctx.L.inputChar >= '1' && ctx.L.inputChar <= '9') {
ctx.L.stringBuffer.Append((char)ctx.L.inputChar);
ctx.NextState = 3;
return true;
}
switch (ctx.L.inputChar) {
case '0':
ctx.L.stringBuffer.Append((char)ctx.L.inputChar);
ctx.NextState = 4;
return true;
default:
return false;
}
}
private static bool State3(FsmContext ctx) {
while (ctx.L.GetChar()) {
if (ctx.L.inputChar >= '0' && ctx.L.inputChar <= '9') {
ctx.L.stringBuffer.Append((char)ctx.L.inputChar);
continue;
}
if (ctx.L.inputChar == ' ' ||
ctx.L.inputChar >= '\t' && ctx.L.inputChar <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.inputChar) {
case ',':
case ']':
case '}':
ctx.L.UngetChar();
ctx.Return = true;
ctx.NextState = 1;
return true;
case '.':
ctx.L.stringBuffer.Append((char)ctx.L.inputChar);
ctx.NextState = 5;
return true;
case 'e':
case 'E':
ctx.L.stringBuffer.Append((char)ctx.L.inputChar);
ctx.NextState = 7;
return true;
default:
return false;
}
}
return true;
}
private static bool State4(FsmContext ctx) {
ctx.L.GetChar ();
if (ctx.L.inputChar == ' ' ||
ctx.L.inputChar >= '\t' && ctx.L.inputChar <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.inputChar) {
case ',':
case ']':
case '}':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 1;
return true;
case '.':
ctx.L.stringBuffer.Append((char)ctx.L.inputChar);
ctx.NextState = 5;
return true;
case 'e':
case 'E':
ctx.L.stringBuffer.Append((char)ctx.L.inputChar);
ctx.NextState = 7;
return true;
default:
return false;
}
}
private static bool State5(FsmContext ctx) {
ctx.L.GetChar();
if (ctx.L.inputChar >= '0' && ctx.L.inputChar <= '9') {
ctx.L.stringBuffer.Append((char)ctx.L.inputChar);
ctx.NextState = 6;
return true;
}
return false;
}
private static bool State6(FsmContext ctx) {
while (ctx.L.GetChar()) {
if (ctx.L.inputChar >= '0' && ctx.L.inputChar <= '9') {
ctx.L.stringBuffer.Append((char)ctx.L.inputChar);
continue;
}
if (ctx.L.inputChar == ' ' ||
ctx.L.inputChar >= '\t' && ctx.L.inputChar <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.inputChar) {
case ',':
case ']':
case '}':
ctx.L.UngetChar();
ctx.Return = true;
ctx.NextState = 1;
return true;
case 'e':
case 'E':
ctx.L.stringBuffer.Append((char)ctx.L.inputChar);
ctx.NextState = 7;
return true;
default:
return false;
}
}
return true;
}
private static bool State7(FsmContext ctx) {
ctx.L.GetChar();
if (ctx.L.inputChar >= '0' && ctx.L.inputChar <= '9') {
ctx.L.stringBuffer.Append((char)ctx.L.inputChar);
ctx.NextState = 8;
return true;
}
switch (ctx.L.inputChar) {
case '+':
case '-':
ctx.L.stringBuffer.Append((char)ctx.L.inputChar);
ctx.NextState = 8;
return true;
default:
return false;
}
}
private static bool State8(FsmContext ctx) {
while (ctx.L.GetChar()) {
if (ctx.L.inputChar >= '0' && ctx.L.inputChar <= '9') {
ctx.L.stringBuffer.Append((char)ctx.L.inputChar);
continue;
}
if (ctx.L.inputChar == ' ' ||
ctx.L.inputChar >= '\t' && ctx.L.inputChar <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.inputChar) {
case ',':
case ']':
case '}':
ctx.L.UngetChar();
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
return true;
}
private static bool State9(FsmContext ctx) {
ctx.L.GetChar();
switch (ctx.L.inputChar) {
case 'r':
ctx.NextState = 10;
return true;
default:
return false;
}
}
private static bool State10(FsmContext ctx) {
ctx.L.GetChar();
switch (ctx.L.inputChar) {
case 'u':
ctx.NextState = 11;
return true;
default:
return false;
}
}
private static bool State11(FsmContext ctx) {
ctx.L.GetChar();
switch (ctx.L.inputChar) {
case 'e':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State12(FsmContext ctx) {
ctx.L.GetChar();
switch (ctx.L.inputChar) {
case 'a':
ctx.NextState = 13;
return true;
default:
return false;
}
}
private static bool State13(FsmContext ctx) {
ctx.L.GetChar();
switch (ctx.L.inputChar) {
case 'l':
ctx.NextState = 14;
return true;
default:
return false;
}
}
private static bool State14(FsmContext ctx) {
ctx.L.GetChar();
switch (ctx.L.inputChar) {
case 's':
ctx.NextState = 15;
return true;
default:
return false;
}
}
private static bool State15(FsmContext ctx) {
ctx.L.GetChar();
switch (ctx.L.inputChar) {
case 'e':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State16(FsmContext ctx) {
ctx.L.GetChar();
switch (ctx.L.inputChar) {
case 'u':
ctx.NextState = 17;
return true;
default:
return false;
}
}
private static bool State17(FsmContext ctx) {
ctx.L.GetChar();
switch (ctx.L.inputChar) {
case 'l':
ctx.NextState = 18;
return true;
default:
return false;
}
}
private static bool State18(FsmContext ctx) {
ctx.L.GetChar();
switch (ctx.L.inputChar) {
case 'l':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State19(FsmContext ctx) {
while (ctx.L.GetChar()) {
switch (ctx.L.inputChar) {
case '"':
ctx.L.UngetChar ();
ctx.Return = true;
ctx.NextState = 20;
return true;
case '\\':
ctx.StateStack = 19;
ctx.NextState = 21;
return true;
default:
ctx.L.stringBuffer.Append((char)ctx.L.inputChar);
continue;
}
}
return true;
}
private static bool State20(FsmContext ctx) {
ctx.L.GetChar();
switch (ctx.L.inputChar) {
case '"':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State21(FsmContext ctx) {
ctx.L.GetChar();
switch (ctx.L.inputChar) {
case 'u':
ctx.NextState = 22;
return true;
case '"':
case '\'':
case '/':
case '\\':
case 'b':
case 'f':
case 'n':
case 'r':
case 't':
ctx.L.stringBuffer.Append(ProcessEscChar(ctx.L.inputChar));
ctx.NextState = ctx.StateStack;
return true;
default:
return false;
}
}
private static bool State22(FsmContext ctx) {
int counter = 0;
int mult = 4096;
ctx.L.unichar = 0;
while (ctx.L.GetChar()) {
if (ctx.L.inputChar >= '0' && ctx.L.inputChar <= '9' ||
ctx.L.inputChar >= 'A' && ctx.L.inputChar <= 'F' ||
ctx.L.inputChar >= 'a' && ctx.L.inputChar <= 'f') {
ctx.L.unichar += HexValue (ctx.L.inputChar) * mult;
counter++;
mult /= 16;
if (counter == 4) {
ctx.L.stringBuffer.Append(Convert.ToChar(ctx.L.unichar));
ctx.NextState = ctx.StateStack;
return true;
}
continue;
}
return false;
}
return true;
}
private static bool State23(FsmContext ctx) {
while (ctx.L.GetChar()) {
switch (ctx.L.inputChar) {
case '\'':
ctx.L.UngetChar();
ctx.Return = true;
ctx.NextState = 24;
return true;
case '\\':
ctx.StateStack = 23;
ctx.NextState = 21;
return true;
default:
ctx.L.stringBuffer.Append((char)ctx.L.inputChar);
continue;
}
}
return true;
}
private static bool State24(FsmContext ctx) {
ctx.L.GetChar();
switch (ctx.L.inputChar) {
case '\'':
ctx.L.inputChar = '"';
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State25(FsmContext ctx) {
ctx.L.GetChar();
switch (ctx.L.inputChar) {
case '*':
ctx.NextState = 27;
return true;
case '/':
ctx.NextState = 26;
return true;
default:
return false;
}
}
private static bool State26(FsmContext ctx) {
while (ctx.L.GetChar()) {
if (ctx.L.inputChar == '\n') {
ctx.NextState = 1;
return true;
}
}
return true;
}
private static bool State27(FsmContext ctx) {
while (ctx.L.GetChar()) {
if (ctx.L.inputChar == '*') {
ctx.NextState = 28;
return true;
}
}
return true;
}
private static bool State28(FsmContext ctx) {
while (ctx.L.GetChar()) {
if (ctx.L.inputChar == '*') {
continue;
}
if (ctx.L.inputChar == '/') {
ctx.NextState = 1;
return true;
}
ctx.NextState = 27;
return true;
}
return true;
}
private bool GetChar() {
if ((inputChar = NextChar()) != -1) {
return true;
}
EndOfInput = true;
return false;
}
private int NextChar() {
if (inputBuffer != 0) {
int tmp = inputBuffer;
inputBuffer = 0;
return tmp;
}
return reader.Read();
}
public bool NextToken() {
StateHandler handler;
context.Return = false;
while (true) {
handler = handlerTable[state - 1];
if (!handler(context)) {
throw new JsonException(inputChar);
}
if (EndOfInput) {
return false;
}
if (context.Return) {
StringValue = stringBuffer.ToString();
stringBuffer.Remove(0, stringBuffer.Length);
Token = returnTable[state - 1];
if (Token == (int)ParserToken.Char) {
Token = inputChar;
}
state = context.NextState;
return true;
}
state = context.NextState;
}
}
private void UngetChar() {
inputBuffer = inputChar;
}
}
}
| |
using System;
using Android.Views;
using Android.Graphics;
using Android.Util;
using Android.Content;
namespace AndroidHUD
{
public class ProgressWheel : AndHUD.ProgressWheel
{
public ProgressWheel(Context context)
: this(context, null, 0)
{
}
public ProgressWheel(Context context, IAttributeSet attrs)
: this(context, attrs, 0)
{
}
public ProgressWheel (Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle)
{
CircleRadius = 80;
BarLength = 60;
BarWidth = 20;
RimWidth = 20;
TextSize = 20;
//Padding (with defaults)
WheelPaddingTop = 5;
WheelPaddingBottom = 5;
WheelPaddingLeft = 5;
WheelPaddingRight = 5;
//Colors (with defaults)
BarColor = Color.White;
CircleColor = Color.Transparent;
RimColor = Color.Gray;
TextColor = Color.White;
//Animation
//The amount of pixels to move the bar by on each draw
SpinSpeed = 2;
//The number of milliseconds to wait inbetween each draw
DelayMillis = 0;
spinHandler = new SpinHandler(msg => {
Invalidate ();
if (isSpinning)
{
progress += SpinSpeed;
if (progress > 360)
progress = 0;
spinHandler.SendEmptyMessageDelayed (0, DelayMillis);
}
});
//ParseAttributes(context.ObtainStyledAttributes(attrs, null)); //TODO: swap null for R.styleable.ProgressWheel
}
// public string Text
// {
// get { return text; }
// set { text = value; splitText = text.Split('\n'); }
// }
//public string[] SplitText { get { return splitText; } }
public int CircleRadius { get;set; }
public int BarLength { get;set; }
public int BarWidth { get;set; }
public int TextSize { get;set; }
public int WheelPaddingTop { get;set; }
public int WheelPaddingBottom { get; set; }
public int WheelPaddingLeft { get;set; }
public int WheelPaddingRight { get;set; }
public Color BarColor { get;set; }
public Color CircleColor { get;set; }
public Color RimColor { get;set; }
public Shader RimShader { get { return rimPaint.Shader; } set { rimPaint.SetShader(value); } }
public Color TextColor { get;set; }
public int SpinSpeed { get;set; }
public int RimWidth { get;set; }
public int DelayMillis { get;set; }
public bool IsSpinning { get { return isSpinning; } }
//Sizes (with defaults)
int fullRadius = 100;
//Paints
Paint barPaint = new Paint();
Paint circlePaint = new Paint();
Paint rimPaint = new Paint();
Paint textPaint = new Paint();
//Rectangles
//RectF rectBounds = new RectF();
RectF circleBounds = new RectF();
int progress = 0;
bool isSpinning = false;
SpinHandler spinHandler;
Android.OS.BuildVersionCodes version = Android.OS.Build.VERSION.SdkInt;
//Other
//string text = "";
//string[] splitText = new string[]{};
protected override void OnAttachedToWindow ()
{
base.OnAttachedToWindow ();
SetupBounds ();
SetupPaints ();
Invalidate ();
}
void SetupPaints()
{
barPaint.Color = BarColor;
barPaint.AntiAlias = true;
barPaint.SetStyle (Paint.Style.Stroke);
barPaint.StrokeWidth = BarWidth;
rimPaint.Color = RimColor;
rimPaint.AntiAlias = true;
rimPaint.SetStyle (Paint.Style.Stroke);
rimPaint.StrokeWidth = RimWidth;
circlePaint.Color = CircleColor;
circlePaint.AntiAlias = true;
circlePaint.SetStyle(Paint.Style.Fill);
textPaint.Color = TextColor;
textPaint.SetStyle(Paint.Style.Fill);
textPaint.AntiAlias = true;
textPaint.TextSize = TextSize;
}
void SetupBounds()
{
WheelPaddingTop = this.WheelPaddingTop;
WheelPaddingBottom = this.WheelPaddingBottom;
WheelPaddingLeft = this.WheelPaddingLeft;
WheelPaddingRight = this.WheelPaddingRight;
// rectBounds = new RectF(WheelPaddingLeft,
// WheelPaddingTop,
// this.LayoutParameters.Width - WheelPaddingRight,
// this.LayoutParameters.Height - WheelPaddingBottom);
//
circleBounds = new RectF(WheelPaddingLeft + BarWidth,
WheelPaddingTop + BarWidth,
this.LayoutParameters.Width - WheelPaddingRight - BarWidth,
this.LayoutParameters.Height - WheelPaddingBottom - BarWidth);
fullRadius = (this.LayoutParameters.Width - WheelPaddingRight - BarWidth)/2;
CircleRadius = (fullRadius - BarWidth) + 1;
}
// void ParseAttributes(Android.Content.Res.TypedArray a)
// {
// BarWidth = (int) a.GetDimension(R.styleable.ProgressWheel_barWidth, barWidth);
// RimWidth = (int) a.GetDimension(R.styleable.ProgressWheel_rimWidth, rimWidth);
// SpinSpeed = (int) a.GetDimension(R.styleable.ProgressWheel_spinSpeed, spinSpeed);
// DelayMillis = (int) a.GetInteger(R.styleable.ProgressWheel_delayMillis, delayMillis);
//
// if(DelayMillis < 0)
// DelayMillis = 0;
//
// BarColor = a.GetColor(R.styleable.ProgressWheel_barColor, barColor);
// BarLength = (int) a.GetDimension(R.styleable.ProgressWheel_barLength, barLength);
// TextSize = (int) a.GetDimension(R.styleable.ProgressWheel_textSize, textSize);
// TextColor = (int) a.GetColor(R.styleable.ProgressWheel_textColor, textColor);
//
// Text = a.GetString(R.styleable.ProgressWheel_text);
//
// RimColor = (int) a.GetColor(R.styleable.ProgressWheel_rimColor, rimColor);
// CircleColor = (int) a.GetColor(R.styleable.ProgressWheel_circleColor, circleColor);
// }
//----------------------------------
//Animation stuff
//----------------------------------
protected override void OnDraw (Canvas canvas)
{
base.OnDraw (canvas);
//Draw the rim
canvas.DrawArc(circleBounds, 360, 360, false, rimPaint);
//Draw the bar
if(isSpinning)
canvas.DrawArc(circleBounds, progress - 90, BarLength, false, barPaint);
else
canvas.DrawArc(circleBounds, -90, progress, false, barPaint);
//Draw the inner circle
canvas.DrawCircle((circleBounds.Width() / 2) + RimWidth + WheelPaddingLeft,
(circleBounds.Height() / 2) + RimWidth + WheelPaddingTop,
CircleRadius,
circlePaint);
//Draw the text (attempts to center it horizontally and vertically)
// int offsetNum = 2;
//
// foreach (var s in splitText)
// {
// float offset = textPaint.MeasureText(s) / 2;
//
// canvas.DrawText(s, this.Width / 2 - offset,
// this.Height / 2 + (TextSize * (offsetNum))
// - ((splitText.Length - 1) * (TextSize / 2)), textPaint);
// offsetNum++;
// }
}
public void ResetCount()
{
progress = 0;
//Text = "0%";
Invalidate();
}
public void StopSpinning()
{
isSpinning = false;
progress = 0;
spinHandler.RemoveMessages(0);
}
public void Spin()
{
isSpinning = true;
spinHandler.SendEmptyMessage(0);
}
public void IncrementProgress()
{
isSpinning = false;
progress++;
//Text = Math.Round(((float)progress/(float)360)*(float)100) + "%";
spinHandler.SendEmptyMessage(0);
}
public void SetProgress(int i) {
isSpinning = false;
var newProgress = (int)((float)i / (float)100 * (float)360);
if (version >= Android.OS.BuildVersionCodes.Honeycomb)
{
Android.Animation.ValueAnimator va =
(Android.Animation.ValueAnimator)Android.Animation.ValueAnimator.OfInt (progress, newProgress).SetDuration (250);
va.Update += (sender, e) => {
var interimValue = (int)e.Animation.AnimatedValue;
progress = interimValue;
//Text = Math.Round(((float)interimValue/(float)360)*(float)100) + "%";
Invalidate ();
};
va.Start ();
} else {
progress = newProgress;
Invalidate ();
}
spinHandler.SendEmptyMessage(0);
}
class SpinHandler : Android.OS.Handler
{
public SpinHandler(Action<Android.OS.Message> msgAction) : base()
{
MessageAction = msgAction;
}
public Action<Android.OS.Message> MessageAction { get; private set; }
public override void HandleMessage (Android.OS.Message msg)
{
MessageAction (msg);
}
}
}
}
| |
/*
* 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.
*/
// Uncomment to make asset Get requests for existing
// #define WAIT_ON_INPROGRESS_REQUESTS
using System;
using System.IO;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Timers;
using log4net;
using Nini.Config;
using Mono.Addins;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
[assembly: Addin("FlotsamAssetCache", "1.1")]
[assembly: AddinDependency("OpenSim", "0.5")]
namespace Flotsam.RegionModules.AssetCache
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
public class FlotsamAssetCache : ISharedRegionModule, IImprovedAssetCache, IAssetService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled;
private const string m_ModuleName = "FlotsamAssetCache";
private const string m_DefaultCacheDirectory = m_ModuleName;
private string m_CacheDirectory = m_DefaultCacheDirectory;
private readonly List<char> m_InvalidChars = new List<char>();
private int m_LogLevel = 0;
private ulong m_HitRateDisplay = 1; // How often to display hit statistics, given in requests
private static ulong m_Requests;
private static ulong m_RequestsForInprogress;
private static ulong m_DiskHits;
private static ulong m_MemoryHits;
private static double m_HitRateMemory;
private static double m_HitRateFile;
#if WAIT_ON_INPROGRESS_REQUESTS
private Dictionary<string, ManualResetEvent> m_CurrentlyWriting = new Dictionary<string, ManualResetEvent>();
private int m_WaitOnInprogressTimeout = 3000;
#else
private List<string> m_CurrentlyWriting = new List<string>();
#endif
private ExpiringCache<string, AssetBase> m_MemoryCache;
private bool m_MemoryCacheEnabled = true;
// Expiration is expressed in hours.
private const double m_DefaultMemoryExpiration = 1.0;
private const double m_DefaultFileExpiration = 48;
private TimeSpan m_MemoryExpiration = TimeSpan.Zero;
private TimeSpan m_FileExpiration = TimeSpan.Zero;
private TimeSpan m_FileExpirationCleanupTimer = TimeSpan.Zero;
private static int m_CacheDirectoryTiers = 1;
private static int m_CacheDirectoryTierLen = 3;
private static int m_CacheWarnAt = 30000;
private System.Timers.Timer m_CacheCleanTimer;
private IAssetService m_AssetService;
private List<Scene> m_Scenes = new List<Scene>();
private bool m_DeepScanBeforePurge;
public FlotsamAssetCache()
{
m_InvalidChars.AddRange(Path.GetInvalidPathChars());
m_InvalidChars.AddRange(Path.GetInvalidFileNameChars());
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return m_ModuleName; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("AssetCaching", String.Empty);
if (name == Name)
{
m_MemoryCache = new ExpiringCache<string, AssetBase>();
m_Enabled = true;
m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0} enabled", this.Name);
IConfig assetConfig = source.Configs["AssetCache"];
if (assetConfig == null)
{
m_log.Warn("[FLOTSAM ASSET CACHE]: AssetCache missing from OpenSim.ini, using defaults.");
m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Directory", m_DefaultCacheDirectory);
return;
}
m_CacheDirectory = assetConfig.GetString("CacheDirectory", m_DefaultCacheDirectory);
m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Directory", m_DefaultCacheDirectory);
m_MemoryCacheEnabled = assetConfig.GetBoolean("MemoryCacheEnabled", false);
m_MemoryExpiration = TimeSpan.FromHours(assetConfig.GetDouble("MemoryCacheTimeout", m_DefaultMemoryExpiration));
#if WAIT_ON_INPROGRESS_REQUESTS
m_WaitOnInprogressTimeout = assetConfig.GetInt("WaitOnInprogressTimeout", 3000);
#endif
m_LogLevel = assetConfig.GetInt("LogLevel", 0);
m_HitRateDisplay = (ulong)assetConfig.GetInt("HitRateDisplay", 1000);
m_FileExpiration = TimeSpan.FromHours(assetConfig.GetDouble("FileCacheTimeout", m_DefaultFileExpiration));
m_FileExpirationCleanupTimer = TimeSpan.FromHours(assetConfig.GetDouble("FileCleanupTimer", m_DefaultFileExpiration));
if ((m_FileExpiration > TimeSpan.Zero) && (m_FileExpirationCleanupTimer > TimeSpan.Zero))
{
m_CacheCleanTimer = new System.Timers.Timer(m_FileExpirationCleanupTimer.TotalMilliseconds);
m_CacheCleanTimer.AutoReset = true;
m_CacheCleanTimer.Elapsed += CleanupExpiredFiles;
lock (m_CacheCleanTimer)
m_CacheCleanTimer.Start();
}
m_CacheDirectoryTiers = assetConfig.GetInt("CacheDirectoryTiers", 1);
if (m_CacheDirectoryTiers < 1)
{
m_CacheDirectoryTiers = 1;
}
else if (m_CacheDirectoryTiers > 3)
{
m_CacheDirectoryTiers = 3;
}
m_CacheDirectoryTierLen = assetConfig.GetInt("CacheDirectoryTierLength", 3);
if (m_CacheDirectoryTierLen < 1)
{
m_CacheDirectoryTierLen = 1;
}
else if (m_CacheDirectoryTierLen > 4)
{
m_CacheDirectoryTierLen = 4;
}
m_CacheWarnAt = assetConfig.GetInt("CacheWarnAt", 30000);
m_DeepScanBeforePurge = assetConfig.GetBoolean("DeepScanBeforePurge", false);
MainConsole.Instance.Commands.AddCommand(this.Name, true, "fcache status", "fcache status", "Display cache status", HandleConsoleCommand);
MainConsole.Instance.Commands.AddCommand(this.Name, true, "fcache clear", "fcache clear [file] [memory]", "Remove all assets in the file and/or memory cache", HandleConsoleCommand);
MainConsole.Instance.Commands.AddCommand(this.Name, true, "fcache assets", "fcache assets", "Attempt a deep scan and cache of all assets in all scenes", HandleConsoleCommand);
MainConsole.Instance.Commands.AddCommand(this.Name, true, "fcache expire", "fcache expire <datetime>", "Purge cached assets older then the specified date/time", HandleConsoleCommand);
}
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (m_Enabled)
{
scene.RegisterModuleInterface<IImprovedAssetCache>(this);
m_Scenes.Add(scene);
if (m_AssetService == null)
{
m_AssetService = scene.RequestModuleInterface<IAssetService>();
}
}
}
public void RemoveRegion(Scene scene)
{
if (m_Enabled)
{
scene.UnregisterModuleInterface<IImprovedAssetCache>(this);
m_Scenes.Remove(scene);
}
}
public void RegionLoaded(Scene scene)
{
}
////////////////////////////////////////////////////////////
// IImprovedAssetCache
//
private void UpdateMemoryCache(string key, AssetBase asset)
{
if (m_MemoryCacheEnabled)
{
if (m_MemoryExpiration > TimeSpan.Zero)
{
m_MemoryCache.AddOrUpdate(key, asset, m_MemoryExpiration);
}
else
{
m_MemoryCache.AddOrUpdate(key, asset, DateTime.MaxValue);
}
}
}
public void Cache(AssetBase asset)
{
// TODO: Spawn this off to some seperate thread to do the actual writing
if (asset != null)
{
UpdateMemoryCache(asset.ID, asset);
string filename = GetFileName(asset.ID);
try
{
// If the file is already cached, don't cache it, just touch it so access time is updated
if (File.Exists(filename))
{
File.SetLastAccessTime(filename, DateTime.Now);
} else {
// Once we start writing, make sure we flag that we're writing
// that object to the cache so that we don't try to write the
// same file multiple times.
lock (m_CurrentlyWriting)
{
#if WAIT_ON_INPROGRESS_REQUESTS
if (m_CurrentlyWriting.ContainsKey(filename))
{
return;
}
else
{
m_CurrentlyWriting.Add(filename, new ManualResetEvent(false));
}
#else
if (m_CurrentlyWriting.Contains(filename))
{
return;
}
else
{
m_CurrentlyWriting.Add(filename);
}
#endif
}
Util.FireAndForget(
delegate { WriteFileCache(filename, asset); });
}
}
catch (Exception e)
{
LogException(e);
}
}
}
public AssetBase Get(string id)
{
m_Requests++;
AssetBase asset = null;
if (m_MemoryCacheEnabled && m_MemoryCache.TryGetValue(id, out asset))
{
m_MemoryHits++;
}
else
{
string filename = GetFileName(id);
if (File.Exists(filename))
{
FileStream stream = null;
try
{
stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryFormatter bformatter = new BinaryFormatter();
asset = (AssetBase)bformatter.Deserialize(stream);
UpdateMemoryCache(id, asset);
m_DiskHits++;
}
catch (System.Runtime.Serialization.SerializationException e)
{
LogException(e);
// If there was a problem deserializing the asset, the asset may
// either be corrupted OR was serialized under an old format
// {different version of AssetBase} -- we should attempt to
// delete it and re-cache
File.Delete(filename);
}
catch (Exception e)
{
LogException(e);
}
finally
{
if (stream != null)
stream.Close();
}
}
#if WAIT_ON_INPROGRESS_REQUESTS
// Check if we're already downloading this asset. If so, try to wait for it to
// download.
if (m_WaitOnInprogressTimeout > 0)
{
m_RequestsForInprogress++;
ManualResetEvent waitEvent;
if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent))
{
waitEvent.WaitOne(m_WaitOnInprogressTimeout);
return Get(id);
}
}
#else
// Track how often we have the problem that an asset is requested while
// it is still being downloaded by a previous request.
if (m_CurrentlyWriting.Contains(filename))
{
m_RequestsForInprogress++;
}
#endif
}
if (((m_LogLevel >= 1)) && (m_HitRateDisplay != 0) && (m_Requests % m_HitRateDisplay == 0))
{
m_HitRateFile = (double)m_DiskHits / m_Requests * 100.0;
m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Get :: {0} :: {1}", id, asset == null ? "Miss" : "Hit");
m_log.InfoFormat("[FLOTSAM ASSET CACHE]: File Hit Rate {0}% for {1} requests", m_HitRateFile.ToString("0.00"), m_Requests);
if (m_MemoryCacheEnabled)
{
m_HitRateMemory = (double)m_MemoryHits / m_Requests * 100.0;
m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Memory Hit Rate {0}% for {1} requests", m_HitRateMemory.ToString("0.00"), m_Requests);
}
m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0} unnessesary requests due to requests for assets that are currently downloading.", m_RequestsForInprogress);
}
return asset;
}
public AssetBase GetCached(string id)
{
return Get(id);
}
public void Expire(string id)
{
if (m_LogLevel >= 2)
m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Expiring Asset {0}.", id);
try
{
string filename = GetFileName(id);
if (File.Exists(filename))
{
File.Delete(filename);
}
if (m_MemoryCacheEnabled)
m_MemoryCache.Remove(id);
}
catch (Exception e)
{
LogException(e);
}
}
public void Clear()
{
if (m_LogLevel >= 2)
m_log.Debug("[FLOTSAM ASSET CACHE]: Clearing Cache.");
foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
{
Directory.Delete(dir);
}
if (m_MemoryCacheEnabled)
m_MemoryCache.Clear();
}
private void CleanupExpiredFiles(object source, ElapsedEventArgs e)
{
if (m_LogLevel >= 2)
m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Checking for expired files older then {0}.", m_FileExpiration.ToString());
// Purge all files last accessed prior to this point
DateTime purgeLine = DateTime.Now - m_FileExpiration;
// An optional deep scan at this point will ensure assets present in scenes,
// or referenced by objects in the scene, but not recently accessed
// are not purged.
if (m_DeepScanBeforePurge)
{
CacheScenes();
}
foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
{
CleanExpiredFiles(dir, purgeLine);
}
}
/// <summary>
/// Recurses through specified directory checking for asset files last
/// accessed prior to the specified purge line and deletes them. Also
/// removes empty tier directories.
/// </summary>
/// <param name="dir"></param>
private void CleanExpiredFiles(string dir, DateTime purgeLine)
{
foreach (string file in Directory.GetFiles(dir))
{
if (File.GetLastAccessTime(file) < purgeLine)
{
File.Delete(file);
}
}
// Recurse into lower tiers
foreach (string subdir in Directory.GetDirectories(dir))
{
CleanExpiredFiles(subdir, purgeLine);
}
// Check if a tier directory is empty, if so, delete it
int dirSize = Directory.GetFiles(dir).Length + Directory.GetDirectories(dir).Length;
if (dirSize == 0)
{
Directory.Delete(dir);
}
else if (dirSize >= m_CacheWarnAt)
{
m_log.WarnFormat("[FLOTSAM ASSET CACHE]: Cache folder exceeded CacheWarnAt limit {0} {1}. Suggest increasing tiers, tier length, or reducing cache expiration", dir, dirSize);
}
}
/// <summary>
/// Determines the filename for an AssetID stored in the file cache
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
private string GetFileName(string id)
{
// Would it be faster to just hash the darn thing?
foreach (char c in m_InvalidChars)
{
id = id.Replace(c, '_');
}
string path = m_CacheDirectory;
for (int p = 1; p <= m_CacheDirectoryTiers; p++)
{
string pathPart = id.Substring((p - 1) * m_CacheDirectoryTierLen, m_CacheDirectoryTierLen);
path = Path.Combine(path, pathPart);
}
return Path.Combine(path, id);
}
/// <summary>
/// Writes a file to the file cache, creating any nessesary
/// tier directories along the way
/// </summary>
/// <param name="filename"></param>
/// <param name="asset"></param>
private void WriteFileCache(string filename, AssetBase asset)
{
Stream stream = null;
// Make sure the target cache directory exists
string directory = Path.GetDirectoryName(filename);
// Write file first to a temp name, so that it doesn't look
// like it's already cached while it's still writing.
string tempname = Path.Combine(directory, Path.GetRandomFileName());
try
{
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
stream = File.Open(tempname, FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(stream, asset);
stream.Close();
// Now that it's written, rename it so that it can be found.
File.Move(tempname, filename);
if (m_LogLevel >= 2)
m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Cache Stored :: {0}", asset.ID);
}
catch (Exception e)
{
LogException(e);
}
finally
{
if (stream != null)
stream.Close();
// Even if the write fails with an exception, we need to make sure
// that we release the lock on that file, otherwise it'll never get
// cached
lock (m_CurrentlyWriting)
{
#if WAIT_ON_INPROGRESS_REQUESTS
ManualResetEvent waitEvent;
if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent))
{
m_CurrentlyWriting.Remove(filename);
waitEvent.Set();
}
#else
if (m_CurrentlyWriting.Contains(filename))
{
m_CurrentlyWriting.Remove(filename);
}
#endif
}
}
}
private static void LogException(Exception e)
{
string[] text = e.ToString().Split(new char[] { '\n' });
foreach (string t in text)
{
m_log.ErrorFormat("[FLOTSAM ASSET CACHE]: {0} ", t);
}
}
/// <summary>
/// Scan through the file cache, and return number of assets currently cached.
/// </summary>
/// <param name="dir"></param>
/// <returns></returns>
private int GetFileCacheCount(string dir)
{
int count = Directory.GetFiles(dir).Length;
foreach (string subdir in Directory.GetDirectories(dir))
{
count += GetFileCacheCount(subdir);
}
return count;
}
/// <summary>
/// This notes the last time the Region had a deep asset scan performed on it.
/// </summary>
/// <param name="RegionID"></param>
private void StampRegionStatusFile(UUID RegionID)
{
string RegionCacheStatusFile = Path.Combine(m_CacheDirectory, "RegionStatus_" + RegionID.ToString() + ".fac");
if (File.Exists(RegionCacheStatusFile))
{
File.SetLastWriteTime(RegionCacheStatusFile, DateTime.Now);
}
else
{
File.WriteAllText(RegionCacheStatusFile, "Please do not delete this file unless you are manually clearing your Flotsam Asset Cache.");
}
}
/// <summary>
/// Iterates through all Scenes, doing a deep scan through assets
/// to cache all assets present in the scene or referenced by assets
/// in the scene
/// </summary>
/// <returns></returns>
private int CacheScenes()
{
UuidGatherer gatherer = new UuidGatherer(m_AssetService);
Dictionary<UUID, int> assets = new Dictionary<UUID, int>();
foreach (Scene s in m_Scenes)
{
StampRegionStatusFile(s.RegionInfo.RegionID);
s.ForEachSOG(delegate(SceneObjectGroup e)
{
gatherer.GatherAssetUuids(e, assets);
}
);
}
foreach (UUID assetID in assets.Keys)
{
string filename = GetFileName(assetID.ToString());
if (File.Exists(filename))
{
File.SetLastAccessTime(filename, DateTime.Now);
}
else
{
m_AssetService.Get(assetID.ToString());
}
}
return assets.Keys.Count;
}
/// <summary>
/// Deletes all cache contents
/// </summary>
private void ClearFileCache()
{
foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
{
try
{
Directory.Delete(dir, true);
}
catch (Exception e)
{
LogException(e);
}
}
foreach (string file in Directory.GetFiles(m_CacheDirectory))
{
try
{
File.Delete(file);
}
catch (Exception e)
{
LogException(e);
}
}
}
#region Console Commands
private void HandleConsoleCommand(string module, string[] cmdparams)
{
if (cmdparams.Length >= 2)
{
string cmd = cmdparams[1];
switch (cmd)
{
case "status":
m_log.InfoFormat("[FLOTSAM ASSET CACHE] Memory Cache : {0} assets", m_MemoryCache.Count);
int fileCount = GetFileCacheCount(m_CacheDirectory);
m_log.InfoFormat("[FLOTSAM ASSET CACHE] File Cache : {0} assets", fileCount);
foreach (string s in Directory.GetFiles(m_CacheDirectory, "*.fac"))
{
m_log.Info("[FLOTSAM ASSET CACHE] Deep Scans were performed on the following regions:");
string RegionID = s.Remove(0,s.IndexOf("_")).Replace(".fac","");
DateTime RegionDeepScanTMStamp = File.GetLastWriteTime(s);
m_log.InfoFormat("[FLOTSAM ASSET CACHE] Region: {0}, {1}", RegionID, RegionDeepScanTMStamp.ToString("MM/dd/yyyy hh:mm:ss"));
}
break;
case "clear":
if (cmdparams.Length < 3)
{
m_log.Warn("[FLOTSAM ASSET CACHE] Please specify memory and/or file cache.");
break;
}
foreach (string s in cmdparams)
{
if (s.ToLower() == "memory")
{
m_MemoryCache.Clear();
m_log.Info("[FLOTSAM ASSET CACHE] Memory cache cleared.");
}
else if (s.ToLower() == "file")
{
ClearFileCache();
m_log.Info("[FLOTSAM ASSET CACHE] File cache cleared.");
}
}
break;
case "assets":
m_log.Info("[FLOTSAM ASSET CACHE] Caching all assets, in all scenes.");
Util.FireAndForget(delegate {
int assetsCached = CacheScenes();
m_log.InfoFormat("[FLOTSAM ASSET CACHE] Completed Scene Caching, {0} assets found.", assetsCached);
});
break;
case "expire":
if (cmdparams.Length < 3)
{
m_log.InfoFormat("[FLOTSAM ASSET CACHE] Invalid parameters for Expire, please specify a valid date & time", cmd);
break;
}
string s_expirationDate = "";
DateTime expirationDate;
if (cmdparams.Length > 3)
{
s_expirationDate = string.Join(" ", cmdparams, 2, cmdparams.Length - 2);
}
else
{
s_expirationDate = cmdparams[2];
}
if (!DateTime.TryParse(s_expirationDate, out expirationDate))
{
m_log.InfoFormat("[FLOTSAM ASSET CACHE] {0} is not a valid date & time", cmd);
break;
}
CleanExpiredFiles(m_CacheDirectory, expirationDate);
break;
default:
m_log.InfoFormat("[FLOTSAM ASSET CACHE] Unknown command {0}", cmd);
break;
}
}
else if (cmdparams.Length == 1)
{
m_log.InfoFormat("[FLOTSAM ASSET CACHE] flotsamcache status - Display cache status");
m_log.InfoFormat("[FLOTSAM ASSET CACHE] flotsamcache clearmem - Remove all assets cached in memory");
m_log.InfoFormat("[FLOTSAM ASSET CACHE] flotsamcache clearfile - Remove all assets cached on disk");
m_log.InfoFormat("[FLOTSAM ASSET CACHE] flotsamcache cachescenes - Attempt a deep cache of all assets in all scenes");
m_log.InfoFormat("[FLOTSAM ASSET CACHE] flotsamcache <datetime> - Purge assets older then the specified date & time");
}
}
#endregion
#region IAssetService Members
public AssetMetadata GetMetadata(string id)
{
AssetBase asset = Get(id);
return asset.Metadata;
}
public byte[] GetData(string id)
{
AssetBase asset = Get(id);
return asset.Data;
}
public bool Get(string id, object sender, AssetRetrieved handler)
{
AssetBase asset = Get(id);
handler(id, sender, asset);
return true;
}
public string Store(AssetBase asset)
{
if (asset.FullID == UUID.Zero)
{
asset.FullID = UUID.Random();
}
Cache(asset);
return asset.ID;
}
public bool UpdateContent(string id, byte[] data)
{
AssetBase asset = Get(id);
asset.Data = data;
Cache(asset);
return true;
}
public bool Delete(string id)
{
Expire(id);
return true;
}
#endregion
}
}
| |
// ADDIN_SendAway_Test.cs
//
// Copyright (c) 2013-2014 Brent Knowles (http://www.brentknowles.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Review documentation at http://www.yourothermind.com for updated implementation notes, license updates
// or other general information/
//
// Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW
// Full source code: https://github.com/BrentKnowles/YourOtherMind
//###
using System;
using NUnit.Framework;
using CoreUtilities;
using SendTextAway;
using System.IO;
using System.Collections.Generic;
namespace Testing
{
[TestFixture]
public class ADDIN_SendAway_Test
{
string PathToSendAwayUnitTestingFIles = Constants.BLANK;
string PathToSendTextAwayFiles = Constants.BLANK;
string PathToOutput =Constants.BLANK;
string PathToProper =Constants.BLANK;
public ADDIN_SendAway_Test ()
{
}
// each test should hapepn in its own otuput directory
public ControlFile Setup (string uniquetestdirectory, ControlFile overrideControl)
{
// deletes contents of the output folder
string path = Environment.CurrentDirectory;
PathToSendAwayUnitTestingFIles = Path.Combine (path, "SendAwayUnitTestingFiles");
PathToSendTextAwayFiles = _TestSingleTon.PathToSendAwayEPUBTemplates;
PathToOutput = Path.Combine (PathToSendAwayUnitTestingFIles, "output");
string code = uniquetestdirectory;
PathToOutput = Path.Combine (PathToOutput,code);
PathToProper = Path.Combine (PathToSendAwayUnitTestingFIles, "proper");
if (Directory.Exists (PathToOutput))
{
Directory.Delete (PathToOutput, true);
}
Directory.CreateDirectory (PathToOutput);
if (Directory.Exists (PathToSendAwayUnitTestingFIles) == false || Directory.Exists (PathToSendTextAwayFiles) == false || Directory.Exists (PathToOutput) == false) {
throw new Exception ("not all paths defined");
}
//tests for existence of needed debug folders
// Sets up a proper epub control file
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
if (overrideControl != null) result = overrideControl;
result.OutputDirectory = PathToOutput;
result.TemplateDirectory = PathToSendTextAwayFiles;
return result;
}
private List<string> ConvertFileToLIstOfStrings(string file)
{
List<string> result = new List<string>();
string line = "";
System.IO.StreamReader fileR = new System.IO.StreamReader(file);
while((line = fileR.ReadLine()) != null)
{
//String line = fileR.ReadToEnd();
result.Add (line);
}
fileR.Close();
return result;
}
public int CompareTwoFiles (string file_1, string file_2)
{
int differences = 0;
string file1Copy = file_1; // we don't copy originalfile_1+"original.txt";
string file2Copy = file_2 +"copy.txt";
//File.Copy (file_1, file1Copy);
File.Copy (file_2,file2Copy);
List<string> FILE1 = ConvertFileToLIstOfStrings (file1Copy);
List<string> FILE2 = ConvertFileToLIstOfStrings (file2Copy);
differences = FILE1.Count - FILE2.Count;
int linescounted = 0;
if (differences == 0) {
// now do line by line compare
for (int i = 0; i < FILE1.Count; i++)
{
linescounted++;
if (FILE1[i] != FILE2[i])
{
differences++;
}
}
}
_w.output("Lines read " + linescounted.ToString());
return differences;
}
// keep each test small so its easier to track down where the failur ehappened
[Test]
public void Fancy()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = true;
PerformTest("fancycharacters.txt", result);
}
[Test]
public void Multilevelbullet()
{
PerformTest("multilevelbullet.txt");
}
[Test]
public void MoreThanThreeBulletLevels()
{
PerformTest("morelevelsthan3.txt");
}
[Test]
public void BugHTMLBroke()
{
PerformTest("bughtml.txt");
}
[Test]
public void Bug001()
{
PerformTest("bug001.txt");
}
[Test]
public void Emdash()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = false;
result.ConvertToEmDash = true;
PerformTest("emdash.txt", result);
}
[Test]
public void ReplaceParagraphTags()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = false;
result.ConvertToEmDash = true;
result.EpubRemoveDoublePageTags = true;
PerformTest("replaceparagraphtags.txt", result);
}
[Test]
public void Bug002()
{
// could not actually replicate the bug but figured I'd leave this in as a baseline.
PerformTest("bug002.txt");
}
[Test]
public void MultipleAlignments_AndExtraBulletAtListEnd()
{
// could not actually replicate the bug but figured I'd leave this in as a baseline.
PerformTest("multiplealignments.txt");
}
[Test]
public void TestHeadings()
{
PerformTest("headings.txt");
}
[Test]
public void chapter8()
{
// January 2014
// noticing some bullet lists start with <ul></ul> and then go onto <li>... never open and close properly
// cannot figure out why.
// This is an example of such a broken entity.
PerformTest ("chapter8.txt");
}
[Test]
public void chapter8stib()
{
// January 2014
// noticing some bullet lists start with <ul></ul> and then go onto <li>... never open and close properly
// cannot figure out why.
// This is an example of such a broken entity.
PerformTest ("chapter8stub.txt");
}
[Test]
public void TestBulletTagMisMatch()
{
// January 2014
// noticing some bullet lists start with <ul></ul> and then go onto <li>... never open and close properly
// cannot figure out why.
// This is an example of such a broken entity.
PerformTest ("bullettagmismatch.txt");
}
[Test]
public void crash1()
{
// January 2014
// noticing some bullet lists start with <ul></ul> and then go onto <li>... never open and close properly
// cannot figure out why.
// This is an example of such a broken entity.
PerformTest ("crash1.txt");
}
[Test]
public void bugformatatstartofsceneitalic()
{
PerformTest("bugformatatstartofsceneitalic.txt");
}
[Test]
public void bugformatatstartofscene()
{
PerformTest("bugformatatstartofscene.txt");
}
[Test]
public void TestBullets()
{
PerformTest("bullet.txt");
}
// I removed this text because I did fix the issue when I added the Multilevelbullet test 08/05/2014
// [Test]
// public void TestBrokenBullets()
// {
// // We accept this will break but test to make sure it is never invisibly fixed. (see FAQ: http://yourothermind.com/yourothermind-2013/using-yourothermind-2013/addin_sendtextaway/)
// PerformTest("bulletbroken.txt");
// }
[Test]
public void LazyDesignerTest2_BreakComments()
{
PerformTest("lazydesignerbreakcomment.txt");
}
[Test]
public void ChatMode()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = true;
result.ChatMode = 0;
PerformTest("chatmode.txt", result);
result.ChatMode = 1;
PerformTest("chatmode.txt", result, "chatmodeitalic.txt","");
result.ChatMode = 2;
PerformTest("chatmode.txt", result, "chatmodebold.txt","");
}
[Test]
public void LazyDesignerTestNumberBulletLevel()
{
// this was actually my fault -- I did not end a list properly
PerformTest("lazydesigner_numberbulleterror.txt");
}
[Test]
public void endchapter()
{
PerformTest("endchapter.txt", null, "", "endnote");
}
[Test]
public void lazydesigner_greaterthan_lessthanwithhtml()
{
PerformTest("lazydesigner_greaterthan_lessthanwithhtml.txt");
}
[Test]
public void LazyDesignerTest1()
{
PerformTest("lazydesignerbug1.txt");
}
[Test]
public void LinksToOtherFilesinEpub()
{
PerformTest("linkstootherfilesinepub.txt");
}
[Test]
public void Novel_Open_Blanklinke()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = true;
result.NovelMode = true;
PerformTest("novel_open_blank_error.txt", result);
}
[Test]
public void emdashnospace()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = true;
result.RemoveTabs = false;
result.SceneBreakHasTab = true;
result.OverrideStyleSheet = @"C:\Users\Public\Documents\YourOtherMind\YourOtherMind\files\SendTextAwayControlFiles\stylesheet.css";
result.NovelMode = true;
result.ChapterTitleOffset = -2;
result.UnderlineShouldBeItalicInstead=true;
result.ArealValidatorSafe_Align = true;
result.ConvertToEmDash = true;
result.Emdash_removespacesbeforeafter = true;
PerformTest("emdashnospace.txt", result);
}
[Test]
public void shortstorytest1()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = true;
result.RemoveTabs = false;
result.SceneBreakHasTab = true;
result.OverrideStyleSheet = @"C:\Users\Public\Documents\YourOtherMind\YourOtherMind\files\SendTextAwayControlFiles\stylesheet.css";
result.NovelMode = true;
result.ChapterTitleOffset = -2;
result.UnderlineShouldBeItalicInstead=true;
result.ArealValidatorSafe_Align = true;
PerformTest("shortstorytest1.txt", result,"", "Chapter_1");
}
[Test]
public void Novel_Facts_Paragraphs()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = true;
result.NovelMode = true;
PerformTest("novel_facts_paragraphs.txt", result);
}
[Test]
public void Novel_factafterscene()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = true;
result.NovelMode = true;
PerformTest("novel_factafterscene.txt", result);
}
[Test]
public void Novel_factafterscene_WITHOUTCOMMA()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = true;
result.NovelMode = true;
PerformTest("novel_factaftersceneWITHOUTCOMMA.txt", result);
}
[Test]
public void novel_past_andblank()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = true;
result.NovelMode = true;
PerformTest("novel_past_andblank.txt", result,"", "Chapter_1");
}
[Test]
public void novel_inlinep()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = true;
result.NovelMode = true;
PerformTest("novel_inlinep.txt", result,"", "Chapter_1");
}
[Test]
public void novel_fact_endofline()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = true;
result.NovelMode = true;
PerformTest("novel_fact_endofline.txt", result);
}
[Test]
public void chaptertitlesintoc()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = true;
result.RemoveTabs = false;
result.SceneBreakHasTab = true;
result.OverrideStyleSheet = @"C:\Users\Public\Documents\YourOtherMind\YourOtherMind\files\SendTextAwayControlFiles\stylesheet.css";
result.NovelMode = true;
result.ChapterTitleOffset = -2;
result.ArealValidatorSafe_Align = true;
PerformTest("chaptertitlesintoc.txt", result,"", "toc");
}
[Test]
public void fancysectionbreak()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = false;
result.RemoveTabs = false;
result.SceneBreakHasTab = true;
result.OverrideStyleSheet = @"C:\Users\Public\Documents\YourOtherMind\YourOtherMind\files\SendTextAwayControlFiles\stylesheet.css";
result.NovelMode = true;
result.ArealValidatorSafe_Align = true;
result.CustomEllip = true;
result.Overridesectionbreak = "src=\".\\images\\fleuron.png\" height=\"39px\" width=\"100px\"";
PerformTest("fancysectionbreak.txt", result);
}
[Test]
public void ellip_new()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = false;
result.RemoveTabs = false;
result.SceneBreakHasTab = true;
result.OverrideStyleSheet = @"C:\Users\Public\Documents\YourOtherMind\YourOtherMind\files\SendTextAwayControlFiles\stylesheet.css";
result.NovelMode = true;
result.ArealValidatorSafe_Align = true;
result.CustomEllip = true;
PerformTest("ellip_new.txt", result);
}
[Test]
public void BetterAlign()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = true;
result.RemoveTabs = false;
result.SceneBreakHasTab = true;
result.OverrideStyleSheet = @"C:\Users\Public\Documents\YourOtherMind\YourOtherMind\files\SendTextAwayControlFiles\stylesheet.css";
result.NovelMode = true;
result.ArealValidatorSafe_Align = true;
PerformTest("betteralign.txt", result,"", "Chapter_1");
}
[Test]
public void novel_fact_endoflinequestion()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = true;
result.NovelMode = true;
PerformTest("novel_fact_endoflinequestion.txt", result);
}
[Test]
public void novel_fact_endoflineexclaim()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = true;
result.NovelMode = true;
PerformTest("novel_fact_endoflineexclaim.txt", result);
}
[Test]
public void novel_preludeerror()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConvertToEmDash = true;
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = true;
result.NovelMode = true;
PerformTest("novel_preludeerror.txt", result);
}
[Test]
public void novel_fact_space_before()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConvertToEmDash = true;
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = true;
result.NovelMode = true;
PerformTest("novel_fact_space_before.txt", result);
}
[Test]
public void novel_fact_endoflinehyphen()
{
ControlFile result = ControlFile.Default;
result.ListOfTags=new string[1]{"game|''"};
result.ConvertToEmDash = true;
result.ConverterType = ControlFile.convertertype.epub;
result.MultiLineFormats= new string[1]{"past"};
result.MultiLineFormatsValues = new string[1]{"blockquote2"};
result.Zipper =_TestSingleTon.Zipper;
result.FancyCharacters = true;
result.NovelMode = true;
PerformTest("novel_fact_endoflinehyphen.txt", result);
}
[Test]
public void TestNumberBullets()
{
PerformTest("numberbullet.txt");
}
[Test]
public void CharacterCount()
{
Assert.AreEqual(3,sendePub2.CountCharacters("***Booyah", '*'));
Assert.AreEqual(5,sendePub2.CountCharacters("*****Booyah", '*'));
Assert.AreEqual(1,sendePub2.CountCharacters("*Booyah hey.!", '*'));
Assert.AreEqual(2,sendePub2.CountCharacters("**Booyah hey.! What else eh\nsnakes!", '*', false));
Assert.AreEqual(3,sendePub2.CountCharacters("**Booyah hey.! What else* eh\nsnakes!", '*', false));
Assert.AreEqual(2,sendePub2.CountCharacters("**Booyah hey.! What else* eh\nsnakes!", '*', true));
}
[Test]
public void TestInlineFormat()
{
// <game</game> on an individual line
PerformTest("inlineformat.txt");
}
[Test]
public void TestStrikeAndSuper()
{
PerformTest("strikeandsuper.txt");
}
[Test]
public void TestAnchorLink ()
{
PerformTest("anchor.txt");
}
[Test]
public void TestVariable()
{
PerformTest ("variable.txt");
}
[Test]
public void SectionFormat()
{
// this is <past> </past> across multiple lines
PerformTest ("sectionformat.txt");
}
void PerformTest (string simpletxt)
{
PerformTest (simpletxt, null,"", "");
}
void PerformTest (string simpletxt, ControlFile overrideControl)
{
PerformTest (simpletxt, overrideControl,"", "");
}
void PerformTest (string simpletxt, ControlFile overrideControl, string overrideoutput, string overridepreface)
{
ControlFile Controller = Setup (simpletxt, overrideControl);
string Incoming = simpletxt;
string FileToTest = Path.Combine (PathToSendAwayUnitTestingFIles, Incoming);
sendePub2 SendAwayIt = new sendePub2 ();
SendAwayIt.SuppressMessages = true;
SendAwayIt.WriteText (FileToTest, Controller, -1);
string FileOutput = Path.Combine (PathToOutput, sendePub2.GetDateDirectory);
FileOutput = Path.Combine (FileOutput, "oebps");
if (overridepreface == "") {
FileOutput = Path.Combine (FileOutput, "preface.xhtml");
} else {
FileOutput = Path.Combine (FileOutput,overridepreface+".xhtml");
}
Assert.True (File.Exists (FileOutput), "NOt found " + FileOutput);
if (overrideoutput != "") {
Incoming = overrideoutput;
}
// now test the file for identicality
string FileToCompareItTo = Path.Combine (PathToProper, Incoming);
if (File.Exists (FileToCompareItTo) == false) {
throw new Exception ("The file does not exist : " + FileToCompareItTo);
}
int differences = CompareTwoFiles(FileToCompareItTo, FileOutput);
Assert.AreEqual(0, differences, "Differences Found " + differences);
}
[Test]
/// <summary>
/// Simples the test.
/// </summary>
public void SimpleTest ()
{
PerformTest("simple.txt");
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace SliceEm
{
/// <summary>
/// Summary description for SliceEditorControl.
/// </summary>
public class SliceEditorControl : System.Windows.Forms.Control, EditorContext
{
private Pen _SliceObjectPen = new Pen(Color.Blue, 1);
private Pen _SliceObjectPenActive = new Pen(Color.Red, 2);
private Pen _BorderPen = new Pen(Color.Black , 2);
private Pen _GridCursor = new Pen(Color.Green , 1);
private Pen _ModePen = new Pen(Color.Purple, 1);
private Pen _ModePenShadow = new Pen(Color.Gray, 1);
private Pen _GridPenCenter = new Pen(Color.Red , 1);
private Pen _GridPenMajor = new Pen(Color.Black , 1);
private Pen _GridPenMinor = new Pen(Color.BlanchedAlmond, 1);
private Font _GridFontMajor = new Font("Arial", 12);
private Font _GridFontMinor = new Font("Arial", 10);
private Brush _Black = new SolidBrush(Color.Black);
public Pen SliceObjectPen
{
get { return _SliceObjectPen; }
}
public Pen SliceObjectPenActive
{
get { return _SliceObjectPenActive; }
}
public Font SliceObjectFont
{
get { return _GridFontMinor; }
}
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private float cursorX;
private float cursorY;
private float originX;
private float originY;
private float scale = .5f;
private SlicePlane _SlicePlane;
private float orig_originX;
private float orig_originY;
private int start_x;
private int start_y;
private bool ldown;
private bool rdown;
private SliceEmFile _SliceFile;
private FileUpdateNotify FUN;
private Bitmap offScreenBmp = null;
private Graphics offScreenDC = null;
private SliceEditor _myEditor;
private ArrayList _SelectionBuffer = new ArrayList();
private ArrayList _SelectionObjectBuffer = new ArrayList();
public void SelectAll()
{
_SelectionBuffer.Clear();
_SelectionObjectBuffer.Clear();
for(int i = 0; i < _SlicePlane.Items.Count; i++)
{
SliceObject SO = _SlicePlane.Items[i] as SliceObject;
_SelectionObjectBuffer.Add(SO);
ArrayList OO = SO.GetControlPoints();
for(int j = 0; j < OO.Count; j++)
{
_SelectionBuffer.Add(OO[j]);
}
}
_myEditor.SelectObjects(_SelectionObjectBuffer);
Refresh();
}
#region EditorContext
public ArrayList getSelectionBuffer()
{ return _SelectionBuffer; }
public ArrayList getObjects()
{ return _SelectionObjectBuffer; }
#endregion
#region FUN
public FileUpdateNotify FUNotify
{ set { FUN = value; } }
#endregion
#region CursorPosAccessor
public float CurX
{ get { return cursorX; } }
public float CurY
{ get { return cursorY; } }
public float getCurX()
{ return cursorX; }
public float getCurY()
{ return cursorY; }
#endregion
#region Constructor
public SliceEditorControl(SliceEditor SE)
{
_myEditor = SE;
InitializeComponent();
cursorX = 0;
cursorY = 0;
// {fix} center code
originX = translatePixelX2GridX(-200);
originY = translatePixelY2GridY(-200);
}
#endregion
#region PostConstructorConstructor
public void FirstLink(SliceEmFile SEM)
{
_SliceFile = SEM;
}
#endregion
#region SetTheScaling
public void SetScale(float x)
{
if(x > 0)
{
scale = x;
}
Refresh();
}
#endregion
#region Translation Util
public int tranlsateGridX2PixelX(float x)
{ return (int)((x - originX) / (0.1f / scale)); }
public int tranlsateGridY2PixelY(float y)
{ return (int)((y - originY) / (0.1f / scale)); }
public float translatePixelX2GridX(int x)
{ return x * 0.1f / scale + originX; }
public float translatePixelY2GridY(int y)
{ return y * 0.1f / scale + originY; }
#endregion Translation Util
public void Link(SlicePlane SP)
{
if(SP != _SlicePlane)
{
_SelectionBuffer.Clear();
_SelectionObjectBuffer.Clear();
bTranslation = false;
bMulti = false;
bSelecting = false;
bTranslationMode2 = false;
}
_SlicePlane = SP;
_myEditor.SelectObjects(_SelectionObjectBuffer);
Refresh();
}
#region RenderGrid
public void DrawGrid(Graphics g)
{
float dxmin = translatePixelX2GridX(0);
float dxmax = translatePixelX2GridX(Width);
_SliceFile._minx = dxmin;
_SliceFile._maxx = dxmax;
for(float dx = ((int)(dxmin / 10)) * 10; dx <= dxmax; dx+=10)
{
int vx = tranlsateGridX2PixelX(dx);
g.DrawLine(_GridPenMajor, vx,0,vx,Size.Height);
g.DrawString(""+(dx), _GridFontMajor, _Black, vx + 5, Height - 15);
}
float dymin = translatePixelY2GridY(0);
float dymax = translatePixelY2GridY(Height);
_SliceFile._minz = dymin;
_SliceFile._maxz = dymax;
FUN.Notify();
for(float dy = ((int)(dymin / 10)) * 10; dy <= dymax; dy+=10)
{
int vy = tranlsateGridY2PixelY(dy);
g.DrawLine(_GridPenMajor, 0,vy,Size.Width,vy);
g.DrawString(""+(-dy), _GridFontMajor, _Black, 0, vy);
}
int cx = tranlsateGridX2PixelX(0);
int cy = tranlsateGridY2PixelY(0);
if(0 <= cx && cx <= Size.Width)
{
g.DrawLine(_GridPenCenter, cx,0,cx,Size.Height);
}
if(0 <= cy && cy <= Size.Height)
{
g.DrawLine(_GridPenCenter, 0,cy,Size.Width,cy);
}
int curx = tranlsateGridX2PixelX(cursorX);
int cury = tranlsateGridY2PixelY(cursorY);
if(-3 <= curx && curx <= Size.Width + 3)
{
if(-3 <= cury && cury <= Size.Height + 3)
{
g.DrawRectangle(_GridCursor, curx - 3, cury - 3, 6, 6);
g.DrawLine(_GridPenMajor, curx - 10, cury, curx + 10, cury);
g.DrawLine(_GridPenMajor, curx , cury - 10, curx, cury + 10);
}
}
g.DrawRectangle(_BorderPen,0,0,Size.Width,Size.Height);
}
#endregion
public void DrawObjects(Graphics g)
{
for(int i = 0; i < _SlicePlane.Items.Count; i++)
{
SliceObject SOSO = (SliceObject) _SlicePlane.Items[i];
SOSO.Draw(g, this, _SelectionObjectBuffer.Contains(SOSO));
}
}
public void DrawControlPoint(Graphics g, ControlPoint cp)
{
Pen myPen = new Pen(cp.c, 1);
int cx = tranlsateGridX2PixelX(cp.x + cp.dx);
int cy = tranlsateGridY2PixelY(cp.y + cp.dy);
int ar = 2;
if(_SelectionBuffer.Contains(cp))
{
g.FillEllipse(new SolidBrush(Color.Red),cx - ar - 2, cy - ar - 2, 2 * (ar + 2), 2 * (ar + 2));
}
g.FillEllipse(new SolidBrush(cp.c),cx - ar, cy - ar, 2 * ar, 2 * ar);
}
#region Dispose
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if( components != null )
components.Dispose();
}
base.Dispose( disposing );
}
#endregion
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
//
// SliceEditorControl
//
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.SliceEditorControl_KeyPress);
this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.SliceEditorControl_MouseUp);
this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.SliceEditorControl_KeyUp);
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.SliceEditorControl_KeyDown);
this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.SliceEditorControl_MouseMove);
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.SliceEditorControl_MouseDown);
}
#endregion
#region Painting
protected override void OnPaint(PaintEventArgs pe)
{
// TODO: Add custom paint code here
if(offScreenBmp==null)
{
offScreenBmp = new Bitmap(this.Width, this.Height);
offScreenDC = Graphics.FromImage(offScreenBmp);
}
else if(offScreenBmp.Width != this.Width || offScreenBmp.Height != this.Height)
{
offScreenBmp = new Bitmap(this.Width, this.Height);
offScreenDC = Graphics.FromImage(offScreenBmp);
}
if(_SlicePlane!=null)
{
offScreenDC.Clear(Color.LightGray );
DrawGrid(offScreenDC);
DrawObjects(offScreenDC);
DrawSelectionBox(offScreenDC);
}
else
{
offScreenDC.Clear(Color.Gray);
}
pe.Graphics.DrawImage(offScreenBmp, 0, 0);
}
protected override void OnPaintBackground(PaintEventArgs pe)
{}
#endregion
public void DrawSelectionBox(Graphics g)
{
if(!bSelecting) return;
int lReg = tranlsateGridX2PixelX(Math.Min(cursorX, end_cursorX));
int tReg = tranlsateGridY2PixelY(Math.Min(cursorY, end_cursorY));
int rReg = tranlsateGridX2PixelX(Math.Max(cursorX, end_cursorX));
int bReg = tranlsateGridY2PixelY(Math.Max(cursorY, end_cursorY));
if(lReg < 0) lReg = -1;
if(rReg > Width) rReg = Width + 1;
if(rReg < 0) return;
if(lReg > Width) return;
if(tReg < 0) tReg = -1;
if(bReg > Height) bReg = Height + 1;
if(bReg < 0) return;
if(tReg > Height) return;
g.DrawRectangle(new Pen(Color.Blue), lReg, tReg, rReg - lReg, bReg - tReg);
}
private float end_cursorX;
private float end_cursorY;
private bool bSelecting = false;
private bool bTranslation = false;
private bool bTranslationMode2 = false;
private bool bMulti = false;
private void SliceEditorControl_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if(_SlicePlane==null) return;
if(e.Button == MouseButtons.Left)
{
bTranslationMode2 = false;
if(rdown)
{
for(int i = 0; i < _SelectionObjectBuffer.Count; i++)
{
SliceObject SO = _SelectionObjectBuffer[i] as SliceObject;
for(int j = 0; j < SO.GetControlPoints().Count; j++)
{
ControlPoint CP = SO.GetControlPoints()[j] as ControlPoint;
CP.dx = 0;
CP.dy = 0;
}
Refresh();
}
}
if(bSelecting)
{
float lCursorX = translatePixelX2GridX(e.X);
float lCursorY = translatePixelY2GridY(e.Y);
if(Math.Min(cursorX, end_cursorX) <= lCursorX && lCursorX <= Math.Max(cursorX, end_cursorX))
{
if(Math.Min(cursorY, end_cursorY) <= lCursorY && lCursorY <= Math.Max(cursorY, end_cursorY))
{
bTranslation = true;
bSelecting = false;
}
}
bSelecting = false;
_myEditor.SelectObjects(null);
}
if(!bTranslation)
bSelecting = true;
ldown = true;
}
start_x = e.X;
start_y = e.Y;
cursorX = translatePixelX2GridX(e.X);
cursorY = translatePixelY2GridY(e.Y);
end_cursorX = cursorX;
end_cursorY = cursorY;
orig_originX = originX;
orig_originY = originY;
Refresh();
if(e.Button == MouseButtons.Right)
{
rdown = true;
bSelecting = false;
bTranslation = false;
SliceObject SO = _SlicePlane.ProcessClick(cursorX, cursorY);
if(SO != null)
{
_SelectionObjectBuffer.Clear();
_SelectionObjectBuffer.Add(SO);
bTranslationMode2 = true;
Link(_SlicePlane);
Refresh();
}
}
}
public void QuerySelectionBuffer()
{
if(!bMulti)
{
_SelectionBuffer.Clear();
_SelectionObjectBuffer.Clear();
}
if(_SlicePlane == null)
{
return;
}
ArrayList Cur = _SlicePlane.SelectPoints(
Math.Min(cursorX, end_cursorX),
Math.Min(cursorY, end_cursorY),
Math.Max(cursorX, end_cursorX),
Math.Max(cursorY, end_cursorY));
for(int k = 0; k < Cur.Count; k++)
{
ControlPoint CP = Cur[k] as ControlPoint;
if(!_SelectionBuffer.Contains(CP))
{
_SelectionBuffer.Add(CP);
}
}
for(int i = 0; i < _SelectionBuffer.Count; i++)
{
ControlPoint CP = _SelectionBuffer[i] as ControlPoint;
if(!_SelectionObjectBuffer.Contains(CP._parent))
{
_SelectionObjectBuffer.Add(CP._parent);
}
CP.dx = 0.0f;
CP.dy = 0.0f;
}
Link(_SlicePlane);
}
private void SliceEditorControl_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if(_SlicePlane==null) return;
if(ldown && rdown)
{
originX = orig_originX - (e.X - start_x) * .1f / scale;
originY = orig_originY - (e.Y - start_y) * .1f / scale;
Refresh();
}
if(rdown && !ldown && bTranslationMode2)
{
for(int i = 0; i < _SelectionObjectBuffer.Count; i++)
{
SliceObject SO = _SelectionObjectBuffer[i] as SliceObject;
for(int j = 0; j < SO.GetControlPoints().Count; j++)
{
ControlPoint CP = SO.GetControlPoints()[j] as ControlPoint;
CP.dx = (e.X - start_x) * .1f / scale;
CP.dy = (e.Y - start_y) * .1f / scale;
}
Refresh();
}
}
if(ldown && !rdown)
{
if(bTranslation)
{
for(int i = 0; i < _SelectionBuffer.Count; i++)
{
ControlPoint CP = _SelectionBuffer[i] as ControlPoint;
CP.dx = (e.X - start_x) * .1f / scale;
CP.dy = (e.Y - start_y) * .1f / scale;
}
Refresh();
}
else
{
end_cursorX = translatePixelX2GridX(e.X);
end_cursorY = translatePixelY2GridY(e.Y);
QuerySelectionBuffer();
Refresh();
}
}
else
{
// bSelecting = false;
}
}
private void SliceEditorControl_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
if(e.Button == MouseButtons.Left)
{
ldown = false;
if(bTranslation)
{
for(int i = 0; i < _SelectionBuffer.Count; i++)
{
ControlPoint CP = _SelectionBuffer[i] as ControlPoint;
CP.x = CP.x + (e.X - start_x) * .1f / scale;
CP.y = CP.y + (e.Y - start_y) * .1f / scale;
CP.dx = 0.0f;
CP.dy = 0.0f;
}
bTranslation = false;
}
end_cursorX = translatePixelX2GridX(e.X);
end_cursorY = translatePixelY2GridY(e.Y);
}
if(e.Button == MouseButtons.Right)
{
rdown = false;
if(bTranslationMode2)
{
for(int i = 0; i < _SelectionObjectBuffer.Count; i++)
{
SliceObject SO = _SelectionObjectBuffer[i] as SliceObject;
for(int j = 0; j < SO.GetControlPoints().Count; j++)
{
ControlPoint CP = SO.GetControlPoints()[j] as ControlPoint;
CP.x = CP.x + (e.X - start_x) * .1f / scale;
CP.y = CP.y + (e.Y - start_y) * .1f / scale;
CP.dx = 0;
CP.dy = 0;
}
Refresh();
}
}
}
}
private void SliceEditorControl_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if(e.Shift)
{
bMulti = true;
}
}
private void SliceEditorControl_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
bMulti = false;
}
private void SliceEditorControl_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
int v = -1;
if(e.KeyChar == '1') v = 1;
if(e.KeyChar == '2') v = 2;
if(e.KeyChar == '3') v = 3;
if(e.KeyChar == '4') v = 4;
if(e.KeyChar == '5') v = 5;
if(e.KeyChar == '6') v = 6;
if(e.KeyChar == '7') v = 7;
if(e.KeyChar == '8') v = 8;
if(e.KeyChar == '9') v = 9;
if(e.KeyChar == '0') v = 0;
if(v>=0)
{
for(int i = 0; i < _SelectionObjectBuffer.Count; i++)
{
SliceObject SO = _SelectionObjectBuffer[i] as SliceObject;
SO.RecieveRegion(v, cursorX, cursorY);
Refresh();
}
}
int m = -1;
if(e.KeyChar == 'd') m = 1;
if(e.KeyChar == 'u') m = 2;
if(e.KeyChar == 't') m = 3;
if(e.KeyChar == 'b') m = 0;
if(m>=0)
{
for(int i = 0; i < _SelectionObjectBuffer.Count; i++)
{
SliceObject SO = _SelectionObjectBuffer[i] as SliceObject;
SO.SetMode(m, cursorX, cursorY);
Refresh();
}
}
int k = 0;
if(e.KeyChar=='n') k = 1;
if(e.KeyChar=='p') k = -1;
if(e.KeyChar=='c') k = -5;
if(k!=0)
{
if(Math.Abs(k) <= 2)
{
for(int i = 0; i < _SelectionObjectBuffer.Count; i++)
{
SliceObject SO = _SelectionObjectBuffer[i] as SliceObject;
SO.SetMark(cursorX, cursorY, SO.MarkAt(cursorX, cursorY) + k);
Refresh();
}
}
else
{
for(int i = 0; i < _SelectionObjectBuffer.Count; i++)
{
SliceObject SO = _SelectionObjectBuffer[i] as SliceObject;
SO.SetMark(cursorX, cursorY, -1);
Refresh();
}
}
}
}
public void DrawMode(Graphics g, PointF PF, int m)
{
int px = tranlsateGridX2PixelX(PF.X);
int py = tranlsateGridY2PixelY(PF.Y);
if(-15 <= px && px <= Width + 15)
{ if(-5 <= py && py <= Height + 5)
{
g.DrawLine(_ModePen, px-7, py - 5, px-7, py + 5);
if(m==1)
{
for(int i = -5; i <= 5; i+=3)
{
g.DrawLine(_ModePenShadow, px-7+1, py + i+1, px-7-5+1, py + i - 5+1);
g.DrawLine(_ModePenShadow, px-7+1, py + i+1, px-7+5+1, py + i - 5+1);
}
}
if(m==2)
{
for(int i = -5; i <= 5; i+=3)
{
g.DrawLine(_ModePenShadow, px-7+1, py + i+1, px-7-5+1, py + i + 5+1);
g.DrawLine(_ModePenShadow, px-7+1, py + i+1, px-7+5+1, py + i + 5+1);
}
}
if(m==3)
{
for(int i = -5; i <= 5; i+=3)
{
g.DrawLine(_ModePenShadow, px-7+1, py + i+1, px-7-5+1, py + i+1);
g.DrawLine(_ModePenShadow, px-7+1, py + i+1, px-7+5+1, py + i+1);
}
}
g.DrawLine(_ModePen, px-7, py - 5, px-7, py + 5);
if(m==1)
{
for(int i = -5; i <= 5; i+=3)
{
g.DrawLine(_ModePen, px-7, py + i, px-7-5, py + i - 5);
g.DrawLine(_ModePen, px-7, py + i, px-7+5, py + i - 5);
}
}
if(m==2)
{
for(int i = -5; i <= 5; i+=3)
{
g.DrawLine(_ModePen, px-7, py + i, px-7-5, py + i + 5);
g.DrawLine(_ModePen, px-7, py + i, px-7+5, py + i + 5);
}
}
if(m==3)
{
for(int i = -5; i <= 5; i+=3)
{
g.DrawLine(_ModePen, px-7, py + i, px-7-5, py + i);
g.DrawLine(_ModePen, px-7, py + i, px-7+5, py + i);
}
}
}
}
}
}
}
/*
if(_SlicePlane==null) return;
if(e.Button == MouseButtons.Right)
{
if(dragging)
{
if(_SelectedControlPoint == null)
{
if(_SliceObject != null)
{
_SliceObject.CommitTranslation((e.X - start_x) * .1f / scale, (e.Y - start_y) * .1f / scale);
}
}
Refresh();
}
rdown = false;
moving = false;
dragging = false;
}
*/
/*
if(e.Button == MouseButtons.Left)
{
if(dragging)
return;
ldown = true;
cursorX = translatePixelX2GridX(e.X);
cursorY = translatePixelY2GridY(e.Y);
Refresh();
SliceObject MySO = _SlicePlane.ProcessClick(cursorX, cursorY);
if(MySO != null)
{
_SelectedControlPoint = MySO.OnClickGetControlPoint(cursorX, cursorY);
}
else
{
_SelectedControlPoint = null;
}
Link(_SlicePlane, MySO);
}
if(e.Button == MouseButtons.Right)
{
rdown = true;
SliceObject MySO = _SlicePlane.ProcessClick(translatePixelX2GridX(e.X), translatePixelY2GridY(e.Y));
Link(_SlicePlane, MySO);
if(_SliceObject != null)
{
dragging = true;
}
if(MySO != null)
{
_SelectedControlPoint = MySO.OnClickGetControlPoint(translatePixelX2GridX(e.X), translatePixelY2GridY(e.Y));
if(_SelectedControlPoint!=null)
{
orig_cp_x = _SelectedControlPoint.x;
orig_cp_y = _SelectedControlPoint.y;
}
}
if(dragging)
{
start_x = e.X;
start_y = e.Y;
}
}
if(ldown && rdown && !dragging)
{
moving = true;
start_x = e.X;
start_y = e.Y;
orig_originX = originX;
orig_originY = originY;
}
Refresh();
*/
/*
if(moving)
{
originX = orig_originX - (e.X - start_x) * .1f / scale;
originY = orig_originY - (e.Y - start_y) * .1f / scale;
Refresh();
}
if(dragging)
{
if(_SelectedControlPoint == null)
{
if(_SliceObject != null)
{
_SliceObject.TempTranslation((e.X - start_x) * .1f / scale, (e.Y - start_y) * .1f / scale);
}
}
else
{
_SelectedControlPoint.x = orig_cp_x + (e.X - start_x) * .1f / scale;
_SelectedControlPoint.y = orig_cp_y + (e.Y - start_y) * .1f / scale;
}
Refresh();
_SliceFile._updated = true;
}
*/
| |
#define COUNT_ACTIVATE_DEACTIVATE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using Orleans.Runtime.Providers;
using Orleans.Streams;
using UnitTests.GrainInterfaces;
namespace UnitTests.Grains
{
[Serializable]
public class StreamLifecycleTestGrainState
{
// For producer and consumer
// -- only need to store this because of how we run our unit tests against multiple providers
public string StreamProviderName { get; set; }
// For producer only.
public IAsyncStream<int> Stream { get; set; }
public bool IsProducer { get; set; }
public int NumMessagesSent { get; set; }
public int NumErrors { get; set; }
// For consumer only.
public HashSet<StreamSubscriptionHandle<int>> ConsumerSubscriptionHandles { get; set; }
public StreamLifecycleTestGrainState()
{
ConsumerSubscriptionHandles = new HashSet<StreamSubscriptionHandle<int>>();
}
}
public class GenericArg
{
public string A { get; private set; }
public int B { get; private set; }
public GenericArg(string a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
var item = obj as GenericArg;
if (item == null)
{
return false;
}
return A.Equals(item.A) && B.Equals(item.B);
}
public override int GetHashCode()
{
return (B * 397) ^ (A != null ? A.GetHashCode() : 0);
}
}
public class AsyncObserverArg : GenericArg
{
public AsyncObserverArg(string a, int b) : base(a, b) { }
}
public class AsyncObservableArg : GenericArg
{
public AsyncObservableArg(string a, int b) : base(a, b) { }
}
public class AsyncStreamArg : GenericArg
{
public AsyncStreamArg(string a, int b) : base(a, b) { }
}
public class StreamSubscriptionHandleArg : GenericArg
{
public StreamSubscriptionHandleArg(string a, int b) : base(a, b) { }
}
public class StreamLifecycleTestGrainBase : Grain<StreamLifecycleTestGrainState>
{
protected Logger logger;
protected string _lastProviderName;
protected IStreamProvider _streamProvider;
#if COUNT_ACTIVATE_DEACTIVATE
private IActivateDeactivateWatcherGrain watcher;
#endif
protected Task RecordActivate()
{
#if COUNT_ACTIVATE_DEACTIVATE
watcher = GrainFactory.GetGrain<IActivateDeactivateWatcherGrain>(0);
return watcher.RecordActivateCall(IdentityString);
#else
return TaskDone.Done;
#endif
}
protected Task RecordDeactivate()
{
#if COUNT_ACTIVATE_DEACTIVATE
return watcher.RecordDeactivateCall(IdentityString);
#else
return TaskDone.Done;
#endif
}
protected void InitStream(Guid streamId, string streamNamespace, string providerToUse)
{
if (streamId == null) throw new ArgumentNullException("streamId", "Can't have null stream id");
if (streamNamespace == null) throw new ArgumentNullException("streamNamespace", "Can't have null stream namespace values");
if (providerToUse == null) throw new ArgumentNullException("providerToUse", "Can't have null stream provider name");
if (State.Stream != null && State.Stream.Guid != streamId)
{
if (logger.IsVerbose) logger.Verbose("Stream already exists for StreamId={0} StreamProvider={1} - Resetting", State.Stream, providerToUse);
// Note: in this test, we are deliberately not doing Unsubscribe consumers, just discard old stream and let auto-cleanup functions do their thing.
State.ConsumerSubscriptionHandles.Clear();
State.IsProducer = false;
State.NumMessagesSent = 0;
State.NumErrors = 0;
State.Stream = null;
}
if (logger.IsVerbose) logger.Verbose("InitStream StreamId={0} StreamProvider={1}", streamId, providerToUse);
if (providerToUse != _lastProviderName)
{
_streamProvider = GetStreamProvider(providerToUse);
_lastProviderName = providerToUse;
}
IAsyncStream<int> stream = _streamProvider.GetStream<int>(streamId, streamNamespace);
State.Stream = stream;
State.StreamProviderName = providerToUse;
if (logger.IsVerbose) logger.Verbose("InitStream returning with Stream={0} with ref type = {1}", State.Stream, State.Stream.GetType().FullName);
}
}
[Orleans.Providers.StorageProvider(ProviderName = "MemoryStore")]
public class StreamLifecycleConsumerGrain : StreamLifecycleTestGrainBase, IStreamLifecycleConsumerGrain
{
protected IDictionary<StreamSubscriptionHandle<int>, MyStreamObserver<int>> Observers { get; set; }
public override async Task OnActivateAsync()
{
logger = GetLogger(GetType().Name + "-" + IdentityString);
if (logger.IsVerbose) logger.Verbose("OnActivateAsync");
await RecordActivate();
if (Observers == null)
{
Observers = new Dictionary<StreamSubscriptionHandle<int>, MyStreamObserver<int>>();
}
if (State.Stream != null && State.StreamProviderName != null)
{
if (State.ConsumerSubscriptionHandles.Count > 0)
{
var handles = State.ConsumerSubscriptionHandles.ToArray();
logger.Info("ReconnectConsumerHandles SubscriptionHandles={0} Grain={1}", Utils.EnumerableToString(handles), this.AsReference<IStreamLifecycleConsumerGrain>());
foreach (var handle in handles)
{
var observer = new MyStreamObserver<int>(logger);
StreamSubscriptionHandle<int> subsHandle = await handle.ResumeAsync(observer);
Observers.Add(subsHandle, observer);
}
}
}
else
{
if (logger.IsVerbose) logger.Verbose("Not conected to stream yet.");
}
}
public override async Task OnDeactivateAsync()
{
if (logger.IsVerbose) logger.Verbose("OnDeactivateAsync");
await RecordDeactivate();
}
public Task<int> GetReceivedCount()
{
int numReceived = Observers.Sum(o => o.Value.NumItems);
if (logger.IsVerbose) logger.Verbose("ReceivedCount={0}", numReceived);
return Task.FromResult(numReceived);
}
public Task<int> GetErrorsCount()
{
int numErrors = Observers.Sum(o => o.Value.NumErrors);
if (logger.IsVerbose) logger.Verbose("ErrorsCount={0}", numErrors);
return Task.FromResult(numErrors);
}
public Task Ping()
{
logger.Info("Ping");
return TaskDone.Done;
}
public virtual async Task BecomeConsumer(Guid streamId, string streamNamespace, string providerToUse)
{
if (logger.IsVerbose) logger.Verbose("BecomeConsumer StreamId={0} StreamProvider={1} Grain={2}", streamId, providerToUse, this.AsReference<IStreamLifecycleConsumerGrain>());
InitStream(streamId, streamNamespace, providerToUse);
var observer = new MyStreamObserver<int>(logger);
var subsHandle = await State.Stream.SubscribeAsync(observer);
State.ConsumerSubscriptionHandles.Add(subsHandle);
Observers.Add(subsHandle, observer);
await WriteStateAsync();
}
public virtual async Task TestBecomeConsumerSlim(Guid streamIdGuid, string streamNamespace, string providerName)
{
InitStream(streamIdGuid, streamNamespace, providerName);
var observer = new MyStreamObserver<int>(logger);
//var subsHandle = await State.Stream.SubscribeAsync(observer);
IStreamConsumerExtension myExtensionReference;
#if USE_CAST
myExtensionReference = StreamConsumerExtensionFactory.Cast(this.AsReference());
#else
var tup = await SiloProviderRuntime.Instance.BindExtension<StreamConsumerExtension, IStreamConsumerExtension>(
() => new StreamConsumerExtension(SiloProviderRuntime.Instance, _streamProvider.IsRewindable));
StreamConsumerExtension myExtension = tup.Item1;
myExtensionReference = tup.Item2;
#endif
string extKey = providerName + "_" + State.Stream.Namespace;
IPubSubRendezvousGrain pubsub = GrainFactory.GetGrain<IPubSubRendezvousGrain>(streamIdGuid, extKey, null);
GuidId subscriptionId = GuidId.GetNewGuidId();
await pubsub.RegisterConsumer(subscriptionId, ((StreamImpl<int>)State.Stream).StreamId, myExtensionReference, null);
myExtension.SetObserver(subscriptionId, ((StreamImpl<int>)State.Stream), observer, null, null);
}
public async Task RemoveConsumer(Guid streamId, string streamNamespace, string providerName, StreamSubscriptionHandle<int> subsHandle)
{
if (logger.IsVerbose) logger.Verbose("RemoveConsumer StreamId={0} StreamProvider={1}", streamId, providerName);
if (State.ConsumerSubscriptionHandles.Count == 0) throw new InvalidOperationException("Not a Consumer");
await subsHandle.UnsubscribeAsync();
Observers.Remove(subsHandle);
State.ConsumerSubscriptionHandles.Remove(subsHandle);
await WriteStateAsync();
}
public async Task ClearGrain()
{
logger.Info("ClearGrain");
var subsHandles = State.ConsumerSubscriptionHandles.ToArray();
foreach (var handle in subsHandles)
{
await handle.UnsubscribeAsync();
}
State.ConsumerSubscriptionHandles.Clear();
State.Stream = null;
State.IsProducer = false;
Observers.Clear();
await ClearStateAsync();
}
}
[Orleans.Providers.StorageProvider(ProviderName = "MemoryStore")]
public class FilteredStreamConsumerGrain : StreamLifecycleConsumerGrain, IFilteredStreamConsumerGrain
{
private static Logger _logger;
private const int FilterDataOdd = 1;
private const int FilterDataEven = 2;
public override Task BecomeConsumer(Guid streamId, string streamNamespace, string providerName)
{
throw new InvalidOperationException("Should not be calling unfiltered BecomeConsumer method on " + GetType());
}
public async Task BecomeConsumer(Guid streamId, string streamNamespace, string providerName, bool sendEvensOnly)
{
_logger = logger;
if (logger.IsVerbose)
logger.Verbose("BecomeConsumer StreamId={0} StreamProvider={1} Filter={2} Grain={3}",
streamId, providerName, sendEvensOnly, this.AsReference<IFilteredStreamConsumerGrain>());
InitStream(streamId, streamNamespace, providerName);
var observer = new MyStreamObserver<int>(logger);
StreamFilterPredicate filterFunc;
object filterData;
if (sendEvensOnly)
{
filterFunc = FilterIsEven;
filterData = FilterDataEven;
}
else
{
filterFunc = FilterIsOdd;
filterData = FilterDataOdd;
}
var subsHandle = await State.Stream.SubscribeAsync(observer, null, filterFunc, filterData);
State.ConsumerSubscriptionHandles.Add(subsHandle);
Observers.Add(subsHandle, observer);
await WriteStateAsync();
}
public async Task SubscribeWithBadFunc(Guid streamId, string streamNamespace, string providerName)
{
logger.Info("SubscribeWithBadFunc StreamId={0} StreamProvider={1}Grain={2}",
streamId, providerName, this.AsReference<IFilteredStreamConsumerGrain>());
InitStream(streamId, streamNamespace, providerName);
var observer = new MyStreamObserver<int>(logger);
StreamFilterPredicate filterFunc = BadFunc;
// This next call should fail because func is not static
await State.Stream.SubscribeAsync(observer, null, filterFunc);
}
public static bool FilterIsEven(IStreamIdentity stream, object filterData, object item)
{
if (!FilterDataEven.Equals(filterData))
{
throw new Exception("Should have got the correct filter data passed in, but got: " + filterData);
}
int val = (int) item;
bool result = val % 2 == 0;
if (_logger != null) _logger.Info("FilterIsEven(Stream={0},FilterData={1},Item={2}) Filter = {3}", stream, filterData, item, result);
return result;
}
public static bool FilterIsOdd(IStreamIdentity stream, object filterData, object item)
{
if (!FilterDataOdd.Equals(filterData))
{
throw new Exception("Should have got the correct filter data passed in, but got: " + filterData);
}
int val = (int) item;
bool result = val % 2 == 1;
if (_logger != null) _logger.Info("FilterIsOdd(Stream={0},FilterData={1},Item={2}) Filter = {3}", stream, filterData, item, result);
return result;
}
// Function is not static, so cannot be used as a filter predicate function.
public bool BadFunc(IStreamIdentity stream, object filterData, object item)
{
return true;
}
}
[Orleans.Providers.StorageProvider(ProviderName = "MemoryStore")]
public class StreamLifecycleProducerGrain : StreamLifecycleTestGrainBase, IStreamLifecycleProducerGrain
{
public override async Task OnActivateAsync()
{
logger = GetLogger(GetType().Name + "-" + IdentityString);
if (logger.IsVerbose) logger.Verbose("OnActivateAsync");
await RecordActivate();
if (State.Stream != null && State.StreamProviderName != null)
{
if (logger.IsVerbose) logger.Verbose("Reconnected to stream {0}", State.Stream);
}
else
{
if (logger.IsVerbose) logger.Verbose("Not connected to stream yet.");
}
}
public override async Task OnDeactivateAsync()
{
if (logger.IsVerbose) logger.Verbose("OnDeactivateAsync");
await RecordDeactivate();
}
public Task<int> GetSendCount()
{
int result = State.NumMessagesSent;
if (logger.IsVerbose) logger.Verbose("GetSendCount={0}", result);
return Task.FromResult(result);
}
public Task<int> GetErrorsCount()
{
int result = State.NumErrors;
if (logger.IsVerbose) logger.Verbose("GetErrorsCount={0}", result);
return Task.FromResult(result);
}
public Task Ping()
{
logger.Info("Ping");
return TaskDone.Done;
}
public async Task SendItem(int item)
{
if (!State.IsProducer || State.Stream == null) throw new InvalidOperationException("Not a Producer");
if (logger.IsVerbose) logger.Verbose("SendItem Item={0}", item);
Exception error = null;
try
{
await State.Stream.OnNextAsync(item);
if (logger.IsVerbose) logger.Verbose("Successful SendItem " + item);
State.NumMessagesSent++;
}
catch (Exception exc)
{
logger.Error(0, "Error from SendItem " + item, exc);
State.NumErrors++;
error = exc;
}
await WriteStateAsync(); // Update counts in persisted state
if (error != null)
{
throw new AggregateException(error);
}
if (logger.IsVerbose) logger.Verbose("Finished SendItem for Item={0}", item);
}
public async Task BecomeProducer(Guid streamId, string streamNamespace, string providerName)
{
if (logger.IsVerbose) logger.Verbose("BecomeProducer StreamId={0} StreamProvider={1}", streamId, providerName);
InitStream(streamId, streamNamespace, providerName);
State.IsProducer = true;
// Send an initial message to ensure we are properly initialized as a Producer.
await State.Stream.OnNextAsync(0);
State.NumMessagesSent++;
await WriteStateAsync();
if (logger.IsVerbose) logger.Verbose("Finished BecomeProducer for StreamId={0} StreamProvider={1}", streamId, providerName);
}
public async Task ClearGrain()
{
logger.Info("ClearGrain");
State.IsProducer = false;
State.Stream = null;
await ClearStateAsync();
}
public async Task DoDeactivateNoClose()
{
if (logger.IsVerbose) logger.Verbose("DoDeactivateNoClose");
State.IsProducer = false;
State.Stream = null;
await WriteStateAsync();
if (logger.IsVerbose) logger.Verbose("Calling DeactivateOnIdle");
DeactivateOnIdle();
}
}
[Serializable]
public class MyStreamObserver<T> : IAsyncObserver<T>
{
internal int NumItems { get; private set; }
internal int NumErrors { get; private set; }
private readonly Logger logger;
internal MyStreamObserver(Logger logger)
{
this.logger = logger;
}
public Task OnNextAsync(T item, StreamSequenceToken token)
{
NumItems++;
if (logger != null && logger.IsVerbose)
{
logger.Verbose("Received OnNextAsync - Item={0} - Total Items={1} Errors={2}", item, NumItems, NumErrors);
}
return TaskDone.Done;
}
public Task OnCompletedAsync()
{
if (logger != null)
{
logger.Info("Receive OnCompletedAsync - Total Items={0} Errors={1}", NumItems, NumErrors);
}
return TaskDone.Done;
}
public Task OnErrorAsync(Exception ex)
{
NumErrors++;
if (logger != null)
{
logger.Warn(1, "Received OnErrorAsync - Exception={0} - Total Items={1} Errors={2}", ex, NumItems, NumErrors);
}
return TaskDone.Done;
}
}
public class ClosedTypeStreamObserver : MyStreamObserver<AsyncObserverArg>
{
public ClosedTypeStreamObserver(Logger logger) : base(logger)
{
}
}
public interface IClosedTypeAsyncObservable : IAsyncObservable<AsyncObservableArg> { }
public interface IClosedTypeAsyncStream : IAsyncStream<AsyncStreamArg> { }
internal class ClosedTypeStreamSubscriptionHandle : StreamSubscriptionHandleImpl<StreamSubscriptionHandleArg>
{
public ClosedTypeStreamSubscriptionHandle() : base(null, null, false) { /* not a subject to the creation */ }
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Extensions.Options;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Services;
using Umbraco.Extensions;
using File = System.IO.File;
namespace Umbraco.Cms.Core.Packaging
{
/// <summary>
/// Manages the storage of installed/created package definitions
/// </summary>
[Obsolete("Packages have now been moved to the database instead of local files, please use CreatedPackageSchemaRepository instead")]
public class PackagesRepository : ICreatedPackagesRepository
{
private readonly IContentService _contentService;
private readonly IContentTypeService _contentTypeService;
private readonly IDataTypeService _dataTypeService;
private readonly IFileService _fileService;
private readonly IMacroService _macroService;
private readonly ILocalizationService _languageService;
private readonly IEntityXmlSerializer _serializer;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly string _packageRepositoryFileName;
private readonly string _createdPackagesFolderPath;
private readonly string _packagesFolderPath;
private readonly string _tempFolderPath;
private readonly PackageDefinitionXmlParser _parser;
private readonly IMediaService _mediaService;
private readonly IMediaTypeService _mediaTypeService;
private readonly MediaFileManager _mediaFileManager;
private readonly FileSystems _fileSystems;
/// <summary>
/// Constructor
/// </summary>
/// <param name="contentService"></param>
/// <param name="contentTypeService"></param>
/// <param name="dataTypeService"></param>
/// <param name="fileService"></param>
/// <param name="macroService"></param>
/// <param name="languageService"></param>
/// <param name="hostingEnvironment"></param>
/// <param name="serializer"></param>
/// <param name="logger"></param>
/// <param name="packageRepositoryFileName">
/// The file name for storing the package definitions (i.e. "createdPackages.config")
/// </param>
/// <param name="tempFolderPath"></param>
/// <param name="packagesFolderPath"></param>
/// <param name="mediaFolderPath"></param>
public PackagesRepository(
IContentService contentService,
IContentTypeService contentTypeService,
IDataTypeService dataTypeService,
IFileService fileService,
IMacroService macroService,
ILocalizationService languageService,
IHostingEnvironment hostingEnvironment,
IEntityXmlSerializer serializer,
IOptions<GlobalSettings> globalSettings,
IMediaService mediaService,
IMediaTypeService mediaTypeService,
MediaFileManager mediaFileManager,
FileSystems fileSystems,
string packageRepositoryFileName,
string tempFolderPath = null,
string packagesFolderPath = null,
string mediaFolderPath = null)
{
if (string.IsNullOrWhiteSpace(packageRepositoryFileName))
throw new ArgumentException("Value cannot be null or whitespace.", nameof(packageRepositoryFileName));
_contentService = contentService;
_contentTypeService = contentTypeService;
_dataTypeService = dataTypeService;
_fileService = fileService;
_macroService = macroService;
_languageService = languageService;
_serializer = serializer;
_hostingEnvironment = hostingEnvironment;
_packageRepositoryFileName = packageRepositoryFileName;
_tempFolderPath = tempFolderPath ?? Constants.SystemDirectories.TempData.EnsureEndsWith('/') + "PackageFiles";
_packagesFolderPath = packagesFolderPath ?? Constants.SystemDirectories.Packages;
_createdPackagesFolderPath = mediaFolderPath ?? Constants.SystemDirectories.CreatedPackages;
_parser = new PackageDefinitionXmlParser();
_mediaService = mediaService;
_mediaTypeService = mediaTypeService;
_mediaFileManager = mediaFileManager;
_fileSystems = fileSystems;
}
private string CreatedPackagesFile => _packagesFolderPath.EnsureEndsWith('/') + _packageRepositoryFileName;
public IEnumerable<PackageDefinition> GetAll()
{
var packagesXml = EnsureStorage(out _);
if (packagesXml?.Root == null)
yield break;
foreach (var packageXml in packagesXml.Root.Elements("package"))
yield return _parser.ToPackageDefinition(packageXml);
}
public PackageDefinition GetById(int id)
{
var packagesXml = EnsureStorage(out var packageFile);
var packageXml = packagesXml?.Root?.Elements("package").FirstOrDefault(x => x.AttributeValue<int>("id") == id);
return packageXml == null ? null : _parser.ToPackageDefinition(packageXml);
}
public void Delete(int id)
{
var packagesXml = EnsureStorage(out var packagesFile);
var packageXml = packagesXml?.Root?.Elements("package").FirstOrDefault(x => x.AttributeValue<int>("id") == id);
if (packageXml == null)
return;
packageXml.Remove();
packagesXml.Save(packagesFile);
}
public bool SavePackage(PackageDefinition definition)
{
if (definition == null)
throw new ArgumentNullException(nameof(definition));
var packagesXml = EnsureStorage(out var packagesFile);
if (packagesXml?.Root == null)
return false;
//ensure it's valid
ValidatePackage(definition);
if (definition.Id == default)
{
//need to gen an id and persist
// Find max id
var maxId = packagesXml.Root.Elements("package").Max(x => x.AttributeValue<int?>("id")) ?? 0;
var newId = maxId + 1;
definition.Id = newId;
definition.PackageId = definition.PackageId == default ? Guid.NewGuid() : definition.PackageId;
var packageXml = _parser.ToXml(definition);
packagesXml.Root.Add(packageXml);
}
else
{
//existing
var packageXml = packagesXml.Root.Elements("package").FirstOrDefault(x => x.AttributeValue<int>("id") == definition.Id);
if (packageXml == null)
return false;
var updatedXml = _parser.ToXml(definition);
packageXml.ReplaceWith(updatedXml);
}
packagesXml.Save(packagesFile);
return true;
}
public string ExportPackage(PackageDefinition definition)
{
if (definition.Id == default)
throw new ArgumentException("The package definition does not have an ID, it must be saved before being exported");
if (definition.PackageId == default)
throw new ArgumentException("the package definition does not have a GUID, it must be saved before being exported");
//ensure it's valid
ValidatePackage(definition);
//Create a folder for building this package
var temporaryPath = _hostingEnvironment.MapPathContentRoot(_tempFolderPath.EnsureEndsWith('/') + Guid.NewGuid());
if (Directory.Exists(temporaryPath) == false)
{
Directory.CreateDirectory(temporaryPath);
}
try
{
//Init package file
XDocument compiledPackageXml = CreateCompiledPackageXml(out XElement root);
//Info section
root.Add(GetPackageInfoXml(definition));
PackageDocumentsAndTags(definition, root);
PackageDocumentTypes(definition, root);
PackageMediaTypes(definition, root);
PackageTemplates(definition, root);
PackageStylesheets(definition, root);
PackageStaticFiles(definition.Scripts, root, "Scripts", "Script", _fileSystems.ScriptsFileSystem);
PackageStaticFiles(definition.PartialViews, root, "PartialViews", "View", _fileSystems.PartialViewsFileSystem);
PackageMacros(definition, root);
PackageDictionaryItems(definition, root);
PackageLanguages(definition, root);
PackageDataTypes(definition, root);
Dictionary<string, Stream> mediaFiles = PackageMedia(definition, root);
string fileName;
string tempPackagePath;
if (mediaFiles.Count > 0)
{
fileName = "package.zip";
tempPackagePath = Path.Combine(temporaryPath, fileName);
using (FileStream fileStream = File.OpenWrite(tempPackagePath))
using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Create, true))
{
ZipArchiveEntry packageXmlEntry = archive.CreateEntry("package.xml");
using (Stream entryStream = packageXmlEntry.Open())
{
compiledPackageXml.Save(entryStream);
}
foreach (KeyValuePair<string, Stream> mediaFile in mediaFiles)
{
var entryPath = $"media{mediaFile.Key.EnsureStartsWith('/')}";
ZipArchiveEntry mediaEntry = archive.CreateEntry(entryPath);
using (Stream entryStream = mediaEntry.Open())
using (mediaFile.Value)
{
mediaFile.Value.Seek(0, SeekOrigin.Begin);
mediaFile.Value.CopyTo(entryStream);
}
}
}
}
else
{
fileName = "package.xml";
tempPackagePath = Path.Combine(temporaryPath, fileName);
using (FileStream fileStream = File.OpenWrite(tempPackagePath))
{
compiledPackageXml.Save(fileStream);
}
}
var directoryName = _hostingEnvironment.MapPathContentRoot(Path.Combine(_createdPackagesFolderPath, definition.Name.Replace(' ', '_')));
Directory.CreateDirectory(directoryName);
var finalPackagePath = Path.Combine(directoryName, fileName);
if (File.Exists(finalPackagePath))
{
File.Delete(finalPackagePath);
}
File.Move(tempPackagePath, finalPackagePath);
definition.PackagePath = finalPackagePath;
SavePackage(definition);
return finalPackagePath;
}
finally
{
// Clean up
Directory.Delete(temporaryPath, true);
}
}
private void ValidatePackage(PackageDefinition definition)
{
// ensure it's valid
var context = new ValidationContext(definition, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(definition, context, results);
if (!isValid)
throw new InvalidOperationException("Validation failed, there is invalid data on the model: " + string.Join(", ", results.Select(x => x.ErrorMessage)));
}
private void PackageDataTypes(PackageDefinition definition, XContainer root)
{
var dataTypes = new XElement("DataTypes");
foreach (var dtId in definition.DataTypes)
{
if (!int.TryParse(dtId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var outInt))
continue;
var dataType = _dataTypeService.GetDataType(outInt);
if (dataType == null)
continue;
dataTypes.Add(_serializer.Serialize(dataType));
}
root.Add(dataTypes);
}
private void PackageLanguages(PackageDefinition definition, XContainer root)
{
var languages = new XElement("Languages");
foreach (var langId in definition.Languages)
{
if (!int.TryParse(langId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var outInt))
continue;
var lang = _languageService.GetLanguageById(outInt);
if (lang == null)
continue;
languages.Add(_serializer.Serialize(lang));
}
root.Add(languages);
}
private void PackageDictionaryItems(PackageDefinition definition, XContainer root)
{
var rootDictionaryItems = new XElement("DictionaryItems");
var items = new Dictionary<Guid, (IDictionaryItem dictionaryItem, XElement serializedDictionaryValue)>();
foreach (var dictionaryId in definition.DictionaryItems)
{
if (!int.TryParse(dictionaryId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var outInt))
{
continue;
}
IDictionaryItem di = _languageService.GetDictionaryItemById(outInt);
if (di == null)
{
continue;
}
items[di.Key] = (di, _serializer.Serialize(di, false));
}
// organize them in hierarchy ...
var itemCount = items.Count;
var processed = new Dictionary<Guid, XElement>();
while (processed.Count < itemCount)
{
foreach (Guid key in items.Keys.ToList())
{
(IDictionaryItem dictionaryItem, XElement serializedDictionaryValue) = items[key];
if (!dictionaryItem.ParentId.HasValue)
{
// if it has no parent, its definitely just at the root
AppendDictionaryElement(rootDictionaryItems, items, processed, key, serializedDictionaryValue);
}
else
{
if (processed.ContainsKey(dictionaryItem.ParentId.Value))
{
// we've processed this parent element already so we can just append this xml child to it
AppendDictionaryElement(processed[dictionaryItem.ParentId.Value], items, processed, key, serializedDictionaryValue);
}
else if (items.ContainsKey(dictionaryItem.ParentId.Value))
{
// we know the parent exists in the dictionary but
// we haven't processed it yet so we'll leave it for the next loop
continue;
}
else
{
// in this case, the parent of this item doesn't exist in our collection, we have no
// choice but to add it to the root.
AppendDictionaryElement(rootDictionaryItems, items, processed, key, serializedDictionaryValue);
}
}
}
}
root.Add(rootDictionaryItems);
static void AppendDictionaryElement(XElement rootDictionaryItems, Dictionary<Guid, (IDictionaryItem dictionaryItem, XElement serializedDictionaryValue)> items, Dictionary<Guid, XElement> processed, Guid key, XElement serializedDictionaryValue)
{
// track it
processed.Add(key, serializedDictionaryValue);
// append it
rootDictionaryItems.Add(serializedDictionaryValue);
// remove it so its not re-processed
items.Remove(key);
}
}
private void PackageMacros(PackageDefinition definition, XContainer root)
{
var packagedMacros = new List<IMacro>();
var macros = new XElement("Macros");
foreach (var macroId in definition.Macros)
{
if (!int.TryParse(macroId, NumberStyles.Integer, CultureInfo.InvariantCulture, out int outInt))
{
continue;
}
XElement macroXml = GetMacroXml(outInt, out IMacro macro);
if (macroXml == null)
{
continue;
}
macros.Add(macroXml);
packagedMacros.Add(macro);
}
root.Add(macros);
// Get the partial views for macros and package those (exclude views outside of the default directory, e.g. App_Plugins\*\Views)
IEnumerable<string> views = packagedMacros.Where(x => x.MacroSource.StartsWith(Constants.SystemDirectories.MacroPartials))
.Select(x => x.MacroSource.Substring(Constants.SystemDirectories.MacroPartials.Length).Replace('/', '\\'));
PackageStaticFiles(views, root, "MacroPartialViews", "View", _fileSystems.MacroPartialsFileSystem);
}
private void PackageStylesheets(PackageDefinition definition, XContainer root)
{
var stylesheetsXml = new XElement("Stylesheets");
foreach (var stylesheet in definition.Stylesheets)
{
if (stylesheet.IsNullOrWhiteSpace())
{
continue;
}
XElement xml = GetStylesheetXml(stylesheet, true);
if (xml != null)
{
stylesheetsXml.Add(xml);
}
}
root.Add(stylesheetsXml);
}
private void PackageStaticFiles(
IEnumerable<string> filePaths,
XContainer root,
string containerName,
string elementName,
IFileSystem fileSystem)
{
var scriptsXml = new XElement(containerName);
foreach (var file in filePaths)
{
if (file.IsNullOrWhiteSpace())
{
continue;
}
if (!fileSystem.FileExists(file))
{
throw new InvalidOperationException("No file found with path " + file);
}
using (Stream stream = fileSystem.OpenFile(file))
using (var reader = new StreamReader(stream))
{
var fileContents = reader.ReadToEnd();
scriptsXml.Add(
new XElement(
elementName,
new XAttribute("path", file),
new XCData(fileContents)));
}
}
root.Add(scriptsXml);
}
private void PackageTemplates(PackageDefinition definition, XContainer root)
{
var templatesXml = new XElement("Templates");
foreach (var templateId in definition.Templates)
{
if (!int.TryParse(templateId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var outInt))
continue;
var template = _fileService.GetTemplate(outInt);
if (template == null)
continue;
templatesXml.Add(_serializer.Serialize(template));
}
root.Add(templatesXml);
}
private void PackageDocumentTypes(PackageDefinition definition, XContainer root)
{
var contentTypes = new HashSet<IContentType>();
var docTypesXml = new XElement("DocumentTypes");
foreach (var dtId in definition.DocumentTypes)
{
if (!int.TryParse(dtId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var outInt))
continue;
var contentType = _contentTypeService.Get(outInt);
if (contentType == null)
continue;
AddDocumentType(contentType, contentTypes);
}
foreach (var contentType in contentTypes)
docTypesXml.Add(_serializer.Serialize(contentType));
root.Add(docTypesXml);
}
private void PackageMediaTypes(PackageDefinition definition, XContainer root)
{
var mediaTypes = new HashSet<IMediaType>();
var mediaTypesXml = new XElement("MediaTypes");
foreach (var mediaTypeId in definition.MediaTypes)
{
if (!int.TryParse(mediaTypeId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var outInt))
continue;
var mediaType = _mediaTypeService.Get(outInt);
if (mediaType == null)
continue;
AddMediaType(mediaType, mediaTypes);
}
foreach (var mediaType in mediaTypes)
mediaTypesXml.Add(_serializer.Serialize(mediaType));
root.Add(mediaTypesXml);
}
private void PackageDocumentsAndTags(PackageDefinition definition, XContainer root)
{
//Documents and tags
if (string.IsNullOrEmpty(definition.ContentNodeId) == false && int.TryParse(definition.ContentNodeId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var contentNodeId))
{
if (contentNodeId > 0)
{
//load content from umbraco.
var content = _contentService.GetById(contentNodeId);
if (content != null)
{
var contentXml = definition.ContentLoadChildNodes ? content.ToDeepXml(_serializer) : content.ToXml(_serializer);
//Create the Documents/DocumentSet node
root.Add(
new XElement("Documents",
new XElement("DocumentSet",
new XAttribute("importMode", "root"),
contentXml)));
// TODO: I guess tags has been broken for a very long time for packaging, we should get this working again sometime
////Create the TagProperties node - this is used to store a definition for all
//// document properties that are tags, this ensures that we can re-import tags properly
//XmlNode tagProps = new XElement("TagProperties");
////before we try to populate this, we'll do a quick lookup to see if any of the documents
//// being exported contain published tags.
//var allExportedIds = documents.SelectNodes("//@id").Cast<XmlNode>()
// .Select(x => x.Value.TryConvertTo<int>())
// .Where(x => x.Success)
// .Select(x => x.Result)
// .ToArray();
//var allContentTags = new List<ITag>();
//foreach (var exportedId in allExportedIds)
//{
// allContentTags.AddRange(
// Current.Services.TagService.GetTagsForEntity(exportedId));
//}
////This is pretty round-about but it works. Essentially we need to get the properties that are tagged
//// but to do that we need to lookup by a tag (string)
//var allTaggedEntities = new List<TaggedEntity>();
//foreach (var group in allContentTags.Select(x => x.Group).Distinct())
//{
// allTaggedEntities.AddRange(
// Current.Services.TagService.GetTaggedContentByTagGroup(group));
//}
////Now, we have all property Ids/Aliases and their referenced document Ids and tags
//var allExportedTaggedEntities = allTaggedEntities.Where(x => allExportedIds.Contains(x.EntityId))
// .DistinctBy(x => x.EntityId)
// .OrderBy(x => x.EntityId);
//foreach (var taggedEntity in allExportedTaggedEntities)
//{
// foreach (var taggedProperty in taggedEntity.TaggedProperties.Where(x => x.Tags.Any()))
// {
// XmlNode tagProp = new XElement("TagProperty");
// var docId = packageManifest.CreateAttribute("docId", "");
// docId.Value = taggedEntity.EntityId.ToString(CultureInfo.InvariantCulture);
// tagProp.Attributes.Append(docId);
// var propertyAlias = packageManifest.CreateAttribute("propertyAlias", "");
// propertyAlias.Value = taggedProperty.PropertyTypeAlias;
// tagProp.Attributes.Append(propertyAlias);
// var group = packageManifest.CreateAttribute("group", "");
// group.Value = taggedProperty.Tags.First().Group;
// tagProp.Attributes.Append(group);
// tagProp.AppendChild(packageManifest.CreateCDataSection(
// JsonConvert.SerializeObject(taggedProperty.Tags.Select(x => x.Text).ToArray())));
// tagProps.AppendChild(tagProp);
// }
//}
//manifestRoot.Add(tagProps);
}
}
}
}
private Dictionary<string, Stream> PackageMedia(PackageDefinition definition, XElement root)
{
var mediaStreams = new Dictionary<string, Stream>();
// callback that occurs on each serialized media item
void OnSerializedMedia(IMedia media, XElement xmlMedia)
{
// get the media file path and store that separately in the XML.
// the media file path is different from the URL and is specifically
// extracted using the property editor for this media file and the current media file system.
Stream mediaStream = _mediaFileManager.GetFile(media, out var mediaFilePath);
if (mediaStream != null)
{
xmlMedia.Add(new XAttribute("mediaFilePath", mediaFilePath));
// add the stream to our outgoing stream
mediaStreams.Add(mediaFilePath, mediaStream);
}
}
IEnumerable<IMedia> medias = _mediaService.GetByIds(definition.MediaUdis);
var mediaXml = new XElement(
"MediaItems",
medias.Select(media =>
{
XElement serializedMedia = _serializer.Serialize(
media,
definition.MediaLoadChildNodes,
OnSerializedMedia);
return new XElement("MediaSet", serializedMedia);
}));
root.Add(mediaXml);
return mediaStreams;
}
// TODO: Delete this
/// <summary>
private XElement GetMacroXml(int macroId, out IMacro macro)
{
macro = _macroService.GetById(macroId);
if (macro == null)
return null;
var xml = _serializer.Serialize(macro);
return xml;
}
/// <summary>
/// Converts a umbraco stylesheet to a package xml node
/// </summary>
/// <param name="path">The path of the stylesheet.</param>
/// <param name="includeProperties">if set to <c>true</c> [include properties].</param>
/// <returns></returns>
private XElement GetStylesheetXml(string path, bool includeProperties)
{
if (string.IsNullOrWhiteSpace(path))
{
throw new ArgumentException("Value cannot be null or whitespace.", nameof(path));
}
IStylesheet stylesheet = _fileService.GetStylesheet(path);
if (stylesheet == null)
{
return null;
}
return _serializer.Serialize(stylesheet, includeProperties);
}
private void AddDocumentType(IContentType dt, HashSet<IContentType> dtl)
{
if (dt.ParentId > 0)
{
var parent = _contentTypeService.Get(dt.ParentId);
if (parent != null) // could be a container
AddDocumentType(parent, dtl);
}
if (!dtl.Contains(dt))
dtl.Add(dt);
}
private void AddMediaType(IMediaType mediaType, HashSet<IMediaType> mediaTypes)
{
if (mediaType.ParentId > 0)
{
var parent = _mediaTypeService.Get(mediaType.ParentId);
if (parent != null) // could be a container
AddMediaType(parent, mediaTypes);
}
if (!mediaTypes.Contains(mediaType))
mediaTypes.Add(mediaType);
}
private static XElement GetPackageInfoXml(PackageDefinition definition)
{
var info = new XElement("info");
//Package info
var package = new XElement("package");
package.Add(new XElement("name", definition.Name));
info.Add(package);
return info;
}
private static XDocument CreateCompiledPackageXml(out XElement root)
{
root = new XElement("umbPackage");
var compiledPackageXml = new XDocument(root);
return compiledPackageXml;
}
private XDocument EnsureStorage(out string packagesFile)
{
var packagesFolder = _hostingEnvironment.MapPathContentRoot(_packagesFolderPath);
Directory.CreateDirectory(packagesFolder);
packagesFile = _hostingEnvironment.MapPathContentRoot(CreatedPackagesFile);
if (!File.Exists(packagesFile))
{
var xml = new XDocument(new XElement("packages"));
xml.Save(packagesFile);
return xml;
}
var packagesXml = XDocument.Load(packagesFile);
return packagesXml;
}
public void DeleteLocalRepositoryFiles()
{
var packagesFile = _hostingEnvironment.MapPathContentRoot(CreatedPackagesFile);
if (File.Exists(packagesFile))
{
File.Delete(packagesFile);
}
var packagesFolder = _hostingEnvironment.MapPathContentRoot(_packagesFolderPath);
if (Directory.Exists(packagesFolder))
{
Directory.Delete(packagesFolder);
}
}
}
}
| |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus SDK License Version 3.4.1 (the "License");
you may not use the Oculus SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/sdk-3.4.1
Unless required by applicable law or agreed to in writing, the Oculus SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
//#define BUILDSESSION
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Diagnostics;
using System.Threading;
using UnityEditor;
using UnityEditor.Android;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEditor.Build;
#if UNITY_2018_1_OR_NEWER
using UnityEditor.Build.Reporting;
#endif
using System;
[InitializeOnLoad]
public class OVRGradleGeneration
#if UNITY_2018_2_OR_NEWER
: IPreprocessBuildWithReport, IPostprocessBuildWithReport, IPostGenerateGradleAndroidProject
{
public OVRADBTool adbTool;
public Process adbProcess;
public int callbackOrder { get { return 3; } }
static private System.DateTime buildStartTime;
static private System.Guid buildGuid;
#if UNITY_ANDROID
private const string prefName = "OVRAutoIncrementVersionCode_Enabled";
private const string menuItemAutoIncVersion = "Oculus/Tools/Auto Increment Version Code";
static bool autoIncrementVersion = false;
#endif
static OVRGradleGeneration()
{
EditorApplication.delayCall += OnDelayCall;
}
static void OnDelayCall()
{
#if UNITY_ANDROID
autoIncrementVersion = PlayerPrefs.GetInt(prefName, 0) != 0;
Menu.SetChecked(menuItemAutoIncVersion, autoIncrementVersion);
#endif
}
#if UNITY_ANDROID
[MenuItem(menuItemAutoIncVersion)]
static void ToggleUtilities()
{
autoIncrementVersion = !autoIncrementVersion;
Menu.SetChecked(menuItemAutoIncVersion, autoIncrementVersion);
int newValue = (autoIncrementVersion) ? 1 : 0;
PlayerPrefs.SetInt(prefName, newValue);
PlayerPrefs.Save();
UnityEngine.Debug.Log("Auto Increment Version Code: " + autoIncrementVersion);
}
#endif
public void OnPreprocessBuild(BuildReport report)
{
#if UNITY_ANDROID
// Generate error when Vulkan is selected as the perferred graphics API, which is not currently supported in Unity XR
if (!PlayerSettings.GetUseDefaultGraphicsAPIs(BuildTarget.Android))
{
GraphicsDeviceType[] apis = PlayerSettings.GetGraphicsAPIs(BuildTarget.Android);
if (apis.Length >= 1 && apis[0] == GraphicsDeviceType.Vulkan)
{
throw new BuildFailedException("XR is currently not supported when using the Vulkan Graphics API. Please go to PlayerSettings and remove 'Vulkan' from the list of Graphics APIs.");
}
}
#endif
buildStartTime = System.DateTime.Now;
buildGuid = System.Guid.NewGuid();
if (!report.summary.outputPath.Contains("OVRGradleTempExport"))
{
OVRPlugin.SetDeveloperMode(OVRPlugin.Bool.True);
OVRPlugin.AddCustomMetadata("build_type", "standard");
}
OVRPlugin.AddCustomMetadata("build_guid", buildGuid.ToString());
OVRPlugin.AddCustomMetadata("target_platform", report.summary.platform.ToString());
#if !UNITY_2019_3_OR_NEWER
OVRPlugin.AddCustomMetadata("scripting_runtime_version", UnityEditor.PlayerSettings.scriptingRuntimeVersion.ToString());
#endif
if (report.summary.platform == UnityEditor.BuildTarget.StandaloneWindows
|| report.summary.platform == UnityEditor.BuildTarget.StandaloneWindows64)
{
OVRPlugin.AddCustomMetadata("target_oculus_platform", "rift");
}
#if BUILDSESSION
StreamWriter writer = new StreamWriter("build_session", false);
UnityEngine.Debug.LogFormat("Build Session: {0}", buildGuid.ToString());
writer.WriteLine(buildGuid.ToString());
writer.Close();
#endif
}
public void OnPostGenerateGradleAndroidProject(string path)
{
UnityEngine.Debug.Log("OVRGradleGeneration triggered.");
var targetOculusPlatform = new List<string>();
if (OVRDeviceSelector.isTargetDeviceGearVrOrGo)
{
targetOculusPlatform.Add("geargo");
}
if (OVRDeviceSelector.isTargetDeviceQuest)
{
targetOculusPlatform.Add("quest");
}
OVRPlugin.AddCustomMetadata("target_oculus_platform", String.Join("_", targetOculusPlatform.ToArray()));
UnityEngine.Debug.LogFormat(" GearVR or Go = {0} Quest = {1}", OVRDeviceSelector.isTargetDeviceGearVrOrGo, OVRDeviceSelector.isTargetDeviceQuest);
bool isQuestOnly = OVRDeviceSelector.isTargetDeviceQuest && !OVRDeviceSelector.isTargetDeviceGearVrOrGo;
if (isQuestOnly)
{
if (File.Exists(Path.Combine(path, "build.gradle")))
{
try
{
string gradle = File.ReadAllText(Path.Combine(path, "build.gradle"));
int v2Signingindex = gradle.IndexOf("v2SigningEnabled false");
if (v2Signingindex != -1)
{
gradle = gradle.Replace("v2SigningEnabled false", "v2SigningEnabled true");
System.IO.File.WriteAllText(Path.Combine(path, "build.gradle"), gradle);
}
}
catch (System.Exception e)
{
UnityEngine.Debug.LogWarningFormat("Unable to overwrite build.gradle, error {0}", e.Message);
}
}
else
{
UnityEngine.Debug.LogWarning("Unable to locate build.gradle");
}
}
PatchAndroidManifest(path);
}
public void PatchAndroidManifest(string path)
{
string manifestFolder = Path.Combine(path, "src/main");
try
{
// Load android manfiest file
XmlDocument doc = new XmlDocument();
doc.Load(manifestFolder + "/AndroidManifest.xml");
string androidNamepsaceURI;
XmlElement element = (XmlElement)doc.SelectSingleNode("/manifest");
if (element == null)
{
UnityEngine.Debug.LogError("Could not find manifest tag in android manifest.");
return;
}
// Get android namespace URI from the manifest
androidNamepsaceURI = element.GetAttribute("xmlns:android");
if (!string.IsNullOrEmpty(androidNamepsaceURI))
{
// Look for intent filter category and change LAUNCHER to INFO
XmlNodeList nodeList = doc.SelectNodes("/manifest/application/activity/intent-filter/category");
foreach (XmlElement e in nodeList)
{
string attr = e.GetAttribute("name", androidNamepsaceURI);
if (attr == "android.intent.category.LAUNCHER")
{
e.SetAttribute("name", androidNamepsaceURI, "android.intent.category.INFO");
}
}
//If Quest is the target device, add the headtracking manifest tag
if (OVRDeviceSelector.isTargetDeviceQuest)
{
XmlNodeList manifestUsesFeatureNodes = doc.SelectNodes("/manifest/uses-feature");
bool foundHeadtrackingTag = false;
foreach (XmlElement e in manifestUsesFeatureNodes)
{
string attr = e.GetAttribute("name", androidNamepsaceURI);
if (attr == "android.hardware.vr.headtracking")
foundHeadtrackingTag = true;
}
//If the tag already exists, don't patch with a new one. If it doesn't, we add it.
if (!foundHeadtrackingTag)
{
XmlNode manifestElement = doc.SelectSingleNode("/manifest");
XmlElement headtrackingTag = doc.CreateElement("uses-feature");
headtrackingTag.SetAttribute("name", androidNamepsaceURI, "android.hardware.vr.headtracking");
headtrackingTag.SetAttribute("version", androidNamepsaceURI, "1");
string tagRequired = OVRDeviceSelector.isTargetDeviceGearVrOrGo ? "false" : "true";
headtrackingTag.SetAttribute("required", androidNamepsaceURI, tagRequired);
manifestElement.AppendChild(headtrackingTag);
}
}
// If Quest is the target device, add the handtracking manifest tags if needed
// Mapping of project setting to manifest setting:
// OVRProjectConfig.HandTrackingSupport.ControllersOnly => manifest entry not present
// OVRProjectConfig.HandTrackingSupport.ControllersAndHands => manifest entry present and required=false
// OVRProjectConfig.HandTrackingSupport.HandsOnly => manifest entry present and required=true
if (OVRDeviceSelector.isTargetDeviceQuest)
{
OVRProjectConfig.HandTrackingSupport targetHandTrackingSupport = OVRProjectConfig.GetProjectConfig().handTrackingSupport;
bool handTrackingEntryNeeded = (targetHandTrackingSupport != OVRProjectConfig.HandTrackingSupport.ControllersOnly);
if (handTrackingEntryNeeded)
{
// uses-feature: <uses-feature android:name="oculus.software.handtracking" android:required="false" />
XmlNodeList manifestUsesFeatureNodes = doc.SelectNodes("/manifest/uses-feature");
bool foundHandTrackingFeature = false;
foreach (XmlElement e in manifestUsesFeatureNodes)
{
string attr = e.GetAttribute("name", androidNamepsaceURI);
if (attr == "oculus.software.handtracking")
foundHandTrackingFeature = true;
}
//If the tag already exists, don't patch with a new one. If it doesn't, we add it.
if (!foundHandTrackingFeature)
{
XmlNode manifestElement = doc.SelectSingleNode("/manifest");
XmlElement handTrackingFeature = doc.CreateElement("uses-feature");
handTrackingFeature.SetAttribute("name", androidNamepsaceURI, "oculus.software.handtracking");
string tagRequired = (targetHandTrackingSupport == OVRProjectConfig.HandTrackingSupport.HandsOnly) ? "true" : "false";
handTrackingFeature.SetAttribute("required", androidNamepsaceURI, tagRequired);
manifestElement.AppendChild(handTrackingFeature);
}
// uses-permission: <uses-permission android:name="oculus.permission.handtracking" />
XmlNodeList manifestUsesPermissionNodes = doc.SelectNodes("/manifest/uses-permission");
bool foundHandTrackingPermission = false;
foreach (XmlElement e in manifestUsesPermissionNodes)
{
string attr = e.GetAttribute("name", androidNamepsaceURI);
if (attr == "oculus.permission.handtracking")
foundHandTrackingPermission = true;
}
//If the tag already exists, don't patch with a new one. If it doesn't, we add it.
if (!foundHandTrackingPermission)
{
XmlNode manifestElement = doc.SelectSingleNode("/manifest");
XmlElement handTrackingPermission = doc.CreateElement("uses-permission");
handTrackingPermission.SetAttribute("name", androidNamepsaceURI, "oculus.permission.handtracking");
manifestElement.AppendChild(handTrackingPermission);
}
}
}
XmlElement applicationNode = (XmlElement)doc.SelectSingleNode("/manifest/application");
if(applicationNode != null)
{
// If android label and icon are missing from the xml, add them
if (applicationNode.GetAttribute("android:label") == null)
{
applicationNode.SetAttribute("label", androidNamepsaceURI, "@string/app_name");
}
if (applicationNode.GetAttribute("android:icon") == null)
{
applicationNode.SetAttribute("icon", androidNamepsaceURI, "@mipmap/app_icon");
}
// Check for VR tag, if missing, append it
bool vrTagFound = false;
XmlNodeList appNodeList = applicationNode.ChildNodes;
foreach (XmlElement e in appNodeList)
{
if (e.GetAttribute("android:name") == "com.samsung.android.vr.application.mode")
{
vrTagFound = true;
break;
}
}
if (!vrTagFound)
{
XmlElement vrTag = doc.CreateElement("meta-data");
vrTag.SetAttribute("name", androidNamepsaceURI, "com.samsung.android.vr.application.mode");
vrTag.SetAttribute("value", androidNamepsaceURI, "vr_only");
applicationNode.AppendChild(vrTag); ;
}
// Disable allowBackup in manifest and add Android NSC XML file
OVRProjectConfig projectConfig = OVRProjectConfig.GetProjectConfig();
if (projectConfig != null)
{
if (projectConfig.disableBackups)
{
applicationNode.SetAttribute("allowBackup", androidNamepsaceURI, "false");
}
if (projectConfig.enableNSCConfig)
{
applicationNode.SetAttribute("networkSecurityConfig", androidNamepsaceURI, "@xml/network_sec_config");
string securityConfigFile = Path.Combine(Application.dataPath, "Oculus/VR/Editor/network_sec_config.xml");
string xmlDirectory = Path.Combine(path, "src/main/res/xml");
try
{
if (!Directory.Exists(xmlDirectory))
{
Directory.CreateDirectory(xmlDirectory);
}
File.Copy(securityConfigFile, Path.Combine(xmlDirectory, "network_sec_config.xml"), true);
}
catch (Exception e)
{
UnityEngine.Debug.LogError(e.Message);
}
}
}
}
doc.Save(manifestFolder + "/AndroidManifest.xml");
}
}
catch (Exception e)
{
UnityEngine.Debug.LogError(e.Message);
}
}
public void OnPostprocessBuild(BuildReport report)
{
#if UNITY_ANDROID
if(autoIncrementVersion)
{
if((report.summary.options & BuildOptions.Development) == 0)
{
PlayerSettings.Android.bundleVersionCode++;
UnityEngine.Debug.Log("Incrementing version code to " + PlayerSettings.Android.bundleVersionCode);
}
}
bool isExporting = true;
foreach (var step in report.steps)
{
if (step.name.Contains("Compile scripts")
|| step.name.Contains("Building scenes")
|| step.name.Contains("Writing asset files")
|| step.name.Contains("Preparing APK resources")
|| step.name.Contains("Creating Android manifest")
|| step.name.Contains("Processing plugins")
|| step.name.Contains("Exporting project")
|| step.name.Contains("Building Gradle project"))
{
OVRPlugin.SendEvent("build_step_" + step.name.ToLower().Replace(' ', '_'),
step.duration.TotalSeconds.ToString(), "ovrbuild");
#if BUILDSESSION
UnityEngine.Debug.LogFormat("build_step_" + step.name.ToLower().Replace(' ', '_') + ": {0}", step.duration.TotalSeconds.ToString());
#endif
if(step.name.Contains("Building Gradle project"))
{
isExporting = false;
}
}
}
OVRPlugin.AddCustomMetadata("build_step_count", report.steps.Length.ToString());
if (report.summary.outputPath.Contains("apk")) // Exclude Gradle Project Output
{
var fileInfo = new System.IO.FileInfo(report.summary.outputPath);
OVRPlugin.AddCustomMetadata("build_output_size", fileInfo.Length.ToString());
}
#endif
if (!report.summary.outputPath.Contains("OVRGradleTempExport"))
{
OVRPlugin.SendEvent("build_complete", (System.DateTime.Now - buildStartTime).TotalSeconds.ToString(), "ovrbuild");
#if BUILDSESSION
UnityEngine.Debug.LogFormat("build_complete: {0}", (System.DateTime.Now - buildStartTime).TotalSeconds.ToString());
#endif
}
#if UNITY_ANDROID
if (!isExporting)
{
// Get the hosts path to Android SDK
if (adbTool == null)
{
adbTool = new OVRADBTool(OVRConfig.Instance.GetAndroidSDKPath(false));
}
if (adbTool.isReady)
{
// Check to see if there are any ADB devices connected before continuing.
List<string> devices = adbTool.GetDevices();
if(devices.Count == 0)
{
return;
}
// Clear current logs on device
Process adbClearProcess;
adbClearProcess = adbTool.RunCommandAsync(new string[] { "logcat --clear" }, null);
// Add a timeout if we cannot get a response from adb logcat --clear in time.
Stopwatch timeout = new Stopwatch();
timeout.Start();
while (!adbClearProcess.WaitForExit(100))
{
if (timeout.ElapsedMilliseconds > 2000)
{
adbClearProcess.Kill();
return;
}
}
// Check if existing ADB process is still running, kill if needed
if (adbProcess != null && !adbProcess.HasExited)
{
adbProcess.Kill();
}
// Begin thread to time upload and install
var thread = new Thread(delegate ()
{
TimeDeploy();
});
thread.Start();
}
}
#endif
}
#if UNITY_ANDROID
public bool WaitForProcess;
public bool TransferStarted;
public DateTime UploadStart;
public DateTime UploadEnd;
public DateTime InstallEnd;
public void TimeDeploy()
{
if (adbTool != null)
{
TransferStarted = false;
DataReceivedEventHandler outputRecieved = new DataReceivedEventHandler(
(s, e) =>
{
if (e.Data != null && e.Data.Length != 0 && !e.Data.Contains("\u001b"))
{
if (e.Data.Contains("free_cache"))
{
// Device recieved install command and is starting upload
UploadStart = System.DateTime.Now;
TransferStarted = true;
}
else if (e.Data.Contains("Running dexopt"))
{
// Upload has finished and Package Manager is starting install
UploadEnd = System.DateTime.Now;
}
else if (e.Data.Contains("dex2oat took"))
{
// Package Manager finished install
InstallEnd = System.DateTime.Now;
WaitForProcess = false;
}
else if (e.Data.Contains("W PackageManager"))
{
// Warning from Package Manager is a failure in the install process
WaitForProcess = false;
}
}
}
);
WaitForProcess = true;
adbProcess = adbTool.RunCommandAsync(new string[] { "logcat" }, outputRecieved);
Stopwatch transferTimeout = new Stopwatch();
transferTimeout.Start();
while (adbProcess != null && !adbProcess.WaitForExit(100))
{
if (!WaitForProcess)
{
adbProcess.Kill();
float UploadTime = (float)(UploadEnd - UploadStart).TotalMilliseconds / 1000f;
float InstallTime = (float)(InstallEnd - UploadEnd).TotalMilliseconds / 1000f;
if (UploadTime > 0f)
{
OVRPlugin.SendEvent("deploy_task", UploadTime.ToString(), "ovrbuild");
}
if (InstallTime > 0f)
{
OVRPlugin.SendEvent("install_task", InstallTime.ToString(), "ovrbuild");
}
}
if (!TransferStarted && transferTimeout.ElapsedMilliseconds > 5000)
{
adbProcess.Kill();
}
}
}
}
#endif
#else
{
#endif
}
| |
// ReSharper disable All
namespace Gu.State.Tests.EqualByTests
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
public static class EqualByTypes
{
public interface IWith
{
object Value { get; }
}
public struct Struct
{
public int Value { get; set; }
}
public struct EquatableStruct : IEquatable<EquatableStruct>
{
public int Value { get; set; }
public static bool operator ==(EquatableStruct left, EquatableStruct right)
{
return left.Equals(right);
}
public static bool operator !=(EquatableStruct left, EquatableStruct right)
{
return !(left == right);
}
public override bool Equals(object obj) => obj is EquatableStruct other &&
this.Equals(other);
public bool Equals(EquatableStruct other) => this.Value == other.Value;
public override int GetHashCode() => this.Value;
}
public class With<T> : IWith
{
public With(T value)
{
this.Value = value;
}
public T Value { get; }
object IWith.Value => this.Value;
#pragma warning disable CA1508 // Avoid dead conditional code, broken analyzer
public override string ToString() => $"With<{typeof(T).PrettyName()}> {{ {this.Value?.ToString() ?? "null"} }}";
#pragma warning restore CA1508 // Avoid dead conditional code
}
public class WithGetSet<T> : IWith
{
public WithGetSet(T value)
{
this.Value = value;
}
public T Value { get; set; }
object IWith.Value => this.Value;
#pragma warning disable CA1508 // Avoid dead conditional code, broken analyzer
public override string ToString() => $"With<{typeof(T).PrettyName()}> {{ {this.Value?.ToString() ?? "null"} }}";
#pragma warning restore CA1508 // Avoid dead conditional code
}
public class IntCollection : IReadOnlyList<int>
{
public static readonly IEqualityComparer<IntCollection> Comparer = new IntsEqualityComparer();
private readonly IReadOnlyList<int> ints;
public IntCollection(params int[] ints)
{
this.ints = ints;
}
public int Count => this.ints.Count;
public int this[int index] => this.ints[index];
public IEnumerator<int> GetEnumerator() => this.ints.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
private sealed class IntsEqualityComparer : IEqualityComparer<IntCollection>
{
public bool Equals(IntCollection x, IntCollection y)
{
if (ReferenceEquals(x, y))
{
return true;
}
if (x is null)
{
return false;
}
if (y is null)
{
return false;
}
if (x.GetType() != y.GetType())
{
return false;
}
return Enumerable.SequenceEqual(x.ints, y.ints);
}
public int GetHashCode(IntCollection obj)
{
throw new NotSupportedException("message");
}
}
}
public sealed class EquatableIntCollection : IReadOnlyList<int>, IEquatable<EquatableIntCollection>
{
private readonly IReadOnlyList<int> ints;
public EquatableIntCollection(params int[] ints)
{
this.ints = ints;
}
public int Count => this.ints.Count;
public int this[int index] => this.ints[index];
public IEnumerator<int> GetEnumerator() => this.ints.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
public bool Equals(EquatableIntCollection other)
{
if (other is null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Enumerable.SequenceEqual(this.ints, other.ints);
}
public override bool Equals(object obj)
{
if (obj is null)
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != typeof(EquatableIntCollection))
{
return false;
}
return this.Equals((EquatableIntCollection)obj);
}
#pragma warning disable CA1065 // Do not raise exceptions in unexpected locations
public override int GetHashCode() => throw new NotSupportedException("message");
#pragma warning restore CA1065 // Do not raise exceptions in unexpected locations
}
public class WithComplexValue
{
private string name;
private int value;
private ComplexType complexValue;
public WithComplexValue()
{
}
public WithComplexValue(string name, int value)
{
this.name = name;
this.value = value;
}
public string Name
{
get => this.name;
set => this.name = value;
}
public int Value
{
get => this.value;
set => this.value = value;
}
public ComplexType ComplexValue
{
get => this.complexValue;
set => this.complexValue = value;
}
}
public class WithSimpleValues
{
private int intValue;
private int? nullableIntValue;
private string stringValue;
private StringSplitOptions enumValue;
public WithSimpleValues(int intValue, int? nullableIntValue, string stringValue, StringSplitOptions enumValue)
{
this.intValue = intValue;
this.nullableIntValue = nullableIntValue;
this.stringValue = stringValue;
this.enumValue = enumValue;
}
public int IntValue
{
get => this.intValue;
set => this.intValue = value;
}
public int? NullableIntValue
{
get => this.nullableIntValue;
set => this.nullableIntValue = value;
}
public string StringValue
{
get => this.stringValue;
set => this.stringValue = value;
}
public StringSplitOptions EnumValue
{
get => this.enumValue;
set => this.enumValue = value;
}
public override string ToString()
{
return $"({this.IntValue}, {this.NullableIntValue}, {this.StringValue}, {this.EnumValue})";
}
}
public class ComplexType
{
public static readonly TestComparer Comparer = new TestComparer();
public static readonly IEqualityComparer<ComplexType> ByNameComparer = new NameComparer();
public ComplexType()
{
}
public ComplexType(string name, int value)
{
this.Name = name;
this.Value = value;
}
public string Name { get; set; }
public int Value { get; set; }
public override string ToString() => $"{this.GetType().Name} {{ Name: {this.Name}, Value: {this.Value} }}";
public sealed class TestComparer : IEqualityComparer<ComplexType>, IComparer<ComplexType>, IComparer
{
public bool Equals(ComplexType x, ComplexType y)
{
if (ReferenceEquals(x, y))
{
return true;
}
if (x is null)
{
return false;
}
if (y is null)
{
return false;
}
if (x.GetType() != y.GetType())
{
return false;
}
return string.Equals(x.Name, y.Name, StringComparison.Ordinal)
&& x.Value == y.Value;
}
public int GetHashCode(ComplexType obj)
{
unchecked
{
return ((obj.Name?.GetHashCode() ?? 0) * 397) ^ obj.Value;
}
}
public int Compare(ComplexType x, ComplexType y)
{
return this.Equals(x, y)
? 0
: -1;
}
int IComparer.Compare(object x, object y)
{
return this.Compare((ComplexType)x, (ComplexType)y);
}
}
private sealed class NameComparer : IEqualityComparer<ComplexType>
{
public bool Equals(ComplexType x, ComplexType y)
{
if (ReferenceEquals(x, y))
{
return true;
}
if (x is null)
{
return false;
}
if (y is null)
{
return false;
}
if (x.GetType() != y.GetType())
{
return false;
}
return string.Equals(x.Name, y.Name, StringComparison.Ordinal);
}
public int GetHashCode(ComplexType obj)
{
return obj?.Name.GetHashCode() ?? 0;
}
}
}
public sealed class Immutable : IEquatable<Immutable>
{
public Immutable(int value)
{
this.Value = value;
}
public int Value { get; }
public static bool operator ==(Immutable left, Immutable right)
{
return Equals(left, right);
}
public static bool operator !=(Immutable left, Immutable right)
{
return !Equals(left, right);
}
public bool Equals(Immutable other)
{
if (other is null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return this.Value == other.Value;
}
public override bool Equals(object obj) => obj is Immutable immutable && this.Equals(immutable);
public override int GetHashCode() => this.Value;
}
public class WithArrayProperty
{
public WithArrayProperty()
{
}
public WithArrayProperty(string name, int value)
{
this.Name = name;
this.Value = value;
}
public WithArrayProperty(string name, int value, int[] array)
{
this.Name = name;
this.Value = value;
this.Array = array;
}
public string Name { get; set; }
public int Value { get; set; }
public int[] Array { get; set; }
}
public class WithCalculatedProperty : INotifyPropertyChanged
{
private readonly int factor;
private int value;
public WithCalculatedProperty(int factor = 1)
{
this.factor = factor;
}
public event PropertyChangedEventHandler PropertyChanged;
public int Value
{
get => this.value;
set
{
if (value == this.value)
{
return;
}
this.value = value;
this.OnPropertyChanged();
this.OnPropertyChanged(nameof(this.CalculatedValue));
}
}
public int CalculatedValue => this.Value * this.factor;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class WithComplexProperty
{
public WithComplexProperty()
{
}
public WithComplexProperty(string name, int value)
{
this.Name = name;
this.Value = value;
}
public WithComplexProperty(string name, int value, ComplexType complexType)
{
this.Name = name;
this.Value = value;
this.ComplexType = complexType;
}
public string Name { get; set; }
public int Value { get; set; }
public ComplexType ComplexType { get; set; }
}
public class WithListProperty<T>
{
public List<T> Items { get; set; } = new List<T>();
}
public class WithSimpleProperties : INotifyPropertyChanged
{
internal static readonly AllMembersComparerImpl AllMembersComparer = new AllMembersComparerImpl();
private int intValue;
private int? nullableIntValue;
private string stringValue;
private StringSplitOptions enumValue;
public WithSimpleProperties()
{
}
public WithSimpleProperties(int intValue, int? nullableIntValue, string stringValue, StringSplitOptions enumValue)
{
this.intValue = intValue;
this.nullableIntValue = nullableIntValue;
this.stringValue = stringValue;
this.enumValue = enumValue;
}
public event PropertyChangedEventHandler PropertyChanged;
public int IntValue
{
get => this.intValue;
set
{
if (value == this.intValue)
{
return;
}
this.intValue = value;
this.OnPropertyChanged();
}
}
public int? NullableIntValue
{
get => this.nullableIntValue;
set
{
if (value == this.nullableIntValue)
{
return;
}
this.nullableIntValue = value;
this.OnPropertyChanged();
}
}
public string StringValue
{
get => this.stringValue;
set
{
if (value == this.stringValue)
{
return;
}
this.stringValue = value;
this.OnPropertyChanged();
}
}
public StringSplitOptions EnumValue
{
get => this.enumValue;
set
{
if (value == this.enumValue)
{
return;
}
this.enumValue = value;
this.OnPropertyChanged();
}
}
public void SetFields(int intValue, string stringValue)
{
this.intValue = intValue;
this.stringValue = stringValue;
}
public virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
internal sealed class AllMembersComparerImpl : IEqualityComparer<WithSimpleProperties>, IComparer
{
public bool Equals(WithSimpleProperties x, WithSimpleProperties y)
{
if (ReferenceEquals(x, y))
{
return true;
}
if (x is null)
{
return false;
}
if (y is null)
{
return false;
}
if (x.GetType() != y.GetType())
{
return false;
}
return x.IntValue == y.IntValue &&
x.NullableIntValue == y.NullableIntValue &&
string.Equals(x.StringValue, y.StringValue, StringComparison.Ordinal) &&
x.EnumValue == y.EnumValue;
}
public int GetHashCode(WithSimpleProperties obj)
{
unchecked
{
var hashCode = obj.IntValue;
hashCode = (hashCode * 397) ^ obj.NullableIntValue.GetHashCode();
hashCode = (hashCode * 397) ^ (obj.StringValue?.GetHashCode() ?? 0);
hashCode = (hashCode * 397) ^ (int)obj.EnumValue;
return hashCode;
}
}
int IComparer.Compare(object x, object y)
{
return this.Equals((WithSimpleProperties)x, (WithSimpleProperties)y)
? 0
: -1;
}
}
}
public class WithIllegalIndexer
{
// ReSharper disable once UnusedParameter.Global
public int this[int index]
{
get { return 0; }
set { }
}
}
public class Parent
{
public Parent(string name, Child child)
{
this.Name = name;
if (child != null)
{
child.Parent = this;
}
this.Child = child;
}
public string Name { get; }
public Child Child { get; set; }
}
public class Child
{
public Child(string name)
{
this.Name = name;
}
public string Name { get; }
public Parent Parent { get; set; }
}
public class SealedParent
{
public SealedParent(string name, SealedChild child)
{
this.Name = name;
if (child != null)
{
child.Parent = this;
}
this.Child = child;
}
public string Name { get; }
public SealedChild Child { get; set; }
}
public class SealedChild
{
public SealedChild(string name)
{
this.Name = name;
}
public string Name { get; }
public SealedParent Parent { get; set; }
}
public sealed class HashCollisionType
{
public int HashValue { get; set; }
public int Value { get; set; }
public override bool Equals(object obj)
{
return obj is HashCollisionType type &&
this.HashValue == type.HashValue &&
this.Value == type.Value;
}
public override int GetHashCode()
{
return this.HashValue;
}
}
public abstract class BaseClass
{
public double BaseValue { get; set; }
}
public class Derived1 : BaseClass
{
public double Derived1Value { get; set; }
public override string ToString() => $"{this.GetType().Name} {{ BaseValue: {this.BaseValue}, Derived1Value: {this.Derived1Value} }}";
}
public class Derived2 : BaseClass
{
public double Derived2Value { get; set; }
public override string ToString() => $"{this.GetType().Name} {{ BaseValue: {this.BaseValue}, Derived2Value: {this.Derived2Value} }}";
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter;
using Microsoft.Protocols.TestSuites.FileSharing.Common.TestSuite;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2;
using Microsoft.Protocols.TestTools.StackSdk.Swn;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Linq;
using System.Net;
namespace Microsoft.Protocols.TestSuites.FileSharing.ServerFailover.TestSuite
{
[TestClass]
public class FileServerFailover : ServerFailoverTestBase
{
#region Variables
/// <summary>
/// SWN client to get interface list.
/// </summary>
private SwnClient swnClientForInterface;
/// <summary>
/// SWN client to witness.
/// </summary>
private SwnClient swnClientForWitness;
/// <summary>
/// The registered handle of witness.
/// </summary>
private System.IntPtr pContext;
/// <summary>
/// The type indicates witness is used or not.
/// </summary>
private WitnessType witnessType;
#endregion
#region Class Initialized and Cleanup
[ClassInitialize()]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
SWNTestUtility.BaseTestSite = BaseTestSite;
}
[ClassCleanup()]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
#region Test Initialize and Cleanup
protected override void TestInitialize()
{
base.TestInitialize();
swnClientForInterface = new SwnClient();
swnClientForWitness = new SwnClient();
pContext = IntPtr.Zero;
witnessType = WitnessType.None;
}
protected override void TestCleanup()
{
if (pContext != IntPtr.Zero)
{
swnClientForWitness.WitnessrUnRegister(pContext);
pContext = IntPtr.Zero;
}
try
{
swnClientForInterface.SwnUnbind(TestConfig.Timeout);
}
catch (Exception ex)
{
BaseTestSite.Log.Add(
LogEntryKind.Warning,
"TestCleanup: Unexpected Exception:", ex);
}
try
{
swnClientForWitness.SwnUnbind(TestConfig.Timeout);
}
catch (Exception ex)
{
BaseTestSite.Log.Add(
LogEntryKind.Warning,
"TestCleanup: Unexpected Exception:", ex);
}
base.TestCleanup();
}
#endregion
#region BVT_FileServerFailover_FileServer
[TestMethod]
[TestCategory(TestCategories.Cluster)]
[TestCategory(TestCategories.Smb30)]
[TestCategory(TestCategories.Positive)]
[Description("This test case is designed to test whether server can handle failover to another node of continuous available file servers.")]
public void FileServerFailover_FileServer()
{
FileServerFailoverTest(TestConfig.ClusteredFileServerName,
FileServerType.GeneralFileServer);
}
#endregion
#region BVT_FileServerFailover_ScaleOutFileServer
[TestMethod]
[TestCategory(TestCategories.Cluster)]
[TestCategory(TestCategories.Smb30)]
[TestCategory(TestCategories.Positive)]
[Description("This test case is designed to test whether server can handle failover to another node of continuous available scale out file servers.")]
public void FileServerFailover_ScaleOutFileServer()
{
FileServerFailoverTest(TestConfig.ClusteredScaleOutFileServerName,
FileServerType.ScaleOutFileServer);
}
#endregion
#region FileServerFailover_ScaleOutFileServer_ReconnectWithoutFailover
[TestMethod]
[TestCategory(TestCategories.Cluster)]
[TestCategory(TestCategories.Smb30)]
[TestCategory(TestCategories.Positive)]
[Description("Ensure persistent handle could be re-connected via connection with another node without failover.")]
public void FileServerFailover_ScaleOutFileServer_ReconnectWithoutFailover()
{
FileServerFailoverTest(TestConfig.ClusteredScaleOutFileServerName,
FileServerType.ScaleOutFileServer,
true);
}
#endregion
#region BVT_SWNFileServerFailover_FileServer
[TestMethod]
[TestCategory(TestCategories.Smb30)]
[TestCategory(TestCategories.Swn)]
[TestCategory(TestCategories.Positive)]
[Description("Get WitnessrAsyncNotify notification on cluster server.")]
public void SWNFileServerFailover_FileServer()
{
witnessType = WitnessType.SwnWitness;
FileServerFailoverTest(TestConfig.ClusteredFileServerName,
FileServerType.GeneralFileServer);
}
#endregion
#region BVT_SWNFileServerFailover_ScaleOutFileServer
[TestMethod]
[TestCategory(TestCategories.Smb30)]
[TestCategory(TestCategories.Swn)]
[TestCategory(TestCategories.Positive)]
[Description("Get WitnessrAsyncNotify notification on scaleout cluster server.")]
public void SWNFileServerFailover_ScaleOutFileServer()
{
witnessType = WitnessType.SwnWitness;
FileServerFailoverTest(TestConfig.ClusteredScaleOutFileServerName,
FileServerType.ScaleOutFileServer);
}
#endregion
#region Test Utility
private void FileServerFailoverTest(string server, FileServerType fsType, bool reconnectWithoutFailover = false)
{
int ret = 0;
uint callId = 0;
IPAddress currentAccessIpAddr = null;
WITNESS_INTERFACE_INFO registerInterface = new WITNESS_INTERFACE_INFO();
WITNESS_INTERFACE_LIST interfaceList = new WITNESS_INTERFACE_LIST();
currentAccessIpAddr = SWNTestUtility.GetCurrentAccessIP(server);
BaseTestSite.Log.Add(LogEntryKind.Debug, "Get current file server IP: {0}.", currentAccessIpAddr);
#region Register SWN witness
if (witnessType == WitnessType.SwnWitness)
{
if (TestConfig.IsWindowsPlatform && fsType == FileServerType.ScaleOutFileServer)
{
// Windows Server: when stopping a non-owner node of ScaleOutFS, no notication will be sent by SMB witness.
// So get one IP of the owner node of ScaleOutFS to access.
string resourceOwnerNode = sutController.GetClusterResourceOwner(server);
IPAddress[] ownerIpList = Dns.GetHostEntry(resourceOwnerNode).AddressList;
foreach (var ip in ownerIpList)
{
BaseTestSite.Log.Add(LogEntryKind.Debug, "Owner IP: {0}", ip);
}
if (!ownerIpList.Contains(currentAccessIpAddr))
{
currentAccessIpAddr = null;
IPAddress[] accessIpList = Dns.GetHostEntry(server).AddressList;
foreach (var ip in accessIpList)
{
if (ownerIpList.Contains(ip))
{
currentAccessIpAddr = ip;
break;
}
}
BaseTestSite.Assert.IsNotNull(currentAccessIpAddr, "IP should not be null.");
BaseTestSite.Log.Add(LogEntryKind.Debug, "Get the owner IP {0} as file server IP.", currentAccessIpAddr);
}
DoUntilSucceed(() => SWNTestUtility.BindServer(swnClientForInterface, currentAccessIpAddr,
TestConfig.DomainName, TestConfig.UserName, TestConfig.UserPassword, TestConfig.DefaultSecurityPackage,
TestConfig.DefaultRpceAuthenticationLevel, TestConfig.Timeout, resourceOwnerNode), TestConfig.FailoverTimeout,
"Retry BindServer until succeed within timeout span");
}
else
{
DoUntilSucceed(() => SWNTestUtility.BindServer(swnClientForInterface, currentAccessIpAddr,
TestConfig.DomainName, TestConfig.UserName, TestConfig.UserPassword, TestConfig.DefaultSecurityPackage,
TestConfig.DefaultRpceAuthenticationLevel, TestConfig.Timeout, server), TestConfig.FailoverTimeout,
"Retry BindServer until succeed within timeout span");
}
DoUntilSucceed(() =>
{
ret = swnClientForInterface.WitnessrGetInterfaceList(out interfaceList);
BaseTestSite.Assert.AreEqual<SwnErrorCode>(
SwnErrorCode.ERROR_SUCCESS,
(SwnErrorCode)ret,
"WitnessrGetInterfaceList returns with result code = 0x{0:x8}", ret);
return SWNTestUtility.VerifyInterfaceList(interfaceList, TestConfig.Platform);
}, TestConfig.FailoverTimeout, "Retry to call WitnessrGetInterfaceList until succeed within timeout span.");
SWNTestUtility.GetRegisterInterface(interfaceList, out registerInterface);
DoUntilSucceed(() => SWNTestUtility.BindServer(swnClientForWitness,
(registerInterface.Flags & (uint)SwnNodeFlagsValue.IPv4) != 0 ? new IPAddress(registerInterface.IPV4) : SWNTestUtility.ConvertIPV6(registerInterface.IPV6),
TestConfig.DomainName, TestConfig.UserName, TestConfig.UserPassword, TestConfig.DefaultSecurityPackage,
TestConfig.DefaultRpceAuthenticationLevel, TestConfig.Timeout, registerInterface.InterfaceGroupName), TestConfig.FailoverTimeout,
"Retry BindServer until succeed within timeout span");
string clientName = TestConfig.WitnessClientName;
BaseTestSite.Log.Add(LogEntryKind.Debug, "Register witness:");
BaseTestSite.Log.Add(LogEntryKind.Debug, "\tNetName: {0}", SWNTestUtility.GetPrincipleName(TestConfig.DomainName, server));
BaseTestSite.Log.Add(LogEntryKind.Debug, "\tIPAddress: {0}", currentAccessIpAddr.ToString());
BaseTestSite.Log.Add(LogEntryKind.Debug, "\tClient Name: {0}", clientName);
ret = swnClientForWitness.WitnessrRegister(SwnVersion.SWN_VERSION_1, SWNTestUtility.GetPrincipleName(TestConfig.DomainName, server),
currentAccessIpAddr.ToString(), clientName, out pContext);
BaseTestSite.Assert.AreEqual<SwnErrorCode>(
SwnErrorCode.ERROR_SUCCESS,
(SwnErrorCode)ret,
"WitnessrRegister returns with result code = 0x{0:x8}", ret);
BaseTestSite.Assert.IsNotNull(
pContext,
"Expect pContext is not null.");
callId = swnClientForWitness.WitnessrAsyncNotify(pContext);
BaseTestSite.Assert.AreNotEqual<uint>(
0,
callId,
"WitnessrAsyncNotify returns callId = {0}", callId);
}
#endregion
#region Create a file and write content
string uncSharePath = Smb2Utility.GetUncPath(server, TestConfig.ClusteredFileShare);
string content = Smb2Utility.CreateRandomString(TestConfig.WriteBufferLengthInKb);
string testDirectory = CreateTestDirectory(uncSharePath);
string file = Path.Combine(testDirectory, Guid.NewGuid().ToString());
Guid clientGuid = Guid.NewGuid();
Guid createGuid = Guid.NewGuid();
DoUntilSucceed(() => WriteContentBeforeFailover(fsType, server, currentAccessIpAddr, uncSharePath, file, content, clientGuid, createGuid),
TestConfig.FailoverTimeout,
"Before failover, retry Write content until succeed within timeout span.");
#endregion
#region Disable accessed node
if (TestConfig.IsWindowsPlatform)
{
AssignCurrentAccessNode(server, fsType, currentAccessIpAddr);
}
if (!reconnectWithoutFailover)
{
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"Disable owner node for general file server or the node currently provides the access for scale-out file server.");
FailoverServer(currentAccessIpAddr, server, fsType);
}
#endregion
#region Wait for available server
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Wait for available server.");
if (witnessType == WitnessType.None)
{
if (fsType == FileServerType.GeneralFileServer)
{
currentAccessIpAddr = null;
IPAddress[] accessIpList = Dns.GetHostEntry(server).AddressList;
DoUntilSucceed(() =>
{
foreach (IPAddress ipAddress in accessIpList)
{
Smb2FunctionalClient pingClient = new Smb2FunctionalClient(TestConfig.FailoverTimeout, TestConfig, BaseTestSite);
try
{
pingClient.ConnectToServerOverTCP(ipAddress);
pingClient.Disconnect();
pingClient = null;
currentAccessIpAddr = ipAddress;
return true;
}
catch
{
}
}
return false;
}, TestConfig.FailoverTimeout, "Retry to ping to server until succeed within timeout span");
}
else
{
currentAccessIpAddr = null;
IPAddress[] accessIpList = Dns.GetHostEntry(server).AddressList;
foreach (IPAddress ipAddress in accessIpList)
{
if (TestConfig.IsWindowsPlatform)
{
// When setting failover mode to StopNodeService for Windows, SMB2 servers on two nodes can still be accessed by the client.
// So the client needs to get the new node to access it after failover by comparing host name.
if (string.Compare(currentAccessNode, Dns.GetHostEntry(ipAddress).HostName, true) == 0)
{
continue;
}
}
Smb2FunctionalClient pingClient = new Smb2FunctionalClient(TestConfig.FailoverTimeout, TestConfig, BaseTestSite);
try
{
pingClient.ConnectToServerOverTCP(ipAddress);
pingClient.Disconnect();
pingClient = null;
currentAccessIpAddr = ipAddress;
break;
}
catch
{
}
}
}
}
else if (witnessType == WitnessType.SwnWitness)
{
// Verifying for notification
RESP_ASYNC_NOTIFY respNotify;
do
{
// Wait the notification
ret = swnClientForWitness.ExpectWitnessrAsyncNotify(callId, out respNotify);
BaseTestSite.Assert.AreEqual<SwnErrorCode>(
SwnErrorCode.ERROR_SUCCESS,
(SwnErrorCode)ret,
"ExpectWitnessrAsyncNotify returns with result code = 0x{0:x8}", ret);
SWNTestUtility.PrintNotification(respNotify);
RESOURCE_CHANGE[] resourceChangeList;
SwnUtility.ParseResourceChange(respNotify, out resourceChangeList);
BaseTestSite.Assert.AreEqual<uint>(0x00000001, respNotify.NumberOfMessages, "Expect NumberOfMessages is set to 1.");
if (resourceChangeList[0].ChangeType == (uint)SwnResourceChangeType.RESOURCE_STATE_AVAILABLE)
{
// Verify RESP_ASYNC_NOTIFY, the resource is available
SWNTestUtility.VerifyResourceChange(respNotify, SwnResourceChangeType.RESOURCE_STATE_AVAILABLE);
break;
}
// Verify RESP_ASYNC_NOTIFY, the resource is unavailable
SWNTestUtility.VerifyResourceChange(respNotify, SwnResourceChangeType.RESOURCE_STATE_UNAVAILABLE);
callId = swnClientForWitness.WitnessrAsyncNotify(pContext);
BaseTestSite.Assert.AreNotEqual<uint>(0, callId, "WitnessrAsyncNotify returns callId = {0}", callId);
} while (true);
ret = swnClientForWitness.WitnessrUnRegister(pContext);
BaseTestSite.Assert.AreEqual<SwnErrorCode>(
SwnErrorCode.ERROR_SUCCESS,
(SwnErrorCode)ret,
"WitnessrUnRegister returns with result code = 0x{0:x8}", ret);
pContext = IntPtr.Zero;
swnClientForWitness.SwnUnbind(TestConfig.Timeout);
if (fsType == FileServerType.ScaleOutFileServer)
{
// For scale-out file server case, retrieve and use another access IP for connection
currentAccessIpAddr =
(registerInterface.Flags & (uint)SwnNodeFlagsValue.IPv4) != 0 ? new IPAddress(registerInterface.IPV4) : SWNTestUtility.ConvertIPV6(registerInterface.IPV6);
}
}
#endregion
#region Read content and close the file
DoUntilSucceed(() => ReadContentAfterFailover(server, currentAccessIpAddr, uncSharePath, file, content, clientGuid, createGuid),
TestConfig.FailoverTimeout,
"After failover, retry Read content until succeed within timeout span.");
#endregion
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Xml;
namespace SIL.Xml
{
public class XmlHelpers
{
public static void AddOrUpdateAttribute(XmlNode node, string attributeName, string value)
{
AddOrUpdateAttribute(node, attributeName, value, null);
}
public static void AddOrUpdateAttribute(XmlNode node, string attributeName, string value, IComparer<XmlNode> nodeOrderComparer)
{
XmlNode attr = node.Attributes.GetNamedItem(attributeName);
if (attr == null)
{
attr = GetDocument(node).CreateAttribute(attributeName);
if (nodeOrderComparer == null)
{
node.Attributes.SetNamedItem(attr);
}
else
{
InsertNodeUsingDefinedOrder(node, attr, nodeOrderComparer);
}
}
attr.Value = value;
}
public static XmlNode GetOrCreateElement(XmlNode node, string xpathNotIncludingElement,
string elementName, string nameSpace, XmlNamespaceManager nameSpaceManager)
{
return GetOrCreateElement(node, xpathNotIncludingElement, elementName, nameSpace, nameSpaceManager, null);
}
public static XmlNode GetOrCreateElement(XmlNode node, string xpathNotIncludingElement,
string elementName, string nameSpace, XmlNamespaceManager nameSpaceManager, IComparer<XmlNode> nodeOrderComparer)
{
//enhance: if the parent path isn't found, strip of the last piece and recurse,
//so that the path will always be created if needed.
XmlNode parentNode = node.SelectSingleNode(xpathNotIncludingElement,nameSpaceManager);
if (parentNode == null)
{
throw new ApplicationException(string.Format("The path {0} could not be found", xpathNotIncludingElement));
}
string prefix = "";
if (!String.IsNullOrEmpty(nameSpace))
{
prefix = nameSpace + ":";
}
XmlNode n = parentNode.SelectSingleNode(prefix+elementName,nameSpaceManager);
if (n == null)
{
if (!String.IsNullOrEmpty(nameSpace))
{
n = GetDocument(node).CreateElement(nameSpace, elementName, nameSpaceManager.LookupNamespace(nameSpace));
}
else
{
n = GetDocument(node).CreateElement(elementName);
}
if (nodeOrderComparer == null)
{
parentNode.AppendChild(n);
}
else
{
XmlNode insertAfterNode = null;
foreach (XmlNode childNode in parentNode.ChildNodes)
{
if (childNode.NodeType != XmlNodeType.Element)
{
continue;
}
if (nodeOrderComparer.Compare(n, childNode) < 0)
{
break;
}
insertAfterNode = childNode;
}
parentNode.InsertAfter(n, insertAfterNode);
}
}
return n;
}
public static void RemoveElement(XmlNode node, string xpath, XmlNamespaceManager nameSpaceManager)
{
XmlNode found = node.SelectSingleNode(xpath, nameSpaceManager);
if (found != null)
{
found.ParentNode.RemoveChild(found);
}
}
private static XmlDocument GetDocument(XmlNode nodeOrDoc)
{
if (nodeOrDoc is XmlDocument)
{
return (XmlDocument)nodeOrDoc;
}
else
{
return nodeOrDoc.OwnerDocument;
}
}
/// <summary>
/// Get an optional attribute value from an XmlNode.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The attribute to find.</param>
/// <param name="defaultValue"></param>
/// <returns>The value of the attribute, or the default value, if the attribute dismissing</returns>
public static bool GetOptionalBooleanAttributeValue(XmlNode node, string attrName, bool defaultValue)
{
return GetBooleanAttributeValue(GetOptionalAttributeValue(node, attrName, defaultValue ? "true" : "false"));
}
/// <summary>
/// Returns true if value of attrName is 'true' or 'yes' (case ignored)
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The optional attribute to find.</param>
/// <returns></returns>
public static bool GetBooleanAttributeValue(XmlNode node, string attrName)
{
return GetBooleanAttributeValue(GetOptionalAttributeValue(node, attrName));
}
/// <summary>
/// Returns true if sValue is 'true' or 'yes' (case ignored)
/// </summary>
public static bool GetBooleanAttributeValue(string sValue)
{
return (sValue != null
&& (sValue.ToLower().Equals("true")
|| sValue.ToLower().Equals("yes")));
}
/// <summary>
/// Deprecated: use GetOptionalAttributeValue instead.
/// </summary>
/// <param name="node"></param>
/// <param name="attrName"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static string GetAttributeValue(XmlNode node, string attrName, string defaultValue)
{
return GetOptionalAttributeValue(node, attrName, defaultValue);
}
/// <summary>
/// Get an optional attribute value from an XmlNode.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The attribute to find.</param>
/// <returns>The value of the attribute, or null, if not found.</returns>
public static string GetAttributeValue(XmlNode node, string attrName)
{
return GetOptionalAttributeValue(node, attrName);
}
/// <summary>
/// Get an optional attribute value from an XmlNode.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The attribute to find.</param>
/// <returns>The value of the attribute, or null, if not found.</returns>
public static string GetOptionalAttributeValue(XmlNode node, string attrName)
{
return GetOptionalAttributeValue(node, attrName, null);
}
/// <summary>
/// Get an optional attribute value from an XmlNode.
/// </summary>
/// <param name="node">The XmlNode to look in.</param>
/// <param name="attrName">The attribute to find.</param>
/// <returns>The value of the attribute, or null, if not found.</returns>
public static string GetOptionalAttributeValue(XmlNode node, string attrName, string defaultString)
{
if (node != null && node.Attributes != null)
{
XmlAttribute xa = node.Attributes[attrName];
if (xa != null)
return xa.Value;
}
return defaultString;
}
public static void InsertNodeUsingDefinedOrder(XmlNode parent, XmlNode newChild, IComparer<XmlNode> nodeOrderComparer)
{
if (newChild.NodeType == XmlNodeType.Attribute)
{
XmlAttribute insertAfterNode = null;
foreach (XmlAttribute childNode in parent.Attributes)
{
if (nodeOrderComparer.Compare(newChild, childNode) < 0)
{
break;
}
insertAfterNode = childNode;
}
parent.Attributes.InsertAfter((XmlAttribute)newChild, insertAfterNode);
}
else
{
XmlNode insertAfterNode = null;
foreach (XmlNode childNode in parent.ChildNodes)
{
if (nodeOrderComparer.Compare(newChild, childNode) < 0)
{
break;
}
insertAfterNode = childNode;
}
parent.InsertAfter(newChild, insertAfterNode);
}
}
public static bool FindNextElementInSequence(XmlReader reader, string name, Comparison<string> comparison)
{
while (!reader.EOF && reader.NodeType != XmlNodeType.EndElement &&
(reader.NodeType != XmlNodeType.Element || comparison(name, reader.Name) > 0))
{
switch (reader.NodeType)
{
case XmlNodeType.Attribute:
case XmlNodeType.Element:
reader.Skip();
break;
default:
reader.Read();
break;
}
}
// Element name comparison returns the order of elements. It is possible that we passed where the element would have been without
// finding it. So, use string comparison to determine whether we found it or not.
return !reader.EOF && reader.NodeType == XmlNodeType.Element && name.Equals(reader.Name);
}
public static bool FindNextElementInSequence(XmlReader reader, string name, string nameSpace, Comparison<string> comparison)
{
while (FindNextElementInSequence(reader, name, comparison))
{
if (reader.NamespaceURI == nameSpace)
{
return true;
}
reader.Skip();
}
return false;
}
/// <summary>
/// Finds and reads the EndElement with the specified name
/// </summary>
/// <param name="reader"></param>
/// <param name="name"></param>
/// REVIEW Hasso 2013.12: This method--and all of our XmlReader code, really--is fragile. Since we don't expect LDML files to be unwieldily
/// large, we could afford to refactor all this using XElement, which would pay off in the long run.
public static void ReadEndElement(XmlReader reader, string name)
{
while (!reader.EOF && (reader.NodeType != XmlNodeType.EndElement || !name.Equals(reader.Name)))
{
reader.Read();
}
if (!reader.EOF)
{
reader.ReadEndElement();
}
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Summary description for ReportCtl.
/// </summary>
internal class GridCtl : System.Windows.Forms.UserControl, IProperty
{
private List<XmlNode> _ReportItems;
private DesignXmlDraw _Draw;
bool fPBBefore, fPBAfter;
bool fCheckRows;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.CheckBox chkPBBefore;
private System.Windows.Forms.CheckBox chkPBAfter;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.CheckBox chkDetails;
private System.Windows.Forms.CheckBox chkHeaderRows;
private System.Windows.Forms.CheckBox chkFooterRows;
private CheckBox chkFooterRepeat;
private CheckBox chkHeaderRepeat;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal GridCtl(DesignXmlDraw dxDraw, List<XmlNode> ris)
{
_ReportItems = ris;
_Draw = dxDraw;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues();
}
private void InitValues()
{
XmlNode riNode = _ReportItems[0];
chkPBBefore.Checked = _Draw.GetElementValue(riNode, "PageBreakAtStart", "false").ToLower()=="true"? true:false;
chkPBAfter.Checked = _Draw.GetElementValue(riNode, "PageBreakAtEnd", "false").ToLower()=="true"? true:false;
this.chkDetails.Checked = _Draw.GetNamedChildNode(riNode, "Details") != null;
XmlNode fNode = _Draw.GetNamedChildNode(riNode, "Footer");
this.chkFooterRows.Checked = fNode != null;
if (fNode != null)
{
chkFooterRepeat.Checked = _Draw.GetElementValue(fNode, "RepeatOnNewPage", "false").ToLower() == "true" ? true : false;
}
else
chkFooterRepeat.Enabled = false;
XmlNode hNode = _Draw.GetNamedChildNode(riNode, "Header");
this.chkHeaderRows.Checked = hNode != null;
if (hNode != null)
{
chkHeaderRepeat.Checked = _Draw.GetElementValue(hNode, "RepeatOnNewPage", "false").ToLower() == "true" ? true : false;
}
else
chkHeaderRepeat.Enabled = false;
fPBBefore = fPBAfter = fCheckRows = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.chkPBAfter = new System.Windows.Forms.CheckBox();
this.chkPBBefore = new System.Windows.Forms.CheckBox();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.chkFooterRepeat = new System.Windows.Forms.CheckBox();
this.chkHeaderRepeat = new System.Windows.Forms.CheckBox();
this.chkFooterRows = new System.Windows.Forms.CheckBox();
this.chkHeaderRows = new System.Windows.Forms.CheckBox();
this.chkDetails = new System.Windows.Forms.CheckBox();
this.groupBox1.SuspendLayout();
this.groupBox3.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.chkPBAfter);
this.groupBox1.Controls.Add(this.chkPBBefore);
this.groupBox1.Location = new System.Drawing.Point(24, 22);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(400, 48);
this.groupBox1.TabIndex = 2;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Page Breaks";
//
// chkPBAfter
//
this.chkPBAfter.Location = new System.Drawing.Point(192, 16);
this.chkPBAfter.Name = "chkPBAfter";
this.chkPBAfter.Size = new System.Drawing.Size(128, 24);
this.chkPBAfter.TabIndex = 1;
this.chkPBAfter.Text = "Insert after Grid";
this.chkPBAfter.CheckedChanged += new System.EventHandler(this.chkPBAfter_CheckedChanged);
//
// chkPBBefore
//
this.chkPBBefore.Location = new System.Drawing.Point(16, 16);
this.chkPBBefore.Name = "chkPBBefore";
this.chkPBBefore.Size = new System.Drawing.Size(128, 24);
this.chkPBBefore.TabIndex = 0;
this.chkPBBefore.Text = "Insert before Grid";
this.chkPBBefore.CheckedChanged += new System.EventHandler(this.chkPBBefore_CheckedChanged);
//
// groupBox3
//
this.groupBox3.Controls.Add(this.chkFooterRepeat);
this.groupBox3.Controls.Add(this.chkHeaderRepeat);
this.groupBox3.Controls.Add(this.chkFooterRows);
this.groupBox3.Controls.Add(this.chkHeaderRows);
this.groupBox3.Controls.Add(this.chkDetails);
this.groupBox3.Location = new System.Drawing.Point(24, 86);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(400, 64);
this.groupBox3.TabIndex = 3;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Include Grid Rows";
//
// chkFooterRepeat
//
this.chkFooterRepeat.Location = new System.Drawing.Point(272, 34);
this.chkFooterRepeat.Name = "chkFooterRepeat";
this.chkFooterRepeat.Size = new System.Drawing.Size(122, 30);
this.chkFooterRepeat.TabIndex = 4;
this.chkFooterRepeat.Text = "Repeat footer on new page";
this.chkFooterRepeat.CheckedChanged += new System.EventHandler(this.chkRows_CheckedChanged);
//
// chkHeaderRepeat
//
this.chkHeaderRepeat.Location = new System.Drawing.Point(144, 34);
this.chkHeaderRepeat.Name = "chkHeaderRepeat";
this.chkHeaderRepeat.Size = new System.Drawing.Size(122, 30);
this.chkHeaderRepeat.TabIndex = 3;
this.chkHeaderRepeat.Text = "Repeat header on new page";
this.chkHeaderRepeat.CheckedChanged += new System.EventHandler(this.chkRows_CheckedChanged);
//
// chkFooterRows
//
this.chkFooterRows.Location = new System.Drawing.Point(272, 13);
this.chkFooterRows.Name = "chkFooterRows";
this.chkFooterRows.Size = new System.Drawing.Size(104, 24);
this.chkFooterRows.TabIndex = 2;
this.chkFooterRows.Text = "Footer Rows";
this.chkFooterRows.CheckedChanged += new System.EventHandler(this.chkRows_CheckedChanged);
//
// chkHeaderRows
//
this.chkHeaderRows.Location = new System.Drawing.Point(144, 13);
this.chkHeaderRows.Name = "chkHeaderRows";
this.chkHeaderRows.Size = new System.Drawing.Size(104, 24);
this.chkHeaderRows.TabIndex = 1;
this.chkHeaderRows.Text = "Header Rows";
this.chkHeaderRows.CheckedChanged += new System.EventHandler(this.chkRows_CheckedChanged);
//
// chkDetails
//
this.chkDetails.Location = new System.Drawing.Point(16, 13);
this.chkDetails.Name = "chkDetails";
this.chkDetails.Size = new System.Drawing.Size(104, 24);
this.chkDetails.TabIndex = 1;
this.chkDetails.Text = "Detail Rows";
this.chkDetails.CheckedChanged += new System.EventHandler(this.chkRows_CheckedChanged);
//
// GridCtl
//
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.groupBox1);
this.Name = "GridCtl";
this.Size = new System.Drawing.Size(472, 288);
this.groupBox1.ResumeLayout(false);
this.groupBox3.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
public bool IsValid()
{
if (this.chkDetails.Checked || this.chkFooterRows.Checked || this.chkHeaderRows.Checked)
return true;
MessageBox.Show("Grid must have at least one Header, Details or Footer row defined.", "Grid");
return false;
}
public void Apply()
{
// take information in control and apply to all the style nodes
// Only change information that has been marked as modified;
// this way when group is selected it is possible to change just
// the items you want and keep the rest the same.
foreach (XmlNode riNode in this._ReportItems)
ApplyChanges(riNode);
// No more changes
fPBBefore = fPBAfter = fCheckRows = false;
}
public void ApplyChanges(XmlNode node)
{
if (fPBBefore)
_Draw.SetElement(node, "PageBreakAtStart", this.chkPBBefore.Checked? "true":"false");
if (fPBAfter)
_Draw.SetElement(node, "PageBreakAtEnd", this.chkPBAfter.Checked? "true":"false");
if (fCheckRows)
{
if (this.chkDetails.Checked)
CreateTableRow(node, "Details", false);
else
_Draw.RemoveElement(node, "Details");
if (this.chkHeaderRows.Checked)
CreateTableRow(node, "Header", chkHeaderRepeat.Checked);
else
_Draw.RemoveElement(node, "Header");
if (this.chkFooterRows.Checked)
CreateTableRow(node, "Footer", chkFooterRepeat.Checked);
else
_Draw.RemoveElement(node, "Footer");
}
}
private void CreateTableRow(XmlNode tblNode, string elementName, bool bRepeatOnNewPage)
{
XmlNode node = _Draw.GetNamedChildNode(tblNode, elementName);
if (node == null)
{
node = _Draw.CreateElement(tblNode, elementName, null);
XmlNode tblRows = _Draw.CreateElement(node, "TableRows", null);
_Draw.InsertTableRow(tblRows);
}
if (bRepeatOnNewPage)
_Draw.SetElement(node, "RepeatOnNewPage", "true");
else
_Draw.RemoveElement(node, "RepeatOnNewPage");
return;
}
private void chkPBBefore_CheckedChanged(object sender, System.EventArgs e)
{
fPBBefore = true;
}
private void chkPBAfter_CheckedChanged(object sender, System.EventArgs e)
{
fPBAfter = true;
}
private void chkRows_CheckedChanged(object sender, System.EventArgs e)
{
this.fCheckRows = true;
chkFooterRepeat.Enabled = chkFooterRows.Checked;
chkHeaderRepeat.Enabled = chkHeaderRows.Checked;
}
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, [email protected] *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using MLifter.DAL.Interfaces;
using MLifter.DAL.Tools;
namespace MLifter.DAL.DB
{
/// <summary>
/// Database implementation of IChapter.
/// </summary>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
class DbChapter : IChapter
{
private Interfaces.DB.IDbChapterConnector connector
{
get
{
switch (parent.CurrentUser.ConnectionString.Typ)
{
case DatabaseType.PostgreSQL:
return MLifter.DAL.DB.PostgreSQL.PgSqlChapterConnector.GetInstance(parent);
case DatabaseType.MsSqlCe:
return MLifter.DAL.DB.MsSqlCe.MsSqlCeChapterConnector.GetInstance(parent);
default:
throw new UnsupportedDatabaseTypeException(parent.CurrentUser.ConnectionString.Typ);
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="DbChapter"/> class.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="parent">The parent.</param>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public DbChapter(int id, ParentClass parent)
: this(id, true, parent) { }
/// <summary>
/// Initializes a new instance of the <see cref="DbChapter"/> class.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="CheckId">if set to <c>true</c> [check id].</param>
/// <param name="parent">The parent.</param>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public DbChapter(int id, bool CheckId, ParentClass parent)
{
this.parent = parent;
if (CheckId)
connector.CheckChapterId(id);
this.id = id;
}
/// <summary>
/// Gets the lm id.
/// </summary>
/// <value>The lm id.</value>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public int LmId
{
get
{
return connector.GetLmId(id);
}
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public override string ToString()
{
return Title;
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
/// </summary>
/// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
/// <returns>
/// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
/// </returns>
/// <exception cref="T:System.NullReferenceException">The <paramref name="obj"/> parameter is null.</exception>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public override bool Equals(object obj)
{
DbChapter chapter = obj as DbChapter;
if (chapter == null)
return false;
return this.GetHashCode() == chapter.GetHashCode();
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public override int GetHashCode()
{
return (this.Id + this.ToString()).GetHashCode();
}
#region IChapter Members
private int id;
/// <summary>
/// Gets or sets the id for a chapter.
/// </summary>
/// <value>The id.</value>
/// <remarks>Documented by Dev03, 2007-09-04</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public int Id
{
get
{
return id;
}
}
/// <summary>
/// Gets an Xml representation of the chapter.
/// </summary>
/// <value>The chapter.</value>
/// <remarks>Documented by Dev03, 2008-08-14</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public System.Xml.XmlElement Chapter
{
get
{
StringBuilder sb = new StringBuilder();
System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
settings.Encoding = Encoding.Unicode;
settings.Indent = true;
System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sb, settings);
writer.WriteStartDocument();
writer.WriteStartElement("chapter");
writer.WriteAttributeString("id", Id.ToString());
writer.WriteStartElement("title");
writer.WriteString(Title);
writer.WriteEndElement();
writer.WriteStartElement("descriptipn");
writer.WriteString(Title);
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
string xml = sb.ToString();
try
{
doc.LoadXml(xml);
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
return doc.DocumentElement;
}
}
/// <summary>
/// Gets or sets the title.
/// </summary>
/// <value>The title.</value>
/// <remarks>Documented by Dev03, 2007-09-04</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public string Title
{
get
{
return connector.GetTitle(id);
}
set
{
connector.SetTitle(id, value);
}
}
/// <summary>
/// Gets or sets the description.
/// </summary>
/// <value>The description.</value>
/// <remarks>Documented by Dev03, 2007-09-04</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public string Description
{
get
{
return connector.GetDescription(id);
}
set
{
connector.SetDescription(id, value);
}
}
/// <summary>
/// Gets the total number of cards.
/// </summary>
/// <value>The total number of cards.</value>
/// <remarks>Documented by Dev03, 2007-11-22</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public int Size
{
get { return connector.GetSize(id); }
}
/// <summary>
/// Gets the number of active cards.
/// </summary>
/// <value>The number of active cards.</value>
/// <remarks>Documented by Dev03, 2007-11-22</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public int ActiveSize
{
get { return connector.GetActiveSize(id); }
}
/// <summary>
/// Gets or sets the style.
/// </summary>
/// <value>The style.</value>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public MLifter.DAL.Interfaces.ICardStyle Style
{
get
{
throw new Exception("The method or operation is not implemented.");
}
set
{
throw new Exception("The method or operation is not implemented.");
}
}
/// <summary>
/// Creates and returns a card style.
/// </summary>
/// <returns></returns>
/// <remarks>Documented by Dev03, 2008-01-08</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public MLifter.DAL.Interfaces.ICardStyle CreateCardStyle()
{
return connector.CreateId();
}
/// <summary>
/// Gets or sets the settings.
/// </summary>
/// <value>The settings.</value>
/// <remarks>Documented by Dev05, 2008-08-19</remarks>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public MLifter.DAL.Interfaces.ISettings Settings
{
get
{
return connector.GetSettings(id);
}
set
{
connector.SetSettings(id, value);
}
}
#endregion
#region ICopy Members
/// <summary>
/// Copies to.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="progressDelegate">The progress delegate.</param>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public void CopyTo(ICopy target, CopyToProgress progressDelegate)
{
IChapter targetChapter = target as IChapter;
if (targetChapter != null && targetChapter.Settings == null && this.Settings != null)
targetChapter.Settings = targetChapter.Parent.GetParentDictionary().CreateSettings();
CopyBase.Copy(this, target, typeof(IChapter), progressDelegate);
}
#endregion
#region IParent Members
private ParentClass parent;
/// <summary>
/// Gets the parent.
/// </summary>
/// <value>The parent.</value>
/// <remarks>Documented by Dev03, 2009-01-13</remarks>
public ParentClass Parent
{
get { return parent; }
}
#endregion
#region ISecurity Members
/// <summary>
/// Determines whether the object has the specified permission.
/// </summary>
/// <param name="permissionName">Name of the permission.</param>
/// <returns>
/// <c>true</c> if the object name has the specified permission; otherwise, <c>false</c>.
/// </returns>
/// <remarks>Documented by Dev03, 2009-01-15</remarks>
/// <remarks>Documented by Dev03, 2009-01-15</remarks>
public bool HasPermission(string permissionName)
{
return Parent.CurrentUser.HasPermission(this, permissionName);
}
/// <summary>
/// Gets the permissions for the object.
/// </summary>
/// <returns>A list of permissions for the object.</returns>
/// <remarks>Documented by Dev03, 2009-01-15</remarks>
/// <remarks>Documented by Dev03, 2009-01-15</remarks>
public List<SecurityFramework.PermissionInfo> GetPermissions()
{
return Parent.CurrentUser.GetPermissions(this);
}
#endregion
}
}
| |
/*
*
* (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.Collections.Generic;
using ASC.MessagingSystem;
namespace ASC.AuditTrail.Mappers
{
internal class ProjectsActionsMapper
{
public static Dictionary<MessageAction, MessageMaps> GetMaps()
{
return new Dictionary<MessageAction, MessageMaps>
{
#region projects
{
MessageAction.ProjectCreated, new MessageMaps
{
ActionTypeTextResourceName = "CreateActionType",
ActionTextResourceName = "ProjectCreated",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ProjectsModule"
}
},
{
MessageAction.ProjectCreatedFromTemplate, new MessageMaps
{
ActionTypeTextResourceName = "CreateActionType",
ActionTextResourceName = "ProjectCreatedFromTemplate",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ProjectsModule"
}
},
{
MessageAction.ProjectUpdated, new MessageMaps
{
ActionTypeTextResourceName = "UpdateActionType",
ActionTextResourceName = "ProjectUpdated",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ProjectsModule"
}
},
{
MessageAction.ProjectUpdatedStatus, new MessageMaps
{
ActionTypeTextResourceName = "UpdateActionType",
ActionTextResourceName = "ProjectUpdatedStatus",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ProjectsModule"
}
},
{
MessageAction.ProjectFollowed, new MessageMaps
{
ActionTypeTextResourceName = "FollowActionType",
ActionTextResourceName = "ProjectFollowed",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ProjectsModule"
}
},
{
MessageAction.ProjectUnfollowed, new MessageMaps
{
ActionTypeTextResourceName = "UnfollowActionType",
ActionTextResourceName = "ProjectUnfollowed",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ProjectsModule"
}
},
{
MessageAction.ProjectDeleted, new MessageMaps
{
ActionTypeTextResourceName = "DeleteActionType",
ActionTextResourceName = "ProjectDeleted",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ProjectsModule"
}
},
#endregion
#region team
{
MessageAction.ProjectDeletedMember, new MessageMaps
{
ActionTypeTextResourceName = "DeleteActionType",
ActionTextResourceName = "ProjectDeletedMember",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ProjectsModule"
}
},
{
MessageAction.ProjectUpdatedTeam, new MessageMaps
{
ActionTypeTextResourceName = "UpdateActionType",
ActionTextResourceName = "ProjectUpdatedTeam",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ProjectsModule"
}
},
{
MessageAction.ProjectUpdatedMemberRights, new MessageMaps
{
ActionTypeTextResourceName = "UpdateAccessActionType",
ActionTextResourceName = "ProjectUpdatedMemberRights",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ProjectsModule"
}
},
#endregion
#region contacts
{
MessageAction.ProjectLinkedCompany, new MessageMaps
{
ActionTypeTextResourceName = "LinkActionType",
ActionTextResourceName = "ProjectLinkedCompany",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ProjectsModule"
}
},
{
MessageAction.ProjectUnlinkedCompany, new MessageMaps
{
ActionTypeTextResourceName = "UnlinkActionType",
ActionTextResourceName = "ProjectUnlinkedCompany",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ProjectsModule"
}
},
{
MessageAction.ProjectLinkedPerson, new MessageMaps
{
ActionTypeTextResourceName = "LinkActionType",
ActionTextResourceName = "ProjectLinkedPerson",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ProjectsModule"
}
},
{
MessageAction.ProjectUnlinkedPerson, new MessageMaps
{
ActionTypeTextResourceName = "UnlinkActionType",
ActionTextResourceName = "ProjectUnlinkedPerson",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ProjectsModule"
}
},
{
MessageAction.ProjectLinkedContacts, new MessageMaps
{
ActionTypeTextResourceName = "LinkActionType",
ActionTextResourceName = "ProjectLinkedContacts",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ProjectsModule"
}
},
#endregion
#region milestones
{
MessageAction.MilestoneCreated, new MessageMaps
{
ActionTypeTextResourceName = "CreateActionType",
ActionTextResourceName = "MilestoneCreated",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "MilestonesModule"
}
},
{
MessageAction.MilestoneUpdated, new MessageMaps
{
ActionTypeTextResourceName = "UpdateActionType",
ActionTextResourceName = "MilestoneUpdated",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "MilestonesModule"
}
},
{
MessageAction.MilestoneUpdatedStatus, new MessageMaps
{
ActionTypeTextResourceName = "UpdateActionType",
ActionTextResourceName = "MilestoneUpdatedStatus",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "MilestonesModule"
}
},
{
MessageAction.MilestoneDeleted, new MessageMaps
{
ActionTypeTextResourceName = "DeleteActionType",
ActionTextResourceName = "MilestoneDeleted",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "MilestonesModule"
}
},
#endregion
#region tasks
{
MessageAction.TaskCreated, new MessageMaps
{
ActionTypeTextResourceName = "CreateActionType",
ActionTextResourceName = "TaskCreated",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TasksModule"
}
},
{
MessageAction.TaskCreatedFromDiscussion, new MessageMaps
{
ActionTypeTextResourceName = "CreateActionType",
ActionTextResourceName = "TaskCreatedFromDiscussion",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TasksModule"
}
},
{
MessageAction.TaskUpdated, new MessageMaps
{
ActionTypeTextResourceName = "UpdateActionType",
ActionTextResourceName = "TaskUpdated",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TasksModule"
}
},
{
MessageAction.TaskUpdatedStatus, new MessageMaps
{
ActionTypeTextResourceName = "UpdateActionType",
ActionTextResourceName = "TaskUpdatedStatus",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TasksModule"
}
},
{
MessageAction.TaskMovedToMilestone, new MessageMaps
{
ActionTypeTextResourceName = "UpdateActionType",
ActionTextResourceName = "TaskMovedToMilestone",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TasksModule"
}
},
{
MessageAction.TaskUnlinkedMilestone, new MessageMaps
{
ActionTypeTextResourceName = "UpdateActionType",
ActionTextResourceName = "TaskUnlinkedMilestone",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TasksModule"
}
},
{
MessageAction.TaskUpdatedFollowing, new MessageMaps
{
ActionTypeTextResourceName = "FollowActionType",
ActionTextResourceName = "TaskUpdatedFollowing",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TasksModule"
}
},
{
MessageAction.TaskAttachedFiles, new MessageMaps
{
ActionTypeTextResourceName = "AttachActionType",
ActionTextResourceName = "TaskAttachedFiles",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TasksModule"
}
},
{
MessageAction.TaskDetachedFile, new MessageMaps
{
ActionTypeTextResourceName = "DetachActionType",
ActionTextResourceName = "TaskDetachedFile",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TasksModule"
}
},
{
MessageAction.TasksLinked, new MessageMaps
{
ActionTypeTextResourceName = "LinkActionType",
ActionTextResourceName = "TasksLinked",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TasksModule"
}
},
{
MessageAction.TasksUnlinked, new MessageMaps
{
ActionTypeTextResourceName = "UnlinkActionType",
ActionTextResourceName = "TasksUnlinked",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TasksModule"
}
},
{
MessageAction.TaskDeleted, new MessageMaps
{
ActionTypeTextResourceName = "DeleteActionType",
ActionTextResourceName = "TaskDeleted",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TasksModule"
}
},
{
MessageAction.TaskCommentCreated, new MessageMaps
{
ActionTypeTextResourceName = "CreateActionType",
ActionTextResourceName = "TaskCommentCreated",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TasksModule"
}
},
{
MessageAction.TaskCommentUpdated, new MessageMaps
{
ActionTypeTextResourceName = "UpdateActionType",
ActionTextResourceName = "TaskCommentUpdated",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TasksModule"
}
},
{
MessageAction.TaskCommentDeleted, new MessageMaps
{
ActionTypeTextResourceName = "DeleteActionType",
ActionTextResourceName = "TaskCommentDeleted",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TasksModule"
}
},
#endregion
#region subtasks
{
MessageAction.SubtaskCreated, new MessageMaps
{
ActionTypeTextResourceName = "CreateActionType",
ActionTextResourceName = "SubtaskCreated",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TasksModule"
}
},
{
MessageAction.SubtaskUpdated, new MessageMaps
{
ActionTypeTextResourceName = "UpdateActionType",
ActionTextResourceName = "SubtaskUpdated",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TasksModule"
}
},
{
MessageAction.SubtaskUpdatedStatus, new MessageMaps
{
ActionTypeTextResourceName = "UpdateActionType",
ActionTextResourceName = "SubtaskUpdatedStatus",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TasksModule"
}
},
{
MessageAction.SubtaskDeleted, new MessageMaps
{
ActionTypeTextResourceName = "DeleteActionType",
ActionTextResourceName = "SubtaskDeleted",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TasksModule"
}
},
#endregion
#region discussions
{
MessageAction.DiscussionCreated, new MessageMaps
{
ActionTypeTextResourceName = "CreateActionType",
ActionTextResourceName = "DiscussionCreated",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "DiscussionsModule"
}
},
{
MessageAction.DiscussionUpdated, new MessageMaps
{
ActionTypeTextResourceName = "UpdateActionType",
ActionTextResourceName = "DiscussionUpdated",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "DiscussionsModule"
}
},
{
MessageAction.DiscussionUpdatedFollowing, new MessageMaps
{
ActionTypeTextResourceName = "FollowActionType",
ActionTextResourceName = "DiscussionUpdatedFollowing",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "DiscussionsModule"
}
},
{
MessageAction.DiscussionAttachedFiles, new MessageMaps
{
ActionTypeTextResourceName = "AttachActionType",
ActionTextResourceName = "DiscussionAttachedFiles",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "DiscussionsModule"
}
},
{
MessageAction.DiscussionDetachedFile, new MessageMaps
{
ActionTypeTextResourceName = "DetachActionType",
ActionTextResourceName = "DiscussionDetachedFile",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "DiscussionsModule"
}
},
{
MessageAction.DiscussionDeleted, new MessageMaps
{
ActionTypeTextResourceName = "DeleteActionType",
ActionTextResourceName = "DiscussionDeleted",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "DiscussionsModule"
}
},
{
MessageAction.DiscussionCommentCreated, new MessageMaps
{
ActionTypeTextResourceName = "CreateActionType",
ActionTextResourceName = "DiscussionCommentCreated",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "DiscussionsModule"
}
},
{
MessageAction.DiscussionCommentUpdated, new MessageMaps
{
ActionTypeTextResourceName = "UpdateActionType",
ActionTextResourceName = "DiscussionCommentUpdated",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "DiscussionsModule"
}
},
{
MessageAction.DiscussionCommentDeleted, new MessageMaps
{
ActionTypeTextResourceName = "DeleteActionType",
ActionTextResourceName = "DiscussionCommentDeleted",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "DiscussionsModule"
}
},
#endregion
#region time tracking
{
MessageAction.TaskTimeCreated, new MessageMaps
{
ActionTypeTextResourceName = "CreateActionType",
ActionTextResourceName = "TaskTimeCreated",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TimeTrackingModule"
}
},
{
MessageAction.TaskTimeUpdated, new MessageMaps
{
ActionTypeTextResourceName = "UpdateActionType",
ActionTextResourceName = "TaskTimeUpdated",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TimeTrackingModule"
}
},
{
MessageAction.TaskTimesUpdatedStatus, new MessageMaps
{
ActionTypeTextResourceName = "UpdateActionType",
ActionTextResourceName = "TaskTimesUpdatedStatus",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TimeTrackingModule"
}
},
{
MessageAction.TaskTimesDeleted, new MessageMaps
{
ActionTypeTextResourceName = "DeleteActionType",
ActionTextResourceName = "TaskTimesDeleted",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "TimeTrackingModule"
}
},
#endregion
#region reports
{
MessageAction.ReportTemplateCreated, new MessageMaps
{
ActionTypeTextResourceName = "CreateActionType",
ActionTextResourceName = "ReportTemplateCreated",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ReportsModule"
}
},
{
MessageAction.ReportTemplateUpdated, new MessageMaps
{
ActionTypeTextResourceName = "UpdateActionType",
ActionTextResourceName = "ReportTemplateUpdated",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ReportsModule"
}
},
{
MessageAction.ReportTemplateDeleted, new MessageMaps
{
ActionTypeTextResourceName = "DeleteActionType",
ActionTextResourceName = "ReportTemplateDeleted",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ReportsModule"
}
},
#endregion
#region settings
{
MessageAction.ProjectTemplateCreated, new MessageMaps
{
ActionTypeTextResourceName = "CreateActionType",
ActionTextResourceName = "ProjectTemplateCreated",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ProjectsSettingsModule"
}
},
{
MessageAction.ProjectTemplateUpdated, new MessageMaps
{
ActionTypeTextResourceName = "UpdateActionType",
ActionTextResourceName = "ProjectTemplateUpdated",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ProjectsSettingsModule"
}
},
{
MessageAction.ProjectTemplateDeleted, new MessageMaps
{
ActionTypeTextResourceName = "DeleteActionType",
ActionTextResourceName = "ProjectTemplateDeleted",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ProjectsSettingsModule"
}
},
{
MessageAction.ProjectsImportedFromBasecamp, new MessageMaps
{
ActionTypeTextResourceName = "ImportActionType",
ActionTextResourceName = "ProjectsImportedFromBasecamp",
ProductResourceName = "ProjectsProduct",
ModuleResourceName = "ProjectsModule"
}
},
#endregion
};
}
}
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email [email protected] |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.ComponentModel; // need this for the properties metadata
using System.Xml;
using System.Text.RegularExpressions;
using System.Drawing.Design;
using System.Globalization;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace Reporting.RdlDesign
{
/// <summary>
/// PropertyReportItem - The ReportItem Properties
/// </summary>
[DefaultPropertyAttribute("Author")]
internal class PropertyReport
{
private DesignXmlDraw _Draw;
private DesignCtl _DesignCtl;
internal PropertyReport(DesignXmlDraw d, DesignCtl dc)
{
_Draw = d;
_DesignCtl = dc;
}
internal DesignXmlDraw Draw
{
get { return _Draw; }
}
internal DesignCtl DesignCtl
{
get { return _DesignCtl; }
}
XmlNode ReportNode
{
get { return _Draw.GetReportNode(); }
}
[CategoryAttribute("Report"),
DescriptionAttribute("The author of the report")]
public string Author
{
get {return GetReportValue("Author"); }
set{SetReportValue("Author", value); }
}
[CategoryAttribute("Report"),
DescriptionAttribute("The description of the report")]
public string Description
{
get { return GetReportValue("Description"); }
set { SetReportValue("Description", value); }
}
[CategoryAttribute("Report"),
DescriptionAttribute("The width of the report.")]
public string Width
{
get { return GetReportValue("Width"); }
set
{
DesignerUtility.ValidateSize(value, false, false);
SetReportValue("Width", value);
DesignCtl.SetScrollControls(); // this will force ruler and scroll bars to be updated
}
}
[CategoryAttribute("Report"),
DescriptionAttribute("Parameters defined in the report.")]
public PropertyReportParameters Parameters
{
get { return new PropertyReportParameters(this); }
}
[CategoryAttribute("Report"),
DescriptionAttribute("Basic functions defined for use in the report.")]
public PropertyReportCode Code
{
get { return new PropertyReportCode(this); }
}
[CategoryAttribute("Report"),
DescriptionAttribute("Modules and instances of classes for use in the report.")]
public PropertyReportModulesClasses ModulesClasses
{
get { return new PropertyReportModulesClasses(this); }
}
[CategoryAttribute("Report"),
DescriptionAttribute("The width of the page.")]
public string PageWidth
{
get { return GetReportValue("PageWidth"); }
set
{
DesignerUtility.ValidateSize(value, false, false);
SetReportValue("PageWidth", value);
DesignCtl.SetScrollControls(); // this will force ruler and scroll bars to be updated
}
}
[CategoryAttribute("Report"),
DescriptionAttribute("The height of the page.")]
public string PageHeight
{
get { return GetReportValue("PageHeight"); }
set
{
DesignerUtility.ValidateSize(value, false, false);
SetReportValue("PageHeight", value);
}
}
[CategoryAttribute("Report"),
DisplayName("Page Margins"),
DescriptionAttribute("Page margins for the report.")]
public PropertyMargin Margins
{
get
{
return new PropertyMargin(this);
}
}
[CategoryAttribute("Report"),
DescriptionAttribute("PageHeader options for the report.")]
public PropertyPrintFirstLast PageHeader
{
get
{
XmlNode phNode = _Draw.GetCreateNamedChildNode(ReportNode, "PageHeader");
return new PropertyPrintFirstLast(this, phNode);
}
}
[CategoryAttribute("Report"),
DescriptionAttribute("PageFooter options for the report.")]
public PropertyPrintFirstLast PageFooter
{
get
{
XmlNode phNode = _Draw.GetCreateNamedChildNode(ReportNode, "PageFooter");
return new PropertyPrintFirstLast(this, phNode);
}
}
[CategoryAttribute("Body"),
DescriptionAttribute("Height of the body region.")]
public string BodyHeight
{
get
{
return GetBodyValue("Height", "");
}
set
{
DesignerUtility.ValidateSize(value, true, false);
SetBodyValue("Height", value);
DesignCtl.SetScrollControls(); // this will force ruler and scroll bars to be updated
}
}
[CategoryAttribute("Body"),
DescriptionAttribute("Number of columns in the body region.")]
public int BodyColumns
{
get
{
string c = GetBodyValue("Columns", "1");
try
{
return Convert.ToInt32(c);
}
catch
{
return 1;
}
}
set
{
if (value < 1)
throw new ArgumentException("The number of columns in the body must be greater than 0.");
SetBodyValue("Columns", value.ToString());
}
}
[CategoryAttribute("Body"),
DescriptionAttribute("Spacing between columns.")]
public string BodyColumnSpacing
{
get
{
return GetBodyValue("ColumnSpacing", "");
}
set
{
if (value.Length == 0)
{
RemoveBodyValue("ColumnSpacing");
}
else
{
DesignerUtility.ValidateSize(value, true, false);
SetBodyValue("ColumnSpacing", value);
}
}
}
[CategoryAttribute("XML"),
DescriptionAttribute("XSL file to use to transform XML after rendering."),
Editor(typeof(FileUIEditor), typeof(System.Drawing.Design.UITypeEditor))]
public string DataTransform
{
get { return GetReportValue("DataTransform"); }
set { SetReportValue("DataTransform", value); }
}
[CategoryAttribute("XML"),
DescriptionAttribute("The schema or namespace to specify when rendering XML.")]
public string DataSchema
{
get { return GetReportValue("DataSchema"); }
set { SetReportValue("DataSchema", value); }
}
[CategoryAttribute("XML"),
DescriptionAttribute("The top level element name used when rendering XML.")]
public string DataElementName
{
get { return GetReportValue("DataElementName"); }
set { SetReportValue("DataElementName", value); }
}
[CategoryAttribute("XML"),
TypeConverter(typeof(ElementStyleConverter)),
DescriptionAttribute("Element style is either Attribute or Element.")]
public string DataElementStyle
{
get { return GetReportValue("DataElementStyle", "AttributeNormal"); }
set { SetReportValue("DataElementStyle", value); }
}
string GetBodyValue(string l, string def)
{
XmlNode rNode = _Draw.GetReportNode();
XmlNode bNode = _Draw.GetNamedChildNode(rNode, "Body");
return _Draw.GetElementValue(bNode, l, def);
}
void SetBodyValue(string l, string v)
{
XmlNode rNode = _Draw.GetReportNode();
XmlNode bNode = _Draw.GetNamedChildNode(rNode, "Body");
_DesignCtl.StartUndoGroup("Body " + l + " change");
_Draw.SetElement(bNode, l, v);
_DesignCtl.EndUndoGroup(true);
_DesignCtl.SignalReportChanged();
_Draw.Invalidate();
}
void RemoveBodyValue(string l)
{
XmlNode rNode = _Draw.GetReportNode();
XmlNode bNode = _Draw.GetNamedChildNode(rNode, "Body");
_DesignCtl.StartUndoGroup("Body " + l + " change");
_Draw.RemoveElement(bNode, l);
_DesignCtl.EndUndoGroup(true);
_DesignCtl.SignalReportChanged();
_Draw.Invalidate();
}
internal string GetReportValue(string l)
{
return GetReportValue(l, "");
}
internal string GetReportValue(string l, string def)
{
XmlNode rNode = _Draw.GetReportNode();
return _Draw.GetElementValue(rNode, l, def);
}
internal void SetReportValue(string l, string v)
{
XmlNode rNode = _Draw.GetReportNode();
_DesignCtl.StartUndoGroup(l + " change");
_Draw.SetElement(rNode, l, v);
_DesignCtl.EndUndoGroup(true);
_DesignCtl.SignalReportChanged();
_Draw.Invalidate();
}
}
#region Parameters
[TypeConverter(typeof(PropertyReportParameterConverter)),
Editor(typeof(PropertyReportParameterUIEditor), typeof(System.Drawing.Design.UITypeEditor))]
internal class PropertyReportParameters
{
PropertyReport pr;
internal PropertyReportParameters(PropertyReport r)
{
pr = r;
}
public override string ToString()
{
XmlNode rNode = pr.Draw.GetReportNode();
XmlNode rpsNode = pr.Draw.GetNamedChildNode(rNode, "ReportParameters");
string s;
if (rpsNode == null)
s = "No parameters defined";
else
{
// show the list of parameters
StringBuilder sb = new StringBuilder();
foreach (XmlNode repNode in rpsNode)
{
XmlAttribute nAttr = repNode.Attributes["Name"];
if (nAttr == null) // shouldn't really happen
continue;
if (sb.Length > 0)
sb.Append(", ");
sb.Append(nAttr.Value);
}
sb.Append(" defined");
s = sb.ToString();
}
return s;
}
}
internal class PropertyReportParameterConverter : StringConverter
{
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false;
}
public override bool CanConvertTo(ITypeDescriptorContext context,
System.Type destinationType)
{
if (destinationType == typeof(PropertyReportParameters))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string) && value is PropertyReportParameters)
{
PropertyReportParameters prp = value as PropertyReportParameters;
return prp.ToString();
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
internal class PropertyReportParameterUIEditor : UITypeEditor
{
internal PropertyReportParameterUIEditor()
{
}
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.Modal;
}
public override object EditValue(ITypeDescriptorContext context,
IServiceProvider provider,
object value)
{
if ((context == null) || (provider == null))
return base.EditValue(context, provider, value);
// Access the Property Browser's UI display service
IWindowsFormsEditorService editorService =
(IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
if (editorService == null)
return base.EditValue(context, provider, value);
// Create an instance of the UI editor form
PropertyReport pr = context.Instance as PropertyReport;
if (pr == null)
return base.EditValue(context, provider, value);
using (SingleCtlDialog scd = new SingleCtlDialog(pr.DesignCtl, pr.Draw, null, SingleCtlTypeEnum.ReportParameterCtl, null))
{
// Display the UI editor dialog
if (editorService.ShowDialog(scd) == DialogResult.OK)
{
// Return the new property value from the UI editor form
return new PropertyReportParameters(pr);
}
return base.EditValue(context, provider, value);
}
}
}
#endregion
#region Code
[TypeConverter(typeof(PropertyReportCodeConverter)),
Editor(typeof(PropertyReportCodeUIEditor), typeof(System.Drawing.Design.UITypeEditor))]
internal class PropertyReportCode
{
PropertyReport pr;
internal PropertyReportCode(PropertyReport r)
{
pr = r;
}
public override string ToString()
{
XmlNode rNode = pr.Draw.GetReportNode();
XmlNode cNode = pr.Draw.GetNamedChildNode(rNode, "Code");
return cNode == null ? "None defined" : "Defined";
}
}
internal class PropertyReportCodeConverter : StringConverter
{
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false;
}
public override bool CanConvertTo(ITypeDescriptorContext context,
System.Type destinationType)
{
if (destinationType == typeof(PropertyReportCode))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string) && value is PropertyReportCode)
{
PropertyReportCode prc = value as PropertyReportCode;
return prc.ToString();
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
internal class PropertyReportCodeUIEditor : UITypeEditor
{
internal PropertyReportCodeUIEditor()
{
}
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.Modal;
}
public override object EditValue(ITypeDescriptorContext context,
IServiceProvider provider,
object value)
{
if ((context == null) || (provider == null))
return base.EditValue(context, provider, value);
// Access the Property Browser's UI display service
IWindowsFormsEditorService editorService =
(IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
if (editorService == null)
return base.EditValue(context, provider, value);
// Create an instance of the UI editor form
PropertyReport pr = context.Instance as PropertyReport;
if (pr == null)
return base.EditValue(context, provider, value);
using (SingleCtlDialog scd = new SingleCtlDialog(pr.DesignCtl, pr.Draw, null, SingleCtlTypeEnum.ReportCodeCtl, null))
{
// Display the UI editor dialog
if (editorService.ShowDialog(scd) == DialogResult.OK)
{
// Return the new property value from the UI editor form
return new PropertyReportCode(pr);
}
return base.EditValue(context, provider, value);
}
}
}
#endregion
#region ModulesClasses
[TypeConverter(typeof(PropertyReportModulesClassesConverter)),
Editor(typeof(PropertyReportModulesClassesUIEditor), typeof(System.Drawing.Design.UITypeEditor))]
internal class PropertyReportModulesClasses
{
PropertyReport pr;
internal PropertyReportModulesClasses(PropertyReport r)
{
pr = r;
}
public override string ToString()
{
XmlNode rNode = pr.Draw.GetReportNode();
StringBuilder sb = new StringBuilder();
XmlNode cmsNode = pr.Draw.GetNamedChildNode(rNode, "CodeModules");
sb.Append(cmsNode == null? "No Modules, ": "Modules, ");
XmlNode clsNode = pr.Draw.GetNamedChildNode(rNode, "Classes");
sb.Append(clsNode == null? "No Classes": "Classes");
sb.Append(" defined");
return sb.ToString();
}
}
internal class PropertyReportModulesClassesConverter : StringConverter
{
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false;
}
public override bool CanConvertTo(ITypeDescriptorContext context,
System.Type destinationType)
{
if (destinationType == typeof(PropertyReportModulesClasses))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string) && value is PropertyReportModulesClasses)
{
PropertyReportModulesClasses prm = value as PropertyReportModulesClasses;
return prm.ToString();
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
internal class PropertyReportModulesClassesUIEditor : UITypeEditor
{
internal PropertyReportModulesClassesUIEditor()
{
}
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.Modal;
}
public override object EditValue(ITypeDescriptorContext context,
IServiceProvider provider,
object value)
{
if ((context == null) || (provider == null))
return base.EditValue(context, provider, value);
// Access the Property Browser's UI display service
IWindowsFormsEditorService editorService =
(IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
if (editorService == null)
return base.EditValue(context, provider, value);
// Create an instance of the UI editor form
PropertyReport pr = context.Instance as PropertyReport;
if (pr == null)
return base.EditValue(context, provider, value);
using (SingleCtlDialog scd = new SingleCtlDialog(pr.DesignCtl, pr.Draw, null, SingleCtlTypeEnum.ReportModulesClassesCtl, null))
{
// Display the UI editor dialog
if (editorService.ShowDialog(scd) == DialogResult.OK)
{
// Return the new property value from the UI editor form
return new PropertyReportModulesClasses(pr);
}
return base.EditValue(context, provider, value);
}
}
}
#endregion
#region XSLFile
internal class FileUIEditor : UITypeEditor
{
internal FileUIEditor()
{
}
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.Modal;
}
public override object EditValue(ITypeDescriptorContext context,
IServiceProvider provider,
object value)
{
if ((context == null) || (provider == null))
return base.EditValue(context, provider, value);
// Access the Property Browser's UI display service
IWindowsFormsEditorService editorService =
(IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
if (editorService == null)
return base.EditValue(context, provider, value);
// Create an instance of the UI editor form
PropertyReport pr = context.Instance as PropertyReport;
if (pr == null)
return base.EditValue(context, provider, value);
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "XSL Files (*.xsl)|*.xsl" +
"|All files (*.*)|*.*";
ofd.FilterIndex = 0;
ofd.CheckFileExists = true;
if (ofd.ShowDialog() == DialogResult.OK)
{
// Return the new property value from the UI editor form
return ofd.FileName;
}
return base.EditValue(context, provider, value);
}
}
}
#endregion
#region ElementStyle
internal class ElementStyleConverter : StringConverter
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return true;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(new string[] {
"AttributeNormal", "ElementNormal"});
}
}
#endregion
}
| |
#region License
// Distributed under the MIT License
// ============================================================
// Copyright (c) 2019 Hotcakes Commerce, LLC
// Copyright (c) 2020 Upendo Ventures, 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.
#endregion
using System;
using System.Collections.Generic;
using System.Net.Mail;
using System.Text;
using Hotcakes.Commerce.Catalog;
using Hotcakes.Commerce.Contacts;
using Hotcakes.Commerce.Membership;
using Hotcakes.Commerce.Orders;
using Hotcakes.Commerce.Utilities;
using Hotcakes.Web.Data;
namespace Hotcakes.Commerce.Content
{
public class HtmlTemplate : ILocalizableModel
{
public HtmlTemplate()
{
Id = 0;
StoreId = 0;
LastUpdatedUtc = DateTime.UtcNow;
From = string.Empty;
DisplayName = string.Empty;
Subject = string.Empty;
Body = string.Empty;
RepeatingSection = string.Empty;
TemplateType = HtmlTemplateType.Custom;
}
public long Id { get; set; }
public long StoreId { get; set; }
public DateTime LastUpdatedUtc { get; set; }
public string DisplayName { get; set; }
public string From { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public string RepeatingSection { get; set; }
public HtmlTemplateType TemplateType { get; set; }
public string ContentCulture { get; set; }
public HtmlTemplate Clone()
{
var t = new HtmlTemplate();
t.Body = Body;
t.DisplayName = DisplayName;
t.From = From;
t.LastUpdatedUtc = LastUpdatedUtc;
t.RepeatingSection = RepeatingSection;
t.StoreId = StoreId;
t.Subject = Subject;
t.TemplateType = HtmlTemplateType.Custom;
t.ContentCulture = ContentCulture;
return t;
}
public HtmlTemplate ReplaceTagsInTemplate(HccRequestContext context, IReplaceable item)
{
var items = new List<IReplaceable>();
items.Add(item);
return ReplaceTagsInTemplate(context, items);
}
public HtmlTemplate ReplaceTagsInTemplate(HccRequestContext context, IReplaceable item,
List<IReplaceable> repeatingItems)
{
var items = new List<IReplaceable>();
items.Add(item);
return ReplaceTagsInTemplate(context, items, repeatingItems);
}
public HtmlTemplate ReplaceTagsInTemplate(HccRequestContext context, List<IReplaceable> items)
{
return ReplaceTagsInTemplate(context, items, new List<IReplaceable>());
}
public HtmlTemplate ReplaceTagsInTemplate(HccRequestContext context, List<IReplaceable> items,
List<IReplaceable> repeatingItems)
{
var copy = Clone();
// Replace Store Defaults
foreach (var tag in DefaultReplacementTags(context))
{
copy.Subject = tag.ReplaceTags(copy.Subject);
copy.Body = tag.ReplaceTags(copy.Body);
copy.From = tag.ReplaceTags(copy.From);
}
// Replace Tags in Body and Subject
foreach (var item in items)
{
foreach (var tag in item.GetReplaceableTags(context))
{
copy.Subject = tag.ReplaceTags(copy.Subject);
copy.Body = tag.ReplaceTags(copy.Body);
copy.From = tag.ReplaceTags(copy.From);
}
}
// Build Repeating Section
var sb = new StringBuilder();
foreach (var repeatingItem in repeatingItems)
{
var temp = copy.RepeatingSection;
foreach (var tag in repeatingItem.GetReplaceableTags(context))
{
temp = tag.ReplaceTags(temp);
}
sb.Append(temp);
}
// Copy repeating section to body
var allrepeating = sb.ToString();
copy.Body = copy.Body.Replace("[[RepeatingSection]]", allrepeating);
return copy;
}
public MailMessage ConvertToMailMessage(string toEmail)
{
try
{
var result = new MailMessage(From, toEmail);
result.IsBodyHtml = true;
result.Body = Body;
result.Subject = Subject;
return result;
}
catch (Exception)
{
return null;
}
}
public List<HtmlTemplateTag> DefaultReplacementTags(HccRequestContext context)
{
var tags = new List<HtmlTemplateTag>();
var store = context.CurrentStore;
var hccApp = new HotcakesApplication(context);
var addressRepository = Factory.CreateRepo<AddressRepository>(context);
tags.Add(new HtmlTemplateTag("[[Store.Address]]", addressRepository.FindStoreContactAddress().ToHtmlString()));
tags.Add(new HtmlTemplateTag("[[Store.ContactEmail]]", store.Settings.MailServer.EmailForGeneral));
tags.Add(new HtmlTemplateTag("[[Store.Logo]]", HtmlRendering.Logo(hccApp, false)));
tags.Add(new HtmlTemplateTag("[[Store.SecureUrl]]", store.RootUrlSecure()));
tags.Add(new HtmlTemplateTag("[[Store.StoreName]]", store.Settings.FriendlyName));
tags.Add(new HtmlTemplateTag("[[Store.RawStoreName]]", store.StoreName));
tags.Add(new HtmlTemplateTag("[[Store.StandardUrl]]", store.RootUrl()));
tags.Add(new HtmlTemplateTag("[[Store.CurrentLocalTime]]", DateTime.Now.ToString()));
tags.Add(new HtmlTemplateTag("[[Store.CurrentUtcTime]]", DateTime.UtcNow.ToString()));
return tags;
}
public List<HtmlTemplateTag> GetEmptyReplacementTags(HccRequestContext context)
{
var tags = new List<HtmlTemplateTag>();
tags.AddRange(DefaultReplacementTags(context));
switch (TemplateType)
{
case HtmlTemplateType.NewOrderForAdmin:
case HtmlTemplateType.AbandonedCart:
case HtmlTemplateType.RecurringPaymentSuccess:
case HtmlTemplateType.RecurringPaymentFailed:
case HtmlTemplateType.NewOrder:
case HtmlTemplateType.VATInvoice:
case HtmlTemplateType.Custom:
tags.AddRange(new Order().GetReplaceableTags(context));
tags.AddRange(new LineItem().GetReplaceableTags(context));
break;
case HtmlTemplateType.OrderUpdated:
// Not used !!
break;
case HtmlTemplateType.OrderShipment:
tags.AddRange(new Order().GetReplaceableTags(context));
tags.AddRange(new OrderPackage().GetReplaceableTags(context));
break;
case HtmlTemplateType.ForgotPassword:
tags.AddRange(new CustomerAccount().GetReplaceableTags(context));
tags.AddRange(new Replaceable("[[NewPassword]]", string.Empty).GetReplaceableTags(context));
break;
case HtmlTemplateType.EmailFriend:
// Not used !!
break;
case HtmlTemplateType.ContactFormToAdmin:
// Not used !!
break;
case HtmlTemplateType.DropShippingNotice:
tags.AddRange(new Order().GetReplaceableTags(context));
tags.AddRange(new VendorManufacturer().GetReplaceableTags(context));
tags.AddRange(new LineItem().GetReplaceableTags(context));
break;
case HtmlTemplateType.ReturnForm:
// Not used !!
break;
case HtmlTemplateType.AffiliateRegistration:
case HtmlTemplateType.AffiliateReview:
tags.AddRange(new Affiliate().GetReplaceableTags(context));
break;
case HtmlTemplateType.AffiliateApprovement:
tags.AddRange(new Affiliate().GetReplaceableTags(context));
break;
case HtmlTemplateType.NewRoleAssignment:
tags.AddRange(new CustomerAccount().GetReplaceableTags(context));
tags.AddRange(new Replaceable("[[User.NewRoles]]", string.Empty).GetReplaceableTags(context));
break;
case HtmlTemplateType.GiftCardNotification:
tags.AddRange(new LineItem().GetReplaceableTags(context));
tags.AddRange(new GiftCard().GetReplaceableTags(context));
break;
case HtmlTemplateType.ContactAbandonedCartUsers:
tags.AddRange(new Replaceable("[[CustomMessage]]", string.Empty).GetReplaceableTags(context));
break;
default:
break;
}
return tags;
}
public bool HasRepeatingSection()
{
switch (TemplateType)
{
case HtmlTemplateType.Custom:
case HtmlTemplateType.NewOrder:
case HtmlTemplateType.NewOrderForAdmin:
case HtmlTemplateType.VATInvoice:
case HtmlTemplateType.OrderUpdated:
case HtmlTemplateType.OrderShipment:
case HtmlTemplateType.DropShippingNotice:
case HtmlTemplateType.AbandonedCart:
case HtmlTemplateType.RecurringPaymentSuccess:
case HtmlTemplateType.RecurringPaymentFailed:
return true;
default:
break;
}
return false;
}
public HtmlTemplate ReplaceTagsInTemplateForOrder(HccRequestContext context, Order order)
{
if (TemplateType != HtmlTemplateType.OrderShipment)
{
return ReplaceTagsInTemplate(context, order, order.ItemsAsReplaceable());
}
return ReplaceTagsInTemplate(context, order, order.PackagesAsReplaceable());
}
}
}
| |
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using System.Diagnostics;
using System.Globalization;
using System.Collections;
using System.IO;
using System.Linq;
using System.Collections.Generic;
namespace Microsoft.VisualStudio.FSharp.ProjectSystem
{
/// <summary>
/// Implements the configuration dependent properties interface
/// </summary>
[CLSCompliant(false), ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class ProjectConfigProperties :
VSLangProj.ProjectConfigurationProperties
{
private ProjectConfig projectConfig;
internal ProjectConfigProperties(ProjectConfig projectConfig)
{
this.projectConfig = projectConfig;
}
public virtual string OutputPath
{
get
{
return this.projectConfig.GetConfigurationProperty(BuildPropertyPageTag.OutputPath.ToString(), true);
}
set
{
this.projectConfig.SetConfigurationProperty(BuildPropertyPageTag.OutputPath.ToString(), value);
}
}
public string __id
{
get { return UIThread.DoOnUIThread(() => projectConfig.ConfigName); }
}
public bool AllowUnsafeBlocks
{
get { return false; }
set { throw new NotImplementedException(); }
}
public uint BaseAddress
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public bool CheckForOverflowUnderflow
{
get { return false; }
set { throw new NotImplementedException(); }
}
public bool RemoveIntegerChecks
{
get { return false; }
set { throw new NotImplementedException(); }
}
public bool IncrementalBuild
{
get { return false; }
set { throw new NotImplementedException(); }
}
public bool StartWithIE
{
get { return false; }
set { throw new NotImplementedException(); }
}
public string ConfigurationOverrideFile
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public string IntermediatePath
{
get { return UIThread.DoOnUIThread(() => projectConfig.GetConfigurationProperty("IntermediatePath", false)); }
set { UIThread.DoOnUIThread(() => { projectConfig.SetConfigurationProperty("IntermediatePath", value); }); }
}
public bool DebugSymbols
{
get { return UIThread.DoOnUIThread(() => projectConfig.DebugSymbols); }
set { projectConfig.DebugSymbols = value; }
}
public string DefineConstants
{
get { return UIThread.DoOnUIThread(() => projectConfig.DefineConstants); }
set { UIThread.DoOnUIThread(() => { projectConfig.DefineConstants = value; }); }
}
private bool IsDefined(string constant)
{
var constants = projectConfig.DefineConstants;
var array = constants.Split(';');
return array.Contains(constant);
}
private void SetDefine(string constant, bool value)
{
var constants = projectConfig.DefineConstants;
var array = constants.Split(';');
if (value && !array.Contains(constant))
{
var l = new List<string>(array);
l.Add(constant);
projectConfig.DefineConstants = String.Join(";", l);
}
else if (!value && array.Contains(constant))
{
projectConfig.DefineConstants = String.Join(";", array.All(s => s != constant));
}
}
public bool DefineDebug
{
get { return UIThread.DoOnUIThread(() => this.IsDefined("DEBUG")); }
set { UIThread.DoOnUIThread(() => { this.SetDefine("DEBUG", value); }); }
}
public bool DefineTrace
{
get { return UIThread.DoOnUIThread(() => this.IsDefined("TRACE")); }
set { UIThread.DoOnUIThread(() => { this.SetDefine("TRACE", value); }); }
}
public bool EnableASPDebugging
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public bool EnableASPXDebugging
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public string StartPage
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public VSLangProj.prjStartAction StartAction
{
get
{
switch(UIThread.DoOnUIThread(() => projectConfig.StartAction))
{
case 1: return VSLangProj.prjStartAction.prjStartActionProgram;
case 2: return VSLangProj.prjStartAction.prjStartActionURL;
default: return VSLangProj.prjStartAction.prjStartActionProject;
}
}
set
{
int result;
switch(value)
{
case VSLangProj.prjStartAction.prjStartActionProject:
result = 0;
break;
case VSLangProj.prjStartAction.prjStartActionURL:
result = 2;
break;
case VSLangProj.prjStartAction.prjStartActionProgram:
result = 1;
break;
default:
result = 0;
break;
}
UIThread.DoOnUIThread(() => { projectConfig.StartAction = result; });
}
}
public VSLangProj.prjWarningLevel WarningLevel
{
get
{
var level = UIThread.DoOnUIThread(() => projectConfig.WarningLevel);
switch(level)
{
case 0: return VSLangProj.prjWarningLevel.prjWarningLevel0;
case 1: return VSLangProj.prjWarningLevel.prjWarningLevel1;
case 2: return VSLangProj.prjWarningLevel.prjWarningLevel2;
case 3: return VSLangProj.prjWarningLevel.prjWarningLevel3;
default: return VSLangProj.prjWarningLevel.prjWarningLevel4;
}
}
set
{
UIThread.DoOnUIThread(() => projectConfig.WarningLevel = (int)value);
}
}
public uint FileAlignment
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public bool RegisterForComInterop
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public string ExtenderCATID
{
get
{
Guid catid = projectConfig.ProjectMgr.GetCATIDForType(this.GetType());
if (Guid.Empty.CompareTo(catid) == 0)
{
return null;
}
return catid.ToString("B");
}
}
public object ExtenderNames
{
get
{
EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)projectConfig.ProjectMgr.GetService(typeof(EnvDTE.ObjectExtenders));
if (extenderService == null)
{
throw new InvalidOperationException();
}
return extenderService.GetExtenderNames(this.ExtenderCATID, projectConfig);
}
}
public object get_Extender(string extenderName)
{
EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)projectConfig.ProjectMgr.GetService(typeof(EnvDTE.ObjectExtenders));
if (extenderService == null)
{
throw new InvalidOperationException();
}
return extenderService.GetExtender(this.ExtenderCATID, extenderName, projectConfig);
}
public string DocumentationFile
{
get { return UIThread.DoOnUIThread(() => projectConfig.DocumentationFile); }
set { UIThread.DoOnUIThread(() => { projectConfig.DocumentationFile = value; }); }
}
public string StartProgram
{
get { return UIThread.DoOnUIThread(() => projectConfig.StartProgram); }
set { UIThread.DoOnUIThread(() => { projectConfig.StartProgram = value; }); }
}
public string StartWorkingDirectory
{
get { return UIThread.DoOnUIThread(() => projectConfig.StartWorkingDirectory); }
set { UIThread.DoOnUIThread(() => { projectConfig.StartWorkingDirectory = value; }); }
}
public string StartURL
{
get { return UIThread.DoOnUIThread(() => projectConfig.StartURL); }
set { UIThread.DoOnUIThread(() => { projectConfig.StartURL = value; }); }
}
public string StartArguments
{
get { return UIThread.DoOnUIThread(() => projectConfig.StartArguments); }
set { UIThread.DoOnUIThread(() => { projectConfig.StartArguments = value; }); }
}
public bool Optimize
{
get { return UIThread.DoOnUIThread(() => projectConfig.Optimize); }
set { UIThread.DoOnUIThread(() => { projectConfig.Optimize = value; }); }
}
public bool EnableUnmanagedDebugging
{
get { return UIThread.DoOnUIThread(() => projectConfig.EnableUnmanagedDebugging); }
set { UIThread.DoOnUIThread(() => { projectConfig.EnableUnmanagedDebugging = value; }); }
}
public bool TreatWarningsAsErrors
{
get { return UIThread.DoOnUIThread(() => projectConfig.TreatWarningsAsErrors); }
set { UIThread.DoOnUIThread(() => { projectConfig.TreatWarningsAsErrors = value; }); }
}
public bool EnableSQLServerDebugging
{
get { return UIThread.DoOnUIThread(() => projectConfig.EnableSQLServerDebugging); }
set { UIThread.DoOnUIThread(() => { projectConfig.EnableSQLServerDebugging = value; }); }
}
public bool RemoteDebugEnabled
{
get { return UIThread.DoOnUIThread(() => projectConfig.RemoteDebugEnabled); }
set { UIThread.DoOnUIThread(() => { projectConfig.RemoteDebugEnabled = value; }); }
}
public string RemoteDebugMachine
{
get { return UIThread.DoOnUIThread(() => projectConfig.RemoteDebugMachine); }
set { UIThread.DoOnUIThread(() => { projectConfig.RemoteDebugMachine = value; }); }
}
}
}
| |
using Bridge.Html5;
using Bridge.Test.NUnit;
using System;
using System.Text;
namespace Bridge.ClientTest.Batch4
{
[TestFixture(TestNameFormat = "DelegateTests - {0}")]
[Reflectable]
public class DelegateTests
{
public delegate void D1();
public delegate void D2();
// #1631
//[BindThisToFirstParameter]
//public delegate int D3(int a, int b);
private class C
{
public void F1()
{
}
public void F2()
{
}
}
private int testField = 12;
private int AddForCreateWorks(int x)
{
return x + this.testField;
}
[Test]
public void CreateWorks()
{
// Not C# API
//var d = (Func<int, int>)Delegate.CreateDelegate(this, new Function("x", "{ return x + this.testField; }"));
// The call above replace with the call below
var d = (Func<int, int>)Delegate.CreateDelegate(this.GetType(), this, this.GetType().GetMethod("AddForCreateWorks"));
Assert.AreEqual(25, d(13));
}
[Test]
public void RemoveDoesNotAffectOriginal_SPI_1563()
{
// #1563
C c = new C();
Action a = c.F1;
Action a2 = a + c.F2;
Action a3 = a2 - a;
// Test restructure to keep assertion count correct (prevent uncaught test exception)
int l = 0;
TestHelper.Safe(() => l = a.GetInvocationList().Length);
Assert.AreEqual(1, l);
int l2 = 0;
TestHelper.Safe(() => l2 = a2.GetInvocationList().Length);
Assert.AreEqual(2, l2);
int l3 = 0;
TestHelper.Safe(() => l3 = a3.GetInvocationList().Length);
Assert.AreEqual(1, l3);
}
private void A()
{
}
[Test]
public void RemoveWorksWithMethodGroupConversion_SPI_1563()
{
// #1563
Action a = () =>
{
};
Action a2 = a + A;
Action a3 = a2 - A;
Assert.False(a.Equals(a2));
Assert.True(a.Equals(a3));
}
[Test]
public void CloneWorks_SPI_1563()
{
var sb = new StringBuilder();
Action d1 = () =>
{
sb.Append("1");
};
// #1563 Clone not implemented
// The original call
// Action d2 = (Action)d1.Clone();
// The temp call
Action d2 = (Action)d1;
Assert.False(ReferenceEquals(d1, d2), "Should not be same");
d2();
Assert.AreEqual("1", sb.ToString());
}
[Template("{d}.apply({t}, {args})")]
public object Call(object t, Delegate d, params object[] args)
{
return null;
}
// Not C# API
//[Test]
//public void ThisFixWorks()
//{
// var target = new
// {
// someField = 13
// };
// var d = Delegate.ThisFix((Func<dynamic, int, int, int>)((t, a, b) => t.someField + this.testField + a + b));
// Assert.AreEqual(Call(target, d, 3, 5), 33);
//}
[Test]
public void CloningDelegateToTheSameTypeCreatesANewClone_SPI_1563()
{
// #1563
int x = 0;
D1 d1 = () => x++;
D1 d2 = new D1(d1);
d1();
d2();
Assert.False(d1 == d2);
Assert.AreEqual(2, x);
}
// #SPI
//[Test]
//public void DelegateWithBindThisToFirstParameterWorksWhenInvokedFromScript_SPI_1620_1631()
//{
// D3 d = (a, b) => a + b;
// // #1620
// Function f = (Function)d;
// Assert.AreEqual(f.Call(10, 20), 30);
//}
// #SPI
//[Test]
//public void DelegateWithBindThisToFirstParameterWorksWhenInvokedFromCode_SPI_1631()
//{
// D3 d = (a, b) => a + b;
// Assert.AreEqual(d(10, 20), 30);
//}
[Test]
public void EqualityAndInequalityOperatorsAndEqualsMethod_SPI_1563()
{
#pragma warning disable 1718
C c1 = new C(), c2 = new C();
Action n = null;
Action f11 = c1.F1, f11_2 = c1.F1, f12 = c1.F2, f21 = c2.F1;
Assert.False(n == f11, "n == f11");
Assert.True(n != f11, "n != f11");
Assert.False(f11 == n, "f11 == n");
Assert.False(f11.Equals(n), "f11.Equals(n)");
Assert.True(f11 != n, "f11 != n");
Assert.True(n == n, "n == n");
Assert.False(n != n, "n != n");
Assert.True(f11 == f11, "f11 == f11");
Assert.True(f11.Equals(f11), "f11.Equals(f11)");
Assert.False(f11 != f11, "f11 != f11");
Assert.True(f11 == f11_2, "f11 == f11_2");
Assert.True(f11.Equals(f11_2), "f11.Equals(f11_2)");
Assert.False(f11 != f11_2, "f11 != f11_2");
Assert.False(f11 == f12, "f11 == f12");
Assert.False(f11.Equals(f12), "f11.Equals(f12)");
Assert.True(f11 != f12, "f11 != f12");
Assert.False(f11 == f21, "f11 == f21");
Assert.False(f11.Equals(f21), "f11.Equals(f21)");
Assert.True(f11 != f21, "f11 != f21");
Action m1 = f11 + f21, m2 = f11 + f21, m3 = f21 + f11;
// #1563
Assert.True(m1 == m2, "m1 == m2");
Assert.True(m1.Equals(m2), "m1.Equals(m2)");
Assert.False(m1 != m2, "m1 != m2");
Assert.False(m1 == m3, "m1 == m3");
Assert.False(m1.Equals(m3), "m1.Equals(m3)");
Assert.True(m1 != m3, "m1 != m3");
Assert.False(m1 == f11, "m1 == f11");
Assert.False(m1.Equals(f11), "m1.Equals(f11)");
Assert.True(m1 != f11, "m1 != f11");
#pragma warning restore 1718
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Transactions
{
public sealed partial class CommittableTransaction : System.Transactions.Transaction, System.IAsyncResult, System.IDisposable, System.Runtime.Serialization.ISerializable
{
public CommittableTransaction() { }
public CommittableTransaction(System.TimeSpan timeout) { }
public CommittableTransaction(System.Transactions.TransactionOptions options) { }
object System.IAsyncResult.AsyncState { get { throw null; } }
System.Threading.WaitHandle System.IAsyncResult.AsyncWaitHandle { get { throw null; } }
bool System.IAsyncResult.CompletedSynchronously { get { throw null; } }
bool System.IAsyncResult.IsCompleted { get { throw null; } }
public System.IAsyncResult BeginCommit(System.AsyncCallback asyncCallback, object asyncState) { throw null; }
public void Commit() { }
public void EndCommit(System.IAsyncResult asyncResult) { }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
}
public enum DependentCloneOption
{
BlockCommitUntilComplete = 0,
RollbackIfNotComplete = 1,
}
public sealed partial class DependentTransaction : System.Transactions.Transaction, System.Runtime.Serialization.ISerializable
{
internal DependentTransaction() { }
public void Complete() { }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
}
public partial class Enlistment
{
internal Enlistment() { }
public void Done() { }
}
[System.FlagsAttribute]
public enum EnlistmentOptions
{
EnlistDuringPrepareRequired = 1,
None = 0,
}
public enum EnterpriseServicesInteropOption
{
Automatic = 1,
Full = 2,
None = 0,
}
public delegate System.Transactions.Transaction HostCurrentTransactionCallback();
public partial interface IDtcTransaction
{
void Abort(System.IntPtr reason, int retaining, int async);
void Commit(int retaining, int commitType, int reserved);
void GetTransactionInfo(System.IntPtr transactionInformation);
}
public partial interface IEnlistmentNotification
{
void Commit(System.Transactions.Enlistment enlistment);
void InDoubt(System.Transactions.Enlistment enlistment);
void Prepare(System.Transactions.PreparingEnlistment preparingEnlistment);
void Rollback(System.Transactions.Enlistment enlistment);
}
public partial interface IPromotableSinglePhaseNotification : System.Transactions.ITransactionPromoter
{
void Initialize();
void Rollback(System.Transactions.SinglePhaseEnlistment singlePhaseEnlistment);
void SinglePhaseCommit(System.Transactions.SinglePhaseEnlistment singlePhaseEnlistment);
}
public partial interface ISimpleTransactionSuperior : System.Transactions.ITransactionPromoter
{
void Rollback();
}
public partial interface ISinglePhaseNotification : System.Transactions.IEnlistmentNotification
{
void SinglePhaseCommit(System.Transactions.SinglePhaseEnlistment singlePhaseEnlistment);
}
public enum IsolationLevel
{
Chaos = 5,
ReadCommitted = 2,
ReadUncommitted = 3,
RepeatableRead = 1,
Serializable = 0,
Snapshot = 4,
Unspecified = 6,
}
public partial interface ITransactionPromoter
{
byte[] Promote();
}
public partial class PreparingEnlistment : System.Transactions.Enlistment
{
internal PreparingEnlistment() { }
public void ForceRollback() { }
public void ForceRollback(System.Exception e) { }
public void Prepared() { }
public byte[] RecoveryInformation() { throw null; }
}
public partial class SinglePhaseEnlistment : System.Transactions.Enlistment
{
internal SinglePhaseEnlistment() { }
public void Aborted() { }
public void Aborted(System.Exception e) { }
public void Committed() { }
public void InDoubt() { }
public void InDoubt(System.Exception e) { }
}
public sealed partial class SubordinateTransaction : System.Transactions.Transaction
{
public SubordinateTransaction(System.Transactions.IsolationLevel isoLevel, System.Transactions.ISimpleTransactionSuperior superior) { }
}
public partial class Transaction : System.IDisposable, System.Runtime.Serialization.ISerializable
{
internal Transaction() { }
public static System.Transactions.Transaction Current { get { throw null; } set { } }
public System.Transactions.IsolationLevel IsolationLevel { get { throw null; } }
public System.Guid PromoterType { get { throw null; } }
public System.Transactions.TransactionInformation TransactionInformation { get { throw null; } }
public event System.Transactions.TransactionCompletedEventHandler TransactionCompleted { add { } remove { } }
protected System.IAsyncResult BeginCommitInternal(System.AsyncCallback callback) { throw null; }
public System.Transactions.Transaction Clone() { throw null; }
public System.Transactions.DependentTransaction DependentClone(System.Transactions.DependentCloneOption cloneOption) { throw null; }
public void Dispose() { }
protected void EndCommitInternal(System.IAsyncResult ar) { }
public System.Transactions.Enlistment EnlistDurable(System.Guid resourceManagerIdentifier, System.Transactions.IEnlistmentNotification enlistmentNotification, System.Transactions.EnlistmentOptions enlistmentOptions) { throw null; }
public System.Transactions.Enlistment EnlistDurable(System.Guid resourceManagerIdentifier, System.Transactions.ISinglePhaseNotification singlePhaseNotification, System.Transactions.EnlistmentOptions enlistmentOptions) { throw null; }
public bool EnlistPromotableSinglePhase(System.Transactions.IPromotableSinglePhaseNotification promotableSinglePhaseNotification) { throw null; }
public bool EnlistPromotableSinglePhase(System.Transactions.IPromotableSinglePhaseNotification promotableSinglePhaseNotification, System.Guid promoterType) { throw null; }
public System.Transactions.Enlistment EnlistVolatile(System.Transactions.IEnlistmentNotification enlistmentNotification, System.Transactions.EnlistmentOptions enlistmentOptions) { throw null; }
public System.Transactions.Enlistment EnlistVolatile(System.Transactions.ISinglePhaseNotification singlePhaseNotification, System.Transactions.EnlistmentOptions enlistmentOptions) { throw null; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public byte[] GetPromotedToken() { throw null; }
public static bool operator ==(System.Transactions.Transaction x, System.Transactions.Transaction y) { throw null; }
public static bool operator !=(System.Transactions.Transaction x, System.Transactions.Transaction y) { throw null; }
public System.Transactions.Enlistment PromoteAndEnlistDurable(System.Guid manager, System.Transactions.IPromotableSinglePhaseNotification promotableNotification, System.Transactions.ISinglePhaseNotification notification, System.Transactions.EnlistmentOptions options) { throw null; }
public void Rollback() { }
public void Rollback(System.Exception e) { }
public void SetDistributedTransactionIdentifier(System.Transactions.IPromotableSinglePhaseNotification promotableNotification, System.Guid distributedTransactionIdentifier) { }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
}
public partial class TransactionAbortedException : System.Transactions.TransactionException
{
public TransactionAbortedException() { }
protected TransactionAbortedException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public TransactionAbortedException(string message) { }
public TransactionAbortedException(string message, System.Exception innerException) { }
}
public delegate void TransactionCompletedEventHandler(object sender, System.Transactions.TransactionEventArgs e);
public partial class TransactionEventArgs : System.EventArgs
{
public TransactionEventArgs() { }
public System.Transactions.Transaction Transaction { get { throw null; } }
}
public partial class TransactionException : System.SystemException
{
public TransactionException() { }
protected TransactionException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public TransactionException(string message) { }
public TransactionException(string message, System.Exception innerException) { }
}
public partial class TransactionInDoubtException : System.Transactions.TransactionException
{
public TransactionInDoubtException() { }
protected TransactionInDoubtException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public TransactionInDoubtException(string message) { }
public TransactionInDoubtException(string message, System.Exception innerException) { }
}
public partial class TransactionInformation
{
internal TransactionInformation() { }
public System.DateTime CreationTime { get { throw null; } }
public System.Guid DistributedIdentifier { get { throw null; } }
public string LocalIdentifier { get { throw null; } }
public System.Transactions.TransactionStatus Status { get { throw null; } }
}
public static partial class TransactionInterop
{
public static readonly System.Guid PromoterTypeDtc;
public static System.Transactions.IDtcTransaction GetDtcTransaction(System.Transactions.Transaction transaction) { throw null; }
public static byte[] GetExportCookie(System.Transactions.Transaction transaction, byte[] whereabouts) { throw null; }
public static System.Transactions.Transaction GetTransactionFromDtcTransaction(System.Transactions.IDtcTransaction transactionNative) { throw null; }
public static System.Transactions.Transaction GetTransactionFromExportCookie(byte[] cookie) { throw null; }
public static System.Transactions.Transaction GetTransactionFromTransmitterPropagationToken(byte[] propagationToken) { throw null; }
public static byte[] GetTransmitterPropagationToken(System.Transactions.Transaction transaction) { throw null; }
public static byte[] GetWhereabouts() { throw null; }
}
public static partial class TransactionManager
{
public static System.TimeSpan DefaultTimeout { get { throw null; } }
public static System.Transactions.HostCurrentTransactionCallback HostCurrentCallback { get { throw null; } set { } }
public static System.TimeSpan MaximumTimeout { get { throw null; } }
public static event System.Transactions.TransactionStartedEventHandler DistributedTransactionStarted { add { } remove { } }
public static void RecoveryComplete(System.Guid resourceManagerIdentifier) { }
public static System.Transactions.Enlistment Reenlist(System.Guid resourceManagerIdentifier, byte[] recoveryInformation, System.Transactions.IEnlistmentNotification enlistmentNotification) { throw null; }
}
public partial class TransactionManagerCommunicationException : System.Transactions.TransactionException
{
public TransactionManagerCommunicationException() { }
protected TransactionManagerCommunicationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public TransactionManagerCommunicationException(string message) { }
public TransactionManagerCommunicationException(string message, System.Exception innerException) { }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct TransactionOptions
{
private int _dummy;
public System.Transactions.IsolationLevel IsolationLevel { get { throw null; } set { } }
public System.TimeSpan Timeout { get { throw null; } set { } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Transactions.TransactionOptions x, System.Transactions.TransactionOptions y) { throw null; }
public static bool operator !=(System.Transactions.TransactionOptions x, System.Transactions.TransactionOptions y) { throw null; }
}
public partial class TransactionPromotionException : System.Transactions.TransactionException
{
public TransactionPromotionException() { }
protected TransactionPromotionException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public TransactionPromotionException(string message) { }
public TransactionPromotionException(string message, System.Exception innerException) { }
}
public sealed partial class TransactionScope : System.IDisposable
{
public TransactionScope() { }
public TransactionScope(System.Transactions.Transaction transactionToUse) { }
public TransactionScope(System.Transactions.Transaction transactionToUse, System.TimeSpan scopeTimeout) { }
public TransactionScope(System.Transactions.Transaction transactionToUse, System.TimeSpan scopeTimeout, System.Transactions.EnterpriseServicesInteropOption interopOption) { }
public TransactionScope(System.Transactions.Transaction transactionToUse, System.TimeSpan scopeTimeout, System.Transactions.TransactionScopeAsyncFlowOption asyncFlowOption) { }
public TransactionScope(System.Transactions.Transaction transactionToUse, System.Transactions.TransactionScopeAsyncFlowOption asyncFlowOption) { }
public TransactionScope(System.Transactions.TransactionScopeAsyncFlowOption asyncFlowOption) { }
public TransactionScope(System.Transactions.TransactionScopeOption scopeOption) { }
public TransactionScope(System.Transactions.TransactionScopeOption scopeOption, System.TimeSpan scopeTimeout) { }
public TransactionScope(System.Transactions.TransactionScopeOption scopeOption, System.TimeSpan scopeTimeout, System.Transactions.TransactionScopeAsyncFlowOption asyncFlow) { }
public TransactionScope(System.Transactions.TransactionScopeOption scopeOption, System.Transactions.TransactionOptions transactionOptions) { }
public TransactionScope(System.Transactions.TransactionScopeOption scopeOption, System.Transactions.TransactionOptions transactionOptions, System.Transactions.EnterpriseServicesInteropOption interopOption) { }
public TransactionScope(System.Transactions.TransactionScopeOption scopeOption, System.Transactions.TransactionOptions transactionOptions, System.Transactions.TransactionScopeAsyncFlowOption asyncFlowOption) { }
public TransactionScope(System.Transactions.TransactionScopeOption option, System.Transactions.TransactionScopeAsyncFlowOption asyncFlow) { }
public void Complete() { }
public void Dispose() { }
}
public enum TransactionScopeAsyncFlowOption
{
Enabled = 1,
Suppress = 0,
}
public enum TransactionScopeOption
{
Required = 0,
RequiresNew = 1,
Suppress = 2,
}
public delegate void TransactionStartedEventHandler(object sender, System.Transactions.TransactionEventArgs e);
public enum TransactionStatus
{
Aborted = 2,
Active = 0,
Committed = 1,
InDoubt = 3,
}
}
| |
// Copyright 2011 Carlos Martins
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Threading;
#pragma warning disable 0420
namespace SlimThreading {
public class StParker {
private const int WAIT_IN_PROGRESS_BIT = 31;
private const int WAIT_IN_PROGRESS = (1 << WAIT_IN_PROGRESS_BIT);
private const int LOCK_COUNT_MASK = (1 << 16) - 1;
//
// The link field used when the parker is registered
// with an alerter.
//
internal volatile StParker pnext;
internal volatile int state;
internal IParkSpot parkSpot;
internal int waitStatus;
public StParker(int releasers, IParkSpot parkSpot) : this(releasers) {
this.parkSpot = parkSpot;
}
public StParker(IParkSpot parkSpot) : this(1, parkSpot) { }
public StParker(int releasers) {
state = releasers | WAIT_IN_PROGRESS;
}
public StParker() : this(1) { }
public static int Sleep(StCancelArgs cargs) {
int ws = new StParker().Park(0, cargs);
StCancelArgs.ThrowIfException(ws);
return ws;
}
public bool IsLocked {
get { return (state & LOCK_COUNT_MASK) == 0; }
}
public void Reset(int releasers) {
pnext = null;
state = releasers | WAIT_IN_PROGRESS;
}
public void Reset() {
Reset(1);
}
public bool TryLock() {
do {
//
// If the parker is already locked, return false.
//
int s;
if (((s = state) & LOCK_COUNT_MASK) == 0) {
return false;
}
//
// Try to decrement the count down lock.
//
if (Interlocked.CompareExchange(ref state, s - 1, s) == s) {
//
// Return true if the count down lock reached zero.
//
return (s & LOCK_COUNT_MASK) == 1;
}
} while (true);
}
public bool TryCancel() {
do {
//
// Fail if the parker is already locked.
//
int s;
if (((s = state) & LOCK_COUNT_MASK) <= 0) {
return false;
}
//
// Try to set the parker's count down lock to zero, preserving
// the wait-in-progress bit.
//
if (Interlocked.CompareExchange(ref state, (s & WAIT_IN_PROGRESS), s) == s) {
return true;
}
} while (true);
}
//
// This method should be called only by the owner thread.
//
public void SelfCancel() {
state = WAIT_IN_PROGRESS;
}
//
// Unparks the parker's owner thread if the wait is still in progress.
//
public bool UnparkInProgress(int ws) {
waitStatus = ws;
return (state & WAIT_IN_PROGRESS) != 0 &&
(Interlocked.Exchange(ref state, 0) & WAIT_IN_PROGRESS) != 0;
}
public void Unpark(int status) {
if (UnparkInProgress(status)) {
return;
}
if (parkSpot != null) {
parkSpot.Set();
} else {
//
// This is a callback parker.
// If a timer was used and it didn't fire, unlink the timer
// (whose parker is already locked) from the timer list.
// Finally, execute the associated callback.
//
var cbpk = (CbParker)this;
if (cbpk.toTimer != null && status != StParkStatus.Timeout) {
TimerList.UnlinkRawTimer(cbpk.toTimer);
cbpk.toTimer = null;
}
cbpk.callback(status);
}
}
//
// This method should be called only by the owner thread.
//
public void UnparkSelf(int status) {
waitStatus = status;
state = 0;
}
public int Park(int spinCount, StCancelArgs cargs) {
do {
if (state == 0) {
return waitStatus;
}
if (cargs.Alerter != null && cargs.Alerter.IsSet && TryCancel()) {
return StParkStatus.Alerted;
}
if (spinCount-- <= 0) {
break;
}
Platform.SpinWait(1);
} while (true);
if (parkSpot == null) {
parkSpot = ThreadExtensions.ForCurrentThread.ParkSpotFactory.Create();
}
//
// Try to clear the wait-in-progress bit. If the bit was already
// cleared, the thread is unparked.
//
if (!TestAndClearInProgress()) {
return waitStatus;
}
//
// If an alerter was specified, we register the parker with
// the alerter before blocking the thread on the park spot.
//
bool unregister = false;
if (cargs.Alerter != null) {
if (!(unregister = cargs.Alerter.RegisterParker(this))) {
//
// The alerter is already set. So, we try to cancel the parker.
//
if (TryCancel()) {
return StParkStatus.Alerted;
}
//
// We can't cancel the parker because someone else acquired
// the count down lock. We must wait unconditionally until
// the park spot is set.
//
cargs = StCancelArgs.None;
}
}
parkSpot.Wait(this, cargs);
if (unregister) {
cargs.Alerter.DeregisterParker(this);
}
return waitStatus;
}
public int Park(StCancelArgs cargs) {
return Park(0, cargs);
}
public int Park() {
return Park(0, StCancelArgs.None);
}
internal bool TestAndClearInProgress() {
do {
int s;
if ((s = state) >= 0) {
return false;
}
if (Interlocked.CompareExchange(ref state, (s & ~WAIT_IN_PROGRESS), s) == s) {
return true;
}
} while (true);
}
//
// CASes on the *pnext* field.
//
internal bool CasNext(StParker n, StParker nn) {
return (pnext == n &&
Interlocked.CompareExchange(ref pnext, nn, n) == n);
}
}
//
// The delegate type used with the callback parker.
//
internal delegate void ParkerCallback(int waitStatus);
//
// This class implements the callback parker.
//
internal class CbParker : StParker {
internal readonly ParkerCallback callback;
internal RawTimer toTimer;
internal CbParker(ParkerCallback pkcb) : base(1) {
callback = pkcb;
}
//
// Enables the unpark callback.
//
internal int EnableCallback(int timeout, RawTimer tmr) {
//
// If the unpark method was already called, return immediately.
//
if (state >= 0) {
return waitStatus;
}
toTimer = null;
if (timeout == 0) {
//
// If a zero timeout is specified with a timer, we record the
// current time as *fireTime* in order to support periodic timers.
//
if (tmr != null) {
tmr.fireTime = Environment.TickCount;
}
if (TryCancel()) {
return StParkStatus.Timeout;
}
} else if (timeout != Timeout.Infinite) {
toTimer = tmr;
if (timeout < 0) {
TimerList.SetPeriodicRawTimer(tmr, timeout & ~(1 << 31));
} else {
TimerList.SetRawTimer(tmr, timeout);
}
}
//
// Clear the wait-in-progress bit. If this bit is already cleared,
// the current thread was already unparked.
//
if (!TestAndClearInProgress()) {
if (toTimer != null && waitStatus != StParkStatus.Timeout) {
TimerList.UnlinkRawTimer(tmr);
}
return waitStatus;
}
return StParkStatus.Pending;
}
}
//
// This class implements a parker that is used as sentinel.
//
public class SentinelParker : StParker {
public SentinelParker() : base(0) { }
}
}
| |
#if SILVERLIGHT
using Microsoft.VisualStudio.TestTools.UnitTesting;
#else
using NUnit.Framework;
using System.Text.RegularExpressions;
#endif
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using DevExpress.Mvvm.DataAnnotations;
using DevExpress.Mvvm.Native;
using System.Security;
using System.Globalization;
using System.Collections.Generic;
using System.Collections;
namespace DevExpress.Mvvm.Tests {
[TestFixture]
public class MetadataBuilderTests {
#region validation
[MetadataType(typeof(ValidationEntityMetadata))]
public class ValidationEntity {
public static string StringProperty1_CustomErrorText_Required;
public static string StringProperty1_CustomErrorText_MinLength;
public static string StringProperty1_CustomErrorText_MaxLength;
public static string StringProperty3_CustomErrorText;
public static string PhoneProperty_CustomErrorText;
public static string CreditCardProperty_CustomErrorText;
public static string EmailAddressProperty_CustomErrorText;
public static string UrlProperty_CustomErrorText;
public static string DoubleRange_CustomErrorText;
public static string StringRegExp_CustomErrorText;
public static string CustomString_CustomErrorText;
public string StringProperty0 { get; set; }
public string StringProperty1 { get; set; }
public string StringProperty1_CustomError { get; set; }
public string StringProperty2 { get; set; }
public string StringProperty3 { get; set; }
public string StringProperty3_CustomError { get; set; }
public string PhoneProperty { get; set; }
public string PhoneProperty_CustomError { get; set; }
public string CreditCardProperty { get; set; }
public string CreditCardProperty_CustomError { get; set; }
public string EmailAddressProperty { get; set; }
public string EmailAddressProperty_CustomError { get; set; }
public string UrlProperty { get; set; }
public string UrlProperty_CustomError { get; set; }
public double DoubleRange { get; set; }
public double? DoubleRange_Nullable { get; set; }
public double DoubleRange_CustomError { get; set; }
public int IntRange { get; set; }
public string StringRange { get; set; }
public string StringRegExp { get; set; }
public string StringRegExp_CustomError { get; set; }
public int IntRegExp { get; set; }
public string CustomString_CustomError { get; set; }
public string CustomString { get; set; }
public string TwoErrorsProperty { get; set; }
}
public class ValidationEntityMetadata : IMetadataProvider<ValidationEntity> {
void IMetadataProvider<ValidationEntity>.BuildMetadata(MetadataBuilder<ValidationEntity> builder) {
builder.Property(x => x.StringProperty1)
.Required()
.MinLength(2)
.MaxLength(5);
builder.Property(x => x.StringProperty1_CustomError)
.Required(() => ValidationEntity.StringProperty1_CustomErrorText_Required)
.MinLength(2, () => ValidationEntity.StringProperty1_CustomErrorText_MinLength)
.MaxLength(5, () => ValidationEntity.StringProperty1_CustomErrorText_MaxLength);
builder.Property(x => x.StringProperty2)
.Required()
.MinLength(2);
builder.Property(x => x.StringProperty3)
.Required(allowEmptyStrings: true);
builder.Property(x => x.StringProperty3_CustomError)
.Required(allowEmptyStrings: true, errorMessageAccessor: () => ValidationEntity.StringProperty3_CustomErrorText);
builder.Property(x => x.PhoneProperty)
.PhoneNumberDataType();
builder.Property(x => x.PhoneProperty_CustomError)
.PhoneNumberDataType(() => ValidationEntity.PhoneProperty_CustomErrorText);
builder.Property(x => x.CreditCardProperty)
.CreditCardDataType();
builder.Property(x => x.CreditCardProperty_CustomError)
.CreditCardDataType(() => ValidationEntity.CreditCardProperty_CustomErrorText);
builder.Property(x => x.EmailAddressProperty)
.EmailAddressDataType();
builder.Property(x => x.EmailAddressProperty_CustomError)
.EmailAddressDataType(() => ValidationEntity.EmailAddressProperty_CustomErrorText);
builder.Property(x => x.UrlProperty)
.UrlDataType();
builder.Property(x => x.UrlProperty_CustomError)
.UrlDataType(() => ValidationEntity.UrlProperty_CustomErrorText);
builder.Property(x => x.DoubleRange)
.InRange(9, 13);
builder.Property(x => x.DoubleRange_Nullable)
.InRange(9, 13);
builder.Property(x => x.DoubleRange_CustomError)
.InRange(9, 13, () => ValidationEntity.DoubleRange_CustomErrorText);
builder.Property(x => x.IntRange)
.InRange(9, 13);
builder.Property(x => x.StringRange)
.InRange("B", "D");
builder.Property(x => x.StringRegExp)
.MatchesRegularExpression(@"^[a-z]{1,2}$");
builder.Property(x => x.StringRegExp_CustomError)
.MatchesRegularExpression(@"^[a-z]{1,2}$", () => ValidationEntity.StringRegExp_CustomErrorText);
builder.Property(x => x.IntRegExp)
.MatchesRegularExpression(@"^[1-2]{1,2}$");
builder.Property(x => x.CustomString)
.MatchesRule(x => x.Length <= 2);
builder.Property(x => x.CustomString_CustomError)
.MatchesRule(x => x.Length <= 2, () => ValidationEntity.CustomString_CustomErrorText);
builder.Property(x => x.TwoErrorsProperty)
.MinLength(10)
.MaxLength(1);
}
}
[Test]
public void Validation() {
var entity = new ValidationEntity();
string required = "The StringProperty1 field is required.";
string minLength = "The field StringProperty1 must be a string or array type with a minimum length of '2'.";
string maxLength = "The field StringProperty1 must be a string or array type with a maximum length of '5'.";
var property1Validator = CreateValidator<ValidationEntity, string>(x => x.StringProperty1);
Assert.AreEqual(required, property1Validator.GetErrorText(null, entity));
Assert.AreEqual(minLength, property1Validator.GetErrorText("1", entity));
Assert.AreEqual(maxLength, property1Validator.GetErrorText("123456", entity));
Assert.AreEqual(string.Empty, property1Validator.GetErrorText("123", entity));
var property1Validator_CustomError = CreateValidator<ValidationEntity, string>(x => x.StringProperty1_CustomError);
ValidationEntity.StringProperty1_CustomErrorText_Required = "{0} property required";
Assert.AreEqual("StringProperty1_CustomError property required", property1Validator_CustomError.GetErrorText(null, entity));
ValidationEntity.StringProperty1_CustomErrorText_MinLength = "{0} min";
Assert.AreEqual("StringProperty1_CustomError min", property1Validator_CustomError.GetErrorText("1", entity));
ValidationEntity.StringProperty1_CustomErrorText_MaxLength= "{0} max";
Assert.AreEqual("StringProperty1_CustomError max", property1Validator_CustomError.GetErrorText("123456", entity));
var property2Validator = CreateValidator<ValidationEntity, string>(x => x.StringProperty2);
Assert.AreEqual(required.Replace("StringProperty1", "StringProperty2") + " " + minLength.Replace("StringProperty1", "StringProperty2"), property2Validator.GetErrorText(string.Empty, entity));
var property3Validator = CreateValidator<ValidationEntity, string>(x => x.StringProperty3);
Assert.AreEqual(string.Empty, property3Validator.GetErrorText(string.Empty, entity));
Assert.AreEqual(required.Replace("StringProperty1", "StringProperty3"), property3Validator.GetErrorText(null, entity));
var property3Validator_CustomError = CreateValidator<ValidationEntity, string>(x => x.StringProperty3_CustomError);
ValidationEntity.StringProperty3_CustomErrorText = "{0} property required and doesn't allow empty strings";
Assert.AreEqual("StringProperty3_CustomError property required and doesn't allow empty strings", property3Validator_CustomError.GetErrorText(null, entity));
var phoneValidator = CreateValidator<ValidationEntity, string>(x => x.PhoneProperty);
Assert.AreEqual("The PhoneProperty field is not a valid phone number.", phoneValidator.GetErrorText("abc", entity));
phoneValidator = CreateValidator<ValidationEntity, string>(x => x.PhoneProperty_CustomError);
ValidationEntity.PhoneProperty_CustomErrorText = "{0} phone";
Assert.AreEqual("PhoneProperty_CustomError phone", phoneValidator.GetErrorText("abc", entity));
var creditCardValidator = CreateValidator<ValidationEntity, string>(x => x.CreditCardProperty);
Assert.AreEqual("The CreditCardProperty field is not a valid credit card number.", creditCardValidator.GetErrorText("1234 5678 1234 5678", entity));
Assert.AreEqual(string.Empty, creditCardValidator.GetErrorText("4012888888881881", entity));
Assert.AreEqual(string.Empty, creditCardValidator.GetErrorText("4012 8888 8888 1881", entity));
creditCardValidator = CreateValidator<ValidationEntity, string>(x => x.CreditCardProperty_CustomError);
ValidationEntity.CreditCardProperty_CustomErrorText= "{0} card";
Assert.AreEqual("CreditCardProperty_CustomError card", creditCardValidator.GetErrorText("1234 5678 1234 5678", entity));
var emailAddressPropertyValidator = CreateValidator<ValidationEntity, string>(x => x.EmailAddressProperty);
Assert.AreEqual("The EmailAddressProperty field is not a valid e-mail address.", emailAddressPropertyValidator.GetErrorText("a@", entity));
Assert.AreEqual(string.Empty, emailAddressPropertyValidator.GetErrorText("[email protected]", entity));
emailAddressPropertyValidator = CreateValidator<ValidationEntity, string>(x => x.EmailAddressProperty_CustomError);
ValidationEntity.EmailAddressProperty_CustomErrorText = "{0} mail";
Assert.AreEqual("EmailAddressProperty_CustomError mail", emailAddressPropertyValidator.GetErrorText("a@", entity));
var urlPropertyValidator = CreateValidator<ValidationEntity, string>(x => x.UrlProperty);
Assert.AreEqual(string.Empty, urlPropertyValidator.GetErrorText("https://www.devexpress.com/", entity));
Assert.AreEqual("The UrlProperty field is not a valid fully-qualified http, https, or ftp URL.", urlPropertyValidator.GetErrorText("abc", entity));
urlPropertyValidator = CreateValidator<ValidationEntity, string>(x => x.UrlProperty_CustomError);
ValidationEntity.UrlProperty_CustomErrorText = "{0} url";
Assert.AreEqual("UrlProperty_CustomError url", urlPropertyValidator.GetErrorText("abc", entity));
var doubleRangeValidator = CreateValidator<ValidationEntity, double>(x => x.DoubleRange);
Assert.AreEqual(string.Empty, doubleRangeValidator.GetErrorText(10d, entity));
Assert.AreEqual("The field DoubleRange must be between 9 and 13.", doubleRangeValidator.GetErrorText(8d, entity));
Assert.AreEqual("The field DoubleRange must be between 9 and 13.", doubleRangeValidator.GetErrorText(14d, entity));
doubleRangeValidator = CreateValidator<ValidationEntity, double?>(x => x.DoubleRange_Nullable);
Assert.AreEqual(string.Empty, doubleRangeValidator.GetErrorText(10d, entity));
Assert.AreEqual("The field DoubleRange_Nullable must be between 9 and 13.", doubleRangeValidator.GetErrorText(8d, entity));
Assert.AreEqual("The field DoubleRange_Nullable must be between 9 and 13.", doubleRangeValidator.GetErrorText(14d, entity));
Assert.AreEqual(string.Empty, doubleRangeValidator.GetErrorText(null, entity));
doubleRangeValidator = CreateValidator<ValidationEntity, double>(x => x.DoubleRange_CustomError);
ValidationEntity.DoubleRange_CustomErrorText = "{0} range {1} {2}";
Assert.AreEqual("DoubleRange_CustomError range 9 13", doubleRangeValidator.GetErrorText(8d, entity));
var intRangeValidator = CreateValidator<ValidationEntity, int>(x => x.IntRange);
Assert.AreEqual(string.Empty, intRangeValidator.GetErrorText(10, entity));
Assert.AreEqual("The field IntRange must be between 9 and 13.", intRangeValidator.GetErrorText(8, entity));
Assert.AreEqual("The field IntRange must be between 9 and 13.", intRangeValidator.GetErrorText(14, entity));
var stringRangeValidator = CreateValidator<ValidationEntity, string>(x => x.StringRange);
Assert.AreEqual(string.Empty, stringRangeValidator.GetErrorText("Clown", entity));
Assert.AreEqual(string.Empty, stringRangeValidator.GetErrorText(string.Empty, entity));
Assert.AreEqual("The field StringRange must be between B and D.", stringRangeValidator.GetErrorText("Apple", entity));
Assert.AreEqual("The field StringRange must be between B and D.", stringRangeValidator.GetErrorText("Express", entity));
var stringRegExpValidator = CreateValidator<ValidationEntity, string>(x => x.StringRegExp);
Assert.AreEqual(string.Empty, stringRegExpValidator.GetErrorText("cl", entity));
Assert.AreEqual(@"The field StringRegExp must match the regular expression '^[a-z]{1,2}$'.", stringRegExpValidator.GetErrorText("Apple", entity));
stringRegExpValidator = CreateValidator<ValidationEntity, string>(x => x.StringRegExp_CustomError);
ValidationEntity.StringRegExp_CustomErrorText = "{0} regexp {1}";
Assert.AreEqual(@"StringRegExp_CustomError regexp ^[a-z]{1,2}$", stringRegExpValidator.GetErrorText("Apple", entity));
var intRegExpValidator = CreateValidator<ValidationEntity, int>(x => x.IntRegExp);
Assert.AreEqual(string.Empty, intRegExpValidator.GetErrorText(1, entity));
Assert.AreEqual(@"The field IntRegExp must match the regular expression '^[1-2]{1,2}$'.", intRegExpValidator.GetErrorText(3, entity));
var customStringValidator = CreateValidator<ValidationEntity, string>(x => x.CustomString);
Assert.AreEqual(string.Empty, customStringValidator.GetErrorText("12", entity));
Assert.AreEqual("CustomString is not valid.", customStringValidator.GetErrorText("123", entity));
customStringValidator = CreateValidator<ValidationEntity, string>(x => x.CustomString_CustomError);
ValidationEntity.CustomString_CustomErrorText = "{0} custom";
Assert.AreEqual("CustomString_CustomError custom", customStringValidator.GetErrorText("123", entity));
var twoErrorsValidator = CreateValidator<ValidationEntity, string>(x => x.TwoErrorsProperty);
Assert.AreEqual("The field TwoErrorsProperty must be a string or array type with a minimum length of '10'. The field TwoErrorsProperty must be a string or array type with a maximum length of '1'.", twoErrorsValidator.GetErrorText("123", entity));
Assert.AreEqual("The field TwoErrorsProperty must be a string or array type with a minimum length of '10'.", twoErrorsValidator.GetErrors("123", entity).ElementAt(0));
Assert.AreEqual("The field TwoErrorsProperty must be a string or array type with a maximum length of '1'.", twoErrorsValidator.GetErrors("123", entity).ElementAt(1));
Assert.AreEqual(2, twoErrorsValidator.GetErrors("123", entity).Count());
}
static PropertyValidator CreateValidator<T, TProperty>(Expression<Func<T, TProperty>> propertyExpression) {
string propertyName = BindableBase.GetPropertyNameFast(propertyExpression);
return PropertyValidator.FromAttributes(MetadataHelper.GetExtenalAndFluentAPIAttrbutes(typeof(T), propertyName), propertyName);
}
#if !SILVERLIGHT
[Test]
public void ResourceStringsTest() {
foreach(var property in typeof(DataAnnotationsResources).GetProperties(BindingFlags.Static | BindingFlags.NonPublic).Where(x => x.PropertyType == typeof(string))) {
Assert.AreEqual(DataAnnotationsResourcesResolver.AnnotationsResourceManager.GetString(property.Name), property.GetValue(null, null));
}
}
#if!MONO
[Test]
public void RegexTest() {
CheckRegex(typeof(PhoneAttribute), typeof(ValidationAttribute).Assembly.GetType(typeof(ValidationAttribute).Namespace + ".PhoneAttribute"));
CheckRegex(typeof(UrlAttribute), typeof(ValidationAttribute).Assembly.GetType(typeof(ValidationAttribute).Namespace + ".UrlAttribute"));
CheckRegex(typeof(EmailAddressAttribute), typeof(ValidationAttribute).Assembly.GetType(typeof(ValidationAttribute).Namespace + ".EmailAddressAttribute"));
}
static void CheckRegex(Type dxType, Type annotationsType) {
Regex dxRegex = (Regex)dxType.GetField("regex", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);
Regex regex = (Regex)annotationsType.GetField("_regex", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);
Assert.AreEqual(GetPatternFromRegex(regex), GetPatternFromRegex(dxRegex));
}
static string GetPatternFromRegex(Regex regex) {
return (string)typeof(Regex).GetField("pattern", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(regex);
}
#endif
#endif
#endregion
#region MetadataHelper tests
#region several external metadata
[MetadataType(typeof(BaseMetadata))]
public class BaseClass {
public class BaseMetadata {
[ReadOnly(true)]
public string BaseProperty { get; set; }
}
public string BaseProperty { get; set; }
}
[MetadataType(typeof(Metadata))]
public class Class : BaseClass {
public class Metadata {
[ReadOnly(true)]
public string Property { get; set; }
}
public string Property { get; set; }
}
[Test]
public void SeveralExternalMetadata() {
Assert.IsNotNull(MetadataHelper.GetExtenalAndFluentAPIAttrbutes(typeof(Class), "Property").OfType<ReadOnlyAttribute>().Single());
Assert.IsNotNull(MetadataHelper.GetExtenalAndFluentAPIAttrbutes(typeof(Class), "BaseProperty").OfType<ReadOnlyAttribute>().Single());
}
#endregion
#endregion
#region sequrity
[Test]
public void SecuritySafeCriticalClassesHasNoInternalAutogeneratedClassesWhichImplementInterfaces() {
foreach(Type type in Assembly.GetExecutingAssembly().GetTypes()) {
if(type.IsNested || !IsSequritySafeCriticalType(type))
continue;
CheckNestedTypes(type);
}
}
void CheckNestedTypes(Type type) {
foreach(Type nestedType in type.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic)) {
if(!IsSequritySafeCriticalType(nestedType))
Assert.IsFalse(nestedType.GetInterfaces().Any(), nestedType.FullName + " type is not SequritySafeCritical");
CheckNestedTypes(nestedType);
}
}
static bool IsSequritySafeCriticalType(Type type) {
return type.GetCustomAttributes(false).OfType<SecuritySafeCriticalAttribute>().Any();
}
#endregion
#region MetadataBuilder test
class StrictPropertiesAndMethodExpressionEntity {
public int Prop { get; set; }
public void Method() { }
}
public int StringProperty0 { get; set; }
public void SomeMethod() { }
public bool SomeMethod2() { return false; }
[Test]
public void StrictPropertiesAndMethodExpression() {
var builder = new MetadataBuilder<StrictPropertiesAndMethodExpressionEntity>();
TestHelper.AssertThrows<ArgumentException>(() => builder.Property(x => StringProperty0));
TestHelper.AssertThrows<ArgumentException>(() => builder.CommandFromMethod(x => SomeMethod()));
TestHelper.AssertThrows<ArgumentException>(() => builder.Property(x => x.Prop).OnPropertyChangedCall(x => SomeMethod()));
TestHelper.AssertThrows<ArgumentException>(() => builder.Property(x => x.Prop).OnPropertyChangingCall(x => SomeMethod()));
TestHelper.AssertThrows<ArgumentException>(() => builder.CommandFromMethod(x => x.Method()).CanExecuteMethod(x => SomeMethod2()));
}
#endregion
}
}
| |
using System;
using HalconDotNet;
namespace ViewROI
{
/// <summary>
/// This class demonstrates one of the possible implementations for a
/// (simple) rectangularly shaped ROI. ROIRectangle1 inherits
/// from the base class ROI and implements (besides other auxiliary
/// methods) all virtual methods defined in ROI.cs.
/// Since a simple rectangle is defined by two data points, by the upper
/// left corner and the lower right corner, we use four values (row1/col1)
/// and (row2/col2) as class members to hold these positions at
/// any time of the program. The four corners of the rectangle can be taken
/// as handles, which the user can use to manipulate the size of the ROI.
/// Furthermore, we define a midpoint as an additional handle, with which
/// the user can grab and drag the ROI. Therefore, we declare NumHandles
/// to be 5 and set the activeHandle to be 0, which will be the upper left
/// corner of our ROI.
/// </summary>
public class ROIRectangle1 : ROI
{
private double row1, col1; // upper left
private double row2, col2; // lower right
private double midR, midC; // midpoint
/// <summary>Constructor</summary>
public ROIRectangle1()
{
NumHandles = 5; // 4 corner points + midpoint
activeHandleIdx = 4;
}
/// <summary>Creates a new ROI instance at the mouse position</summary>
/// <param name="midX">
/// x (=column) coordinate for interactive ROI
/// </param>
/// <param name="midY">
/// y (=row) coordinate for interactive ROI
/// </param>
public override void createROI(double midX, double midY)
{
midR = midY;
midC = midX;
row1 = midR - 50;
col1 = midC - 50;
row2 = midR + 50;
col2 = midC + 50;
}
/// <summary>Paints the ROI into the supplied window</summary>
/// <param name="window">HALCON window</param>
public override void draw(HalconDotNet.HWindow window)
{
window.DispRectangle1(row1, col1, row2, col2);
window.DispRectangle2(row1, col1, 0, 5, 5);
window.DispRectangle2(row1, col2, 0, 5, 5);
window.DispRectangle2(row2, col2, 0, 5, 5);
window.DispRectangle2(row2, col1, 0, 5, 5);
window.DispRectangle2(midR, midC, 0, 5, 5);
}
/// <summary>
/// Returns the distance of the ROI handle being
/// closest to the image point(x,y)
/// </summary>
/// <param name="x">x (=column) coordinate</param>
/// <param name="y">y (=row) coordinate</param>
/// <returns>
/// Distance of the closest ROI handle.
/// </returns>
public override double distToClosestHandle(double x, double y)
{
double max = 10000;
double [] val = new double[NumHandles];
midR = ((row2 - row1) / 2) + row1;
midC = ((col2 - col1) / 2) + col1;
val[0] = HMisc.DistancePp(y, x, row1, col1); // upper left
val[1] = HMisc.DistancePp(y, x, row1, col2); // upper right
val[2] = HMisc.DistancePp(y, x, row2, col2); // lower right
val[3] = HMisc.DistancePp(y, x, row2, col1); // lower left
val[4] = HMisc.DistancePp(y, x, midR, midC); // midpoint
for (int i=0; i < NumHandles; i++)
{
if (val[i] < max)
{
max = val[i];
activeHandleIdx = i;
}
}// end of for
return val[activeHandleIdx];
}
/// <summary>
/// Paints the active handle of the ROI object into the supplied window
/// </summary>
/// <param name="window">HALCON window</param>
public override void displayActive(HalconDotNet.HWindow window)
{
switch (activeHandleIdx)
{
case 0:
window.DispRectangle2(row1, col1, 0, 5, 5);
break;
case 1:
window.DispRectangle2(row1, col2, 0, 5, 5);
break;
case 2:
window.DispRectangle2(row2, col2, 0, 5, 5);
break;
case 3:
window.DispRectangle2(row2, col1, 0, 5, 5);
break;
case 4:
window.DispRectangle2(midR, midC, 0, 5, 5);
break;
}
}
/// <summary>Gets the HALCON region described by the ROI</summary>
public override HRegion getRegion()
{
HRegion region = new HRegion();
region.GenRectangle1(row1, col1, row2, col2);
return region;
}
/// <summary>
/// Gets the model information described by
/// the interactive ROI
/// </summary>
public override HTuple getModelData()
{
return new HTuple(new double[] { row1, col1, row2, col2 });
}
/// <summary>
/// Recalculates the shape of the ROI instance. Translation is
/// performed at the active handle of the ROI object
/// for the image coordinate (x,y)
/// </summary>
/// <param name="newX">x mouse coordinate</param>
/// <param name="newY">y mouse coordinate</param>
public override void moveByHandle(double newX, double newY)
{
double len1, len2;
double tmp;
switch (activeHandleIdx)
{
case 0: // upper left
row1 = newY;
col1 = newX;
break;
case 1: // upper right
row1 = newY;
col2 = newX;
break;
case 2: // lower right
row2 = newY;
col2 = newX;
break;
case 3: // lower left
row2 = newY;
col1 = newX;
break;
case 4: // midpoint
len1 = ((row2 - row1) / 2);
len2 = ((col2 - col1) / 2);
row1 = newY - len1;
row2 = newY + len1;
col1 = newX - len2;
col2 = newX + len2;
break;
}
if (row2 <= row1)
{
tmp = row1;
row1 = row2;
row2 = tmp;
}
if (col2 <= col1)
{
tmp = col1;
col1 = col2;
col2 = tmp;
}
midR = ((row2 - row1) / 2) + row1;
midC = ((col2 - col1) / 2) + col1;
}//end of method
}//end of class
}//end of namespace
| |
// 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.Text;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
using System.Reflection.Runtime.General;
using System.Reflection.Runtime.TypeInfos;
using System.Reflection.Runtime.Assemblies;
using System.Reflection.Runtime.CustomAttributes;
namespace Internal.Reflection.Tracing
{
public static partial class ReflectionTrace
{
//==============================================================================
// Returns the type name to emit into the ETW record.
//
// - If it returns null, skip writing the ETW record. Null returns can happen
// for the following reasons:
// - Missing metadata
// - Open type (no need to trace these - open type creations always succeed)
// - Third-party-implemented Types.
//
// The implementation does a reasonable-effort to avoid MME's to avoid an annoying
// debugger experience. However, some MME's will still get caught by the try/catch.
//
// - The format happens to match what the AssemblyQualifiedName property returns
// but we cannot invoke that here due to the risk of infinite recursion.
// The implementation must be very careful what it calls.
//==============================================================================
private static String NameString(this Type type)
{
try
{
return type.AssemblyQualifiedTypeName();
}
catch
{
return null;
}
}
//==============================================================================
// Returns the assembly name to emit into the ETW record.
//==============================================================================
private static String NameString(this Assembly assembly)
{
try
{
RuntimeAssembly runtimeAssembly = assembly as RuntimeAssembly;
if (runtimeAssembly == null)
return null;
return runtimeAssembly.RuntimeAssemblyName.FullName;
}
catch
{
return null;
}
}
//==============================================================================
// Returns the custom attribute type name to emit into the ETW record.
//==============================================================================
private static String AttributeTypeNameString(this CustomAttributeData customAttributeData)
{
try
{
RuntimeCustomAttributeData runtimeCustomAttributeData = customAttributeData as RuntimeCustomAttributeData;
if (runtimeCustomAttributeData == null)
return null;
return runtimeCustomAttributeData.AttributeType.NameString();
}
catch
{
return null;
}
}
//==============================================================================
// Returns the declaring type name (without calling MemberInfo.DeclaringType) to emit into the ETW record.
//==============================================================================
private static String DeclaringTypeNameString(this MemberInfo memberInfo)
{
try
{
ITraceableTypeMember traceableTypeMember = memberInfo as ITraceableTypeMember;
if (traceableTypeMember == null)
return null;
return traceableTypeMember.ContainingType.NameString();
}
catch
{
return null;
}
}
//==============================================================================
// Returns the MemberInfo.Name value (without calling MemberInfo.Name) to emit into the ETW record.
//==============================================================================
private static String NameString(this MemberInfo memberInfo)
{
try
{
TypeInfo typeInfo = memberInfo as TypeInfo;
if (typeInfo != null)
return typeInfo.AsType().NameString();
ITraceableTypeMember traceableTypeMember = memberInfo as ITraceableTypeMember;
if (traceableTypeMember == null)
return null;
return traceableTypeMember.MemberName;
}
catch
{
return null;
}
}
//==============================================================================
// Append type argument strings.
//==============================================================================
private static String GenericTypeArgumentStrings(this Type[] typeArguments)
{
if (typeArguments == null)
return null;
String s = "";
foreach (Type typeArgument in typeArguments)
{
String typeArgumentString = typeArgument.NameString();
if (typeArgumentString == null)
return null;
s += "@" + typeArgumentString;
}
return s;
}
private static String NonQualifiedTypeName(this Type type)
{
if (!type.IsRuntimeImplemented())
return null;
RuntimeTypeInfo runtimeType = type.CastToRuntimeTypeInfo();
if (runtimeType.HasElementType)
{
String elementTypeName = runtimeType.InternalRuntimeElementType.NonQualifiedTypeName();
if (elementTypeName == null)
return null;
String suffix;
if (runtimeType.IsArray)
{
int rank = runtimeType.GetArrayRank();
if (rank == 1)
suffix = "[" + (runtimeType.IsVariableBoundArray ? "*" : "") + "]";
else
suffix = "[" + new String(',', rank - 1) + "]";
}
else if (runtimeType.IsByRef)
suffix = "&";
else if (runtimeType.IsPointer)
suffix = "*";
else
return null;
return elementTypeName + suffix;
}
else if (runtimeType.IsGenericParameter)
{
return null;
}
else if (runtimeType.IsConstructedGenericType)
{
StringBuilder sb = new StringBuilder();
String genericTypeDefinitionTypeName = runtimeType.GetGenericTypeDefinition().NonQualifiedTypeName();
if (genericTypeDefinitionTypeName == null)
return null;
sb.Append(genericTypeDefinitionTypeName);
sb.Append("[");
String sep = "";
foreach (RuntimeTypeInfo ga in runtimeType.InternalRuntimeGenericTypeArguments)
{
String gaTypeName = ga.AssemblyQualifiedTypeName();
if (gaTypeName == null)
return null;
sb.Append(sep + "[" + gaTypeName + "]");
sep = ",";
}
sb.Append("]");
return sb.ToString();
}
else
{
RuntimeNamedTypeInfo runtimeNamedTypeInfo = type.GetTypeInfo() as RuntimeNamedTypeInfo;
if (runtimeNamedTypeInfo == null)
return null;
return runtimeNamedTypeInfo.TraceableTypeName;
}
}
private static String AssemblyQualifiedTypeName(this Type type)
{
if (!type.IsRuntimeImplemented())
return null;
RuntimeTypeInfo runtimeType = type.CastToRuntimeTypeInfo();
if (runtimeType == null)
return null;
String nonqualifiedTypeName = runtimeType.NonQualifiedTypeName();
if (nonqualifiedTypeName == null)
return null;
String assemblyName = runtimeType.ContainingAssemblyName();
if (assemblyName == null)
return assemblyName;
return nonqualifiedTypeName + ", " + assemblyName;
}
private static String ContainingAssemblyName(this Type type)
{
if (!type.IsRuntimeImplemented())
return null;
RuntimeTypeInfo runtimeTypeInfo = type.CastToRuntimeTypeInfo();
if (runtimeTypeInfo is RuntimeNoMetadataNamedTypeInfo)
return null;
return runtimeTypeInfo.Assembly.NameString();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ApiVersionLocalOperations operations.
/// </summary>
internal partial class ApiVersionLocalOperations : Microsoft.Rest.IServiceOperations<AutoRestAzureSpecialParametersTestClient>, IApiVersionLocalOperations
{
/// <summary>
/// Initializes a new instance of the ApiVersionLocalOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ApiVersionLocalOperations(AutoRestAzureSpecialParametersTestClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestAzureSpecialParametersTestClient
/// </summary>
public AutoRestAzureSpecialParametersTestClient Client { get; private set; }
/// <summary>
/// Get method with api-version modeled in the method. pass in api-version =
/// '2.0' to succeed
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> GetMethodLocalValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
string apiVersion = "2.0";
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetMethodLocalValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/method/string/none/query/local/2.0").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get method with api-version modeled in the method. pass in api-version =
/// null to succeed
/// </summary>
/// <param name='apiVersion'>
/// This should appear as a method parameter, use value null, this should
/// result in no serialized parameter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> GetMethodLocalNullWithHttpMessagesAsync(string apiVersion = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetMethodLocalNull", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/method/string/none/query/local/null").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get method with api-version modeled in the method. pass in api-version =
/// '2.0' to succeed
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> GetPathLocalValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
string apiVersion = "2.0";
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetPathLocalValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/path/string/none/query/local/2.0").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get method with api-version modeled in the method. pass in api-version =
/// '2.0' to succeed
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> GetSwaggerLocalValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
string apiVersion = "2.0";
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetSwaggerLocalValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/swagger/string/none/query/local/2.0").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Reflection;
using System.Text.RegularExpressions;
namespace Raccoom.Xml.ComponentModel
{
/// <summary>
/// Generic xml parser. Works like OR Mapper, reflects target object and set corresponding values from xml file.
/// </summary>
public class SyndicationObjectParser
{
#region fields
/// <summary></summary>
System.Collections.Generic.Dictionary<Type, System.Collections.Generic.Dictionary<string, System.Reflection.PropertyInfo>> _complexTypeRepository;
#endregion
#region internal interface
/// <summary>Xml parsing against reflected target object</summary>
/// <param name="target">Target object instance that will hold the gained data</param>
/// <param name="xmlTextReader">XmlReader instance that holds the source xml</param>
/// <exception cref="XmlException">The exception that is thrown on XML parse errors. </exception>
/// <exception cref="System.IO.IOException">The exception that is thrown when an I/O error occurs.</exception>
protected virtual void Parse(object target, System.Xml.XmlReader xmlTextReader)
{
Parse(target, xmlTextReader, null);
}
protected virtual void Parse(object target, System.Xml.XmlReader xmlTextReader, IParseableObject parseableObject)
{
try
{
IExtendableObject expandableTarget = target as IExtendableObject;
if (target is IParseableObject)
{
((IParseableObject)target).BeginParse();
parseableObject = (IParseableObject)target;
}
//
int depth = xmlTextReader.Depth;
// cache meta info to gain performance
System.Collections.Generic.Dictionary<string, System.Reflection.PropertyInfo> complexProperties = GetComplexProperties(target);
// initalize
System.Reflection.PropertyInfo pi = null;
string name;
object childObject;
XmlReader r = null;
XmlNode node = null, childNode = null;
// process target
while (!xmlTextReader.EOF)
{
if (xmlTextReader.ReadState == ReadState.Error) return;
xmlTextReader.Read();
xmlTextReader.MoveToContent();
//
if (xmlTextReader.NodeType == XmlNodeType.EndElement || xmlTextReader.NodeType == XmlNodeType.None) continue;
// skip elements with namespace ( extensions )
if (!string.IsNullOrEmpty(xmlTextReader.Prefix) & expandableTarget == null) continue;
//
name = xmlTextReader.LocalName;
// value of element strictly mapped to Value property _> rss guid
if (string.IsNullOrEmpty(name)) name = "Value";
// is it a complex type like item or source
if (complexProperties.ContainsKey(name) & depth < xmlTextReader.Depth)
{
// is it a collection based item and needs to be created and added?
if (complexProperties[name].PropertyType.GetInterface(typeof(System.Collections.IList).Name) != null)
{
// get create item method
System.Reflection.MethodInfo mi = target.GetType().GetMethod("Create" + name, System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.NonPublic | BindingFlags.Public | System.Reflection.BindingFlags.Instance);
// invoke create method
childObject = mi.Invoke(target, null);
// add item
complexProperties[name].PropertyType.InvokeMember("Add", BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, complexProperties[name].GetValue(target, null), new object[] { childObject });
}
else
{
// get existing instance from target
childObject = complexProperties[name].GetValue(target, null);
}
// recursive call to parse child object
Parse(childObject, xmlTextReader.ReadSubtree(), parseableObject);
}
else
{
// Check namespace
if (!string.IsNullOrEmpty(xmlTextReader.Prefix) & xmlTextReader.NodeType == XmlNodeType.Element)
{
r = xmlTextReader.ReadSubtree();
//
while (!r.EOF)
{
r.Read();
if (r.NodeType == XmlNodeType.EndElement || r.NodeType == XmlNodeType.None) continue;
node = expandableTarget.ExtendedContent.OwnerDocument.CreateNode(r.NodeType, r.Prefix, r.LocalName, r.NamespaceURI);
if (r.IsEmptyElement) continue;
r.Read();
childNode = expandableTarget.ExtendedContent.OwnerDocument.CreateNode(r.NodeType, r.Prefix, r.LocalName, r.NamespaceURI);
childNode.Value = System.Web.HttpUtility.HtmlEncode(r.Value);
node.AppendChild(childNode);
}
expandableTarget.ExtendedContent.AppendChild(node);
//
continue;
}
// get attributes if any exists
if (xmlTextReader.HasAttributes)
{
while (xmlTextReader.MoveToNextAttribute())
{
try
{
// xmlns
if (xmlTextReader.NamespaceURI.Equals("http://www.w3.org/2000/xmlns/") & xmlTextReader.LocalName != "xmlns" & expandableTarget != null)
{
expandableTarget.Xmlns.Add(xmlTextReader.LocalName, xmlTextReader.Value);
}
else
{
// try to get attribute property
pi = GetPropertyByName(xmlTextReader.Name, target);
if (pi == null) continue;
// get attribute value
SetPropertyValue(xmlTextReader, target, pi);
}
}
catch (Exception e)
{
if (parseableObject != null) parseableObject.Errors.Add(target.GetType().Name + "." + pi.Name, e);
}
}
}
// empty elements have no value, even if they exists as property on the class move on
if (xmlTextReader.IsEmptyElement) continue;
// try to get element property
pi = GetPropertyByName(name, target);
if (pi == null) continue;
// read if not already done
if (xmlTextReader.NodeType == XmlNodeType.Element) xmlTextReader.Read();
// get element value
try
{
SetPropertyValue(xmlTextReader, target, pi);
}
catch (Exception e)
{
if (parseableObject != null)
{
// try to find a unique key name
string key = target.GetType().Name + "." + pi.Name;
int i = 1;
while (parseableObject.Errors.ContainsKey(key))
{
key += i;
i++;
}
// add item with unique key to the list
parseableObject.Errors.Add(key, e);
}
}
}
}
}
catch (XmlException)
{
throw;
}
catch (System.IO.IOException)
{
throw;
}
catch (System.Exception e)
{
if (parseableObject != null) parseableObject.Errors.Add(target.GetType().Name, e);
}
finally
{
//
if (target is IParseableObject)
{
((IParseableObject)target).EndParse();
}
}
}
/// <summary>Reflects all the complex properties contained in target</summary>
protected virtual System.Collections.Generic.Dictionary<string, System.Reflection.PropertyInfo> GetComplexProperties(object target)
{
System.Collections.Generic.Dictionary<string, System.Reflection.PropertyInfo> complexProperties = null;
// reflect complex tags
if (_complexTypeRepository == null) _complexTypeRepository = new System.Collections.Generic.Dictionary<Type, System.Collections.Generic.Dictionary<string, PropertyInfo>>();
if (_complexTypeRepository.ContainsKey(target.GetType())) return _complexTypeRepository[target.GetType()];
complexProperties = new System.Collections.Generic.Dictionary<string, PropertyInfo>(StringComparer.OrdinalIgnoreCase);
foreach (System.Reflection.PropertyInfo pInfo in target.GetType().GetProperties())
{
if (!pInfo.PropertyType.Assembly.Equals(target.GetType().Assembly)) continue;
if (pInfo.PropertyType.IsEnum) continue;
//
object[] attributes = pInfo.GetCustomAttributes(typeof(System.Xml.Serialization.XmlElementAttribute), true);
if (attributes.Length == 0) continue;
//
System.Xml.Serialization.XmlElementAttribute xmlAttribute = attributes[0] as System.Xml.Serialization.XmlElementAttribute;
if (xmlAttribute == null) continue;
//
complexProperties.Add(xmlAttribute.ElementName + xmlAttribute.Namespace, pInfo);
}
//
_complexTypeRepository.Add(target.GetType(), complexProperties);
return complexProperties;
}
/// <summary>
/// Try to get property by name
/// </summary>
protected virtual System.Reflection.PropertyInfo GetPropertyByName(string name, object target)
{
return target.GetType().GetProperty(name, System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
}
/// <summary>
/// Set property value
/// </summary>
protected virtual void SetPropertyValue(System.Xml.XmlReader xmlTextReader, object target, System.Reflection.PropertyInfo pi)
{
switch (xmlTextReader.NodeType)
{
case XmlNodeType.Attribute:
case XmlNodeType.CDATA:
case XmlNodeType.Text:
string content = xmlTextReader.ReadContentAsString().Trim();
if (pi.PropertyType.Equals(typeof(DateTime)))
{
pi.SetValue(target, ParseDateTime(content), null);
}
else if (pi.PropertyType.IsEnum)
{
// try to set enum value
if (System.Enum.IsDefined(pi.PropertyType, content))
{
pi.SetValue(target, System.ComponentModel.TypeDescriptor.GetConverter(pi.PropertyType).ConvertFromString(content), null);
}
else
{
// take the long way, we have to look up xml enum substitute name
System.Reflection.FieldInfo[] fields = pi.PropertyType.GetFields();
for (int i = 1; i < fields.Length; i++)
{
System.Reflection.FieldInfo field = fields[i];
object[] attributes = field.GetCustomAttributes(false);
if (attributes.Length == 0) continue;
//
System.Xml.Serialization.XmlEnumAttribute enumAttribute = attributes[0] as System.Xml.Serialization.XmlEnumAttribute;
if (enumAttribute == null) continue;
//
if (!StringComparer.OrdinalIgnoreCase.Equals(enumAttribute.Name, content)) continue;
// set substituted enum value
pi.SetValue(target, System.ComponentModel.TypeDescriptor.GetConverter(pi.PropertyType).ConvertFromString(field.Name), null);
break;
}
}
}
else if (pi.PropertyType.Equals(typeof(string)))
{
pi.SetValue(target, System.Web.HttpUtility.HtmlDecode(content), null);
}
else
{
pi.SetValue(target, System.ComponentModel.TypeDescriptor.GetConverter(pi.PropertyType).ConvertFromString(content), null);
}
break;
}
}
#region rfs datetime
/// <summary>
/// <remarks>
///Copyright (c) [email protected]
///All rights reserved.
/// </remarks>
/// </summary>
/// <param name="adate">rfc date time</param>
/// <returns>Rfc date as DateTime</returns>
public static System.DateTime ParseDateTime(string adate)
{
System.DateTime dt = System.DateTime.Now;
if (DateTime.TryParse(adate, out dt)) return dt;
//
string tmp;
string[] resp;
string dayName;
string dpart;
string hour, minute;
string timeZone;
//--- strip comments
//--- XXX : FIXME : how to handle nested comments ?
tmp = Regex.Replace(adate, "(\\([^(].*\\))", "");
// strip extra white spaces
tmp = Regex.Replace(tmp, "\\s+", " ");
tmp = Regex.Replace(tmp, "^\\s+", "");
tmp = Regex.Replace(tmp, "\\s+$", "");
// extract week name part
resp = tmp.Split(new char[] { ',' }, 2);
if (resp.Length == 2)
{
// there's week name
dayName = resp[0];
tmp = resp[1];
}
else dayName = "";
try
{
// extract date and time
int pos = tmp.LastIndexOf(" ");
if (pos < 1) throw new FormatException("probably not a date");
dpart = tmp.Substring(0, pos - 1);
timeZone = tmp.Substring(pos + 1);
dt = Convert.ToDateTime(dpart);
// check weekDay name
// this must be done befor convert to GMT
if (!string.IsNullOrEmpty(dayName))
{
if ((dt.DayOfWeek == DayOfWeek.Friday && dayName != "Fri") ||
(dt.DayOfWeek == DayOfWeek.Monday && dayName != "Mon") ||
(dt.DayOfWeek == DayOfWeek.Saturday && dayName != "Sat") ||
(dt.DayOfWeek == DayOfWeek.Sunday && dayName != "Sun") ||
(dt.DayOfWeek == DayOfWeek.Thursday && dayName != "Thu") ||
(dt.DayOfWeek == DayOfWeek.Tuesday && dayName != "Tue") ||
(dt.DayOfWeek == DayOfWeek.Wednesday && dayName != "Wed")
)
throw new FormatException("invalide week of day");
}
// adjust to localtime
if (Regex.IsMatch(timeZone, "[+\\-][0-9][0-9][0-9][0-9]"))
{
// it's a modern ANSI style timezone
int factor = 0;
hour = timeZone.Substring(1, 2);
minute = timeZone.Substring(3, 2);
if (timeZone.Substring(0, 1) == "+") factor = 1;
else if (timeZone.Substring(0, 1) == "-") factor = -1;
else throw new FormatException("incorrect tiem zone");
dt = dt.AddHours(factor * Convert.ToInt32(hour));
dt = dt.AddMinutes(factor * Convert.ToInt32(minute));
}
else
{
// it's a old style military time zone ?
switch (timeZone)
{
case "A": dt = dt.AddHours(1); break;
case "B": dt = dt.AddHours(2); break;
case "C": dt = dt.AddHours(3); break;
case "D": dt = dt.AddHours(4); break;
case "E": dt = dt.AddHours(5); break;
case "F": dt = dt.AddHours(6); break;
case "G": dt = dt.AddHours(7); break;
case "H": dt = dt.AddHours(8); break;
case "I": dt = dt.AddHours(9); break;
case "K": dt = dt.AddHours(10); break;
case "L": dt = dt.AddHours(11); break;
case "M": dt = dt.AddHours(12); break;
case "N": dt = dt.AddHours(-1); break;
case "O": dt = dt.AddHours(-2); break;
case "P": dt = dt.AddHours(-3); break;
case "Q": dt = dt.AddHours(-4); break;
case "R": dt = dt.AddHours(-5); break;
case "S": dt = dt.AddHours(-6); break;
case "T": dt = dt.AddHours(-7); break;
case "U": dt = dt.AddHours(-8); break;
case "V": dt = dt.AddHours(-9); break;
case "W": dt = dt.AddHours(-10); break;
case "X": dt = dt.AddHours(-11); break;
case "Y": dt = dt.AddHours(-12); break;
case "Z":
case "UT":
case "GMT": break; // It's UTC
case "EST": dt = dt.AddHours(5); break;
case "EDT": dt = dt.AddHours(4); break;
case "CST": dt = dt.AddHours(6); break;
case "CDT": dt = dt.AddHours(5); break;
case "MST": dt = dt.AddHours(7); break;
case "MDT": dt = dt.AddHours(6); break;
case "PST": dt = dt.AddHours(8); break;
case "PDT": dt = dt.AddHours(7); break;
default: throw new FormatException("invalide time zone");
}
}
}
catch (Exception e)
{
throw new FormatException(string.Format("Invalide date:{0}:{1}", e.Message, adate));
}
return dt;
}
#endregion
#endregion
}
/// <summary>
/// IParseableObject interface is used by <see cref="SyndicationObjectParser"/> and enables the class to supress events during the parsing operation.
/// </summary>
public interface IParseableObject
{
/// <summary>
/// Called by <see cref="SyndicationObjectParser"/> before the parsing operation starts.
/// </summary>
void BeginParse();
/// <summary>
/// Called by <see cref="SyndicationObjectParser"/> after the parsing operation took place.
/// </summary>
void EndParse();
/// <summary>
/// Key: Type.Propertyname Value: Parser exception message
/// </summary>
System.Collections.Generic.SortedList<string, Exception> Errors { get;}
}
public interface IExtendableObject
{
System.Xml.Serialization.XmlSerializerNamespaces Xmlns { get;}
System.Xml.XmlDocumentFragment ExtendedContent { get;}
}
}
| |
// ---------------------------------------------------------------------------------
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ---------------------------------------------------------------------------------
//#define DEBUG_LOG
using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using Microsoft.WindowsAzure.Diagnostics;
namespace WorkerHost
{
class ADResult
{
[DataMember]
public string table { get; set; }
public List<AnomalyRecord> GetADResults()
{
var rowDelim = ";";
var colDelim = ",";
var rows = table.Split(new string[] { rowDelim }, StringSplitOptions.RemoveEmptyEntries);
List<AnomalyRecord> series = new List<AnomalyRecord>();
for (int i = 0; i < rows.Length; i++)
{
var row = rows[i].Replace("\"", "").Trim();
if (i == 0 || row.Length == 0)
{
continue; // ignore headers and empty rows
}
var cols = row.Split(new string[] { colDelim }, StringSplitOptions.RemoveEmptyEntries);
series.Add(AnomalyRecord.Parse(cols));
}
return series;
}
}
class Analyzer
{
private static string _detectorUrl;
private static string _detectorAuthKey;
private static string _liveId;
private static string _spikeDetectorParams;
private static bool _useMarketApi;
public Analyzer(string anomalyDetectionApiUrl, string anomalyDetectionAuthKey, string liveId, bool useMarketApi, string tukeyThresh, string zscoreThresh)
{
_detectorUrl = anomalyDetectionApiUrl;
_detectorAuthKey = anomalyDetectionAuthKey;
_liveId = liveId;
_useMarketApi = useMarketApi;
_spikeDetectorParams = string.Format("SpikeDetector.TukeyThresh={0}; SpikeDetector.ZscoreThresh={1}", tukeyThresh, zscoreThresh);
}
public Task<AnomalyRecord[]> Analyze(SensorDataContract[] data)
{
var timeSeriesData = GetTimeseriesData(data);
#if DEBUG_LOG
Trace.TraceInformation("AzureML request: {0}", timeSeriesData);
#endif
if (_useMarketApi)
{
return Task.Run(() => GetAlertsFromAnomalyDetectionAPI(timeSeriesData));
}
return GetAlertsFromRRS(timeSeriesData);
}
private static string GetTimeseriesData(SensorDataContract[] data)
{
var step = 1;
var prevTime = DateTime.MinValue;
var prevVal = 0d;
List<SensorDataContract> newData = new List<SensorDataContract>();
foreach (var d in data.OrderBy(dd => dd.TimeCreated))
{
d.TimeCreated = d.TimeCreated.AddTicks(-(d.TimeCreated.Ticks % TimeSpan.TicksPerSecond)); // round off the millisecs
if (prevTime != DateTime.MinValue)
{
for (; prevTime.AddSeconds(step) < d.TimeCreated; )
{
prevTime = prevTime.AddSeconds(step);
newData.Add(new SensorDataContract { TimeCreated = prevTime, Value = prevVal });
}
}
newData.Add(d);
prevTime = d.TimeCreated;
prevVal = d.Value;
}
var sb = new StringBuilder();
foreach (var d in newData)
{
sb.Append(string.Format("{0}={1};", d.TimeCreated.ToString("O"), d.Value));
}
return sb.ToString();
}
public static double FindMaxValue(IEnumerable<double> values)
{
var avg = values.Average();
var sd = Math.Sqrt(values.Average(v => Math.Pow(v - avg, 2)));
return avg + 5 * sd;
}
private AnomalyRecord[] filterAnomaly(IEnumerable<AnomalyRecord> analyzedRecords)
{
return analyzedRecords.Where(ar => ar.Spike1 == 1 || ar.Spike2 == 1 || ar.LevelScore > 3).ToArray();
}
public AnomalyRecord[] GetAlertsFromAnomalyDetectionAPI(string timeSeriesData)
{
var acitionUri = new Uri(_detectorUrl);
var cred = new NetworkCredential(_liveId, _detectorAuthKey); // your Microsoft live Id here
var cache = new CredentialCache();
cache.Add(acitionUri, "Basic", cred);
DataServiceContext ctx = new DataServiceContext(acitionUri);
ctx.Credentials = cache;
var query = ctx.Execute<ADResult>(acitionUri, "POST", true,
new BodyOperationParameter("data", timeSeriesData),
new BodyOperationParameter("params", _spikeDetectorParams));
var resultTable = query.FirstOrDefault();
var results = resultTable.GetADResults();
var presults = results;
return filterAnomaly(presults);
}
private Task<AnomalyRecord[]> GetAlertsFromRRS(string timeSeriesData)
{
var rrs = _detectorUrl;
var apikey = _detectorAuthKey;
using (var wb = new WebClient())
{
wb.Headers[HttpRequestHeader.ContentType] = "application/json";
wb.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + apikey);
var featureVector = string.Format("\"data\": \"{0}\",\"params\": \"{1}\"", timeSeriesData, _spikeDetectorParams);
string jsonData = "{\"Id\":\"scoring0001\", \"Instance\": {\"FeatureVector\": {" + featureVector + "}, \"GlobalParameters\":{\"level_mhist\": 300, \"level_shist\": 100, \"trend_mhist\": 300, \"trend_shist\": 100 }}}";
var jsonBytes = Encoding.Default.GetBytes(jsonData);
return wb.UploadDataTaskAsync(rrs, "POST", jsonBytes)
.ContinueWith(
resp =>
{
var response = Encoding.Default.GetString(resp.Result);
#if DEBUG_LOG
Trace.TraceInformation("AzureML response: {0}...", response.Substring(0, Math.Min(100, response.Length)));
#endif
JavaScriptSerializer ser = new JavaScriptSerializer { MaxJsonLength = int.MaxValue };
var results = ser.Deserialize<List<string[]>>(response);
var presults = results.Select(AnomalyRecord.Parse);
return filterAnomaly(presults);
}
);
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace SAEON.Observations.Data
{
/// <summary>
/// Strongly-typed collection for the Observation class.
/// </summary>
[Serializable]
public partial class ObservationCollection : ActiveList<Observation, ObservationCollection>
{
public ObservationCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>ObservationCollection</returns>
public ObservationCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
Observation o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Observation table.
/// </summary>
[Serializable]
public partial class Observation : ActiveRecord<Observation>, IActiveRecord
{
#region .ctors and Default Settings
public Observation()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public Observation(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public Observation(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public Observation(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Observation", TableType.Table, DataService.GetInstance("ObservationsDB"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarSensorID = new TableSchema.TableColumn(schema);
colvarSensorID.ColumnName = "SensorID";
colvarSensorID.DataType = DbType.Guid;
colvarSensorID.MaxLength = 0;
colvarSensorID.AutoIncrement = false;
colvarSensorID.IsNullable = false;
colvarSensorID.IsPrimaryKey = false;
colvarSensorID.IsForeignKey = true;
colvarSensorID.IsReadOnly = false;
colvarSensorID.DefaultSetting = @"";
colvarSensorID.ForeignKeyTableName = "Sensor";
schema.Columns.Add(colvarSensorID);
TableSchema.TableColumn colvarValueDate = new TableSchema.TableColumn(schema);
colvarValueDate.ColumnName = "ValueDate";
colvarValueDate.DataType = DbType.DateTime;
colvarValueDate.MaxLength = 0;
colvarValueDate.AutoIncrement = false;
colvarValueDate.IsNullable = false;
colvarValueDate.IsPrimaryKey = false;
colvarValueDate.IsForeignKey = false;
colvarValueDate.IsReadOnly = false;
colvarValueDate.DefaultSetting = @"";
colvarValueDate.ForeignKeyTableName = "";
schema.Columns.Add(colvarValueDate);
TableSchema.TableColumn colvarRawValue = new TableSchema.TableColumn(schema);
colvarRawValue.ColumnName = "RawValue";
colvarRawValue.DataType = DbType.Double;
colvarRawValue.MaxLength = 0;
colvarRawValue.AutoIncrement = false;
colvarRawValue.IsNullable = true;
colvarRawValue.IsPrimaryKey = false;
colvarRawValue.IsForeignKey = false;
colvarRawValue.IsReadOnly = false;
colvarRawValue.DefaultSetting = @"";
colvarRawValue.ForeignKeyTableName = "";
schema.Columns.Add(colvarRawValue);
TableSchema.TableColumn colvarDataValue = new TableSchema.TableColumn(schema);
colvarDataValue.ColumnName = "DataValue";
colvarDataValue.DataType = DbType.Double;
colvarDataValue.MaxLength = 0;
colvarDataValue.AutoIncrement = false;
colvarDataValue.IsNullable = true;
colvarDataValue.IsPrimaryKey = false;
colvarDataValue.IsForeignKey = false;
colvarDataValue.IsReadOnly = false;
colvarDataValue.DefaultSetting = @"";
colvarDataValue.ForeignKeyTableName = "";
schema.Columns.Add(colvarDataValue);
TableSchema.TableColumn colvarComment = new TableSchema.TableColumn(schema);
colvarComment.ColumnName = "Comment";
colvarComment.DataType = DbType.AnsiString;
colvarComment.MaxLength = 250;
colvarComment.AutoIncrement = false;
colvarComment.IsNullable = true;
colvarComment.IsPrimaryKey = false;
colvarComment.IsForeignKey = false;
colvarComment.IsReadOnly = false;
colvarComment.DefaultSetting = @"";
colvarComment.ForeignKeyTableName = "";
schema.Columns.Add(colvarComment);
TableSchema.TableColumn colvarPhenomenonOfferingID = new TableSchema.TableColumn(schema);
colvarPhenomenonOfferingID.ColumnName = "PhenomenonOfferingID";
colvarPhenomenonOfferingID.DataType = DbType.Guid;
colvarPhenomenonOfferingID.MaxLength = 0;
colvarPhenomenonOfferingID.AutoIncrement = false;
colvarPhenomenonOfferingID.IsNullable = false;
colvarPhenomenonOfferingID.IsPrimaryKey = false;
colvarPhenomenonOfferingID.IsForeignKey = true;
colvarPhenomenonOfferingID.IsReadOnly = false;
colvarPhenomenonOfferingID.DefaultSetting = @"";
colvarPhenomenonOfferingID.ForeignKeyTableName = "PhenomenonOffering";
schema.Columns.Add(colvarPhenomenonOfferingID);
TableSchema.TableColumn colvarPhenomenonUOMID = new TableSchema.TableColumn(schema);
colvarPhenomenonUOMID.ColumnName = "PhenomenonUOMID";
colvarPhenomenonUOMID.DataType = DbType.Guid;
colvarPhenomenonUOMID.MaxLength = 0;
colvarPhenomenonUOMID.AutoIncrement = false;
colvarPhenomenonUOMID.IsNullable = false;
colvarPhenomenonUOMID.IsPrimaryKey = false;
colvarPhenomenonUOMID.IsForeignKey = true;
colvarPhenomenonUOMID.IsReadOnly = false;
colvarPhenomenonUOMID.DefaultSetting = @"";
colvarPhenomenonUOMID.ForeignKeyTableName = "PhenomenonUOM";
schema.Columns.Add(colvarPhenomenonUOMID);
TableSchema.TableColumn colvarImportBatchID = new TableSchema.TableColumn(schema);
colvarImportBatchID.ColumnName = "ImportBatchID";
colvarImportBatchID.DataType = DbType.Guid;
colvarImportBatchID.MaxLength = 0;
colvarImportBatchID.AutoIncrement = false;
colvarImportBatchID.IsNullable = false;
colvarImportBatchID.IsPrimaryKey = false;
colvarImportBatchID.IsForeignKey = true;
colvarImportBatchID.IsReadOnly = false;
colvarImportBatchID.DefaultSetting = @"";
colvarImportBatchID.ForeignKeyTableName = "ImportBatch";
schema.Columns.Add(colvarImportBatchID);
TableSchema.TableColumn colvarStatusID = new TableSchema.TableColumn(schema);
colvarStatusID.ColumnName = "StatusID";
colvarStatusID.DataType = DbType.Guid;
colvarStatusID.MaxLength = 0;
colvarStatusID.AutoIncrement = false;
colvarStatusID.IsNullable = true;
colvarStatusID.IsPrimaryKey = false;
colvarStatusID.IsForeignKey = true;
colvarStatusID.IsReadOnly = false;
colvarStatusID.DefaultSetting = @"";
colvarStatusID.ForeignKeyTableName = "Status";
schema.Columns.Add(colvarStatusID);
TableSchema.TableColumn colvarStatusReasonID = new TableSchema.TableColumn(schema);
colvarStatusReasonID.ColumnName = "StatusReasonID";
colvarStatusReasonID.DataType = DbType.Guid;
colvarStatusReasonID.MaxLength = 0;
colvarStatusReasonID.AutoIncrement = false;
colvarStatusReasonID.IsNullable = true;
colvarStatusReasonID.IsPrimaryKey = false;
colvarStatusReasonID.IsForeignKey = true;
colvarStatusReasonID.IsReadOnly = false;
colvarStatusReasonID.DefaultSetting = @"";
colvarStatusReasonID.ForeignKeyTableName = "StatusReason";
schema.Columns.Add(colvarStatusReasonID);
TableSchema.TableColumn colvarCorrelationID = new TableSchema.TableColumn(schema);
colvarCorrelationID.ColumnName = "CorrelationID";
colvarCorrelationID.DataType = DbType.Guid;
colvarCorrelationID.MaxLength = 0;
colvarCorrelationID.AutoIncrement = false;
colvarCorrelationID.IsNullable = true;
colvarCorrelationID.IsPrimaryKey = false;
colvarCorrelationID.IsForeignKey = false;
colvarCorrelationID.IsReadOnly = false;
colvarCorrelationID.DefaultSetting = @"";
colvarCorrelationID.ForeignKeyTableName = "";
schema.Columns.Add(colvarCorrelationID);
TableSchema.TableColumn colvarUserId = new TableSchema.TableColumn(schema);
colvarUserId.ColumnName = "UserId";
colvarUserId.DataType = DbType.Guid;
colvarUserId.MaxLength = 0;
colvarUserId.AutoIncrement = false;
colvarUserId.IsNullable = false;
colvarUserId.IsPrimaryKey = false;
colvarUserId.IsForeignKey = true;
colvarUserId.IsReadOnly = false;
colvarUserId.DefaultSetting = @"";
colvarUserId.ForeignKeyTableName = "aspnet_Users";
schema.Columns.Add(colvarUserId);
TableSchema.TableColumn colvarAddedDate = new TableSchema.TableColumn(schema);
colvarAddedDate.ColumnName = "AddedDate";
colvarAddedDate.DataType = DbType.DateTime;
colvarAddedDate.MaxLength = 0;
colvarAddedDate.AutoIncrement = false;
colvarAddedDate.IsNullable = false;
colvarAddedDate.IsPrimaryKey = false;
colvarAddedDate.IsForeignKey = false;
colvarAddedDate.IsReadOnly = false;
colvarAddedDate.DefaultSetting = @"(getdate())";
colvarAddedDate.ForeignKeyTableName = "";
schema.Columns.Add(colvarAddedDate);
TableSchema.TableColumn colvarAddedAt = new TableSchema.TableColumn(schema);
colvarAddedAt.ColumnName = "AddedAt";
colvarAddedAt.DataType = DbType.DateTime;
colvarAddedAt.MaxLength = 0;
colvarAddedAt.AutoIncrement = false;
colvarAddedAt.IsNullable = true;
colvarAddedAt.IsPrimaryKey = false;
colvarAddedAt.IsForeignKey = false;
colvarAddedAt.IsReadOnly = false;
colvarAddedAt.DefaultSetting = @"(getdate())";
colvarAddedAt.ForeignKeyTableName = "";
schema.Columns.Add(colvarAddedAt);
TableSchema.TableColumn colvarUpdatedAt = new TableSchema.TableColumn(schema);
colvarUpdatedAt.ColumnName = "UpdatedAt";
colvarUpdatedAt.DataType = DbType.DateTime;
colvarUpdatedAt.MaxLength = 0;
colvarUpdatedAt.AutoIncrement = false;
colvarUpdatedAt.IsNullable = true;
colvarUpdatedAt.IsPrimaryKey = false;
colvarUpdatedAt.IsForeignKey = false;
colvarUpdatedAt.IsReadOnly = false;
colvarUpdatedAt.DefaultSetting = @"(getdate())";
colvarUpdatedAt.ForeignKeyTableName = "";
schema.Columns.Add(colvarUpdatedAt);
TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema);
colvarId.ColumnName = "ID";
colvarId.DataType = DbType.Int32;
colvarId.MaxLength = 0;
colvarId.AutoIncrement = true;
colvarId.IsNullable = false;
colvarId.IsPrimaryKey = true;
colvarId.IsForeignKey = false;
colvarId.IsReadOnly = false;
colvarId.DefaultSetting = @"";
colvarId.ForeignKeyTableName = "";
schema.Columns.Add(colvarId);
TableSchema.TableColumn colvarRowVersion = new TableSchema.TableColumn(schema);
colvarRowVersion.ColumnName = "RowVersion";
colvarRowVersion.DataType = DbType.Binary;
colvarRowVersion.MaxLength = 0;
colvarRowVersion.AutoIncrement = false;
colvarRowVersion.IsNullable = false;
colvarRowVersion.IsPrimaryKey = false;
colvarRowVersion.IsForeignKey = false;
colvarRowVersion.IsReadOnly = true;
colvarRowVersion.DefaultSetting = @"";
colvarRowVersion.ForeignKeyTableName = "";
schema.Columns.Add(colvarRowVersion);
TableSchema.TableColumn colvarTextValue = new TableSchema.TableColumn(schema);
colvarTextValue.ColumnName = "TextValue";
colvarTextValue.DataType = DbType.AnsiString;
colvarTextValue.MaxLength = 10;
colvarTextValue.AutoIncrement = false;
colvarTextValue.IsNullable = true;
colvarTextValue.IsPrimaryKey = false;
colvarTextValue.IsForeignKey = false;
colvarTextValue.IsReadOnly = false;
colvarTextValue.DefaultSetting = @"";
colvarTextValue.ForeignKeyTableName = "";
schema.Columns.Add(colvarTextValue);
TableSchema.TableColumn colvarElevation = new TableSchema.TableColumn(schema);
colvarElevation.ColumnName = "Elevation";
colvarElevation.DataType = DbType.Double;
colvarElevation.MaxLength = 0;
colvarElevation.AutoIncrement = false;
colvarElevation.IsNullable = true;
colvarElevation.IsPrimaryKey = false;
colvarElevation.IsForeignKey = false;
colvarElevation.IsReadOnly = false;
colvarElevation.DefaultSetting = @"";
colvarElevation.ForeignKeyTableName = "";
schema.Columns.Add(colvarElevation);
TableSchema.TableColumn colvarLatitude = new TableSchema.TableColumn(schema);
colvarLatitude.ColumnName = "Latitude";
colvarLatitude.DataType = DbType.Double;
colvarLatitude.MaxLength = 0;
colvarLatitude.AutoIncrement = false;
colvarLatitude.IsNullable = true;
colvarLatitude.IsPrimaryKey = false;
colvarLatitude.IsForeignKey = false;
colvarLatitude.IsReadOnly = false;
colvarLatitude.DefaultSetting = @"";
colvarLatitude.ForeignKeyTableName = "";
schema.Columns.Add(colvarLatitude);
TableSchema.TableColumn colvarLongitude = new TableSchema.TableColumn(schema);
colvarLongitude.ColumnName = "Longitude";
colvarLongitude.DataType = DbType.Double;
colvarLongitude.MaxLength = 0;
colvarLongitude.AutoIncrement = false;
colvarLongitude.IsNullable = true;
colvarLongitude.IsPrimaryKey = false;
colvarLongitude.IsForeignKey = false;
colvarLongitude.IsReadOnly = false;
colvarLongitude.DefaultSetting = @"";
colvarLongitude.ForeignKeyTableName = "";
schema.Columns.Add(colvarLongitude);
TableSchema.TableColumn colvarValueDay = new TableSchema.TableColumn(schema);
colvarValueDay.ColumnName = "ValueDay";
colvarValueDay.DataType = DbType.Date;
colvarValueDay.MaxLength = 0;
colvarValueDay.AutoIncrement = false;
colvarValueDay.IsNullable = true;
colvarValueDay.IsPrimaryKey = false;
colvarValueDay.IsForeignKey = false;
colvarValueDay.IsReadOnly = true;
colvarValueDay.DefaultSetting = @"";
colvarValueDay.ForeignKeyTableName = "";
schema.Columns.Add(colvarValueDay);
TableSchema.TableColumn colvarValueYear = new TableSchema.TableColumn(schema);
colvarValueYear.ColumnName = "ValueYear";
colvarValueYear.DataType = DbType.Int32;
colvarValueYear.MaxLength = 0;
colvarValueYear.AutoIncrement = false;
colvarValueYear.IsNullable = true;
colvarValueYear.IsPrimaryKey = false;
colvarValueYear.IsForeignKey = false;
colvarValueYear.IsReadOnly = true;
colvarValueYear.DefaultSetting = @"";
colvarValueYear.ForeignKeyTableName = "";
schema.Columns.Add(colvarValueYear);
TableSchema.TableColumn colvarValueDecade = new TableSchema.TableColumn(schema);
colvarValueDecade.ColumnName = "ValueDecade";
colvarValueDecade.DataType = DbType.Int32;
colvarValueDecade.MaxLength = 0;
colvarValueDecade.AutoIncrement = false;
colvarValueDecade.IsNullable = true;
colvarValueDecade.IsPrimaryKey = false;
colvarValueDecade.IsForeignKey = false;
colvarValueDecade.IsReadOnly = true;
colvarValueDecade.DefaultSetting = @"";
colvarValueDecade.ForeignKeyTableName = "";
schema.Columns.Add(colvarValueDecade);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["ObservationsDB"].AddSchema("Observation",schema);
}
}
#endregion
#region Props
[XmlAttribute("SensorID")]
[Bindable(true)]
public Guid SensorID
{
get { return GetColumnValue<Guid>(Columns.SensorID); }
set { SetColumnValue(Columns.SensorID, value); }
}
[XmlAttribute("ValueDate")]
[Bindable(true)]
public DateTime ValueDate
{
get { return GetColumnValue<DateTime>(Columns.ValueDate); }
set { SetColumnValue(Columns.ValueDate, value); }
}
[XmlAttribute("RawValue")]
[Bindable(true)]
public double? RawValue
{
get { return GetColumnValue<double?>(Columns.RawValue); }
set { SetColumnValue(Columns.RawValue, value); }
}
[XmlAttribute("DataValue")]
[Bindable(true)]
public double? DataValue
{
get { return GetColumnValue<double?>(Columns.DataValue); }
set { SetColumnValue(Columns.DataValue, value); }
}
[XmlAttribute("Comment")]
[Bindable(true)]
public string Comment
{
get { return GetColumnValue<string>(Columns.Comment); }
set { SetColumnValue(Columns.Comment, value); }
}
[XmlAttribute("PhenomenonOfferingID")]
[Bindable(true)]
public Guid PhenomenonOfferingID
{
get { return GetColumnValue<Guid>(Columns.PhenomenonOfferingID); }
set { SetColumnValue(Columns.PhenomenonOfferingID, value); }
}
[XmlAttribute("PhenomenonUOMID")]
[Bindable(true)]
public Guid PhenomenonUOMID
{
get { return GetColumnValue<Guid>(Columns.PhenomenonUOMID); }
set { SetColumnValue(Columns.PhenomenonUOMID, value); }
}
[XmlAttribute("ImportBatchID")]
[Bindable(true)]
public Guid ImportBatchID
{
get { return GetColumnValue<Guid>(Columns.ImportBatchID); }
set { SetColumnValue(Columns.ImportBatchID, value); }
}
[XmlAttribute("StatusID")]
[Bindable(true)]
public Guid? StatusID
{
get { return GetColumnValue<Guid?>(Columns.StatusID); }
set { SetColumnValue(Columns.StatusID, value); }
}
[XmlAttribute("StatusReasonID")]
[Bindable(true)]
public Guid? StatusReasonID
{
get { return GetColumnValue<Guid?>(Columns.StatusReasonID); }
set { SetColumnValue(Columns.StatusReasonID, value); }
}
[XmlAttribute("CorrelationID")]
[Bindable(true)]
public Guid? CorrelationID
{
get { return GetColumnValue<Guid?>(Columns.CorrelationID); }
set { SetColumnValue(Columns.CorrelationID, value); }
}
[XmlAttribute("UserId")]
[Bindable(true)]
public Guid UserId
{
get { return GetColumnValue<Guid>(Columns.UserId); }
set { SetColumnValue(Columns.UserId, value); }
}
[XmlAttribute("AddedDate")]
[Bindable(true)]
public DateTime AddedDate
{
get { return GetColumnValue<DateTime>(Columns.AddedDate); }
set { SetColumnValue(Columns.AddedDate, value); }
}
[XmlAttribute("AddedAt")]
[Bindable(true)]
public DateTime? AddedAt
{
get { return GetColumnValue<DateTime?>(Columns.AddedAt); }
set { SetColumnValue(Columns.AddedAt, value); }
}
[XmlAttribute("UpdatedAt")]
[Bindable(true)]
public DateTime? UpdatedAt
{
get { return GetColumnValue<DateTime?>(Columns.UpdatedAt); }
set { SetColumnValue(Columns.UpdatedAt, value); }
}
[XmlAttribute("Id")]
[Bindable(true)]
public int Id
{
get { return GetColumnValue<int>(Columns.Id); }
set { SetColumnValue(Columns.Id, value); }
}
[XmlAttribute("RowVersion")]
[Bindable(true)]
public byte[] RowVersion
{
get { return GetColumnValue<byte[]>(Columns.RowVersion); }
set { SetColumnValue(Columns.RowVersion, value); }
}
[XmlAttribute("TextValue")]
[Bindable(true)]
public string TextValue
{
get { return GetColumnValue<string>(Columns.TextValue); }
set { SetColumnValue(Columns.TextValue, value); }
}
[XmlAttribute("Elevation")]
[Bindable(true)]
public double? Elevation
{
get { return GetColumnValue<double?>(Columns.Elevation); }
set { SetColumnValue(Columns.Elevation, value); }
}
[XmlAttribute("Latitude")]
[Bindable(true)]
public double? Latitude
{
get { return GetColumnValue<double?>(Columns.Latitude); }
set { SetColumnValue(Columns.Latitude, value); }
}
[XmlAttribute("Longitude")]
[Bindable(true)]
public double? Longitude
{
get { return GetColumnValue<double?>(Columns.Longitude); }
set { SetColumnValue(Columns.Longitude, value); }
}
[XmlAttribute("ValueDay")]
[Bindable(true)]
public DateTime? ValueDay
{
get { return GetColumnValue<DateTime?>(Columns.ValueDay); }
set { SetColumnValue(Columns.ValueDay, value); }
}
[XmlAttribute("ValueYear")]
[Bindable(true)]
public int? ValueYear
{
get { return GetColumnValue<int?>(Columns.ValueYear); }
set { SetColumnValue(Columns.ValueYear, value); }
}
[XmlAttribute("ValueDecade")]
[Bindable(true)]
public int? ValueDecade
{
get { return GetColumnValue<int?>(Columns.ValueDecade); }
set { SetColumnValue(Columns.ValueDecade, value); }
}
#endregion
#region ForeignKey Properties
private SAEON.Observations.Data.AspnetUser _AspnetUser = null;
/// <summary>
/// Returns a AspnetUser ActiveRecord object related to this Observation
///
/// </summary>
public SAEON.Observations.Data.AspnetUser AspnetUser
{
// get { return SAEON.Observations.Data.AspnetUser.FetchByID(this.UserId); }
get { return _AspnetUser ?? (_AspnetUser = SAEON.Observations.Data.AspnetUser.FetchByID(this.UserId)); }
set { SetColumnValue("UserId", value.UserId); }
}
private SAEON.Observations.Data.ImportBatch _ImportBatch = null;
/// <summary>
/// Returns a ImportBatch ActiveRecord object related to this Observation
///
/// </summary>
public SAEON.Observations.Data.ImportBatch ImportBatch
{
// get { return SAEON.Observations.Data.ImportBatch.FetchByID(this.ImportBatchID); }
get { return _ImportBatch ?? (_ImportBatch = SAEON.Observations.Data.ImportBatch.FetchByID(this.ImportBatchID)); }
set { SetColumnValue("ImportBatchID", value.Id); }
}
private SAEON.Observations.Data.PhenomenonOffering _PhenomenonOffering = null;
/// <summary>
/// Returns a PhenomenonOffering ActiveRecord object related to this Observation
///
/// </summary>
public SAEON.Observations.Data.PhenomenonOffering PhenomenonOffering
{
// get { return SAEON.Observations.Data.PhenomenonOffering.FetchByID(this.PhenomenonOfferingID); }
get { return _PhenomenonOffering ?? (_PhenomenonOffering = SAEON.Observations.Data.PhenomenonOffering.FetchByID(this.PhenomenonOfferingID)); }
set { SetColumnValue("PhenomenonOfferingID", value.Id); }
}
private SAEON.Observations.Data.PhenomenonUOM _PhenomenonUOM = null;
/// <summary>
/// Returns a PhenomenonUOM ActiveRecord object related to this Observation
///
/// </summary>
public SAEON.Observations.Data.PhenomenonUOM PhenomenonUOM
{
// get { return SAEON.Observations.Data.PhenomenonUOM.FetchByID(this.PhenomenonUOMID); }
get { return _PhenomenonUOM ?? (_PhenomenonUOM = SAEON.Observations.Data.PhenomenonUOM.FetchByID(this.PhenomenonUOMID)); }
set { SetColumnValue("PhenomenonUOMID", value.Id); }
}
private SAEON.Observations.Data.Sensor _Sensor = null;
/// <summary>
/// Returns a Sensor ActiveRecord object related to this Observation
///
/// </summary>
public SAEON.Observations.Data.Sensor Sensor
{
// get { return SAEON.Observations.Data.Sensor.FetchByID(this.SensorID); }
get { return _Sensor ?? (_Sensor = SAEON.Observations.Data.Sensor.FetchByID(this.SensorID)); }
set { SetColumnValue("SensorID", value.Id); }
}
private SAEON.Observations.Data.Status _Status = null;
/// <summary>
/// Returns a Status ActiveRecord object related to this Observation
///
/// </summary>
public SAEON.Observations.Data.Status Status
{
// get { return SAEON.Observations.Data.Status.FetchByID(this.StatusID); }
get { return _Status ?? (_Status = SAEON.Observations.Data.Status.FetchByID(this.StatusID)); }
set { SetColumnValue("StatusID", value.Id); }
}
private SAEON.Observations.Data.StatusReason _StatusReason = null;
/// <summary>
/// Returns a StatusReason ActiveRecord object related to this Observation
///
/// </summary>
public SAEON.Observations.Data.StatusReason StatusReason
{
// get { return SAEON.Observations.Data.StatusReason.FetchByID(this.StatusReasonID); }
get { return _StatusReason ?? (_StatusReason = SAEON.Observations.Data.StatusReason.FetchByID(this.StatusReasonID)); }
set { SetColumnValue("StatusReasonID", value.Id); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(Guid varSensorID,DateTime varValueDate,double? varRawValue,double? varDataValue,string varComment,Guid varPhenomenonOfferingID,Guid varPhenomenonUOMID,Guid varImportBatchID,Guid? varStatusID,Guid? varStatusReasonID,Guid? varCorrelationID,Guid varUserId,DateTime varAddedDate,DateTime? varAddedAt,DateTime? varUpdatedAt,byte[] varRowVersion,string varTextValue,double? varElevation,double? varLatitude,double? varLongitude,DateTime? varValueDay,int? varValueYear,int? varValueDecade)
{
Observation item = new Observation();
item.SensorID = varSensorID;
item.ValueDate = varValueDate;
item.RawValue = varRawValue;
item.DataValue = varDataValue;
item.Comment = varComment;
item.PhenomenonOfferingID = varPhenomenonOfferingID;
item.PhenomenonUOMID = varPhenomenonUOMID;
item.ImportBatchID = varImportBatchID;
item.StatusID = varStatusID;
item.StatusReasonID = varStatusReasonID;
item.CorrelationID = varCorrelationID;
item.UserId = varUserId;
item.AddedDate = varAddedDate;
item.AddedAt = varAddedAt;
item.UpdatedAt = varUpdatedAt;
item.RowVersion = varRowVersion;
item.TextValue = varTextValue;
item.Elevation = varElevation;
item.Latitude = varLatitude;
item.Longitude = varLongitude;
item.ValueDay = varValueDay;
item.ValueYear = varValueYear;
item.ValueDecade = varValueDecade;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(Guid varSensorID,DateTime varValueDate,double? varRawValue,double? varDataValue,string varComment,Guid varPhenomenonOfferingID,Guid varPhenomenonUOMID,Guid varImportBatchID,Guid? varStatusID,Guid? varStatusReasonID,Guid? varCorrelationID,Guid varUserId,DateTime varAddedDate,DateTime? varAddedAt,DateTime? varUpdatedAt,int varId,byte[] varRowVersion,string varTextValue,double? varElevation,double? varLatitude,double? varLongitude,DateTime? varValueDay,int? varValueYear,int? varValueDecade)
{
Observation item = new Observation();
item.SensorID = varSensorID;
item.ValueDate = varValueDate;
item.RawValue = varRawValue;
item.DataValue = varDataValue;
item.Comment = varComment;
item.PhenomenonOfferingID = varPhenomenonOfferingID;
item.PhenomenonUOMID = varPhenomenonUOMID;
item.ImportBatchID = varImportBatchID;
item.StatusID = varStatusID;
item.StatusReasonID = varStatusReasonID;
item.CorrelationID = varCorrelationID;
item.UserId = varUserId;
item.AddedDate = varAddedDate;
item.AddedAt = varAddedAt;
item.UpdatedAt = varUpdatedAt;
item.Id = varId;
item.RowVersion = varRowVersion;
item.TextValue = varTextValue;
item.Elevation = varElevation;
item.Latitude = varLatitude;
item.Longitude = varLongitude;
item.ValueDay = varValueDay;
item.ValueYear = varValueYear;
item.ValueDecade = varValueDecade;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn SensorIDColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn ValueDateColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn RawValueColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn DataValueColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn CommentColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn PhenomenonOfferingIDColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn PhenomenonUOMIDColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn ImportBatchIDColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn StatusIDColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn StatusReasonIDColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn CorrelationIDColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn UserIdColumn
{
get { return Schema.Columns[11]; }
}
public static TableSchema.TableColumn AddedDateColumn
{
get { return Schema.Columns[12]; }
}
public static TableSchema.TableColumn AddedAtColumn
{
get { return Schema.Columns[13]; }
}
public static TableSchema.TableColumn UpdatedAtColumn
{
get { return Schema.Columns[14]; }
}
public static TableSchema.TableColumn IdColumn
{
get { return Schema.Columns[15]; }
}
public static TableSchema.TableColumn RowVersionColumn
{
get { return Schema.Columns[16]; }
}
public static TableSchema.TableColumn TextValueColumn
{
get { return Schema.Columns[17]; }
}
public static TableSchema.TableColumn ElevationColumn
{
get { return Schema.Columns[18]; }
}
public static TableSchema.TableColumn LatitudeColumn
{
get { return Schema.Columns[19]; }
}
public static TableSchema.TableColumn LongitudeColumn
{
get { return Schema.Columns[20]; }
}
public static TableSchema.TableColumn ValueDayColumn
{
get { return Schema.Columns[21]; }
}
public static TableSchema.TableColumn ValueYearColumn
{
get { return Schema.Columns[22]; }
}
public static TableSchema.TableColumn ValueDecadeColumn
{
get { return Schema.Columns[23]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string SensorID = @"SensorID";
public static string ValueDate = @"ValueDate";
public static string RawValue = @"RawValue";
public static string DataValue = @"DataValue";
public static string Comment = @"Comment";
public static string PhenomenonOfferingID = @"PhenomenonOfferingID";
public static string PhenomenonUOMID = @"PhenomenonUOMID";
public static string ImportBatchID = @"ImportBatchID";
public static string StatusID = @"StatusID";
public static string StatusReasonID = @"StatusReasonID";
public static string CorrelationID = @"CorrelationID";
public static string UserId = @"UserId";
public static string AddedDate = @"AddedDate";
public static string AddedAt = @"AddedAt";
public static string UpdatedAt = @"UpdatedAt";
public static string Id = @"ID";
public static string RowVersion = @"RowVersion";
public static string TextValue = @"TextValue";
public static string Elevation = @"Elevation";
public static string Latitude = @"Latitude";
public static string Longitude = @"Longitude";
public static string ValueDay = @"ValueDay";
public static string ValueYear = @"ValueYear";
public static string ValueDecade = @"ValueDecade";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
/*
* 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;
using OpenSim.Region.ScriptEngine.Interfaces;
using key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
using vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
namespace OpenSim.Region.ScriptEngine.Shared.Api.Interfaces
{
/// <summary>
/// To permit region owners to enable the extended scripting functionality
/// of OSSL, without allowing malicious scripts to access potentially
/// troublesome functions, each OSSL function is assigned a threat level,
/// and access to the functions is granted or denied based on a default
/// threshold set in OpenSim.ini (which can be overridden for individual
/// functions on a case-by-case basis)
/// </summary>
public enum ThreatLevel
{
// Not documented, presumably means permanently disabled ?
NoAccess = -1,
/// <summary>
/// Function is no threat at all. It doesn't constitute a threat to
/// either users or the system and has no known side effects.
/// </summary>
None = 0,
/// <summary>
/// Abuse of this command can cause a nuisance to the region operator,
/// such as log message spew.
/// </summary>
Nuisance = 1,
/// <summary>
/// Extreme levels of abuse of this function can cause impaired
/// functioning of the region, or very gullible users can be tricked
/// into experiencing harmless effects.
/// </summary>
VeryLow = 2,
/// <summary>
/// Intentional abuse can cause crashes or malfunction under certain
/// circumstances, which can be easily rectified; or certain users can
/// be tricked into certain situations in an avoidable manner.
/// </summary>
Low = 3,
/// <summary>
/// Intentional abuse can cause denial of service and crashes with
/// potential of data or state loss; or trusting users can be tricked
/// into embarrassing or uncomfortable situations.
/// </summary>
Moderate = 4,
/// <summary>
/// Casual abuse can cause impaired functionality or temporary denial
/// of service conditions. Intentional abuse can easily cause crashes
/// with potential data loss, or can be used to trick experienced and
/// cautious users into unwanted situations, or changes global data
/// permanently and without undo ability.
/// </summary>
High = 5,
/// <summary>
/// Even normal use may, depending on the number of instances, or
/// frequency of use, result in severe service impairment or crash
/// with loss of data, or can be used to cause unwanted or harmful
/// effects on users without giving the user a means to avoid it.
/// </summary>
VeryHigh = 6,
/// <summary>
/// Even casual use is a danger to region stability, or function allows
/// console or OS command execution, or function allows taking money
/// without consent, or allows deletion or modification of user data,
/// or allows the compromise of sensitive data by design.
/// </summary>
Severe = 7
};
public interface IOSSL_Api
{
void CheckThreatLevel(ThreatLevel level, string function);
//OpenSim functions
string osSetDynamicTextureURL(string dynamicID, string contentType, string url, string extraParams, int timer);
string osSetDynamicTextureURLBlend(string dynamicID, string contentType, string url, string extraParams,
int timer, int alpha);
string osSetDynamicTextureURLBlendFace(string dynamicID, string contentType, string url, string extraParams,
bool blend, int disp, int timer, int alpha, int face);
string osSetDynamicTextureData(string dynamicID, string contentType, string data, string extraParams, int timer);
string osSetDynamicTextureDataBlend(string dynamicID, string contentType, string data, string extraParams,
int timer, int alpha);
string osSetDynamicTextureDataBlendFace(string dynamicID, string contentType, string data, string extraParams,
bool blend, int disp, int timer, int alpha, int face);
LSL_Float osGetTerrainHeight(int x, int y);
LSL_Float osTerrainGetHeight(int x, int y); // Deprecated
LSL_Integer osSetTerrainHeight(int x, int y, double val);
LSL_Integer osTerrainSetHeight(int x, int y, double val); //Deprecated
void osTerrainFlush();
int osRegionRestart(double seconds);
int osRegionRestart(double seconds, string msg);
void osRegionNotice(string msg);
bool osConsoleCommand(string Command);
void osSetParcelMediaURL(string url);
void osSetPrimFloatOnWater(int floatYN);
void osSetParcelSIPAddress(string SIPAddress);
// Avatar Info Commands
string osGetAgentIP(string agent);
LSL_List osGetAgents();
// Teleport commands
void osTeleportAgent(string agent, string regionName, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat);
void osTeleportAgent(string agent, int regionX, int regionY, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat);
void osTeleportAgent(string agent, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat);
void osTeleportOwner(string regionName, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat);
void osTeleportOwner(int regionX, int regionY, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat);
void osTeleportOwner(LSL_Types.Vector3 position, LSL_Types.Vector3 lookat);
// Animation commands
void osAvatarPlayAnimation(string avatar, string animation);
void osAvatarStopAnimation(string avatar, string animation);
#region Attachment commands
/// <summary>
/// Attach the object containing this script to the avatar that owns it without asking for PERMISSION_ATTACH
/// </summary>
/// <param name='attachment'>The attachment point. For example, ATTACH_CHEST</param>
void osForceAttachToAvatar(int attachment);
/// <summary>
/// Attach an inventory item in the object containing this script to the avatar that owns it without asking for PERMISSION_ATTACH
/// </summary>
/// <remarks>
/// Nothing happens if the owner is not in the region.
/// </remarks>
/// <param name='itemName'>Tha name of the item. If this is not found then a warning is said to the owner</param>
/// <param name='attachment'>The attachment point. For example, ATTACH_CHEST</param>
void osForceAttachToAvatarFromInventory(string itemName, int attachment);
/// <summary>
/// Attach an inventory item in the object containing this script to any avatar in the region without asking for PERMISSION_ATTACH
/// </summary>
/// <remarks>
/// Nothing happens if the avatar is not in the region.
/// </remarks>
/// <param name='rawAvatarId'>The UUID of the avatar to which to attach. Nothing happens if this is not a UUID</para>
/// <param name='itemName'>The name of the item. If this is not found then a warning is said to the owner</param>
/// <param name='attachment'>The attachment point. For example, ATTACH_CHEST</param>
void osForceAttachToOtherAvatarFromInventory(string rawAvatarId, string itemName, int attachmentPoint);
/// <summary>
/// Detach the object containing this script from the avatar it is attached to without checking for PERMISSION_ATTACH
/// </summary>
/// <remarks>Nothing happens if the object is not attached.</remarks>
void osForceDetachFromAvatar();
/// <summary>
/// Returns a strided list of the specified attachment points and the number of attachments on those points.
/// </summary>
/// <param name="avatar">avatar UUID</param>
/// <param name="attachmentPoints">list of ATTACH_* constants</param>
/// <returns></returns>
LSL_List osGetNumberOfAttachments(LSL_Key avatar, LSL_List attachmentPoints);
/// <summary>
/// Sends a specified message to the specified avatar's attachments on
/// the specified attachment points.
/// </summary>
/// <remarks>
/// Behaves as osMessageObject(), without the sending script needing to know the attachment keys in advance.
/// </remarks>
/// <param name="avatar">avatar UUID</param>
/// <param name="message">message string</param>
/// <param name="attachmentPoints">list of ATTACH_* constants, or -1 for all attachments. If -1 is specified and OS_ATTACH_MSG_INVERT_POINTS is present in flags, no action is taken.</param>
/// <param name="flags">flags further constraining the attachments to deliver the message to.</param>
void osMessageAttachments(LSL_Key avatar, string message, LSL_List attachmentPoints, int flags);
#endregion
//texture draw functions
string osMovePen(string drawList, int x, int y);
string osDrawLine(string drawList, int startX, int startY, int endX, int endY);
string osDrawLine(string drawList, int endX, int endY);
string osDrawText(string drawList, string text);
string osDrawEllipse(string drawList, int width, int height);
string osDrawRectangle(string drawList, int width, int height);
string osDrawFilledRectangle(string drawList, int width, int height);
string osDrawPolygon(string drawList, LSL_List x, LSL_List y);
string osDrawFilledPolygon(string drawList, LSL_List x, LSL_List y);
string osSetFontName(string drawList, string fontName);
string osSetFontSize(string drawList, int fontSize);
string osSetPenSize(string drawList, int penSize);
string osSetPenColor(string drawList, string color);
string osSetPenColour(string drawList, string colour); // Deprecated
string osSetPenCap(string drawList, string direction, string type);
string osDrawImage(string drawList, int width, int height, string imageUrl);
vector osGetDrawStringSize(string contentType, string text, string fontName, int fontSize);
void osSetStateEvents(int events);
double osList2Double(LSL_Types.list src, int index);
void osSetRegionWaterHeight(double height);
void osSetRegionSunSettings(bool useEstateSun, bool sunFixed, double sunHour);
void osSetEstateSunSettings(bool sunFixed, double sunHour);
double osGetCurrentSunHour();
double osGetSunParam(string param);
double osSunGetParam(string param); // Deprecated
void osSetSunParam(string param, double value);
void osSunSetParam(string param, double value); // Deprecated
// Wind Module Functions
string osWindActiveModelPluginName();
void osSetWindParam(string plugin, string param, LSL_Float value);
LSL_Float osGetWindParam(string plugin, string param);
// Parcel commands
void osParcelJoin(vector pos1, vector pos2);
void osParcelSubdivide(vector pos1, vector pos2);
void osSetParcelDetails(vector pos, LSL_List rules);
void osParcelSetDetails(vector pos, LSL_List rules); // Deprecated
string osGetScriptEngineName();
string osGetSimulatorVersion();
LSL_Integer osCheckODE();
string osGetPhysicsEngineType();
string osGetPhysicsEngineName();
Object osParseJSONNew(string JSON);
Hashtable osParseJSON(string JSON);
void osMessageObject(key objectUUID,string message);
void osMakeNotecard(string notecardName, LSL_Types.list contents);
string osGetNotecardLine(string name, int line);
string osGetNotecard(string name);
int osGetNumberOfNotecardLines(string name);
string osAvatarName2Key(string firstname, string lastname);
string osKey2Name(string id);
// Grid Info Functions
string osGetGridNick();
string osGetGridName();
string osGetGridLoginURI();
string osGetGridHomeURI();
string osGetGridGatekeeperURI();
string osGetGridCustom(string key);
string osGetAvatarHomeURI(string uuid);
LSL_String osFormatString(string str, LSL_List strings);
LSL_List osMatchString(string src, string pattern, int start);
LSL_String osReplaceString(string src, string pattern, string replace, int count, int start);
// Information about data loaded into the region
string osLoadedCreationDate();
string osLoadedCreationTime();
string osLoadedCreationID();
LSL_List osGetLinkPrimitiveParams(int linknumber, LSL_List rules);
/// <summary>
/// Identical to llCreateLink() but does not require permission from the owner.
/// </summary>
/// <param name='target'></param>
/// <param name='parent'></param>
void osForceCreateLink(string target, int parent);
/// <summary>
/// Identical to llBreakLink() but does not require permission from the owner.
/// </summary>
/// <param name='linknum'></param>
void osForceBreakLink(int linknum);
/// <summary>
/// Identical to llBreakAllLinks() but does not require permission from the owner.
/// </summary>
void osForceBreakAllLinks();
/// <summary>
/// Similar to llDie but given an object UUID
/// </summary>
/// <param name="objectUUID"></param>
void osDie(LSL_Key objectUUID);
/// <summary>
/// Check if the given key is an npc
/// </summary>
/// <param name="npc"></param>
/// <returns>TRUE if the key belongs to an npc in the scene. FALSE otherwise.</returns>
LSL_Integer osIsNpc(LSL_Key npc);
key osNpcCreate(string user, string name, vector position, string notecard);
key osNpcCreate(string user, string name, vector position, string notecard, int options);
LSL_Key osNpcSaveAppearance(key npc, string notecard);
void osNpcLoadAppearance(key npc, string notecard);
vector osNpcGetPos(key npc);
void osNpcMoveTo(key npc, vector position);
void osNpcMoveToTarget(key npc, vector target, int options);
/// <summary>
/// Get the owner of the NPC
/// </summary>
/// <param name="npc"></param>
/// <returns>
/// The owner of the NPC for an owned NPC. The NPC's agent id for an unowned NPC. UUID.Zero if the key is not an npc.
/// </returns>
LSL_Key osNpcGetOwner(key npc);
rotation osNpcGetRot(key npc);
void osNpcSetRot(LSL_Key npc, rotation rot);
void osNpcStopMoveToTarget(LSL_Key npc);
void osNpcSetProfileAbout(LSL_Key npc, string about);
void osNpcSetProfileImage(LSL_Key npc, string image);
void osNpcSay(key npc, string message);
void osNpcSay(key npc, int channel, string message);
void osNpcShout(key npc, int channel, string message);
void osNpcSit(key npc, key target, int options);
void osNpcStand(LSL_Key npc);
void osNpcRemove(key npc);
void osNpcPlayAnimation(LSL_Key npc, string animation);
void osNpcStopAnimation(LSL_Key npc, string animation);
void osNpcTouch(LSL_Key npcLSL_Key, LSL_Key object_key, LSL_Integer link_num);
void osNpcWhisper(key npc, int channel, string message);
LSL_Key osOwnerSaveAppearance(string notecard);
LSL_Key osAgentSaveAppearance(key agentId, string notecard);
key osGetGender(LSL_Key rawAvatarId);
key osGetMapTexture();
key osGetRegionMapTexture(string regionName);
LSL_List osGetRegionStats();
vector osGetRegionSize();
int osGetSimulatorMemory();
void osKickAvatar(string FirstName,string SurName,string alert);
void osSetSpeed(string UUID, LSL_Float SpeedModifier);
LSL_Float osGetHealth(string avatar);
void osCauseHealing(string avatar, double healing);
void osSetHealth(string avatar, double health);
void osSetHealRate(string avatar, double health);
LSL_Float osGetHealRate(string avatar);
void osCauseDamage(string avatar, double damage);
void osForceOtherSit(string avatar);
void osForceOtherSit(string avatar, string target);
LSL_List osGetPrimitiveParams(LSL_Key prim, LSL_List rules);
void osSetPrimitiveParams(LSL_Key prim, LSL_List rules);
void osSetProjectionParams(bool projection, LSL_Key texture, double fov, double focus, double amb);
void osSetProjectionParams(LSL_Key prim, bool projection, LSL_Key texture, double fov, double focus, double amb);
LSL_List osGetAvatarList();
LSL_String osUnixTimeToTimestamp(long time);
LSL_String osGetInventoryDesc(string item);
LSL_Integer osInviteToGroup(LSL_Key agentId);
LSL_Integer osEjectFromGroup(LSL_Key agentId);
void osSetTerrainTexture(int level, LSL_Key texture);
void osSetTerrainTextureHeight(int corner, double low, double high);
/// <summary>
/// Checks if thing is a UUID.
/// </summary>
/// <param name="thing"></param>
/// <returns>1 if thing is a valid UUID, 0 otherwise</returns>
LSL_Integer osIsUUID(string thing);
/// <summary>
/// Wraps to Math.Min()
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
LSL_Float osMin(double a, double b);
/// <summary>
/// Wraps to Math.max()
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
LSL_Float osMax(double a, double b);
/// <summary>
/// Get the key of the object that rezzed this object.
/// </summary>
/// <returns>Rezzing object key or NULL_KEY if rezzed by agent or otherwise unknown.</returns>
LSL_Key osGetRezzingObject();
/// <summary>
/// Sets the response type for an HTTP request/response
/// </summary>
/// <returns></returns>
void osSetContentType(LSL_Key id, string type);
/// <summary>
/// Attempts to drop an attachment to the ground
/// </summary>
void osDropAttachment();
/// <summary>
/// Attempts to drop an attachment to the ground while bypassing the script permissions
/// </summary>
void osForceDropAttachment();
/// <summary>
/// Attempts to drop an attachment at the specified coordinates.
/// </summary>
/// <param name="pos"></param>
/// <param name="rot"></param>
void osDropAttachmentAt(vector pos, rotation rot);
/// <summary>
/// Attempts to drop an attachment at the specified coordinates while bypassing the script permissions
/// </summary>
/// <param name="pos"></param>
/// <param name="rot"></param>
void osForceDropAttachmentAt(vector pos, rotation rot);
/// <summary>
/// Identical to llListen except for a bitfield which indicates which
/// string parameters should be parsed as regex patterns.
/// </summary>
/// <param name="channelID"></param>
/// <param name="name"></param>
/// <param name="ID"></param>
/// <param name="msg"></param>
/// <param name="regexBitfield">
/// OS_LISTEN_REGEX_NAME
/// OS_LISTEN_REGEX_MESSAGE
/// </param>
/// <returns></returns>
LSL_Integer osListenRegex(int channelID, string name, string ID,
string msg, int regexBitfield);
/// <summary>
/// Wraps to bool Regex.IsMatch(string input, string pattern)
/// </summary>
/// <param name="input">string to test for match</param>
/// <param name="regex">string to use as pattern</param>
/// <returns>boolean</returns>
LSL_Integer osRegexIsMatch(string input, string pattern);
LSL_String osRequestURL(LSL_List options);
LSL_String osRequestSecureURL(LSL_List options);
void osCollisionSound(string impact_sound, double impact_volume);
void osVolumeDetect(int detect);
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Targets
{
#if !NET35
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using NLog.Config;
using NLog.Targets;
using Xunit;
public class AsyncTaskTargetTest : NLogTestBase
{
[Target("AsyncTaskTest")]
class AsyncTaskTestTarget : AsyncTaskTarget
{
private readonly AutoResetEvent _writeEvent = new AutoResetEvent(false);
internal readonly ConcurrentQueue<string> Logs = new ConcurrentQueue<string>();
internal int WriteTasks => _writeTasks;
protected int _writeTasks;
public Type RequiredDependency { get; set; }
public bool WaitForWriteEvent(int timeoutMilliseconds = 1000)
{
if (_writeEvent.WaitOne(TimeSpan.FromMilliseconds(timeoutMilliseconds)))
{
Thread.Sleep(25);
return true;
}
return false;
}
protected override void InitializeTarget()
{
base.InitializeTarget();
if (RequiredDependency != null)
{
try
{
var resolveServiceMethod = typeof(Target).GetMethod(nameof(ResolveService), System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
resolveServiceMethod = resolveServiceMethod.MakeGenericMethod(new[] { RequiredDependency });
resolveServiceMethod.Invoke(this, NLog.Internal.ArrayHelper.Empty<object>());
}
catch (System.Reflection.TargetInvocationException ex)
{
throw ex.InnerException;
}
}
}
protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken token)
{
Interlocked.Increment(ref _writeTasks);
return WriteLogQueue(logEvent, token);
}
protected async Task WriteLogQueue(LogEventInfo logEvent, CancellationToken token)
{
if (logEvent.Message == "EXCEPTION")
throw new InvalidOperationException("AsyncTaskTargetTest Failure");
else if (logEvent.Message == "ASYNCEXCEPTION")
await Task.Delay(10, token).ContinueWith((t) => { throw new InvalidOperationException("AsyncTaskTargetTest Async Failure"); }).ConfigureAwait(false);
else if (logEvent.Message == "TIMEOUT")
await Task.Delay(15000, token).ConfigureAwait(false);
else
{
if (logEvent.Message == "SLEEP")
Task.Delay(5000, token).GetAwaiter().GetResult();
await Task.Delay(10, token).ContinueWith((t) => Logs.Enqueue(RenderLogEvent(Layout, logEvent)), token).ContinueWith(async (t) => await Task.Delay(10).ConfigureAwait(false)).ConfigureAwait(false);
}
_writeEvent.Set();
}
}
class AsyncTaskBatchTestTarget : AsyncTaskTestTarget
{
protected override async Task WriteAsyncTask(IList<LogEventInfo> logEvents, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _writeTasks);
for (int i = 0; i < logEvents.Count; ++i)
await WriteLogQueue(logEvents[i], cancellationToken);
}
protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
}
class AsyncTaskBatchExceptionTestTarget : AsyncTaskTestTarget
{
public List<int> retryDelayLog = new List<int>();
protected override async Task WriteAsyncTask(IList<LogEventInfo> logEvents, CancellationToken cancellationToken)
{
await Task.Delay(50);
throw new Exception("Failed to write to message queue, or something");
}
protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
protected override bool RetryFailedAsyncTask(Exception exception, CancellationToken cancellationToken, int retryCountRemaining, out TimeSpan retryDelay)
{
var shouldRetry = base.RetryFailedAsyncTask(exception, cancellationToken, retryCountRemaining, out retryDelay);
retryDelayLog.Add((int)retryDelay.TotalMilliseconds);
return shouldRetry;
}
}
[Fact]
public void AsyncTaskTarget_TestLogging()
{
var asyncTarget = new AsyncTaskTestTarget { Layout = "${threadid}|${level}|${message}|${mdlc:item=Test}" };
var logger = new LogFactory().Setup().LoadConfiguration(builder =>
{
builder.ForLogger().WriteTo(asyncTarget);
}).GetCurrentClassLogger();
int managedThreadId = 0;
Task task;
using (ScopeContext.PushProperty("Test", 42))
{
task = Task.Run(() =>
{
managedThreadId = Thread.CurrentThread.ManagedThreadId;
logger.Trace("TTT");
logger.Debug("DDD");
logger.Info("III");
logger.Warn("WWW");
logger.Error("EEE");
logger.Fatal("FFF");
});
}
Assert.True(asyncTarget.WaitForWriteEvent());
Assert.NotEmpty(asyncTarget.Logs);
task.Wait();
logger.Factory.Flush();
Assert.Equal(6, asyncTarget.Logs.Count);
while (asyncTarget.Logs.TryDequeue(out var logEventMessage))
{
Assert.Equal(0, logEventMessage.IndexOf(managedThreadId.ToString() + "|"));
Assert.EndsWith("|42", logEventMessage);
}
logger.Factory.Configuration = null;
}
[Fact]
public void AsyncTaskTarget_SkipAsyncTargetWrapper()
{
var logFactory = new LogFactory().Setup()
.SetupExtensions(ext => ext.RegisterTarget<AsyncTaskTestTarget>("AsyncTaskTest"))
.LoadConfigurationFromXml(@"
<nlog throwExceptions='true'>
<targets async='true'>
<target name='asyncDebug' type='AsyncTaskTest' />
<target name='debug' type='Debug' />
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>").LogFactory;
Assert.NotNull(logFactory.Configuration.FindTargetByName<AsyncTaskTestTarget>("asyncDebug"));
Assert.NotNull(logFactory.Configuration.FindTargetByName<NLog.Targets.Wrappers.AsyncTargetWrapper>("debug"));
}
[Fact]
public void AsyncTaskTarget_SkipDefaultAsyncWrapper()
{
var logFactory = new LogFactory().Setup()
.SetupExtensions(ext => ext.RegisterTarget<AsyncTaskTestTarget>("AsyncTaskTest"))
.LoadConfigurationFromXml(@"
<nlog throwExceptions='true'>
<targets>
<default-wrapper type='AsyncWrapper' />
<target name='asyncDebug' type='AsyncTaskTest' />
<target name='debug' type='Debug' />
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>").LogFactory;
Assert.NotNull(logFactory.Configuration.FindTargetByName<AsyncTaskTestTarget>("asyncDebug"));
Assert.NotNull(logFactory.Configuration.FindTargetByName<NLog.Targets.Wrappers.AsyncTargetWrapper>("debug"));
}
[Fact]
public void AsyncTaskTarget_AllowDefaultBufferWrapper()
{
var logFactory = new LogFactory().Setup()
.SetupExtensions(ext => ext.RegisterTarget<AsyncTaskTestTarget>("AsyncTaskTest"))
.LoadConfigurationFromXml(@"
<nlog throwExceptions='true'>
<targets>
<default-wrapper type='BufferingWrapper' />
<target name='asyncDebug' type='AsyncTaskTest' />
<target name='debug' type='Debug' />
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>").LogFactory;
Assert.NotNull(logFactory.Configuration.FindTargetByName<NLog.Targets.Wrappers.BufferingTargetWrapper>("asyncDebug"));
Assert.NotNull(logFactory.Configuration.FindTargetByName<NLog.Targets.Wrappers.BufferingTargetWrapper>("debug"));
}
[Fact]
public void AsyncTaskTarget_TestAsyncException()
{
var asyncTarget = new AsyncTaskTestTarget
{
Layout = "${level}",
RetryDelayMilliseconds = 50
};
var logger = new LogFactory().Setup().LoadConfiguration(builder =>
{
builder.ForLogger().WriteTo(asyncTarget);
}).GetCurrentClassLogger();
foreach (var logLevel in LogLevel.AllLoggingLevels)
logger.Log(logLevel, logLevel == LogLevel.Debug ? "ASYNCEXCEPTION" : logLevel.Name.ToUpperInvariant());
Assert.True(asyncTarget.WaitForWriteEvent());
Assert.NotEmpty(asyncTarget.Logs);
logger.Factory.Flush();
Assert.Equal(LogLevel.MaxLevel.Ordinal, asyncTarget.Logs.Count);
int ordinal = 0;
while (asyncTarget.Logs.TryDequeue(out var logEventMessage))
{
var logLevel = LogLevel.FromString(logEventMessage);
Assert.NotEqual(LogLevel.Debug, logLevel);
Assert.Equal(ordinal++, logLevel.Ordinal);
if (ordinal == LogLevel.Debug.Ordinal)
++ordinal;
}
logger.Factory.Configuration = null;
}
[Fact]
public void AsyncTaskTarget_TestTimeout()
{
RetryingIntegrationTest(3, () =>
{
var asyncTarget = new AsyncTaskTestTarget
{
Layout = "${level}",
TaskTimeoutSeconds = 1
};
var logger = new LogFactory().Setup().LoadConfiguration(builder =>
{
builder.ForLogger().WriteTo(asyncTarget);
}).GetCurrentClassLogger();
logger.Trace("TTT");
logger.Debug("TIMEOUT");
logger.Info("III");
logger.Warn("WWW");
logger.Error("EEE");
logger.Fatal("FFF");
Assert.True(asyncTarget.WaitForWriteEvent());
Assert.NotEmpty(asyncTarget.Logs);
logger.Factory.Flush();
Assert.Equal(5, asyncTarget.Logs.Count);
while (asyncTarget.Logs.TryDequeue(out var logEventMessage))
{
Assert.Equal(-1, logEventMessage.IndexOf("Debug|"));
}
logger.Factory.Configuration = null;
});
}
[Fact]
public void AsyncTaskTarget_TestRetryAsyncException()
{
var asyncTarget = new AsyncTaskTestTarget
{
Layout = "${level}",
RetryDelayMilliseconds = 10,
RetryCount = 3
};
var logger = new LogFactory().Setup().LoadConfiguration(builder =>
{
builder.ForLogger().WriteTo(asyncTarget);
}).GetCurrentClassLogger();
foreach (var logLevel in LogLevel.AllLoggingLevels)
logger.Log(logLevel, logLevel == LogLevel.Debug ? "ASYNCEXCEPTION" : logLevel.Name.ToUpperInvariant());
Assert.True(asyncTarget.WaitForWriteEvent());
Assert.NotEmpty(asyncTarget.Logs);
logger.Factory.Flush();
Assert.Equal(LogLevel.MaxLevel.Ordinal, asyncTarget.Logs.Count);
Assert.Equal(LogLevel.MaxLevel.Ordinal + 4, asyncTarget.WriteTasks);
int ordinal = 0;
while (asyncTarget.Logs.TryDequeue(out var logEventMessage))
{
var logLevel = LogLevel.FromString(logEventMessage);
Assert.NotEqual(LogLevel.Debug, logLevel);
Assert.Equal(ordinal++, logLevel.Ordinal);
if (ordinal == LogLevel.Debug.Ordinal)
++ordinal;
}
logger.Factory.Configuration = null;
}
[Fact]
public void AsyncTaskTarget_TestRetryException()
{
var asyncTarget = new AsyncTaskTestTarget
{
Layout = "${level}",
RetryDelayMilliseconds = 10,
RetryCount = 3
};
var logger = new LogFactory().Setup().LoadConfiguration(builder =>
{
builder.ForLogger().WriteTo(asyncTarget);
}).GetCurrentClassLogger();
foreach (var logLevel in LogLevel.AllLoggingLevels)
logger.Log(logLevel, logLevel == LogLevel.Debug ? "EXCEPTION" : logLevel.Name.ToUpperInvariant());
Assert.True(asyncTarget.WaitForWriteEvent());
Assert.NotEmpty(asyncTarget.Logs);
logger.Factory.Flush();
Assert.Equal(LogLevel.MaxLevel.Ordinal, asyncTarget.Logs.Count);
Assert.Equal(LogLevel.MaxLevel.Ordinal + 4, asyncTarget.WriteTasks);
int ordinal = 0;
while (asyncTarget.Logs.TryDequeue(out var logEventMessage))
{
var logLevel = LogLevel.FromString(logEventMessage);
Assert.NotEqual(LogLevel.Debug, logLevel);
Assert.Equal(ordinal++, logLevel.Ordinal);
if (ordinal == LogLevel.Debug.Ordinal)
++ordinal;
}
logger.Factory.Configuration = null;
}
[Fact]
public void AsyncTaskTarget_TestBatchWriting()
{
var asyncTarget = new AsyncTaskBatchTestTarget
{
Layout = "${level}",
BatchSize = 3,
TaskDelayMilliseconds = 10
};
var logger = new LogFactory().Setup().LoadConfiguration(builder =>
{
builder.ForLogger().WriteTo(asyncTarget);
}).GetCurrentClassLogger();
foreach (var logLevel in LogLevel.AllLoggingLevels)
logger.Log(logLevel, logLevel.Name.ToUpperInvariant());
Assert.True(asyncTarget.WaitForWriteEvent());
Assert.NotEmpty(asyncTarget.Logs);
logger.Factory.Flush();
Assert.Equal(LogLevel.MaxLevel.Ordinal + 1, asyncTarget.Logs.Count);
Assert.Equal(LogLevel.MaxLevel.Ordinal / 2, asyncTarget.WriteTasks);
int ordinal = 0;
while (asyncTarget.Logs.TryDequeue(out var logEventMessage))
{
var logLevel = LogLevel.FromString(logEventMessage);
Assert.Equal(ordinal++, logLevel.Ordinal);
}
logger.Factory.Configuration = null;
}
[Fact]
public void AsyncTaskTarget_TestBatchRetryTimings()
{
var asyncTarget = new AsyncTaskBatchExceptionTestTarget
{
Layout = "${level}",
BatchSize = 10,
TaskDelayMilliseconds = 10,
RetryCount = 5,
RetryDelayMilliseconds = 3
};
var logger = new LogFactory().Setup().LoadConfiguration(builder =>
{
builder.ForLogger().WriteTo(asyncTarget);
}).GetCurrentClassLogger();
logger.Log(LogLevel.Info, "test");
logger.Factory.Flush();
// The zero at the end of the array is used when there will be no more retries.
Assert.Equal(new[] { 3, 6, 12, 24, 48, 0 }, asyncTarget.retryDelayLog);
logger.Factory.Configuration = null;
}
[Fact]
public void AsyncTaskTarget_TestFakeBatchWriting()
{
var asyncTarget = new AsyncTaskTestTarget
{
Layout = "${level}",
BatchSize = 3,
TaskDelayMilliseconds = 10
};
var logger = new LogFactory().Setup().LoadConfiguration(builder =>
{
builder.ForLogger().WriteTo(asyncTarget);
}).GetCurrentClassLogger();
foreach (var logLevel in LogLevel.AllLoggingLevels)
logger.Log(logLevel, logLevel.Name.ToUpperInvariant());
Assert.True(asyncTarget.WaitForWriteEvent());
Assert.NotEmpty(asyncTarget.Logs);
logger.Factory.Flush();
Assert.Equal(LogLevel.MaxLevel.Ordinal + 1, asyncTarget.Logs.Count);
Assert.Equal(LogLevel.MaxLevel.Ordinal + 1, asyncTarget.WriteTasks);
int ordinal = 0;
while (asyncTarget.Logs.TryDequeue(out var logEventMessage))
{
var logLevel = LogLevel.FromString(logEventMessage);
Assert.Equal(ordinal++, logLevel.Ordinal);
}
logger.Factory.Configuration = null;
}
[Fact]
public void AsyncTaskTarget_TestSlowBatchWriting()
{
var asyncTarget = new AsyncTaskBatchTestTarget
{
Layout = "${level}",
TaskDelayMilliseconds = 200
};
var logger = new LogFactory().Setup().LoadConfiguration(builder =>
{
builder.ForLogger().WriteTo(asyncTarget);
}).GetCurrentClassLogger();
DateTime utcNow = DateTime.UtcNow;
logger.Log(LogLevel.Info, LogLevel.Info.ToString().ToUpperInvariant());
logger.Log(LogLevel.Fatal, "SLEEP");
Assert.True(asyncTarget.WaitForWriteEvent());
Assert.Single(asyncTarget.Logs);
logger.Log(LogLevel.Error, LogLevel.Error.ToString().ToUpperInvariant());
asyncTarget.Dispose(); // Trigger fast shutdown
logger.Factory.Configuration = null;
TimeSpan shutdownTime = DateTime.UtcNow - utcNow;
Assert.True(shutdownTime < TimeSpan.FromSeconds(4), $"Shutdown took {shutdownTime.TotalMilliseconds} msec");
}
[Fact]
public void AsyncTaskTarget_TestThrottleOnTaskDelay()
{
var asyncTarget = new AsyncTaskBatchTestTarget
{
Layout = "${level}",
TaskDelayMilliseconds = 50,
BatchSize = 10,
};
var logger = new LogFactory().Setup().LoadConfiguration(builder =>
{
builder.ForLogger().WriteTo(asyncTarget);
}).GetCurrentClassLogger();
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 10; ++j)
{
logger.Log(LogLevel.Info, i.ToString());
Thread.Sleep(20);
}
Assert.True(asyncTarget.WaitForWriteEvent());
}
Assert.True(asyncTarget.Logs.Count > 25, $"{asyncTarget.Logs.Count} LogEvents are too few after {asyncTarget.WriteTasks} writes");
Assert.True(asyncTarget.WriteTasks < 20, $"{asyncTarget.WriteTasks} writes are too many.");
}
[Fact]
public void AsynTaskTarget_AutoFlushWrapper()
{
var asyncTarget = new AsyncTaskBatchTestTarget
{
Layout = "${level}",
TaskDelayMilliseconds = 5000,
BatchSize = 10,
};
var autoFlush = new NLog.Targets.Wrappers.AutoFlushTargetWrapper("autoflush", asyncTarget);
autoFlush.Condition = "level > LogLevel.Warn";
var logger = new LogFactory().Setup().LoadConfiguration(builder =>
{
builder.ForLogger().WriteTo(autoFlush);
}).GetCurrentClassLogger();
logger.Info("Hello World");
Assert.Empty(asyncTarget.Logs);
logger.Error("Goodbye World");
Assert.True(asyncTarget.WaitForWriteEvent());
Assert.NotEmpty(asyncTarget.Logs);
}
[Fact]
public void AsyncTaskTarget_FlushWhenBlocked()
{
// Arrange
var logFactory = new LogFactory();
var logConfig = new LoggingConfiguration(logFactory);
var asyncTarget = new AsyncTaskBatchTestTarget
{
Layout = "${level}",
TaskDelayMilliseconds = 10000,
BatchSize = 10,
QueueLimit = 10,
OverflowAction = NLog.Targets.Wrappers.AsyncTargetWrapperOverflowAction.Block,
};
logConfig.AddRuleForAllLevels(asyncTarget);
logFactory.Configuration = logConfig;
var logger = logFactory.GetLogger(nameof(AsyncTaskTarget_FlushWhenBlocked));
// Act
for (int i = 0; i < 10; ++i)
logger.Info("Testing {0}", i);
logFactory.Flush(TimeSpan.FromSeconds(5));
// Assert
Assert.Equal(1, asyncTarget.WriteTasks);
}
[Fact]
public void AsyncTaskTarget_MissingDependency_EnqueueLogEvents()
{
using (new NoThrowNLogExceptions())
{
// Arrange
var logFactory = new LogFactory();
logFactory.ThrowConfigExceptions = true;
var logConfig = new LoggingConfiguration(logFactory);
var asyncTarget = new AsyncTaskTestTarget() { Name = "asynctarget", RequiredDependency = typeof(IMisingDependencyClass) };
logConfig.AddRuleForAllLevels(asyncTarget);
logFactory.Configuration = logConfig;
var logger = logFactory.GetLogger(nameof(AsyncTaskTarget_MissingDependency_EnqueueLogEvents));
// Act
logger.Info("Hello World");
Assert.False(asyncTarget.WaitForWriteEvent(50));
logFactory.ServiceRepository.RegisterService(typeof(IMisingDependencyClass), new MisingDependencyClass());
// Assert
Assert.True(asyncTarget.WaitForWriteEvent());
}
}
private interface IMisingDependencyClass
{
}
private class MisingDependencyClass : IMisingDependencyClass
{
}
}
#endif
}
| |
// semmle-extractor-options: /r:System.Security.Cryptography.Primitives.dll /r:System.Security.Cryptography.Csp.dll /r:System.Security.Cryptography.Algorithms.dll
using System;
using System.Text;
using System.Security.Cryptography;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;
public class Test
{
private const int SaltSize = 32;
// BAD - Hash without a salt.
public static String HashPassword(string password, string strAlgName ="SHA256")
{
IBuffer passBuff = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
HashAlgorithmProvider algProvider = HashAlgorithmProvider.OpenAlgorithm(strAlgName);
IBuffer hashBuff = algProvider.HashData(passBuff);
return CryptographicBuffer.EncodeToBase64String(hashBuff);
}
// GOOD - Hash with a salt.
public static string HashPassword2(string password, string salt, string strAlgName ="SHA256")
{
// Concatenate the salt with the password.
IBuffer passBuff = CryptographicBuffer.ConvertStringToBinary(password+salt, BinaryStringEncoding.Utf8);
HashAlgorithmProvider algProvider = HashAlgorithmProvider.OpenAlgorithm(strAlgName);
IBuffer hashBuff = algProvider.HashData(passBuff);
return CryptographicBuffer.EncodeToBase64String(hashBuff);
}
// BAD - Hash without a salt.
public static string HashPassword(string password)
{
SHA256 sha256Hash = SHA256.Create();
byte[] passBytes = System.Text.Encoding.ASCII.GetBytes(password);
byte[] hashBytes = sha256Hash.ComputeHash(passBytes);
return Convert.ToBase64String(hashBytes);
}
// GOOD - Hash with a salt.
public static string HashPassword2(string password)
{
byte[] passBytes = System.Text.Encoding.ASCII.GetBytes(password);
byte[] saltBytes = GenerateSalt();
// Add the salt to the hash.
byte[] rawSalted = new byte[passBytes.Length + saltBytes.Length];
passBytes.CopyTo(rawSalted, 0);
saltBytes.CopyTo(rawSalted, passBytes.Length);
//Create the salted hash.
SHA256 sha256 = SHA256.Create();
byte[] saltedPassBytes = sha256.ComputeHash(rawSalted);
// Add the salt value to the salted hash.
byte[] dbPassword = new byte[saltedPassBytes.Length + saltBytes.Length];
saltedPassBytes.CopyTo(dbPassword, 0);
saltBytes.CopyTo(dbPassword, saltedPassBytes.Length);
return Convert.ToBase64String(dbPassword);
}
// BAD - Hash without a salt.
public static string HashPassword3(string password)
{
HashAlgorithm hashAlg = new SHA256CryptoServiceProvider();
byte[] passBytes = System.Text.Encoding.ASCII.GetBytes(password);
byte[] hashBytes = hashAlg.ComputeHash(passBytes);
return Convert.ToBase64String(hashBytes);
}
// GOOD - Hash with a salt.
public bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
{
using(var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
{
var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
for(int i = 0;i<computedHash.Length;i++)
{
if (computedHash[i] != passwordHash[i])
return false;
}
return true;
}
}
public static byte[] GenerateSalt()
{
using (var rng = new RNGCryptoServiceProvider())
{
var randomNumber = new byte[SaltSize];
rng.GetBytes(randomNumber);
return randomNumber;
}
}
public static byte[] Combine(byte[] first, byte[] second)
{
// helper to combine two byte arrays
byte[] ret = new byte[first.Length + second.Length];
Buffer.BlockCopy(first, 0, ret, 0, first.Length);
Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
return ret;
}
// GOOD - Hash with a salt.
public static byte[] CalculateKeys(string password, string userid)
{
var utf16pass = System.Text.Encoding.UTF8.GetBytes(password);
var utf16sid = System.Text.Encoding.UTF8.GetBytes(userid);
var utf16sidfinal = new byte[utf16sid.Length + 2];
utf16sid.CopyTo(utf16sidfinal, 0);
utf16sidfinal[utf16sidfinal.Length - 2] = 0x00;
byte[] sha1bytes_password;
byte[] hmacbytes;
//Calculate SHA1 from user password
using (var sha1 = new SHA1Managed())
{
sha1bytes_password = sha1.ComputeHash(utf16pass);
}
var combined = Combine(sha1bytes_password, utf16sidfinal);
using (var hmac = new HMACSHA1(sha1bytes_password))
{
hmacbytes = hmac.ComputeHash(utf16sidfinal);
}
return hmacbytes;
}
private byte[] TryDecrypt(byte[] buffer, int offset, int length, byte[] password, int keyLen) {
byte[] key = new byte[16];
Array.Copy(SHA1.Create().ComputeHash(password, 0, password.Length), 0, key, 0, keyLen);
byte[] ret = Aes.Create().CreateDecryptor(key, null).TransformFinalBlock(buffer, offset, length);
return ret;
}
// GOOD - Use password hash without a salt having further processing.
public byte[] encrypt(byte[] pass, byte[] salt, byte[] blob) {
byte[] key = new byte[salt.Length + pass.Length];
Array.Copy(salt, 0, key, 0, salt.Length);
Array.Copy(pass, 0, key, salt.Length, pass.Length);
byte[] pkb = TryDecrypt(blob, 8, blob.Length - 8, key, 16);
return pkb;
}
public string CreatePasswordHash(string password, string saltkey)
{
var saltAndPassword = string.Concat(password, saltkey);
HashAlgorithm algorithm = SHA256.Create();
var hashByteArray = algorithm.ComputeHash(Encoding.UTF8.GetBytes(saltAndPassword));
return BitConverter.ToString(hashByteArray).Replace("-", "");
}
private string GetMD5HashBinHex (string toBeHashed)
{
MD5 hash = MD5.Create ();
byte[] result = hash.ComputeHash (Encoding.ASCII.GetBytes (toBeHashed));
StringBuilder sb = new StringBuilder ();
foreach (byte b in result)
sb.Append (b.ToString ("x2"));
return sb.ToString ();
}
// GOOD: Password concatenated with other information before hashing
public string CreatePasswordHash2(string username, string realm, string password)
{
string A1 = String.Format ("{0}:{1}:{2}", username, realm, password);
string HA1 = GetMD5HashBinHex (A1);
return HA1;
}
private byte[] Xor(byte[] array1, byte[] array2) {
var result = new byte[array1.Length];
for (int i = 0; i < array1.Length; i++) {
result[i] = (byte)(array1[i] ^ array2[i]);
}
return result;
}
// GOOD: Password hash without salt is further hashed with salt
public byte[] GetScrable(byte[] password, byte[] decodedSalt) {
var first20SaltBytes = new byte[20];
Array.Copy(decodedSalt, first20SaltBytes, 20);
var step1 = Sha1Utils.Hash(password);
var step2 = Sha1Utils.Hash(step1);
var step3 = Sha1Utils.Hash(first20SaltBytes, step2);
var scrambleBytes = Xor(step1, step3);
return scrambleBytes;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Graphics;
using Android.Graphics.Drawables;
namespace Sino.Droid.MaterialProgressbar
{
public class Ring
{
private float ARROW_OFFSET_ANGLE = 0;
private RectF mTempBounds = new RectF();
private Paint mPaint = new Paint();
private Paint mArrowPaint = new Paint();
private Drawable.ICallback mCallback;
private Paint mCirclePaint = new Paint();
private float mStartTrim = 0.0f;
private float mEndTrim = 0.0f;
private float mRotation = 0.0f;
private float mStrokeWidth = 5.0f;
private float mStrokeInset = 2.5f;
private Color[] mColors;
private int mColorIndex;
private float mStartingStartTrim;
private float mStartingEndTrim;
private float mStartingRotation;
private bool mShowArrow;
private Path mArrow;
private float mArrowScale;
private int mArrowWidth;
private int mArrowHeight;
public double RingCenterRadius { get; set; }
public float Rotation
{
get
{
return mRotation;
}
set
{
mRotation = value;
InvalidateSelf();
}
}
public float EndTrim
{
get
{
return mEndTrim;
}
set
{
mEndTrim = value;
InvalidateSelf();
}
}
public float StartingStartTrim
{
get
{
return mStartingStartTrim;
}
}
public float StartingEndTrim
{
get
{
return mStartingEndTrim;
}
}
public float StartTrim
{
get
{
return mStartTrim;
}
set
{
mStartTrim = value;
InvalidateSelf();
}
}
public float StrokeWidth
{
get
{
return mStrokeWidth;
}
set
{
mStrokeWidth = value;
mPaint.StrokeWidth = value;
InvalidateSelf();
}
}
public int Alpha { get; set; }
public Color BackgrounColor { get; set; }
public Ring(Drawable.ICallback callback)
{
this.mCallback = callback;
mPaint.StrokeCap = Paint.Cap.Square;
mPaint.AntiAlias = true;
mPaint.SetStyle(Paint.Style.Stroke);
mArrowPaint.SetStyle(Paint.Style.Fill);
mArrowPaint.AntiAlias = true;
}
public void SetArrowDimensions(float width, float height)
{
mArrowWidth = (int)width;
mArrowHeight = (int)height;
}
public void Draw(Canvas c, Rect bounds)
{
RectF arcBounds = mTempBounds;
arcBounds.Set(bounds);
arcBounds.Inset(mStrokeInset, mStrokeInset);
float startAngle = (mStartTrim + mRotation) * 360;
float endAngle = (mEndTrim + mRotation) * 360;
float sweepAngle = endAngle - startAngle;
mPaint.Color = mColors[mColorIndex];
c.DrawArc(arcBounds, startAngle, sweepAngle, false, mPaint);
DrawTriangle(c, startAngle, sweepAngle, bounds);
if (Alpha < 255)
{
mCirclePaint.Color = BackgrounColor;
mCirclePaint.Alpha = 255 - Alpha;
c.DrawCircle(bounds.ExactCenterX(), bounds.ExactCenterY(), bounds.Width() / 2, mCirclePaint);
}
}
private void DrawTriangle(Canvas c, float startAngle, float sweepAngle, Rect bounds)
{
if (mShowArrow)
{
if (mArrow == null)
{
mArrow = new Path();
mArrow.SetFillType(Path.FillType.EvenOdd);
}
else
{
mArrow.Reset();
}
float x = (float)(RingCenterRadius * Math.Cos(0) + bounds.ExactCenterX());
float y = (float)(RingCenterRadius * Math.Sin(0) + bounds.ExactCenterY());
mArrow.MoveTo(0, 0);
mArrow.LineTo((mArrowWidth) * mArrowScale, 0);
mArrow.LineTo(((mArrowWidth) * mArrowScale / 2), (mArrowHeight * mArrowScale));
mArrow.Offset(x - ((mArrowWidth) * mArrowScale / 2), y);
mArrow.Close();
mArrowPaint.Color = mColors[mColorIndex];
c.Rotate(startAngle + (sweepAngle < 0 ? 0 : sweepAngle) - ARROW_OFFSET_ANGLE, bounds.ExactCenterX(), bounds.ExactCenterY());
c.DrawPath(mArrow, mArrowPaint);
}
}
public void SetColors(params Color[] colors)
{
mColors = colors;
SetColorIndex(0);
}
public void SetColorIndex(int p)
{
mColorIndex = p;
}
public void GoToNextColor()
{
mColorIndex = (mColorIndex + 1) % (mColors.Length);
}
public void SetColorFilter(ColorFilter filter)
{
mPaint.SetColorFilter(filter);
InvalidateSelf();
}
public void SetInsets(int width, int height)
{
float minEdge = (float)Math.Min(width, height);
float insets = 0;
if (RingCenterRadius <= 0 || minEdge < 0)
{
insets = (float)Math.Ceiling(mStrokeWidth / 2.0f);
}
else
{
insets = (float)(minEdge / 2.0f - RingCenterRadius);
}
mStrokeInset = insets;
}
public float GetInsets()
{
return mStrokeInset;
}
public void SetShowArrow(bool show)
{
if (mShowArrow != show)
{
mShowArrow = show;
InvalidateSelf();
}
}
public void SetArrowScale(float scale)
{
if (scale != mArrowScale)
{
mArrowScale = scale;
InvalidateSelf();
}
}
public float GetStartingRotation()
{
return mStartingRotation;
}
public void StoreOriginals()
{
mStartingStartTrim = mStartTrim;
mStartingEndTrim = mEndTrim;
mStartingRotation = mRotation;
}
public void ResetOriginals()
{
mStartingStartTrim = 0;
mStartingEndTrim = 0;
mStartingRotation = 0;
StartTrim = 0;
EndTrim = 0;
Rotation = 0;
}
private void InvalidateSelf()
{
mCallback.InvalidateDrawable(null);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.