context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using HoldemPlayerContract; namespace HoldemController.ConsoleDisplay { public class ConsoleRenderer { private const int PlayerWidth = 10; private const int PlayerHeight = 2; // todo: calculated? private const int PotWidth = 17; private const int PotHeight = 5; private const int MaxMoneyWidth = 10; private const int CardWidth = 3; private const int HoldCardWidth = CardWidth*2 + 1; private const int CardHeight = 3; private const int CommunityCardsWidth = CardWidth*5 + 4; private const int DealerChipWidth = 3; //private const int DealerChipHeight = 1; private const int TurnIndicatorWidth = 3; //private const int TurnIndicatorHeight = 1; private const int ActionWidth = 10; private const int ActionHeight = 2; private const int HorizontalPadding = 1; private const int TableBorderWidth = HorizontalPadding + PlayerWidth + HorizontalPadding; private const int VerticalPadding = 1; private const int TableBorderHeight = VerticalPadding + PlayerHeight + VerticalPadding; private readonly Dictionary<int, PlayerDrawArea> _players = new Dictionary<int, PlayerDrawArea>(8); private readonly DrawArea[] _communityCards; private readonly DrawArea _pots; public ConsoleRenderer(int width, int height, int playerCount) { Console.SetWindowSize(width, height); Console.OutputEncoding = System.Text.Encoding.Unicode; if (playerCount > 8) { throw new ArgumentOutOfRangeException(nameof(playerCount), "Too many players. Maximum is 8."); } var tableWidth = width - (2*TableBorderWidth); // todo: validate min width var tableHeight = height - (2*TableBorderHeight); // todo: validate min height DrawTable(TableBorderWidth, TableBorderHeight, tableWidth, tableHeight); var yMid = height / 2 - 1; var potCommunityCardPadding = 3; var potX = (width - PotWidth - potCommunityCardPadding - CommunityCardsWidth)/2; _pots = new DrawArea(potX, yMid, PotWidth, PotHeight, ConsoleColor.DarkGreen); _communityCards = GetCardDrawAreas(potX + PotWidth + potCommunityCardPadding, yMid, 5); for (var i = 0; i < playerCount; i++) { int playerY; if (i == 0 || i == 4) { playerY = yMid; } else if (i < 4) { playerY = VerticalPadding; } else { playerY = height - VerticalPadding - PlayerHeight; } int playerX; if (i == 0) { playerX = HorizontalPadding; } else if (i == 4) { playerX = width - HorizontalPadding - PlayerWidth; } else { var playerWidth = tableWidth/4; var leftMost = TableBorderWidth + playerWidth - PlayerWidth/2; playerX = leftMost + (3 - Math.Abs(4 - i))* playerWidth; } var cardX = playerX; var cardY = playerY; if (i == 0) { cardX = TableBorderWidth + HorizontalPadding; } else if (i == 4) { cardX = width - (TableBorderWidth + HorizontalPadding + HoldCardWidth); } else if (i < 4) { cardY = TableBorderHeight + VerticalPadding; } else { cardY = height - (TableBorderHeight + VerticalPadding + CardHeight); } var dealerChipX = cardX; var dealerChipY = cardY; if (i == 0) { dealerChipY -= 2; dealerChipX += 4; } else if (i == 4) { dealerChipY += CardHeight + 1; } else if (i < 4) { dealerChipX += HoldCardWidth + 2; dealerChipY += 2; } else { dealerChipX -= DealerChipWidth + 2; } var actionX = cardX; var actionY = cardY; if (i == 0) { actionX = TableBorderWidth + HoldCardWidth + HorizontalPadding + HorizontalPadding; } else if (i == 4) { actionX = width - (TableBorderWidth + HorizontalPadding + HoldCardWidth + HorizontalPadding + ActionWidth); } else if (i < 4) { actionY = cardY + CardHeight + VerticalPadding; } else { actionY = cardY - (CardHeight + VerticalPadding); } var turnX = actionX; var turnY = actionY; if (i == 0) { turnX += ActionWidth + HorizontalPadding; turnY++; } else if (i == 4) { turnX -= HorizontalPadding + TurnIndicatorWidth; turnY++; } else if (i < 4) { turnY += ActionHeight; } else { turnY -= 1; } _players.Add(i, new PlayerDrawArea { Name = new DrawArea(playerX, playerY, PlayerWidth, 1, ConsoleColor.Black, ConsoleColor.White), Stack = new DrawArea(playerX, playerY + 1, PlayerWidth, 1, ConsoleColor.Black, ConsoleColor.White), Cards = GetCardDrawAreas(cardX, cardY, 2), BetAction = new DrawArea(actionX, actionY, ActionWidth, 1, ConsoleColor.DarkGreen, ConsoleColor.White), BetAmount = new DrawArea(actionX, actionY + 1, ActionWidth, 1, ConsoleColor.DarkGreen, ConsoleColor.White), ActionIndicator = new DrawArea(turnX, turnY, TurnIndicatorWidth, 1, ConsoleColor.DarkGreen, ConsoleColor.White), DealerChip = new DrawArea(dealerChipX, dealerChipY, DealerChipWidth, 1, ConsoleColor.DarkGreen, ConsoleColor.DarkRed) }); } } private static DrawArea[] GetCardDrawAreas(int x, int y, int count) { const int cardDistance = CardWidth + HorizontalPadding; return Enumerable.Range(0, count).Select(i => new DrawArea(x + (i*cardDistance), y, CardWidth, CardHeight, ConsoleColor.White)).ToArray(); } private static void DrawTable(int x, int y, int width, int height) { Console.BackgroundColor = ConsoleColor.DarkGreen; var radius = (int)Math.Ceiling(height/2d); var lineY = 0; while (lineY < radius) { var lineX = CalculateRoundTableOffset(radius, lineY); var line = new string(' ', width - 2*lineX); // top Console.SetCursorPosition(lineX + x, lineY + y); Console.Write(line); // bottom Console.SetCursorPosition(lineX + x, height - 1 - lineY + y); Console.Write(line); lineY++; } Console.ResetColor(); Console.SetCursorPosition(0, 0); } private static int CalculateRoundTableOffset(int radius, int y) { const double horizontalMultiplier = 1.83; y -= radius; var x = (int) -Math.Ceiling(Math.Sqrt(radius*radius - y*y)); var actualX = (int) ((x + radius)*horizontalMultiplier); return actualX; } public void UpdatePlayerName(int playerId, string name) { _players[playerId].Name.Draw(name); } public void UpdatePlayerStackSize(int playerId, int stackSize) { _players[playerId].Stack.Draw(stackSize.ToString()); } public void UpdateDealer(int playerId) { foreach (var player in _players) { var text = player.Key == playerId ? "(D)" : string.Empty; player.Value.DealerChip.Draw(text); } } public void UpdatePlayerCards(int playerId, Card card1, Card card2) { UpdateCards(_players[playerId].Cards, new[] {card1, card2}); } public void UpdateCommunityCards(Card[] cards) { UpdateCards(_communityCards, cards); } private static void UpdateCards(IReadOnlyList<DrawArea> cardAreas, IReadOnlyList<Card> cards) { for (var i = 0; i < cardAreas.Count; i++) { Card card; if (cards == null || cards.Count <= i || (card = cards[i]) == null) { cardAreas[i].DrawLines(CardFormatter.NoCard(), null, ConsoleColor.DarkGreen); continue; } ConsoleColor cardColor; var cardText = CardFormatter.FormatCard(card, out cardColor); cardAreas[i].DrawLines(cardText, cardColor); } } public void UpdatePlayerTurn(int? playerId) { foreach (var player in _players) { var isTurn = player.Key == playerId; var text = isTurn ? "..." : string.Empty; var bgColor = isTurn ? ConsoleColor.Black : (ConsoleColor?)null; player.Value.ActionIndicator.Draw(text, null, bgColor); } } public void UpdatePlayerAction(int playerId, ActionType? action, int amount) { var color = ConsoleColor.Green; switch (action) { case ActionType.Check: case ActionType.Blind: case ActionType.Call: color = ConsoleColor.Cyan; break; case ActionType.Raise: color = ConsoleColor.Yellow; break; case ActionType.Fold: color = ConsoleColor.Black; break; case ActionType.Show: break; case ActionType.Win: color = ConsoleColor.Blue; break; } var player = _players[playerId]; player.BetAction.Draw(action?.ToString(), color); var bet = ((IList) new[] {ActionType.Blind, ActionType.Call, ActionType.Raise, ActionType.Win}).Contains(action) ? amount.ToString() : string.Empty; player.BetAmount.Draw(bet); } public void UpdatePots(IEnumerable<int> pots) { _pots.DrawLines(pots?.Select((p, i) => $"Pot {i + 1}: {p,MaxMoneyWidth}").ToArray() ?? new string[0]); } private class PlayerDrawArea { public DrawArea Name { get; set; } public DrawArea Stack { get; set; } public DrawArea[] Cards { get; set; } public DrawArea BetAction { get; set; } public DrawArea BetAmount { get; set; } public DrawArea DealerChip { get; set; } public DrawArea ActionIndicator { get; set; } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Windows.Forms; using Bloom.Api; using Bloom.Book; using Bloom.web; using Fleck; using L10NSharp; using SIL.Reporting; using SIL.Windows.Forms.Reporting; namespace Bloom.Edit { public partial class PageListView : UserControl { private readonly PageSelection _pageSelection; private readonly EditingModel _model; private bool _dontForwardSelectionEvent; private IPage _pageWeThinkShouldBeSelected; private bool _hyperlinkMessageShown = false; public PageListView(PageSelection pageSelection, RelocatePageEvent relocatePageEvent, EditingModel model, HtmlThumbNailer thumbnailProvider, NavigationIsolator isolator, ControlKeyEvent controlKeyEvent, PageListApi pageListApi, BloomWebSocketServer webSocketServer) { _pageSelection = pageSelection; _model = model; this.Font= SystemFonts.MessageBoxFont; InitializeComponent(); _thumbNailList.PageListApi = pageListApi; _thumbNailList.WebSocketServer = webSocketServer; this.BackColor = Palette.SidePanelBackgroundColor; _thumbNailList.Thumbnailer = thumbnailProvider; _thumbNailList.RelocatePageEvent = relocatePageEvent; _thumbNailList.PageSelectedChanged+=new EventHandler(OnPageSelectedChanged); _thumbNailList.ControlKeyEvent = controlKeyEvent; _thumbNailList.Model = model; _thumbNailList.BringToFront(); // needed to get DockStyle.Fill to work right. // First action determines whether the menu item is enabled, second performs it. var menuItems = new List<WebThumbNailList.MenuItemSpec>(); menuItems.Add( new WebThumbNailList.MenuItemSpec() { Label = LocalizationManager.GetString("EditTab.DuplicatePageButton", "Duplicate Page"), EnableFunction = (page) => page != null && _model.CanDuplicatePage, ExecuteCommand = (page) => _model.DuplicatePage(page)}); menuItems.Add( new WebThumbNailList.MenuItemSpec() { Label = LocalizationManager.GetString("EditTab.DuplicatePageMultiple", "Duplicate Page Many Times..."), EnableFunction = (page) => page != null && _model.CanDuplicatePage, ExecuteCommand = (page) => _model.DuplicateManyPages(page) }); menuItems.Add( new WebThumbNailList.MenuItemSpec() { Label = LocalizationManager.GetString("EditTab.CopyPage", "Copy Page"), EnableFunction = (page) => page != null && _model.CanCopyPage, ExecuteCommand = (page) => _model.CopyPage(page) }); menuItems.Add( new WebThumbNailList.MenuItemSpec() { Label = LocalizationManager.GetString("EditTab.CopyHyperlink", "Copy Hyperlink"), EnableFunction = (page) => page != null && _model.CanCopyHyperlink, ExecuteCommand = (page) => { _model.CopyHyperlink(page); if (!_hyperlinkMessageShown) { _hyperlinkMessageShown = true; var msg = LocalizationManager.GetString("EditTab.HowToUseHyperlink", "To use this hyperlink, go to the page where you are making a Table of Contents. Next, select some text and then click on the image of chain link. This will turn the selected text into a hyperlink to this page."); var title = LocalizationManager.GetString("EditTab.UsingHyperlink", "Using a hyperlink"); var dlg = new ProblemNotificationDialog( msg, title); dlg.Icon = SystemIcons.Information.ToBitmap(); dlg.ReoccurenceMessage = null; dlg.Show(); } } }); menuItems.Add( new WebThumbNailList.MenuItemSpec() { Label = LocalizationManager.GetString("EditTab.PastePage", "Paste Page"), EnableFunction = (page) => page != null && _model.CanAddPages && _model.GetClipboardHasPage(), ExecuteCommand = (page) => _model.PastePage(page) }); menuItems.Add( new WebThumbNailList.MenuItemSpec() { Label = LocalizationManager.GetString("EditTab.DeletePageButton", "Remove Page"), EnableFunction = (page) => page != null && _model.CanDeletePage, ExecuteCommand = (page) => { if (ConfirmRemovePageDialog.Confirm()) _model.DeletePage(page); }}); menuItems.Add( new WebThumbNailList.MenuItemSpec() { Label = LocalizationManager.GetString("EditTab.ChooseLayoutButton", "Choose Different Layout"), EnableFunction = (page) => page != null && !page.Required && !_model.CurrentBook.LockedDown, ExecuteCommand = (page) => _model.ChangePageLayout(page)}); // This adds the desired menu items to the Gecko context menu that happens when we right-click _thumbNailList.ContextMenuProvider = args => { var page = _thumbNailList.GetPageContaining(args.TargetNode); if (page == null) return true; // no page-related commands if we didn't click on one. if(page != _pageSelection.CurrentSelection) { return true; //it's too dangerous to let users do thing to a page they aren't seeing } foreach (var item in menuItems) { var menuItem = new MenuItem(item.Label, (sender, eventArgs) => item.ExecuteCommand(page)); args.ContextMenu.MenuItems.Add(menuItem); menuItem.Enabled = item.EnableFunction(page); } return true; }; // This sets up the context menu items that will be shown when the user clicks the // arrow in the thumbnail list. _thumbNailList.ContextMenuItems = menuItems; } private void OnPageSelectedChanged(object page, EventArgs e) { if (page == null) return; if (!_dontForwardSelectionEvent) { _pageSelection.SelectPage(page as Page); } } private void PageListView_BackColorChanged(object sender, EventArgs e) { _thumbNailList.BackColor = BackColor; } public void SetBook(Book.Book book)//review: could do this instead by giving this class the bookselection object { if (book == null) { _thumbNailList.SetItems(new Page[] { }); } else { _thumbNailList.SetItems(new IPage[] { new PlaceHolderPage() }.Concat(book.GetPages())); // _thumbNailList.SetItems(book.GetPages()); if(_pageWeThinkShouldBeSelected !=null) { //this var will be set previously when someone told us the page we're to select, //but had not yet given us leave to do the time-consuming process of actually //making the thumbnails and showing them. SelectThumbnailWithoutSendingEvent(_pageWeThinkShouldBeSelected); } } } public void UpdateThumbnailAsync(IPage page) { Logger.WriteMinorEvent("Updating thumbnail for page"); // This might be redundant, we no longer use premade images of pages in this view. // However, it's just possible that when the cover page is modified we need this // to get an updated cover image in the Collections view. _thumbNailList.Thumbnailer.PageChanged(page.Id); _thumbNailList.UpdateThumbnailAsync(page); } public void UpdateAllThumbnails() { _thumbNailList.UpdateAllThumbnails(); } public void Clear() { _thumbNailList.SetItems(new IPage[]{}); } public void SelectThumbnailWithoutSendingEvent(IPage page) { _pageWeThinkShouldBeSelected = page; try { _dontForwardSelectionEvent = true; _thumbNailList.SelectPage(page); } finally { _dontForwardSelectionEvent = false; } } public void EmptyThumbnailCache() { _thumbNailList.EmptyThumbnailCache(); } public new bool Enabled { set { _thumbNailList.Enabled = value; } } } }
using NBitcoin; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using WalletWasabi.Blockchain.TransactionOutputs; using WalletWasabi.CoinJoin.Common.Models; using WalletWasabi.Helpers; using WalletWasabi.Logging; namespace WalletWasabi.CoinJoin.Client.Rounds { public class ClientState { public ClientState() { StateLock = new object(); WaitingList = new Dictionary<SmartCoin, DateTimeOffset>(); Rounds = new List<ClientRound>(); } private object StateLock { get; } /// <summary> /// The coin that is waiting to be mixed. DateTimeOffset: utc, at what time it is allowed to start registering this coin. /// </summary> private Dictionary<SmartCoin, DateTimeOffset> WaitingList { get; } private List<ClientRound> Rounds { get; } public bool IsInErrorState { get; private set; } public void AddCoinToWaitingList(SmartCoin coin) { lock (StateLock) { if (!(WaitingList.ContainsKey(coin) || Rounds.Any(x => x.CoinsRegistered.Contains(coin)))) { WaitingList.Add(coin, DateTimeOffset.UtcNow); Logger.LogInfo($"Coin added to the waiting list: {coin.Index}:{coin.TransactionId}."); } } } public IEnumerable<OutPoint> GetSpentCoins() { lock (StateLock) { return WaitingList.Keys.Concat(Rounds.SelectMany(x => x.CoinsRegistered)).Where(x => x.IsSpent()).Select(x => x.OutPoint).ToArray(); } } public void RemoveCoinFromWaitingList(SmartCoin coin) { lock (StateLock) { if (WaitingList.ContainsKey(coin)) { WaitingList.Remove(coin); Logger.LogInfo($"Coin removed from the waiting list: {coin.Index}:{coin.TransactionId}."); } } } public bool Contains(SmartCoin coin) { lock (StateLock) { return WaitingList.ContainsKey(coin) || Rounds.Any(x => x.CoinsRegistered.Contains(coin)); } } public bool Contains(IEnumerable<OutPoint> outpoints) { lock (StateLock) { foreach (OutPoint txo in outpoints) { if (WaitingList.Keys .Concat(Rounds.SelectMany(x => x.CoinsRegistered)) .Any(x => x.OutPoint == txo)) { return true; } } } return false; } public SmartCoin GetSingleOrDefaultFromWaitingList(SmartCoin coin) { lock (StateLock) { return WaitingList.Keys.SingleOrDefault(x => x == coin); } } public SmartCoin GetSingleOrDefaultCoin(OutPoint coinReference) { lock (StateLock) { return WaitingList.Keys.Concat(Rounds.SelectMany(x => x.CoinsRegistered)).SingleOrDefault(x => x.OutPoint == coinReference); } } public int GetWaitingListCount() { lock (StateLock) { return WaitingList.Count; } } public SmartCoin GetSingleOrDefaultFromWaitingList(OutPoint coinReference) { lock (StateLock) { return WaitingList.Keys.SingleOrDefault(x => x.OutPoint == coinReference); } } public IEnumerable<OutPoint> GetAllQueuedCoins() { lock (StateLock) { return WaitingList.Keys.Concat(Rounds.SelectMany(x => x.CoinsRegistered)).Select(x => x.OutPoint).ToArray(); } } public Money SumAllQueuedCoinAmounts() { lock (StateLock) { return WaitingList.Keys.Concat(Rounds.SelectMany(x => x.CoinsRegistered)).Sum(x => x.Amount); } } public int CountAllQueuedCoins() { lock (StateLock) { return WaitingList.Count + Rounds.Sum(x => x.CoinsRegistered.Count()); } } public IEnumerable<Money> GetAllQueuedCoinAmounts() { lock (StateLock) { return WaitingList.Keys.Concat(Rounds.SelectMany(x => x.CoinsRegistered)).Select(x => x.Amount).ToArray(); } } public IEnumerable<OutPoint> GetAllWaitingCoins() { lock (StateLock) { return WaitingList.Keys.Select(x => x.OutPoint).ToArray(); } } public IEnumerable<OutPoint> GetAllRegisteredCoins() { lock (StateLock) { return Rounds.SelectMany(x => x.CoinsRegistered).Select(x => x.OutPoint).ToArray(); } } public IEnumerable<OutPoint> GetRegistrableCoins(int maximumInputCountPerPeer, Money denomination, Money feePerInputs, Money feePerOutputs) { lock (StateLock) { if (!WaitingList.Any()) // To avoid computations. { return Enumerable.Empty<OutPoint>(); } Money amountNeededExceptInputFees = denomination + (feePerOutputs * 2); var coins = WaitingList .Where(x => x.Value <= DateTimeOffset.UtcNow) .Select(x => x.Key) // Only if registering coins is already allowed. .Where(x => x.Confirmed) .ToList(); // So to not redo it in every cycle. bool lazyMode = false; for (int i = 1; i <= maximumInputCountPerPeer; i++) // The smallest number of coins we can register the better it is. { List<IEnumerable<SmartCoin>> coinGroups; Money amountNeeded = amountNeededExceptInputFees + (feePerInputs * i); // If the sum reaches the minimum amount. if (lazyMode) // Do the largest valid combination. { IEnumerable<SmartCoin> highestValueEnumeration = coins.OrderByDescending(x => x.Amount).Take(i); coinGroups = highestValueEnumeration.Sum(x => x.Amount) >= amountNeeded ? new List<IEnumerable<SmartCoin>> { highestValueEnumeration } : new List<IEnumerable<SmartCoin>>(); } else { DateTimeOffset start = DateTimeOffset.UtcNow; coinGroups = coins.GetPermutations(i, amountNeeded).ToList(); if (DateTimeOffset.UtcNow - start > TimeSpan.FromMilliseconds(10)) // If the permutations took long then then if there's a nextTime, calculating permutations would be too CPU intensive. { lazyMode = true; } } if (i == 1) // If only one coin is to be registered. { // Prefer the largest one, so more mixing volume is more likely. coinGroups = coinGroups.OrderByDescending(x => x.Sum(y => y.Amount)).ToList(); // Try to register with the smallest anonymity set, so new unmixed coins come to the mix. coinGroups = coinGroups.OrderBy(x => x.Sum(y => y.HdPubKey.AnonymitySet)).ToList(); } else // Else coin merging will happen. { // Prefer the lowest amount sum, so perfect mix should be more likely. coinGroups = coinGroups.OrderBy(x => x.Sum(y => y.Amount)).ToList(); // Try to register the largest anonymity set, so red and green coins input merging should be less likely. coinGroups = coinGroups.OrderByDescending(x => x.Sum(y => y.HdPubKey.AnonymitySet)).ToList(); } coinGroups = coinGroups.OrderBy(x => x.Count(y => y.Confirmed == false)).ToList(); // Where the lowest amount of unconfirmed coins there are. IEnumerable<SmartCoin> best = coinGroups.FirstOrDefault(); if (best is { }) { var bestSet = best.ToHashSet(); // -- OPPORTUNISTIC CONSOLIDATION -- // https://github.com/zkSNACKs/WalletWasabi/issues/1651 if (bestSet.Count < maximumInputCountPerPeer) // Ensure limits. { // Generating toxic change leads to mass merging so it's better to merge sooner in coinjoin than the user do it himself in a non-CJ. // The best selection's anonset should not be lowered by this merge. int bestMinAnonset = bestSet.Min(x => x.HdPubKey.AnonymitySet); var bestSum = Money.Satoshis(bestSet.Sum(x => x.Amount)); if (!bestSum.Almost(amountNeeded, Money.Coins(0.0001m)) // Otherwise it wouldn't generate change so consolidation would make no sense. && bestMinAnonset > 1) // Red coins should never be merged. { IEnumerable<SmartCoin> coinsThatCanBeConsolidated = coins .Except(bestSet) // Get all the registrable coins, except the already chosen ones. .Where(x => x.HdPubKey.AnonymitySet >= bestMinAnonset // The anonset must be at least equal to the bestSet's anonset so we do not ruin the change's after mix anonset. && x.HdPubKey.AnonymitySet > 1 // Red coins should never be merged. && x.Amount < amountNeeded // The amount needs to be smaller than the amountNeeded (so to make sure this is toxic change.) && bestSum + x.Amount > amountNeeded) // Sanity check that the amount added do not ruin the registration. .OrderBy(x => x.Amount); // Choose the smallest ones. if (coinsThatCanBeConsolidated.Count() > 1) // Because the last one change should not be circulating, ruining privacy. { var bestCoinToAdd = coinsThatCanBeConsolidated.First(); bestSet.Add(bestCoinToAdd); } } } return bestSet.Select(x => x.OutPoint).ToArray(); } } return Enumerable.Empty<OutPoint>(); // Inputs are too small, max input to be registered is reached. } } public bool AnyCoinsQueued() { lock (StateLock) { return WaitingList.Any() || Rounds.SelectMany(x => x.CoinsRegistered).Any(); } } public IEnumerable<ClientRound> GetActivelyMixingRounds() { lock (StateLock) { return Rounds.Where(x => x.Registration is { } && x.State.Phase >= RoundPhase.ConnectionConfirmation).ToArray(); } } public IEnumerable<ClientRound> GetPassivelyMixingRounds() { lock (StateLock) { return Rounds.Where(x => x.Registration is { } && x.State.Phase == RoundPhase.InputRegistration).ToArray(); } } public IEnumerable<ClientRound> GetAllMixingRounds() { lock (StateLock) { return Rounds.Where(x => x.Registration is { }).ToArray(); } } public ClientRound GetRegistrableRoundOrDefault() { lock (StateLock) { return Rounds.FirstOrDefault(x => x.State.Phase == RoundPhase.InputRegistration); } } public ClientRound GetLatestRoundOrDefault() { lock (StateLock) { return Rounds.LastOrDefault(); } } public ClientRound GetMostAdvancedRoundOrDefault() { lock (StateLock) { var foundAdvanced = Rounds.FirstOrDefault(x => x.State.Phase != RoundPhase.InputRegistration); if (foundAdvanced is { }) { return foundAdvanced; } else { return Rounds.FirstOrDefault(); } } } public int GetSmallestRegistrationTimeout() { lock (StateLock) { if (Rounds.Count == 0) { return 0; } return Rounds.Min(x => x.State.RegistrationTimeout); } } public ClientRound GetSingleOrDefaultRound(long roundId) { lock (StateLock) { return Rounds.SingleOrDefault(x => x.State.RoundId == roundId); } } public void UpdateRoundsByStates(ConcurrentDictionary<OutPoint, IEnumerable<HdPubKeyBlindedPair>> exposedLinks, params RoundStateResponseBase[] allRunningRoundsStates) { Guard.NotNullOrEmpty(nameof(allRunningRoundsStates), allRunningRoundsStates); IsInErrorState = false; lock (StateLock) { // Find the rounds that are not running anymore // Put their coins back to the waiting list // Remove them // Find the rounds that need to be updated // Update them IEnumerable<long> roundsToRemove = Rounds.Select(x => x.State.RoundId).Where(y => !allRunningRoundsStates.Select(z => z.RoundId).Contains(y)); foreach (ClientRound round in Rounds.Where(x => roundsToRemove.Contains(x.State.RoundId))) { var newSuccessfulRoundCount = allRunningRoundsStates.FirstOrDefault()?.SuccessfulRoundCount; bool roundFailed = newSuccessfulRoundCount is { } && round.State.SuccessfulRoundCount == newSuccessfulRoundCount; if (roundFailed) { IsInErrorState = true; } foreach (SmartCoin coin in round.CoinsRegistered) { if (round.Registration.IsPhaseActionsComleted(RoundPhase.Signing)) { var delayRegistration = TimeSpan.FromSeconds(60); WaitingList.Add(coin, DateTimeOffset.UtcNow + delayRegistration); Logger.LogInfo($"Coin added to the waiting list: {coin.Index}:{coin.TransactionId}, but its registration is not allowed till {delayRegistration.TotalSeconds} seconds, because this coin might already be spent."); if (roundFailed) { // Cleanup non-exposed links. foreach (OutPoint input in round.Registration.CoinsRegistered.Select(x => x.OutPoint)) { if (exposedLinks.ContainsKey(input)) // This should always be the case. { exposedLinks[input] = exposedLinks[input].Where(x => !x.IsBlinded); } } } } else { WaitingList.Add(coin, DateTimeOffset.UtcNow); Logger.LogInfo($"Coin added to the waiting list: {coin.Index}:{coin.TransactionId}."); } } round?.Registration?.AliceClient?.Dispose(); Logger.LogInfo($"Round ({round.State.RoundId}) removed. Reason: It's not running anymore."); } Rounds.RemoveAll(x => roundsToRemove.Contains(x.State.RoundId)); foreach (ClientRound round in Rounds) { if (allRunningRoundsStates.Select(x => x.RoundId).Contains(round.State.RoundId)) { round.State = allRunningRoundsStates.Single(x => x.RoundId == round.State.RoundId); } } foreach (RoundStateResponseBase state in allRunningRoundsStates) { if (!Rounds.Select(x => x.State.RoundId).Contains(state.RoundId)) { var r = new ClientRound(state); Rounds.Add(r); Logger.LogInfo($"Round ({r.State.RoundId}) added."); } } } } public void ClearRoundRegistration(long roundId) { lock (StateLock) { foreach (var round in Rounds.Where(x => x.State.RoundId == roundId)) { foreach (var coin in round.CoinsRegistered) { WaitingList.Add(coin, DateTimeOffset.UtcNow); Logger.LogInfo($"Coin added to the waiting list: {coin.Index}:{coin.TransactionId}."); } round.ClearRegistration(); Logger.LogInfo($"Round ({round.State.RoundId}) registration is cleared."); } } } public void DisposeAllAliceClients() { lock (StateLock) { foreach (var aliceClient in Rounds?.Select(x => x?.Registration?.AliceClient)) { aliceClient?.Dispose(); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.Xml; namespace System.ServiceModel.Dispatcher { internal class StreamFormatter { private string _wrapperName; private string _wrapperNS; private string _partName; private string _partNS; private int _streamIndex; private bool _isRequest; private string _operationName; private const int returnValueIndex = -1; internal static StreamFormatter Create(MessageDescription messageDescription, string operationName, bool isRequest) { MessagePartDescription streamPart = ValidateAndGetStreamPart(messageDescription, isRequest, operationName); if (streamPart == null) return null; return new StreamFormatter(messageDescription, streamPart, operationName, isRequest); } private StreamFormatter(MessageDescription messageDescription, MessagePartDescription streamPart, string operationName, bool isRequest) { if ((object)streamPart == (object)messageDescription.Body.ReturnValue) _streamIndex = returnValueIndex; else _streamIndex = streamPart.Index; _wrapperName = messageDescription.Body.WrapperName; _wrapperNS = messageDescription.Body.WrapperNamespace; _partName = streamPart.Name; _partNS = streamPart.Namespace; _isRequest = isRequest; _operationName = operationName; } internal void Serialize(XmlDictionaryWriter writer, object[] parameters, object returnValue) { Stream streamValue = GetStreamAndWriteStartWrapperIfNecessary(writer, parameters, returnValue); var streamProvider = new OperationStreamProvider(streamValue); StreamFormatterHelper.WriteValue(writer, streamProvider); WriteEndWrapperIfNecessary(writer); } internal async Task SerializeAsync(XmlDictionaryWriter writer, object[] parameters, object returnValue) { Stream streamValue = await GetStreamAndWriteStartWrapperIfNecessaryAsync(writer, parameters, returnValue); var streamProvider = new OperationStreamProvider(streamValue); await StreamFormatterHelper.WriteValueAsync(writer, streamProvider); await WriteEndWrapperIfNecessaryAsync(writer); } private Stream GetStreamAndWriteStartWrapperIfNecessary(XmlDictionaryWriter writer, object[] parameters, object returnValue) { Stream streamValue = GetStreamValue(parameters, returnValue); if (streamValue == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(_partName); if (WrapperName != null) writer.WriteStartElement(WrapperName, WrapperNamespace); writer.WriteStartElement(PartName, PartNamespace); return streamValue; } private async Task<Stream> GetStreamAndWriteStartWrapperIfNecessaryAsync(XmlDictionaryWriter writer, object[] parameters, object returnValue) { Stream streamValue = GetStreamValue(parameters, returnValue); if (streamValue == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(_partName); if (WrapperName != null) await writer.WriteStartElementAsync(null, WrapperName, WrapperNamespace); await writer.WriteStartElementAsync(null, PartName, PartNamespace); return streamValue; } private void WriteEndWrapperIfNecessary(XmlDictionaryWriter writer) { writer.WriteEndElement(); if (_wrapperName != null) writer.WriteEndElement(); } private Task WriteEndWrapperIfNecessaryAsync(XmlDictionaryWriter writer) { writer.WriteEndElement(); if (_wrapperName != null) writer.WriteEndElement(); return Task.CompletedTask; } internal IAsyncResult BeginSerialize(XmlDictionaryWriter writer, object[] parameters, object returnValue, AsyncCallback callback, object state) { return new SerializeAsyncResult(this, writer, parameters, returnValue, callback, state); } public void EndSerialize(IAsyncResult result) { SerializeAsyncResult.End(result); } internal class SerializeAsyncResult : AsyncResult { private static AsyncCompletion s_handleEndSerialize = new AsyncCompletion(HandleEndSerialize); private StreamFormatter _streamFormatter; private XmlDictionaryWriter _writer; internal SerializeAsyncResult(StreamFormatter streamFormatter, XmlDictionaryWriter writer, object[] parameters, object returnValue, AsyncCallback callback, object state) : base(callback, state) { _streamFormatter = streamFormatter; _writer = writer; // As we use the Task-returning method for async operation, // we shouldn't get to this point. Throw exception just in case. throw ExceptionHelper.AsError(NotImplemented.ByDesign); } private static bool HandleEndSerialize(IAsyncResult result) { SerializeAsyncResult thisPtr = (SerializeAsyncResult)result.AsyncState; thisPtr._streamFormatter.WriteEndWrapperIfNecessary(thisPtr._writer); return true; } public static void End(IAsyncResult result) { AsyncResult.End<SerializeAsyncResult>(result); } } internal void Deserialize(object[] parameters, ref object retVal, Message message) { SetStreamValue(parameters, ref retVal, new MessageBodyStream(message, WrapperName, WrapperNamespace, PartName, PartNamespace, _isRequest)); } internal string WrapperName { get { return _wrapperName; } set { _wrapperName = value; } } internal string WrapperNamespace { get { return _wrapperNS; } set { _wrapperNS = value; } } internal string PartName { get { return _partName; } } internal string PartNamespace { get { return _partNS; } } private Stream GetStreamValue(object[] parameters, object returnValue) { if (_streamIndex == returnValueIndex) return (Stream)returnValue; return (Stream)parameters[_streamIndex]; } private void SetStreamValue(object[] parameters, ref object returnValue, Stream streamValue) { if (_streamIndex == returnValueIndex) returnValue = streamValue; else parameters[_streamIndex] = streamValue; } private static MessagePartDescription ValidateAndGetStreamPart(MessageDescription messageDescription, bool isRequest, string operationName) { MessagePartDescription part = GetStreamPart(messageDescription); if (part != null) return part; if (HasStream(messageDescription)) { if (messageDescription.IsTypedMessage) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInvalidStreamInTypedMessage, messageDescription.MessageName))); else if (isRequest) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInvalidStreamInRequest, operationName))); else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInvalidStreamInResponse, operationName))); } return null; } private static bool HasStream(MessageDescription messageDescription) { if (messageDescription.Body.ReturnValue != null && messageDescription.Body.ReturnValue.Type == typeof(Stream)) return true; foreach (MessagePartDescription part in messageDescription.Body.Parts) { if (part.Type == typeof(Stream)) return true; } return false; } private static MessagePartDescription GetStreamPart(MessageDescription messageDescription) { if (OperationFormatter.IsValidReturnValue(messageDescription.Body.ReturnValue)) { if (messageDescription.Body.Parts.Count == 0) if (messageDescription.Body.ReturnValue.Type == typeof(Stream)) return messageDescription.Body.ReturnValue; } else { if (messageDescription.Body.Parts.Count == 1) if (messageDescription.Body.Parts[0].Type == typeof(Stream)) return messageDescription.Body.Parts[0]; } return null; } internal static bool IsStream(MessageDescription messageDescription) { return GetStreamPart(messageDescription) != null; } internal class MessageBodyStream : Stream { private Message _message; private XmlDictionaryReader _reader; private long _position; private string _wrapperName, _wrapperNs; private string _elementName, _elementNs; private bool _isRequest; internal MessageBodyStream(Message message, string wrapperName, string wrapperNs, string elementName, string elementNs, bool isRequest) { _message = message; _position = 0; _wrapperName = wrapperName; _wrapperNs = wrapperNs; _elementName = elementName; _elementNs = elementNs; _isRequest = isRequest; } public override int Read(byte[] buffer, int offset, int count) { EnsureStreamIsOpen(); if (buffer == null) throw TraceUtility.ThrowHelperError(new ArgumentNullException("buffer"), _message); if (offset < 0) throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", offset, SR.Format(SR.ValueMustBeNonNegative)), _message); if (count < 0) throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", count, SR.Format(SR.ValueMustBeNonNegative)), _message); if (buffer.Length - offset < count) throw TraceUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.SFxInvalidStreamOffsetLength, offset + count)), _message); try { if (_reader == null) { _reader = _message.GetReaderAtBodyContents(); if (_wrapperName != null) { _reader.MoveToContent(); _reader.ReadStartElement(_wrapperName, _wrapperNs); } _reader.MoveToContent(); if (_reader.NodeType == XmlNodeType.EndElement) { return 0; } _reader.ReadStartElement(_elementName, _elementNs); } if (_reader.MoveToContent() != XmlNodeType.Text) { Exhaust(_reader); return 0; } int bytesRead = _reader.ReadContentAsBase64(buffer, offset, count); _position += bytesRead; if (bytesRead == 0) { Exhaust(_reader); } return bytesRead; } catch (Exception ex) { if (Fx.IsFatal(ex)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new IOException(SR.Format(SR.SFxStreamIOException), ex)); } } private void EnsureStreamIsOpen() { if (_message.State == MessageState.Closed) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(SR.Format( _isRequest ? SR.SFxStreamRequestMessageClosed : SR.SFxStreamResponseMessageClosed))); } private static void Exhaust(XmlDictionaryReader reader) { if (reader != null) { while (reader.Read()) { // drain } } } public override long Position { get { EnsureStreamIsOpen(); return _position; } set { throw TraceUtility.ThrowHelperError(new NotSupportedException(), _message); } } protected override void Dispose(bool isDisposing) { _message.Close(); if (_reader != null) { _reader.Dispose(); _reader = null; } base.Dispose(isDisposing); } public override bool CanRead { get { return _message.State != MessageState.Closed; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override long Length { get { throw TraceUtility.ThrowHelperError(new NotSupportedException(), _message); } } public override void Flush() { throw TraceUtility.ThrowHelperError(new NotSupportedException(), _message); } public override long Seek(long offset, SeekOrigin origin) { throw TraceUtility.ThrowHelperError(new NotSupportedException(), _message); } public override void SetLength(long value) { throw TraceUtility.ThrowHelperError(new NotSupportedException(), _message); } public override void Write(byte[] buffer, int offset, int count) { throw TraceUtility.ThrowHelperError(new NotSupportedException(), _message); } } internal class OperationStreamProvider { private Stream _stream; internal OperationStreamProvider(Stream stream) { _stream = stream; } public Stream GetStream() { return _stream; } public void ReleaseStream(Stream stream) { //Noop } } internal class StreamFormatterHelper { // The method was duplicated from the desktop implementation of // System.Xml.XmlDictionaryWriter.WriteValue(IStreamProvider) public static void WriteValue(XmlDictionaryWriter writer, OperationStreamProvider value) { if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); Stream stream = value.GetStream(); if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.XmlInvalidStream))); } int blockSize = 256; int bytesRead = 0; byte[] block = new byte[blockSize]; while (true) { bytesRead = stream.Read(block, 0, blockSize); if (bytesRead > 0) { writer.WriteBase64(block, 0, bytesRead); } else { break; } if (blockSize < 65536 && bytesRead == blockSize) { blockSize = blockSize * 16; block = new byte[blockSize]; } } value.ReleaseStream(stream); } public static async Task WriteValueAsync(XmlDictionaryWriter writer, OperationStreamProvider value) { if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); Stream stream = value.GetStream(); if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.XmlInvalidStream))); } int blockSize = 256; int bytesRead = 0; byte[] block = new byte[blockSize]; while (true) { bytesRead = await stream.ReadAsync(block, 0, blockSize); if (bytesRead > 0) { // XmlDictionaryWriter has not implemented WriteBase64Async() yet. writer.WriteBase64(block, 0, bytesRead); } else { break; } if (blockSize < 65536 && bytesRead == blockSize) { blockSize = blockSize * 16; block = new byte[blockSize]; } } value.ReleaseStream(stream); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using Validation; namespace System.Collections.Immutable { /// <summary> /// A node in the AVL tree storing key/value pairs with Int32 keys. /// </summary> /// <remarks> /// This is a trimmed down version of <see cref="ImmutableSortedDictionary{TKey, TValue}.Node"/> /// with TKey fixed to be Int32. This avoids multiple interface-based dispatches while examining /// each node in the tree during a lookup: an interface call to the comparer's Compare method, /// and then an interface call to Int32's IComparable's CompareTo method as part of /// the GenericComparer{Int32}'s Compare implementation. /// </remarks> [DebuggerDisplay("{_key} = {_value}")] internal sealed class SortedInt32KeyNode<TValue> : IBinaryTree { /// <summary> /// The default empty node. /// </summary> internal static readonly SortedInt32KeyNode<TValue> EmptyNode = new SortedInt32KeyNode<TValue>(); /// <summary> /// The Int32 key associated with this node. /// </summary> private readonly int _key; /// <summary> /// The value associated with this node. /// </summary> /// <remarks> /// Sadly, this field could be readonly but doing so breaks serialization due to bug: /// http://connect.microsoft.com/VisualStudio/feedback/details/312970/weird-argumentexception-when-deserializing-field-in-typedreferences-cannot-be-static-or-init-only /// </remarks> private TValue _value; /// <summary> /// A value indicating whether this node has been frozen (made immutable). /// </summary> /// <remarks> /// Nodes must be frozen before ever being observed by a wrapping collection type /// to protect collections from further mutations. /// </remarks> private bool _frozen; /// <summary> /// The depth of the tree beneath this node. /// </summary> private byte _height; // AVL tree height <= ~1.44 * log2(numNodes + 2) /// <summary> /// The left tree. /// </summary> private SortedInt32KeyNode<TValue> _left; /// <summary> /// The right tree. /// </summary> private SortedInt32KeyNode<TValue> _right; /// <summary> /// Initializes a new instance of the <see cref="SortedInt32KeyNode{TValue}"/> class that is pre-frozen. /// </summary> private SortedInt32KeyNode() { _frozen = true; // the empty node is *always* frozen. } /// <summary> /// Initializes a new instance of the <see cref="SortedInt32KeyNode{TValue}"/> class that is not yet frozen. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <param name="frozen">Whether this node is prefrozen.</param> private SortedInt32KeyNode(int key, TValue value, SortedInt32KeyNode<TValue> left, SortedInt32KeyNode<TValue> right, bool frozen = false) { Requires.NotNull(left, "left"); Requires.NotNull(right, "right"); Debug.Assert(!frozen || (left._frozen && right._frozen)); _key = key; _value = value; _left = left; _right = right; _frozen = frozen; _height = checked((byte)(1 + Math.Max(left._height, right._height))); } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> public bool IsEmpty { get { return _left == null; } } /// <summary> /// Gets the height of the tree beneath this node. /// </summary> public int Height { get { return _height; } } /// <summary> /// Gets the left branch of this node. /// </summary> public SortedInt32KeyNode<TValue> Left { get { return _left; } } /// <summary> /// Gets the right branch of this node. /// </summary> public SortedInt32KeyNode<TValue> Right { get { return _right; } } /// <summary> /// Gets the left branch of this node. /// </summary> IBinaryTree IBinaryTree.Left { get { return _left; } } /// <summary> /// Gets the right branch of this node. /// </summary> IBinaryTree IBinaryTree.Right { get { return _right; } } /// <summary> /// Gets the number of elements contained by this node and below. /// </summary> int IBinaryTree.Count { get { throw new NotSupportedException(); } } /// <summary> /// Gets the value represented by the current node. /// </summary> public KeyValuePair<int, TValue> Value { get { return new KeyValuePair<int, TValue>(_key, _value); } } /// <summary> /// Gets the values. /// </summary> internal IEnumerable<TValue> Values { get { foreach (var pair in this) { yield return pair.Value; } } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> public Enumerator GetEnumerator() { return new Enumerator(this); } /// <summary> /// Adds the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="valueComparer">The value comparer.</param> /// <param name="replacedExistingValue">Receives a value indicating whether an existing value was replaced.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> internal SortedInt32KeyNode<TValue> SetItem(int key, TValue value, IEqualityComparer<TValue> valueComparer, out bool replacedExistingValue, out bool mutated) { Requires.NotNull(valueComparer, "valueComparer"); return this.SetOrAdd(key, value, valueComparer, true, out replacedExistingValue, out mutated); } /// <summary> /// Removes the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> /// <returns>The new AVL tree.</returns> internal SortedInt32KeyNode<TValue> Remove(int key, out bool mutated) { return this.RemoveRecursive(key, out mutated); } /// <summary> /// Gets the value or default. /// </summary> /// <param name="key">The key.</param> /// <returns>The value.</returns> [Pure] internal TValue GetValueOrDefault(int key) { var match = this.Search(key); return match.IsEmpty ? default(TValue) : match._value; } /// <summary> /// Tries to get the value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>True if the key was found.</returns> [Pure] internal bool TryGetValue(int key, out TValue value) { var match = this.Search(key); if (match.IsEmpty) { value = default(TValue); return false; } else { value = match._value; return true; } } /// <summary> /// Freezes this node and all descendent nodes so that any mutations require a new instance of the nodes. /// </summary> internal void Freeze(Action<KeyValuePair<int, TValue>> freezeAction = null) { // If this node is frozen, all its descendents must already be frozen. if (!_frozen) { if (freezeAction != null) { freezeAction(new KeyValuePair<int, TValue>(_key, _value)); } _left.Freeze(freezeAction); _right.Freeze(freezeAction); _frozen = true; } } /// <summary> /// AVL rotate left operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static SortedInt32KeyNode<TValue> RotateLeft(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); if (tree._right.IsEmpty) { return tree; } var right = tree._right; return right.Mutate(left: tree.Mutate(right: right._left)); } /// <summary> /// AVL rotate right operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static SortedInt32KeyNode<TValue> RotateRight(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); if (tree._left.IsEmpty) { return tree; } var left = tree._left; return left.Mutate(right: tree.Mutate(left: left._right)); } /// <summary> /// AVL rotate double-left operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static SortedInt32KeyNode<TValue> DoubleLeft(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); if (tree._right.IsEmpty) { return tree; } SortedInt32KeyNode<TValue> rotatedRightChild = tree.Mutate(right: RotateRight(tree._right)); return RotateLeft(rotatedRightChild); } /// <summary> /// AVL rotate double-right operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static SortedInt32KeyNode<TValue> DoubleRight(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); if (tree._left.IsEmpty) { return tree; } SortedInt32KeyNode<TValue> rotatedLeftChild = tree.Mutate(left: RotateLeft(tree._left)); return RotateRight(rotatedLeftChild); } /// <summary> /// Returns a value indicating whether the tree is in balance. /// </summary> /// <param name="tree">The tree.</param> /// <returns>0 if the tree is in balance, a positive integer if the right side is heavy, or a negative integer if the left side is heavy.</returns> [Pure] private static int Balance(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); return tree._right._height - tree._left._height; } /// <summary> /// Determines whether the specified tree is right heavy. /// </summary> /// <param name="tree">The tree.</param> /// <returns> /// <c>true</c> if [is right heavy] [the specified tree]; otherwise, <c>false</c>. /// </returns> [Pure] private static bool IsRightHeavy(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); return Balance(tree) >= 2; } /// <summary> /// Determines whether the specified tree is left heavy. /// </summary> [Pure] private static bool IsLeftHeavy(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); return Balance(tree) <= -2; } /// <summary> /// Balances the specified tree. /// </summary> /// <param name="tree">The tree.</param> /// <returns>A balanced tree.</returns> [Pure] private static SortedInt32KeyNode<TValue> MakeBalanced(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); if (IsRightHeavy(tree)) { return Balance(tree._right) < 0 ? DoubleLeft(tree) : RotateLeft(tree); } if (IsLeftHeavy(tree)) { return Balance(tree._left) > 0 ? DoubleRight(tree) : RotateRight(tree); } return tree; } /// <summary> /// Creates a node tree that contains the contents of a list. /// </summary> /// <param name="items">An indexable list with the contents that the new node tree should contain.</param> /// <param name="start">The starting index within <paramref name="items"/> that should be captured by the node tree.</param> /// <param name="length">The number of elements from <paramref name="items"/> that should be captured by the node tree.</param> /// <returns>The root of the created node tree.</returns> [Pure] private static SortedInt32KeyNode<TValue> NodeTreeFromList(IOrderedCollection<KeyValuePair<int, TValue>> items, int start, int length) { Requires.NotNull(items, "items"); Requires.Range(start >= 0, "start"); Requires.Range(length >= 0, "length"); if (length == 0) { return EmptyNode; } int rightCount = (length - 1) / 2; int leftCount = (length - 1) - rightCount; SortedInt32KeyNode<TValue> left = NodeTreeFromList(items, start, leftCount); SortedInt32KeyNode<TValue> right = NodeTreeFromList(items, start + leftCount + 1, rightCount); var item = items[start + leftCount]; return new SortedInt32KeyNode<TValue>(item.Key, item.Value, left, right, true); } /// <summary> /// Adds the specified key. Callers are expected to have validated arguments. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="valueComparer">The value comparer.</param> /// <param name="overwriteExistingValue">if <c>true</c>, an existing key=value pair will be overwritten with the new one.</param> /// <param name="replacedExistingValue">Receives a value indicating whether an existing value was replaced.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> /// <returns>The new AVL tree.</returns> private SortedInt32KeyNode<TValue> SetOrAdd(int key, TValue value, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue, out bool replacedExistingValue, out bool mutated) { // Arg validation skipped in this private method because it's recursive and the tax // of revalidating arguments on each recursive call is significant. // All our callers are therefore required to have done input validation. replacedExistingValue = false; if (this.IsEmpty) { mutated = true; return new SortedInt32KeyNode<TValue>(key, value, this, this); } else { SortedInt32KeyNode<TValue> result = this; if (key > _key) { var newRight = _right.SetOrAdd(key, value, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated); if (mutated) { result = this.Mutate(right: newRight); } } else if (key < _key) { var newLeft = _left.SetOrAdd(key, value, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated); if (mutated) { result = this.Mutate(left: newLeft); } } else { if (valueComparer.Equals(_value, value)) { mutated = false; return this; } else if (overwriteExistingValue) { mutated = true; replacedExistingValue = true; result = new SortedInt32KeyNode<TValue>(key, value, _left, _right); } else { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Strings.DuplicateKey, key)); } } return mutated ? MakeBalanced(result) : result; } } /// <summary> /// Removes the specified key. Callers are expected to validate arguments. /// </summary> /// <param name="key">The key.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> /// <returns>The new AVL tree.</returns> private SortedInt32KeyNode<TValue> RemoveRecursive(int key, out bool mutated) { if (this.IsEmpty) { mutated = false; return this; } else { SortedInt32KeyNode<TValue> result = this; if (key == _key) { // We have a match. mutated = true; // If this is a leaf, just remove it // by returning Empty. If we have only one child, // replace the node with the child. if (_right.IsEmpty && _left.IsEmpty) { result = EmptyNode; } else if (_right.IsEmpty && !_left.IsEmpty) { result = _left; } else if (!_right.IsEmpty && _left.IsEmpty) { result = _right; } else { // We have two children. Remove the next-highest node and replace // this node with it. var successor = _right; while (!successor._left.IsEmpty) { successor = successor._left; } bool dummyMutated; var newRight = _right.Remove(successor._key, out dummyMutated); result = successor.Mutate(left: _left, right: newRight); } } else if (key < _key) { var newLeft = _left.Remove(key, out mutated); if (mutated) { result = this.Mutate(left: newLeft); } } else { var newRight = _right.Remove(key, out mutated); if (mutated) { result = this.Mutate(right: newRight); } } return result.IsEmpty ? result : MakeBalanced(result); } } /// <summary> /// Creates a node mutation, either by mutating this node (if not yet frozen) or by creating a clone of this node /// with the described changes. /// </summary> /// <param name="left">The left branch of the mutated node.</param> /// <param name="right">The right branch of the mutated node.</param> /// <returns>The mutated (or created) node.</returns> private SortedInt32KeyNode<TValue> Mutate(SortedInt32KeyNode<TValue> left = null, SortedInt32KeyNode<TValue> right = null) { if (_frozen) { return new SortedInt32KeyNode<TValue>(_key, _value, left ?? _left, right ?? _right); } else { if (left != null) { _left = left; } if (right != null) { _right = right; } _height = checked((byte)(1 + Math.Max(_left._height, _right._height))); return this; } } /// <summary> /// Searches the specified key. Callers are expected to validate arguments. /// </summary> /// <param name="key">The key.</param> [Pure] private SortedInt32KeyNode<TValue> Search(int key) { if (this.IsEmpty || key == _key) { return this; } if (key > _key) { return _right.Search(key); } return _left.Search(key); } /// <summary> /// Enumerates the contents of a binary tree. /// </summary> /// <remarks> /// This struct can and should be kept in exact sync with the other binary tree enumerators: /// ImmutableList.Enumerator, ImmutableSortedMap.Enumerator, and ImmutableSortedSet.Enumerator. /// /// CAUTION: when this enumerator is actually used as a valuetype (not boxed) do NOT copy it by assigning to a second variable /// or by passing it to another method. When this enumerator is disposed of it returns a mutable reference type stack to a resource pool, /// and if the value type enumerator is copied (which can easily happen unintentionally if you pass the value around) there is a risk /// that a stack that has already been returned to the resource pool may still be in use by one of the enumerator copies, leading to data /// corruption and/or exceptions. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] public struct Enumerator : IEnumerator<KeyValuePair<int, TValue>>, ISecurePooledObjectUser { /// <summary> /// The resource pool of reusable mutable stacks for purposes of enumeration. /// </summary> /// <remarks> /// We utilize this resource pool to make "allocation free" enumeration achievable. /// </remarks> private static readonly SecureObjectPool<Stack<RefAsValueType<SortedInt32KeyNode<TValue>>>, Enumerator> s_enumeratingStacks = new SecureObjectPool<Stack<RefAsValueType<SortedInt32KeyNode<TValue>>>, Enumerator>(); /// <summary> /// A unique ID for this instance of this enumerator. /// Used to protect pooled objects from use after they are recycled. /// </summary> private readonly int _poolUserId; /// <summary> /// The set being enumerated. /// </summary> private SortedInt32KeyNode<TValue> _root; /// <summary> /// The stack to use for enumerating the binary tree. /// </summary> private SecurePooledObject<Stack<RefAsValueType<SortedInt32KeyNode<TValue>>>> _stack; /// <summary> /// The node currently selected. /// </summary> private SortedInt32KeyNode<TValue> _current; /// <summary> /// Initializes an Enumerator structure. /// </summary> /// <param name="root">The root of the set to be enumerated.</param> internal Enumerator(SortedInt32KeyNode<TValue> root) { Requires.NotNull(root, "root"); _root = root; _current = null; _poolUserId = SecureObjectPool.NewId(); _stack = null; if (!_root.IsEmpty) { if (!s_enumeratingStacks.TryTake(this, out _stack)) { _stack = s_enumeratingStacks.PrepNew(this, new Stack<RefAsValueType<SortedInt32KeyNode<TValue>>>(root.Height)); } this.PushLeft(_root); } } /// <summary> /// The current element. /// </summary> public KeyValuePair<int, TValue> Current { get { this.ThrowIfDisposed(); if (_current != null) { return _current.Value; } throw new InvalidOperationException(); } } /// <inheritdoc/> int ISecurePooledObjectUser.PoolUserId { get { return _poolUserId; } } /// <summary> /// The current element. /// </summary> object IEnumerator.Current { get { return this.Current; } } /// <summary> /// Disposes of this enumerator and returns the stack reference to the resource pool. /// </summary> public void Dispose() { _root = null; _current = null; Stack<RefAsValueType<SortedInt32KeyNode<TValue>>> stack; if (_stack != null && _stack.TryUse(ref this, out stack)) { stack.ClearFastWhenEmpty(); s_enumeratingStacks.TryAdd(this, _stack); } _stack = null; } /// <summary> /// Advances enumeration to the next element. /// </summary> /// <returns>A value indicating whether there is another element in the enumeration.</returns> public bool MoveNext() { this.ThrowIfDisposed(); if (_stack != null) { var stack = _stack.Use(ref this); if (stack.Count > 0) { SortedInt32KeyNode<TValue> n = stack.Pop().Value; _current = n; this.PushLeft(n.Right); return true; } } _current = null; return false; } /// <summary> /// Restarts enumeration. /// </summary> public void Reset() { this.ThrowIfDisposed(); _current = null; if (_stack != null) { var stack = _stack.Use(ref this); stack.ClearFastWhenEmpty(); this.PushLeft(_root); } } /// <summary> /// Throws an ObjectDisposedException if this enumerator has been disposed. /// </summary> internal void ThrowIfDisposed() { // Since this is a struct, copies might not have been marked as disposed. // But the stack we share across those copies would know. // This trick only works when we have a non-null stack. // For enumerators of empty collections, there isn't any natural // way to know when a copy of the struct has been disposed of. if (_root == null || (_stack != null && !_stack.IsOwned(ref this))) { Validation.Requires.FailObjectDisposed(this); } } /// <summary> /// Pushes this node and all its Left descendents onto the stack. /// </summary> /// <param name="node">The starting node to push onto the stack.</param> private void PushLeft(SortedInt32KeyNode<TValue> node) { Requires.NotNull(node, "node"); var stack = _stack.Use(ref this); while (!node.IsEmpty) { stack.Push(new RefAsValueType<SortedInt32KeyNode<TValue>>(node)); node = node.Left; } } } } }
// ********************************************************************************************************* // Product Name: DotSpatial.Tools.DialogElement // Description: The abstract tool Element class to be inherited by elements of the tool dialog // // ********************************************************************************************************* // // The Original Code is Toolbox.dll for the DotSpatial 4.6/6 ToolManager project // // The Initial Developer of this Original Code is Brian Marchionni. Created in Oct, 2008. // // Contributor(s): (Open source contributors should list themselves and their modifications here). // ------------------|------------|--------------------------------------------------------------- // Ted Dunsford | 8/28/2009 | Cleaned up some code formatting using resharper // ********************************************************************************************************* using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace DotSpatial.Modeling.Forms.Elements { /// <summary> /// A modular component that can be inherited to retrieve parameters for functions. /// </summary> public class DialogElement : UserControl { #region Class Variables //Status stuff private readonly ToolTip _lightTip = new ToolTip(); /// <summary> /// The group box for this element /// </summary> private GroupBox _groupBox; // The group box that every other component sites in // The label that contains the icon private Label _lblStatus; private Parameter _param; private ToolStatus _status; /// <summary> /// Fires when the inactive areas around the controls are clicked on the element. /// </summary> public event EventHandler Clicked; #endregion #region Methods /// <summary> /// Creates a blank dialog element /// </summary> public DialogElement() { //Required by the constructor InitializeComponent(); //Sets up the tooltip _lightTip.SetToolTip(_lblStatus, string.Empty); } /// <summary> /// Fires whenever the /// </summary> /// <param name="sender"></param> protected virtual void ParamValueChanged(Parameter sender) { Refresh(); } /// <summary> /// Sets the given text as the tooltip text of the given control. /// </summary> /// <param name="control">Control whose tooltip text is set.</param> /// <param name="toolTipText">Text that should be shown in tooltip of the control.</param> protected void SetToolTipText(Control control, string toolTipText) { _lightTip.SetToolTip(control, toolTipText); } #endregion #region Events /// <summary> /// Called to fire the click event for this element /// </summary> /// <param name="e">A mouse event args thingy</param> protected new void OnClick(EventArgs e) { if (Clicked != null) Clicked(this, e); } /// <summary> /// Occurs when the dialong element is clicked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void DialogElement_Click(object sender, EventArgs e) { OnClick(e); } #endregion #region Properties /// <summary> /// Gets or sets the group box that surrounds the element contents /// </summary> protected GroupBox GroupBox { get { return _groupBox; } set { _groupBox = value; } } /// <summary> /// Gets or sets the status label /// </summary> protected Label StatusLabel { get { return _lblStatus; } set { _lblStatus = value; } } /// <summary> /// Gets or sets the tool tip text to display when the mouse hovers over the light status /// </summary> protected string LightTipText { get { return _lightTip.GetToolTip(_lblStatus); } set { _lightTip.SetToolTip(_lblStatus, value); } } /// <summary> /// Gets the current status the input /// </summary> public virtual ToolStatus Status { get { return _status; } set { _status = value; if (_status == ToolStatus.Empty) _lblStatus.Image = Images.Caution; else if (_status == ToolStatus.Error) _lblStatus.Image = Images.Error; else _lblStatus.Image = Images.valid; } } /// <summary> /// Gets or sets the Parameter that the element represents /// </summary> public Parameter Param { get { return _param; } protected set { _param = value; _param.ValueChanged += ParamValueChanged; } } #endregion /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required designer variable /// </summary> protected IContainer components; /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { ComponentResourceManager resources = new ComponentResourceManager(typeof(DialogElement)); this._groupBox = new GroupBox(); this._lblStatus = new Label(); this._groupBox.SuspendLayout(); this.SuspendLayout(); // // GroupBox1 // this._groupBox.BackgroundImageLayout = ImageLayout.None; this._groupBox.Controls.Add(this._lblStatus); this._groupBox.Dock = DockStyle.Fill; this._groupBox.Location = new Point(0, 0); this._groupBox.Name = "_groupBox"; this._groupBox.Size = new Size(492, 45); this._groupBox.TabIndex = 2; this._groupBox.TabStop = false; this._groupBox.Click += new EventHandler(this.DialogElement_Click); // // _lblStatus // this._lblStatus.Image = ((Image)(resources.GetObject("_lblStatus.Image"))); this._lblStatus.Location = new Point(12, 20); this._lblStatus.Name = "_lblStatus"; this._lblStatus.Size = new Size(16, 16); this._lblStatus.TabIndex = 1; this._lblStatus.Click += new EventHandler(this.DialogElement_Click); // // DialogElement // this.AutoScaleDimensions = new SizeF(6F, 13F); this.AutoSize = true; this.Controls.Add(this._groupBox); this.Name = "DialogElement"; this.Size = new Size(492, 45); this.Click += new EventHandler(this.DialogElement_Click); this._groupBox.ResumeLayout(false); this.ResumeLayout(false); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using TelemData = System.Collections.Generic.KeyValuePair<string, object>; using Xunit; namespace System.Diagnostics.Tests { /// <summary> /// Tests for DiagnosticSource and DiagnosticListener /// </summary> public class DiagnosticSourceTest { /// <summary> /// Trivial example of passing an integer /// </summary> [Fact] public void IntPayload() { using (DiagnosticListener listener = new DiagnosticListener("Testing")) { DiagnosticSource source = listener; var result = new List<KeyValuePair<string, object>>(); var observer = new ObserverToList<TelemData>(result); using (listener.Subscribe(new ObserverToList<TelemData>(result))) { listener.Write("IntPayload", 5); Assert.Equal(1, result.Count); Assert.Equal("IntPayload", result[0].Key); Assert.Equal(5, result[0].Value); } // unsubscribe // Make sure that after unsubscribing, we don't get more events. source.Write("IntPayload", 5); Assert.Equal(1, result.Count); } } /// <summary> /// slightly less trivial of passing a structure with a couple of fields /// </summary> [Fact] public void StructPayload() { using (DiagnosticListener listener = new DiagnosticListener("Testing")) { DiagnosticSource source = listener; var result = new List<KeyValuePair<string, object>>(); using (listener.Subscribe(new ObserverToList<TelemData>(result))) { source.Write("StructPayload", new Payload() { Name = "Hi", Id = 67 }); Assert.Equal(1, result.Count); Assert.Equal("StructPayload", result[0].Key); var payload = (Payload)result[0].Value; Assert.Equal(67, payload.Id); Assert.Equal("Hi", payload.Name); } source.Write("StructPayload", new Payload() { Name = "Hi", Id = 67 }); Assert.Equal(1, result.Count); } } /// <summary> /// Tests the IObserver OnCompleted callback. /// </summary> [Fact] public void Completed() { var result = new List<KeyValuePair<string, object>>(); var observer = new ObserverToList<TelemData>(result); var listener = new DiagnosticListener("MyListener"); var subscription = listener.Subscribe(observer); listener.Write("IntPayload", 5); Assert.Equal(1, result.Count); Assert.Equal("IntPayload", result[0].Key); Assert.Equal(5, result[0].Value); Assert.False(observer.Completed); // The listener dies listener.Dispose(); Assert.True(observer.Completed); // confirm that we can unsubscribe without crashing subscription.Dispose(); // If we resubscribe after dispose, but it does not do anything. subscription = listener.Subscribe(observer); listener.Write("IntPayload", 5); Assert.Equal(1, result.Count); } /// <summary> /// Simple tests for the IsEnabled method. /// </summary> [Fact] public void BasicIsEnabled() { using (DiagnosticListener listener = new DiagnosticListener("Testing")) { DiagnosticSource source = listener; var result = new List<KeyValuePair<string, object>>(); bool seenUninteresting = false; bool seenStructPayload = false; Predicate<string> predicate = delegate (string name) { if (name == "Uninteresting") seenUninteresting = true; if (name == "StructPayload") seenStructPayload = true; return name == "StructPayload"; }; Assert.False(listener.IsEnabled()); using (listener.Subscribe(new ObserverToList<TelemData>(result), predicate)) { Assert.False(source.IsEnabled("Uninteresting")); Assert.False(source.IsEnabled("Uninteresting", "arg1", "arg2")); Assert.True(source.IsEnabled("StructPayload")); Assert.True(source.IsEnabled("StructPayload", "arg1", "arg2")); Assert.True(seenUninteresting); Assert.True(seenStructPayload); Assert.True(listener.IsEnabled()); } } } /// <summary> /// Simple tests for the IsEnabled method. /// </summary> [Fact] public void IsEnabledMultipleArgs() { using (DiagnosticListener listener = new DiagnosticListener("Testing")) { DiagnosticSource source = listener; var result = new List<KeyValuePair<string, object>>(); Func<string, object, object, bool> isEnabled = (name, arg1, arg2) => { if (arg1 != null) return (bool) arg1; if (arg2 != null) return (bool) arg2; return true; }; using (listener.Subscribe(new ObserverToList<TelemData>(result), isEnabled)) { Assert.True(source.IsEnabled("event")); Assert.True(source.IsEnabled("event", null, null)); Assert.True(source.IsEnabled("event", null, true)); Assert.False(source.IsEnabled("event", false, false)); Assert.False(source.IsEnabled("event", false, null)); Assert.False(source.IsEnabled("event", null, false)); } } } /// <summary> /// Test if it works when you have two subscribers active simultaneously /// </summary> [Fact] public void MultiSubscriber() { using (DiagnosticListener listener = new DiagnosticListener("Testing")) { DiagnosticSource source = listener; var subscriber1Result = new List<KeyValuePair<string, object>>(); Predicate<string> subscriber1Predicate = name => (name == "DataForSubscriber1"); var subscriber1Oberserver = new ObserverToList<TelemData>(subscriber1Result); var subscriber2Result = new List<KeyValuePair<string, object>>(); Predicate<string> subscriber2Predicate = name => (name == "DataForSubscriber2"); var subscriber2Oberserver = new ObserverToList<TelemData>(subscriber2Result); // Get two subscribers going. using (var subscription1 = listener.Subscribe(subscriber1Oberserver, subscriber1Predicate)) { using (var subscription2 = listener.Subscribe(subscriber2Oberserver, subscriber2Predicate)) { // Things that neither subscribe to get filtered out. if (listener.IsEnabled("DataToFilterOut")) listener.Write("DataToFilterOut", -1); Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); /****************************************************/ // If a Source does not use the IsEnabled, then every subscriber gets it. subscriber1Result.Clear(); subscriber2Result.Clear(); listener.Write("UnfilteredData", 3); Assert.Equal(1, subscriber1Result.Count); Assert.Equal("UnfilteredData", subscriber1Result[0].Key); Assert.Equal(3, (int)subscriber1Result[0].Value); Assert.Equal(1, subscriber2Result.Count); Assert.Equal("UnfilteredData", subscriber2Result[0].Key); Assert.Equal(3, (int)subscriber2Result[0].Value); /****************************************************/ // Filters not filter out everything, they are just a performance optimization. // Here you actually get more than you want even though you use a filter subscriber1Result.Clear(); subscriber2Result.Clear(); if (listener.IsEnabled("DataForSubscriber1")) listener.Write("DataForSubscriber1", 1); Assert.Equal(1, subscriber1Result.Count); Assert.Equal("DataForSubscriber1", subscriber1Result[0].Key); Assert.Equal(1, (int)subscriber1Result[0].Value); // Subscriber 2 happens to get it Assert.Equal(1, subscriber2Result.Count); Assert.Equal("DataForSubscriber1", subscriber2Result[0].Key); Assert.Equal(1, (int)subscriber2Result[0].Value); /****************************************************/ subscriber1Result.Clear(); subscriber2Result.Clear(); if (listener.IsEnabled("DataForSubscriber2")) listener.Write("DataForSubscriber2", 2); // Subscriber 1 happens to get it Assert.Equal(1, subscriber1Result.Count); Assert.Equal("DataForSubscriber2", subscriber1Result[0].Key); Assert.Equal(2, (int)subscriber1Result[0].Value); Assert.Equal(1, subscriber2Result.Count); Assert.Equal("DataForSubscriber2", subscriber2Result[0].Key); Assert.Equal(2, (int)subscriber2Result[0].Value); } // subscriber2 drops out /*********************************************************************/ /* Only Subscriber 1 is left */ /*********************************************************************/ // Things that neither subscribe to get filtered out. subscriber1Result.Clear(); subscriber2Result.Clear(); if (listener.IsEnabled("DataToFilterOut")) listener.Write("DataToFilterOut", -1); Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); /****************************************************/ // If a Source does not use the IsEnabled, then every subscriber gets it. subscriber1Result.Clear(); listener.Write("UnfilteredData", 3); Assert.Equal(1, subscriber1Result.Count); Assert.Equal("UnfilteredData", subscriber1Result[0].Key); Assert.Equal(3, (int)subscriber1Result[0].Value); // Subscriber 2 has dropped out. Assert.Equal(0, subscriber2Result.Count); /****************************************************/ // Filters not filter out everything, they are just a performance optimization. // Here you actually get more than you want even though you use a filter subscriber1Result.Clear(); if (listener.IsEnabled("DataForSubscriber1")) listener.Write("DataForSubscriber1", 1); Assert.Equal(1, subscriber1Result.Count); Assert.Equal("DataForSubscriber1", subscriber1Result[0].Key); Assert.Equal(1, (int)subscriber1Result[0].Value); // Subscriber 2 has dropped out. Assert.Equal(0, subscriber2Result.Count); /****************************************************/ subscriber1Result.Clear(); if (listener.IsEnabled("DataForSubscriber2")) listener.Write("DataForSubscriber2", 2); // Subscriber 1 filters Assert.Equal(0, subscriber1Result.Count); // Subscriber 2 has dropped out Assert.Equal(0, subscriber2Result.Count); } // subscriber1 drops out /*********************************************************************/ /* No Subscribers are left */ /*********************************************************************/ // Things that neither subscribe to get filtered out. subscriber1Result.Clear(); subscriber2Result.Clear(); if (listener.IsEnabled("DataToFilterOut")) listener.Write("DataToFilterOut", -1); Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); /****************************************************/ // If a Source does not use the IsEnabled, then every subscriber gets it. listener.Write("UnfilteredData", 3); // No one subscribing Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); /****************************************************/ // Filters not filter out everything, they are just a performance optimization. // Here you actually get more than you want even though you use a filter if (listener.IsEnabled("DataForSubscriber1")) listener.Write("DataForSubscriber1", 1); // No one subscribing Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); /****************************************************/ if (listener.IsEnabled("DataForSubscriber2")) listener.Write("DataForSubscriber2", 2); // No one subscribing Assert.Equal(0, subscriber1Result.Count); Assert.Equal(0, subscriber2Result.Count); } } /// <summary> /// Stresses the Subscription routine by having many threads subscribe and /// unsubscribe concurrently /// </summary> [Fact] public void MultiSubscriberStress() { using (DiagnosticListener listener = new DiagnosticListener("MultiSubscriberStressTest")) { DiagnosticSource source = listener; var random = new Random(); // Beat on the default listener by subscribing and unsubscribing on many threads simultaneously. var factory = new TaskFactory(); // To the whole stress test 10 times. This keeps the task array size needed down while still // having lots of concurrency. for (int j = 0; j < 20; j++) { // Spawn off lots of concurrent activity var tasks = new Task[1000]; for (int i = 0; i < tasks.Length; i++) { tasks[i] = factory.StartNew(delegate (object taskData) { int taskNum = (int)taskData; var taskName = "Task" + taskNum; var result = new List<KeyValuePair<string, object>>(); Predicate<string> predicate = (name) => name == taskName; Predicate<KeyValuePair<string, object>> filter = (keyValue) => keyValue.Key == taskName; // set up the observer to only see events set with the task name as the name. var observer = new ObserverToList<TelemData>(result, filter, taskName); using (listener.Subscribe(observer, predicate)) { source.Write(taskName, taskNum); Assert.Equal(1, result.Count); Assert.Equal(taskName, result[0].Key); Assert.Equal(taskNum, result[0].Value); // Spin a bit randomly. This mixes of the lifetimes of the subscriptions and makes it // more stressful var cnt = random.Next(10, 100) * 1000; while (0 < --cnt) GC.KeepAlive(""); } // Unsubscribe // Send the notification again, to see if it now does NOT come through (count remains unchanged). source.Write(taskName, -1); Assert.Equal(1, result.Count); }, i); } Task.WaitAll(tasks); } } } /// <summary> /// Tests if as we create new DiagnosticListerns, we get callbacks for them /// </summary> [Fact] public void AllListenersAddRemove() { using (DiagnosticListener listener = new DiagnosticListener("TestListen0")) { DiagnosticSource source = listener; // This callback will return the listener that happens on the callback DiagnosticListener returnedListener = null; Action<DiagnosticListener> onNewListener = delegate (DiagnosticListener listen) { // Other tests can be running concurrently with this test, which will make // this callback fire for those listeners as well. We only care about // the Listeners we generate here so ignore any that d if (!listen.Name.StartsWith("TestListen")) return; Assert.Null(returnedListener); Assert.NotNull(listen); returnedListener = listen; }; // Subscribe, which delivers catch-up event for the Default listener using (var allListenerSubscription = DiagnosticListener.AllListeners.Subscribe(MakeObserver(onNewListener))) { Assert.Equal(listener, returnedListener); returnedListener = null; } // Now we unsubscribe // Create an dispose a listener, but we won't get a callback for it. using (new DiagnosticListener("TestListen")) { } Assert.Null(returnedListener); // No callback was made // Resubscribe using (var allListenerSubscription = DiagnosticListener.AllListeners.Subscribe(MakeObserver(onNewListener))) { Assert.Equal(listener, returnedListener); returnedListener = null; // add two new subscribers using (var listener1 = new DiagnosticListener("TestListen1")) { Assert.Equal(listener1.Name, "TestListen1"); Assert.Equal(listener1, returnedListener); returnedListener = null; using (var listener2 = new DiagnosticListener("TestListen2")) { Assert.Equal(listener2.Name, "TestListen2"); Assert.Equal(listener2, returnedListener); returnedListener = null; } // Dispose of listener2 } // Dispose of listener1 } // Unsubscribe // Check that we are back to just the DefaultListener. using (var allListenerSubscription = DiagnosticListener.AllListeners.Subscribe(MakeObserver(onNewListener))) { Assert.Equal(listener, returnedListener); returnedListener = null; } // cleanup } } /// <summary> /// Tests that the 'catchupList' of active listeners is accurate even as we /// add and remove DiagnosticListeners randomly. /// </summary> [Fact] public void AllListenersCheckCatchupList() { var expected = new List<DiagnosticListener>(); var list = GetActiveListenersWithPrefix("TestListener"); Assert.Equal(list, expected); for (int i = 0; i < 50; i++) { expected.Insert(0, (new DiagnosticListener("TestListener" + i))); list = GetActiveListenersWithPrefix("TestListener"); Assert.Equal(list, expected); } // Remove the element randomly. var random = new Random(0); while (0 < expected.Count) { var toRemoveIdx = random.Next(0, expected.Count - 1); // Always leave the Default listener. var toRemoveListener = expected[toRemoveIdx]; toRemoveListener.Dispose(); // Kill it (which removes it from the list) expected.RemoveAt(toRemoveIdx); list = GetActiveListenersWithPrefix("TestListener"); Assert.Equal(list.Count, expected.Count); Assert.Equal(list, expected); } } /// <summary> /// Stresses the AllListeners by having many threads be adding and removing. /// </summary> [OuterLoop] [Theory] [InlineData(100, 100)] // run multiple times to stress it further [InlineData(100, 100)] [InlineData(100, 100)] [InlineData(100, 100)] [InlineData(100, 100)] public void AllSubscriberStress(int numThreads, int numListenersPerThread) { // No listeners have been created yet Assert.Equal(0, GetActiveListenersWithPrefix(nameof(AllSubscriberStress)).Count); // Run lots of threads to add/remove listeners Task.WaitAll(Enumerable.Range(0, numThreads).Select(i => Task.Factory.StartNew(delegate { // Create a set of DiagnosticListeners, which add themselves to the AllListeners list. var listeners = new List<DiagnosticListener>(numListenersPerThread); for (int j = 0; j < numListenersPerThread; j++) { var listener = new DiagnosticListener($"{nameof(AllSubscriberStress)}_Task {i} TestListener{j}"); listeners.Add(listener); } // They are all in the list. List<DiagnosticListener> list = GetActiveListenersWithPrefix(nameof(AllSubscriberStress)); Assert.All(listeners, listener => Assert.Contains(listener, list)); // Dispose them all, first the even then the odd, just to mix it up and be more stressful. for (int j = 0; j < listeners.Count; j += 2) // even listeners[j].Dispose(); for (int j = 1; j < listeners.Count; j += 2) // odd listeners[j].Dispose(); // None should be left in the list list = GetActiveListenersWithPrefix(nameof(AllSubscriberStress)); Assert.All(listeners, listener => Assert.DoesNotContain(listener, list)); }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray()); // None of the created listeners should remain Assert.Equal(0, GetActiveListenersWithPrefix(nameof(AllSubscriberStress)).Count); } [Fact] public void DoubleDisposeOfListener() { var listener = new DiagnosticListener("MyListener"); int completionCount = 0; IDisposable subscription = listener.Subscribe(MakeObserver<KeyValuePair<string, object>>(_ => { }, () => completionCount++)); listener.Dispose(); listener.Dispose(); subscription.Dispose(); subscription.Dispose(); Assert.Equal(1, completionCount); } [Fact] public void ListenerToString() { string name = Guid.NewGuid().ToString(); using (var listener = new DiagnosticListener(name)) { Assert.Equal(name, listener.ToString()); } } [Fact] public void DisposeAllListenerSubscriptionInSameOrderSubscribed() { int count1 = 0, count2 = 0, count3 = 0; IDisposable sub1 = DiagnosticListener.AllListeners.Subscribe(MakeObserver<DiagnosticListener>(onCompleted: () => count1++)); IDisposable sub2 = DiagnosticListener.AllListeners.Subscribe(MakeObserver<DiagnosticListener>(onCompleted: () => count2++)); IDisposable sub3 = DiagnosticListener.AllListeners.Subscribe(MakeObserver<DiagnosticListener>(onCompleted: () => count3++)); Assert.Equal(0, count1); Assert.Equal(0, count2); Assert.Equal(0, count3); sub1.Dispose(); Assert.Equal(1, count1); Assert.Equal(0, count2); Assert.Equal(0, count3); sub1.Dispose(); // dispose again just to make sure nothing bad happens sub2.Dispose(); Assert.Equal(1, count1); Assert.Equal(1, count2); Assert.Equal(0, count3); sub2.Dispose(); sub3.Dispose(); Assert.Equal(1, count1); Assert.Equal(1, count2); Assert.Equal(1, count3); sub3.Dispose(); } [Fact] public void SubscribeWithNullPredicate() { using (DiagnosticListener listener = new DiagnosticListener("Testing")) { Predicate<string> predicate = null; using (listener.Subscribe(new ObserverToList<TelemData>(new List<KeyValuePair<string, object>>()), predicate)) { Assert.True(listener.IsEnabled("event")); Assert.True(listener.IsEnabled("event", null)); Assert.True(listener.IsEnabled("event", "arg1")); Assert.True(listener.IsEnabled("event", "arg1", "arg2")); } } using (DiagnosticListener listener = new DiagnosticListener("Testing")) { DiagnosticSource source = listener; Func<string, object, object, bool> predicate = null; using (listener.Subscribe(new ObserverToList<TelemData>(new List<KeyValuePair<string, object>>()), predicate)) { Assert.True(source.IsEnabled("event")); Assert.True(source.IsEnabled("event", null)); Assert.True(source.IsEnabled("event", "arg1")); Assert.True(source.IsEnabled("event", "arg1", "arg2")); } } } #region Helpers /// <summary> /// Returns the list of active diagnostic listeners. /// </summary> /// <returns></returns> private static List<DiagnosticListener> GetActiveListenersWithPrefix(string prefix) { var ret = new List<DiagnosticListener>(); Action<DiagnosticListener> onNewListener = delegate (DiagnosticListener listen) { if (listen.Name.StartsWith(prefix)) ret.Add(listen); }; // Subscribe, which gives you the list using (var allListenerSubscription = DiagnosticListener.AllListeners.Subscribe(MakeObserver(onNewListener))) { } // Unsubscribe to remove side effects. return ret; } /// <summary> /// Used to make an observer out of a action delegate. /// </summary> public static IObserver<T> MakeObserver<T>( Action<T> onNext = null, Action onCompleted = null) { return new Observer<T>(onNext, onCompleted); } /// <summary> /// Used in the implementation of MakeObserver. /// </summary> /// <typeparam name="T"></typeparam> private class Observer<T> : IObserver<T> { public Observer(Action<T> onNext, Action onCompleted) { _onNext = onNext ?? new Action<T>(_ => { }); _onCompleted = onCompleted ?? new Action(() => { }); } public void OnCompleted() { _onCompleted(); } public void OnError(Exception error) { } public void OnNext(T value) { _onNext(value); } private Action<T> _onNext; private Action _onCompleted; } #endregion } // Takes an IObserver and returns a List<T> that are the elements observed. // Will assert on error and 'Completed' is set if the 'OnCompleted' callback // is issued. internal class ObserverToList<T> : IObserver<T> { public ObserverToList(List<T> output, Predicate<T> filter = null, string name = null) { _output = output; _output.Clear(); _filter = filter; _name = name; } public bool Completed { get; private set; } #region private public void OnCompleted() { Completed = true; } public void OnError(Exception error) { Assert.True(false, "Error happened on IObserver"); } public void OnNext(T value) { Assert.False(Completed); if (_filter == null || _filter(value)) _output.Add(value); } private List<T> _output; private Predicate<T> _filter; private string _name; // for debugging #endregion } /// <summary> /// Trivial class used for payloads. (Usually anonymous types are used. /// </summary> internal class Payload { public string Name { get; set; } public int Id { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans; using Orleans.Runtime; using UnitTests.GrainInterfaces; namespace UnitTests.Grains { public class TestGrain : Grain, ITestGrain { private string label; private Logger logger; private IDisposable timer; public override Task OnActivateAsync() { if (this.GetPrimaryKeyLong() == -2) throw new ArgumentException("Primary key cannot be -2 for this test case"); logger = this.GetLogger("TestGrain " + Data.Address); label = this.GetPrimaryKeyLong().ToString(); logger.Info("OnActivateAsync"); return base.OnActivateAsync(); } public override Task OnDeactivateAsync() { logger.Info("!!! OnDeactivateAsync"); return base.OnDeactivateAsync(); } #region Implementation of ITestGrain public Task<long> GetKey() { return Task.FromResult(this.GetPrimaryKeyLong()); } public Task<string> GetLabel() { return Task.FromResult(label); } public async Task DoLongAction(TimeSpan timespan, string str) { logger.Info("DoLongAction {0} received", str); await Task.Delay(timespan); } public Task SetLabel(string label) { this.label = label; logger.Info("SetLabel {0} received", label); return Task.CompletedTask; } public Task StartTimer() { logger.Info("StartTimer."); timer = base.RegisterTimer(TimerTick, null, TimeSpan.Zero, TimeSpan.FromSeconds(10)); return Task.CompletedTask; } private Task TimerTick(object data) { logger.Info("TimerTick."); return Task.CompletedTask; } public async Task<Tuple<string, string>> TestRequestContext() { string bar1 = null; RequestContext.Set("jarjar", "binks"); var task = Task.Factory.StartNew(() => { bar1 = (string) RequestContext.Get("jarjar"); logger.Info("bar = {0}.", bar1); }); string bar2 = null; var ac = Task.Factory.StartNew(() => { bar2 = (string) RequestContext.Get("jarjar"); logger.Info("bar = {0}.", bar2); }); await Task.WhenAll(task, ac); return new Tuple<string, string>(bar1, bar2); } public Task<string> GetRuntimeInstanceId() { return Task.FromResult(RuntimeIdentity); } public Task<string> GetActivationId() { return Task.FromResult(Data.ActivationId.ToString()); } public Task<ITestGrain> GetGrainReference() { return Task.FromResult(this.AsReference<ITestGrain>()); } public Task<IGrain[]> GetMultipleGrainInterfaces_Array() { var grains = new IGrain[5]; for (var i = 0; i < grains.Length; i++) { grains[i] = GrainFactory.GetGrain<ITestGrain>(i); } return Task.FromResult(grains); } public Task<List<IGrain>> GetMultipleGrainInterfaces_List() { var grains = new IGrain[5]; for (var i = 0; i < grains.Length; i++) { grains[i] = GrainFactory.GetGrain<ITestGrain>(i); } return Task.FromResult(grains.ToList()); } #endregion } internal class GuidTestGrain : Grain, IGuidTestGrain { private string label; private Logger logger; public override Task OnActivateAsync() { //if (this.GetPrimaryKeyLong() == -2) // throw new ArgumentException("Primary key cannot be -2 for this test case"); label = this.GetPrimaryKey().ToString(); logger = this.GetLogger("GuidTestGrain " + Data.Address); logger.Info("OnActivateAsync"); return Task.CompletedTask; } #region Implementation of ITestGrain public Task<Guid> GetKey() { return Task.FromResult(this.GetPrimaryKey()); } public Task<string> GetLabel() { return Task.FromResult(label); } public Task SetLabel(string label) { this.label = label; return Task.CompletedTask; } public Task<string> GetRuntimeInstanceId() { return Task.FromResult(RuntimeIdentity); } public Task<string> GetActivationId() { return Task.FromResult(Data.ActivationId.ToString()); } #endregion } public class OneWayGrain : Grain, IOneWayGrain { private int count; public Task Notify() { this.count++; return Task.CompletedTask; } public Task Notify(ISimpleGrainObserver observer) { this.count++; observer.StateChanged(this.count - 1, this.count); return Task.CompletedTask; } public async Task<bool> NotifyOtherGrain(IOneWayGrain otherGrain, ISimpleGrainObserver observer) { var task = otherGrain.Notify(observer); var completedSynchronously = task.Status == TaskStatus.RanToCompletion; await task; return completedSynchronously; } public Task<int> GetCount() => Task.FromResult(this.count); public Task ThrowsOneWay() { throw new Exception("GET OUT!"); } } public class CanBeOneWayGrain : Grain, ICanBeOneWayGrain { private int count; public Task Notify() { this.count++; return Task.CompletedTask; } public Task Notify(ISimpleGrainObserver observer) { this.count++; observer.StateChanged(this.count - 1, this.count); return Task.CompletedTask; } public Task<int> GetCount() => Task.FromResult(this.count); public Task Throws() { throw new Exception("GET OUT!"); } } }
// 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. //////////////////////////////////////////////////////////////////////////// // // // Purpose: This class implements a set of methods for retrieving // character type information. Character type information is // independent of culture and region. // // //////////////////////////////////////////////////////////////////////////// using System.Buffers.Binary; using System.Diagnostics; using System.Text; using Internal.Runtime.CompilerServices; namespace System.Globalization { public static partial class CharUnicodeInfo { //--------------------------------------------------------------------// // Internal Information // //--------------------------------------------------------------------// // // Native methods to access the Unicode category data tables in charinfo.nlp. // internal const char HIGH_SURROGATE_START = '\ud800'; internal const char HIGH_SURROGATE_END = '\udbff'; internal const char LOW_SURROGATE_START = '\udc00'; internal const char LOW_SURROGATE_END = '\udfff'; internal const int HIGH_SURROGATE_RANGE = 0x3FF; internal const int UNICODE_CATEGORY_OFFSET = 0; internal const int BIDI_CATEGORY_OFFSET = 1; // The starting codepoint for Unicode plane 1. Plane 1 contains 0x010000 ~ 0x01ffff. internal const int UNICODE_PLANE01_START = 0x10000; //////////////////////////////////////////////////////////////////////// // // Actions: // Convert the BMP character or surrogate pointed by index to a UTF32 value. // This is similar to char.ConvertToUTF32, but the difference is that // it does not throw exceptions when invalid surrogate characters are passed in. // // WARNING: since it doesn't throw an exception it CAN return a value // in the surrogate range D800-DFFF, which are not legal unicode values. // //////////////////////////////////////////////////////////////////////// internal static int InternalConvertToUtf32(string s, int index) { Debug.Assert(s != null, "s != null"); Debug.Assert(index >= 0 && index < s.Length, "index < s.Length"); if (index < s.Length - 1) { int temp1 = (int)s[index] - HIGH_SURROGATE_START; if ((uint)temp1 <= HIGH_SURROGATE_RANGE) { int temp2 = (int)s[index + 1] - LOW_SURROGATE_START; if ((uint)temp2 <= HIGH_SURROGATE_RANGE) { // Convert the surrogate to UTF32 and get the result. return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START); } } } return ((int)s[index]); } internal static int InternalConvertToUtf32(StringBuilder s, int index) { Debug.Assert(s != null, "s != null"); Debug.Assert(index >= 0 && index < s.Length, "index < s.Length"); int c = (int)s[index]; if (index < s.Length - 1) { int temp1 = c - HIGH_SURROGATE_START; if ((uint)temp1 <= HIGH_SURROGATE_RANGE) { int temp2 = (int)s[index + 1] - LOW_SURROGATE_START; if ((uint)temp2 <= HIGH_SURROGATE_RANGE) { // Convert the surrogate to UTF32 and get the result. return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START); } } } return c; } //////////////////////////////////////////////////////////////////////// // // Convert a character or a surrogate pair starting at index of string s // to UTF32 value. // // Parameters: // s The string // index The starting index. It can point to a BMP character or // a surrogate pair. // len The length of the string. // charLength [out] If the index points to a BMP char, charLength // will be 1. If the index points to a surrogate pair, // charLength will be 2. // // WARNING: since it doesn't throw an exception it CAN return a value // in the surrogate range D800-DFFF, which are not legal unicode values. // // Returns: // The UTF32 value // //////////////////////////////////////////////////////////////////////// internal static int InternalConvertToUtf32(string s, int index, out int charLength) { Debug.Assert(s != null, "s != null"); Debug.Assert(s.Length > 0, "s.Length > 0"); Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length"); charLength = 1; if (index < s.Length - 1) { int temp1 = (int)s[index] - HIGH_SURROGATE_START; if ((uint)temp1 <= HIGH_SURROGATE_RANGE) { int temp2 = (int)s[index + 1] - LOW_SURROGATE_START; if ((uint)temp2 <= HIGH_SURROGATE_RANGE) { // Convert the surrogate to UTF32 and get the result. charLength++; return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START); } } } return ((int)s[index]); } // // This is called by the public char and string, index versions // // Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character internal static double InternalGetNumericValue(int ch) { Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); // Get the level 2 item from the highest 12 bit (8 - 19) of ch. int index = ch >> 8; if ((uint)index < (uint)NumericLevel1Index.Length) { index = NumericLevel1Index[index]; // Get the level 2 offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. // Note that & has the lower precedence than addition, so don't forget the parathesis. index = NumericLevel2Index[(index << 4) + ((ch >> 4) & 0x000f)]; index = NumericLevel3Index[(index << 4) + (ch & 0x000f)]; ref var value = ref Unsafe.AsRef(in NumericValues[index * 8]); if (BitConverter.IsLittleEndian) return Unsafe.ReadUnaligned<double>(ref value); return BitConverter.Int64BitsToDouble(BinaryPrimitives.ReverseEndianness(Unsafe.ReadUnaligned<long>(ref value))); } return -1; } internal static byte InternalGetDigitValues(int ch, int offset) { Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); // Get the level 2 item from the highest 12 bit (8 - 19) of ch. int index = ch >> 8; if ((uint)index < (uint)NumericLevel1Index.Length) { index = NumericLevel1Index[index]; // Get the level 2 offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. // Note that & has the lower precedence than addition, so don't forget the parathesis. index = NumericLevel2Index[(index << 4) + ((ch >> 4) & 0x000f)]; index = NumericLevel3Index[(index << 4) + (ch & 0x000f)]; return DigitValues[index * 2 + offset]; } return 0xff; } //////////////////////////////////////////////////////////////////////// // //Returns the numeric value associated with the character c. If the character is a fraction, // the return value will not be an integer. If the character does not have a numeric value, the return value is -1. // //Returns: // the numeric value for the specified Unicode character. If the character does not have a numeric value, the return value is -1. //Arguments: // ch a Unicode character //Exceptions: // ArgumentNullException // ArgumentOutOfRangeException // //////////////////////////////////////////////////////////////////////// public static double GetNumericValue(char ch) { return (InternalGetNumericValue(ch)); } public static double GetNumericValue(string s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } return (InternalGetNumericValue(InternalConvertToUtf32(s, index))); } public static int GetDecimalDigitValue(char ch) { return (sbyte)InternalGetDigitValues(ch, 0); } public static int GetDecimalDigitValue(string s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } return (sbyte)InternalGetDigitValues(InternalConvertToUtf32(s, index), 0); } public static int GetDigitValue(char ch) { return (sbyte)InternalGetDigitValues(ch, 1); } public static int GetDigitValue(string s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } return (sbyte)InternalGetDigitValues(InternalConvertToUtf32(s, index), 1); } public static UnicodeCategory GetUnicodeCategory(char ch) { return (GetUnicodeCategory((int)ch)); } public static UnicodeCategory GetUnicodeCategory(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } return InternalGetUnicodeCategory(s, index); } public static UnicodeCategory GetUnicodeCategory(int codePoint) { return ((UnicodeCategory)InternalGetCategoryValue(codePoint, UNICODE_CATEGORY_OFFSET)); } //////////////////////////////////////////////////////////////////////// // //Action: Returns the Unicode Category property for the character c. //Returns: // an value in UnicodeCategory enum //Arguments: // ch a Unicode character //Exceptions: // None // //Note that this API will return values for D800-DF00 surrogate halves. // //////////////////////////////////////////////////////////////////////// internal static byte InternalGetCategoryValue(int ch, int offset) { Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); // Get the level 2 item from the highest 11 bits of ch. int index = CategoryLevel1Index[ch >> 9]; // Get the level 2 WORD offset from the next 5 bits of ch. This provides the base offset of the level 3 table. // Note that & has the lower precedence than addition, so don't forget the parathesis. index = Unsafe.ReadUnaligned<ushort>(ref Unsafe.AsRef(in CategoryLevel2Index[(index << 6) + ((ch >> 3) & 0b111110)])); if (!BitConverter.IsLittleEndian) index = BinaryPrimitives.ReverseEndianness((ushort)index); // Get the result from the 0 -3 bit of ch. index = CategoryLevel3Index[(index << 4) + (ch & 0x000f)]; return CategoriesValue[index * 2 + offset]; } //////////////////////////////////////////////////////////////////////// // //Action: Returns the Unicode Category property for the character c. //Returns: // an value in UnicodeCategory enum //Arguments: // value a Unicode String // index Index for the specified string. //Exceptions: // None // //////////////////////////////////////////////////////////////////////// internal static UnicodeCategory InternalGetUnicodeCategory(string value, int index) { Debug.Assert(value != null, "value can not be null"); Debug.Assert(index < value.Length, "index < value.Length"); return (GetUnicodeCategory(InternalConvertToUtf32(value, index))); } internal static BidiCategory GetBidiCategory(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } return ((BidiCategory) InternalGetCategoryValue(InternalConvertToUtf32(s, index), BIDI_CATEGORY_OFFSET)); } internal static BidiCategory GetBidiCategory(StringBuilder s, int index) { Debug.Assert(s != null, "s can not be null"); Debug.Assert(index >= 0 && index < s.Length, "invalid index"); ; return ((BidiCategory) InternalGetCategoryValue(InternalConvertToUtf32(s, index), BIDI_CATEGORY_OFFSET)); } //////////////////////////////////////////////////////////////////////// // // Get the Unicode category of the character starting at index. If the character is in BMP, charLength will return 1. // If the character is a valid surrogate pair, charLength will return 2. // //////////////////////////////////////////////////////////////////////// internal static UnicodeCategory InternalGetUnicodeCategory(string str, int index, out int charLength) { Debug.Assert(str != null, "str can not be null"); Debug.Assert(str.Length > 0, "str.Length > 0"); ; Debug.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length"); return (GetUnicodeCategory(InternalConvertToUtf32(str, index, out charLength))); } internal static bool IsCombiningCategory(UnicodeCategory uc) { Debug.Assert(uc >= 0, "uc >= 0"); return ( uc == UnicodeCategory.NonSpacingMark || uc == UnicodeCategory.SpacingCombiningMark || uc == UnicodeCategory.EnclosingMark ); } } }
using System.Data.Entity; using MediatR; using Microsoft.AspNetCore.Mvc.RazorPages; using MoreLinq; using NodaTime; using SupportManager.DAL; namespace SupportManager.Web.Areas.Teams.Pages.Report { public class MonthlyModel : PageModel { private readonly IMediator mediator; public MonthlyModel(IMediator mediator) => this.mediator = mediator; public Result Data { get; set; } public async Task OnGetAsync(Query query) { Data = await mediator.Send(query.Year == 0 ? query with { Year = DateTime.Now.Year, Month = DateTime.Now.Month } : query); } public record Query(int TeamId, int Year, int Month) : IRequest<Result>; public class Ref { public LocalDate Date { get; } public Query Query { get; } public Ref(int teamId, LocalDate date) { Date = date; Query = new Query(teamId, date.Year, date.Month); } } public class Result { public Result(int teamId, int year, int month) { TeamId = teamId; Year = year; Month = month; Date = new LocalDate(Year, Month, 1); Previous = new Ref(teamId, Date.PlusMonths(-1)); Next = new Ref(teamId, Date.PlusMonths(1)); } public LocalDate Date { get; } public int Year { get; } public int Month { get; } public int TeamId { get; } public List<Week> Weeks { get; set; } public Ref Previous { get; } public Ref Next { get; } public class Week { public LocalDate Start { get; set; } public LocalDate End { get; set; } public List<TimeSlot> Slots { get; set; } public List<Summary> Summaries { get; set; } } public class TimeSlot { public DateTimeOffset StartTime { get; set; } public DateTimeOffset EndTime { get; set; } public string GroupingKey { get; set; } public List<Participation> Participations { get; set; } } public class Summary { public TimeSpan Duration { get; set; } public string GroupingKey { get; set; } public List<Participation> Participations { get; set; } } public class Participation { public string UserName { get; set; } public TimeSpan Duration { get; set; } } } public class TimeSlot { public TimeSlot(TimeSpan start, string groupingKey) { Start = start; GroupingKey = groupingKey; } public TimeSpan Start { get; set; } public string GroupingKey { get; set; } } public class Handler : IRequestHandler<Query, Result> { private readonly SupportManagerContext db; public Handler(SupportManagerContext db) { this.db = db; } public async Task<Result> Handle(Query request, CancellationToken cancellationToken) { TimeSlot BuildSlot(DayOfWeek day, double hours, string groupingKey) { return new TimeSlot(TimeSpan.FromDays((int) day).Add(TimeSpan.FromHours(hours)), groupingKey); } const string WORK = "Kantooruren"; const string WEEK = "Doordeweeks"; const string WEEKEND = "Weekend"; var weekSlots = new List<TimeSlot>(); for (var day = DayOfWeek.Monday; day < DayOfWeek.Friday; day++) { weekSlots.Add(BuildSlot(day, 7.5, WORK)); weekSlots.Add(BuildSlot(day, 16.5, WEEK)); } weekSlots.Add(BuildSlot(DayOfWeek.Friday, 7.5, WORK)); weekSlots.Add(BuildSlot(DayOfWeek.Friday, 16.5, WEEKEND)); var dt = new DateTime(request.Year, request.Month, 1); int dayOfWeek = (int) dt.DayOfWeek; var resultStart = dt.AddDays(-dayOfWeek).Add(weekSlots[0].Start); var nextMonth = dt.AddMonths(1); var resultEnd = nextMonth.AddDays(7 - (int) nextMonth.DayOfWeek).Add(weekSlots[0].Start); if (resultStart.Month == dt.Month && resultStart.Day > 1) { resultStart = resultStart.AddDays(-7); } if (resultEnd.Day > 6) { resultEnd = resultEnd.AddDays(-7); } if (resultEnd > DateTime.Now) resultEnd = DateTime.Now; var weeks = new List<Result.Week>(); var slots = new List<(Result.Week, DateTime, string)>(); for (var weekStart = resultStart; weekStart < resultEnd; weekStart = weekStart.AddDays(7)) { var start = LocalDate.FromDateTime(weekStart); var week = new Result.Week { Start = start, End = start.PlusDays(6), Slots = new List<Result.TimeSlot>(), Summaries = new List<Result.Summary>(), }; weeks.Add(week); slots.AddRange(weekSlots.Select(s => (week, weekStart.Add(s.Start).Subtract(weekSlots[0].Start), s.GroupingKey))); } slots.Add((null, resultEnd, null)); // Add end var registrations = db.ForwardingStates.AsNoTracking().Where(s => s.TeamId == request.TeamId); var lastBefore = await registrations.Where(s => s.When < resultStart) .OrderByDescending(s => s.When) .FirstOrDefaultAsync(); var inRange = await registrations.Where(s => s.When >= resultStart && s.When <= resultEnd) .OrderBy(s => s.When) .ToListAsync(); if (lastBefore != null) inRange.Insert(0, lastBefore); if (!inRange.Any()) return new Result(request.TeamId, request.Year, request.Month) {Weeks = new List<Result.Week>()}; foreach (var (week, start, end, groupingKey) in GetSlots(slots)) { var before = inRange.TakeWhile(res => res.When < start).ToList(); var skip = before.Count - 1; if (skip == -1) skip = 0; var thisSlot = inRange.Skip(skip).TakeUntil(res => res.When > end).ToList(); var results = new List<(string user, TimeSpan duration)>(); if (!thisSlot.Any() || thisSlot[0].When > end) { results.Add((null, end.Subtract(start))); continue; } if (thisSlot[0].When > start) results.Add((null, thisSlot[0].When.Subtract(start))); for (int j = 0; j < thisSlot.Count - 1; j++) { var pStart = thisSlot[j].When; if (pStart < start) pStart = start; var pEnd = thisSlot[j + 1].When; if (pEnd > end) pEnd = end; if (thisSlot[j].DetectedPhoneNumber != null) results.Add((thisSlot[j].DetectedPhoneNumber.User.DisplayName, pEnd - pStart)); } var last = thisSlot[thisSlot.Count - 1]; if (last.When < end) { var pStart = last.When; if (pStart < start) pStart = start; if (last.DetectedPhoneNumber != null) results.Add((last.DetectedPhoneNumber.User.DisplayName, end - pStart)); } week.Slots.Add(new Result.TimeSlot { StartTime = start, EndTime = end, GroupingKey = groupingKey, Participations = results.GroupBy(r => r.user) .Select(g => new Result.Participation { Duration = TimeSpan.FromSeconds(g.Sum(x => x.duration.TotalSeconds)), UserName = g.Key }) .OrderByDescending(p => p.Duration) .ToList() }); } foreach (var week in weeks) { var grouped = week.Slots.GroupBy(s => s.GroupingKey); foreach (var group in grouped) { Dictionary<string, TimeSpan> participations = new Dictionary<string, TimeSpan>(); foreach (var p in group.SelectMany(g => g.Participations)) { if (participations.TryGetValue(p.UserName, out var duration)) { duration += p.Duration; } else { duration = p.Duration; } participations[p.UserName] = duration; } var summary = new Result.Summary { Duration = TimeSpan.FromSeconds(group.Sum(g => (g.EndTime - g.StartTime).TotalSeconds)), GroupingKey = group.Key, Participations = participations.Select(x => new Result.Participation {Duration = x.Value, UserName = x.Key}).ToList() }; week.Summaries.Add(summary); } } return new Result(request.TeamId, request.Year, request.Month) {Weeks = weeks}; } private IEnumerable<(Result.Week, DateTime, DateTime, string)> GetSlots(List<(Result.Week week, DateTime start, string groupingKey)> startTimes) { for (int i = 0; i < startTimes.Count - 1; i++) { yield return (startTimes[i].week, startTimes[i].start, startTimes[i + 1].start, startTimes[i].groupingKey); } } } } }
/*! Copyright (C) 2003-2013 Kody Brown (kody@bricksoft.com). MIT License: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; namespace Bricksoft.PowerCode { /// <summary> /// Provides an easier way to get environment variables. /// </summary> public class EnvironmentVariables { public string prefix { get { return _prefix + "_"; } set { if (value.IndexOfAny(new char[] { '`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+', '=', '{', '[', '}', '}', '|', '\\', ':', ';', '"', '\'', '<', '>', ',', '.', '?', '/' }) > -1) { throw new ArgumentException("only alphanumeric characters and underscores (_) are allowed for environment variable names."); } _prefix = value != null && value.Trim().Length > 0 ? value.Trim() : ""; if (_prefix.EndsWith("_")) { _prefix = _prefix.Substring(0, _prefix.Length - 1); } } } private string _prefix = ""; public string postfix { get { return _postfix + "_"; } set { if (value.IndexOfAny(new char[] { '`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+', '=', '{', '[', '}', '}', '|', '\\', ':', ';', '"', '\'', '<', '>', ',', '.', '?', '/' }) > -1) { throw new ArgumentException("only alphanumeric characters and underscores (_) are allowed for environment variable names."); } _postfix = value != null && value.Trim().Length > 0 ? value.Trim() : ""; if (_postfix.EndsWith("_")) { _postfix = _postfix.Substring(0, _postfix.Length - 1); } } } private string _postfix = ""; public EnvironmentVariableTarget target { get { return _target; } set { _target = value; } } private EnvironmentVariableTarget _target; public EnvironmentVariables() { this.prefix = "_"; this.postfix = ""; this.target = EnvironmentVariableTarget.Process; } public EnvironmentVariables( string prefix, string postfix = "", EnvironmentVariableTarget target = EnvironmentVariableTarget.Process ) { this.prefix = prefix; this.postfix = postfix; this.target = target; } /// <summary> /// Returns a dictionary of all environment variables that begin with the current instance's prefix (and ends with this instance's postfix, if specified). /// </summary> /// <returns></returns> /// <remarks> /// If prefix (and postfix) is empty, ALL environment variables are returned. /// </remarks> public Dictionary<string, string> all( EnvironmentVariableTarget target = EnvironmentVariableTarget.Process ) { Dictionary<string, string> l = new Dictionary<string, string>(); foreach (KeyValuePair<string, string> p in Environment.GetEnvironmentVariables(target)) { if ((prefix.Length == 0 && postfix.Length == 0) || (p.Key.StartsWith(prefix, StringComparison.CurrentCultureIgnoreCase) && p.Key.EndsWith(postfix, StringComparison.CurrentCultureIgnoreCase))) { l.Add(p.Key, p.Value); } } return l; } /// <summary> /// Returns a list of all environment variable names that begin with prefix (and end with postfix, if specified). /// </summary> /// <returns></returns> /// <remarks> /// If prefix (and postfix) is empty, ALL environment variable names are returned. /// </remarks> public List<string> keys( EnvironmentVariableTarget target = EnvironmentVariableTarget.Process ) { List<string> l = new List<string>(); foreach (KeyValuePair<string, string> p in Environment.GetEnvironmentVariables(target)) { //if (prefix.Length == 0 || p.Key.StartsWith(prefix, StringComparison.CurrentCultureIgnoreCase)) { if ((prefix.Length == 0 && postfix.Length == 0) || (p.Key.StartsWith(prefix, StringComparison.CurrentCultureIgnoreCase) && p.Key.EndsWith(postfix, StringComparison.CurrentCultureIgnoreCase))) { l.Add(p.Key); } } return l; } /// <summary> /// Returns whether the specified environment variable exists. /// The key is automatically prefixed by this instance's prefix property. /// The target (scope) is specified by <paramref name="target"/>. /// </summary> /// <param name="key"></param> /// <param name="target"></param> /// <returns></returns> public bool contains( string key, EnvironmentVariableTarget target = EnvironmentVariableTarget.Process ) { if (Environment.GetEnvironmentVariable(prefix + key + postfix, target) != null) { return true; } return false; } /// <summary> /// Returns the index of the first environment variable that exists. /// The target (scope) is the current process. /// </summary> /// <param name="key"></param> /// <returns></returns> public int indexOfAny( params string[] keys ) { return indexOfAny(EnvironmentVariableTarget.Process, keys); } /// <summary> /// Returns the index of the first environment variable that exists. /// The target (scope) is specified by <paramref name="target"/>. /// </summary> /// <param name="target"></param> /// <param name="key"></param> /// <returns></returns> public int indexOfAny( EnvironmentVariableTarget target, params string[] keys ) { for (int i = 0; i < keys.Length; i++) { if (Environment.GetEnvironmentVariable(prefix + keys[i] + postfix, target) != null) { return i; } } return -1; } /// <summary> /// Gets the value of <paramref name="key"/> from the environment variables. /// The prefix and postfix values are applied. /// Returns it as type T. /// The target (scope) is specified by <paramref name="target"/>. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="defaultValue"></param> /// <param name="separator"></param> /// <param name="target"></param> /// <returns></returns> public T attr<T>( string key, T defaultValue = default(T), string separator = "||", EnvironmentVariableTarget target = EnvironmentVariableTarget.Process ) { if (key == null || key.Length == 0) { throw new InvalidOperationException("key is required"); } if (Environment.GetEnvironmentVariable(prefix + key + postfix, target) != null) { return getAttrValue<T>(Environment.GetEnvironmentVariable(prefix + key + postfix, target), defaultValue, separator); } return defaultValue; } /// <summary> /// Gets the value of <paramref name="key"/> from the environment variables. /// The prefix and postfix values are ignored. /// Returns it as type T. /// The target (scope) is specified by <paramref name="target"/>. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="defaultValue"></param> /// <param name="separator"></param> /// <param name="target"></param> /// <returns></returns> public T global<T>( string key, T defaultValue = default(T), string separator = "||", EnvironmentVariableTarget target = EnvironmentVariableTarget.Process ) { if (key == null || key.Length == 0) { throw new InvalidOperationException("key is required"); } if (Environment.GetEnvironmentVariable(key, target) != null) { return getAttrValue<T>(Environment.GetEnvironmentVariable(key, target), defaultValue, separator); } return defaultValue; } private T getAttrValue<T>( string keydata, T defaultValue = default(T), string separator = "||" ) { if (typeof(T) == typeof(bool) || typeof(T).IsSubclassOf(typeof(bool))) { if ((object)keydata != null) { return (T)(object)(keydata.StartsWith("t", StringComparison.CurrentCultureIgnoreCase)); } } else if (typeof(T) == typeof(DateTime) || typeof(T).IsSubclassOf(typeof(DateTime))) { DateTime dt; if ((object)keydata != null && DateTime.TryParse(keydata, out dt)) { return (T)(object)dt; } } else if (typeof(T) == typeof(short) || typeof(T).IsSubclassOf(typeof(short))) { short i; if ((object)keydata != null && short.TryParse(keydata, out i)) { return (T)(object)i; } } else if (typeof(T) == typeof(int) || typeof(T).IsSubclassOf(typeof(int))) { int i; if ((object)keydata != null && int.TryParse(keydata, out i)) { return (T)(object)i; } } else if (typeof(T) == typeof(long) || typeof(T).IsSubclassOf(typeof(long))) { long i; if ((object)keydata != null && long.TryParse(keydata, out i)) { return (T)(object)i; } } else if (typeof(T) == typeof(ulong) || typeof(T).IsSubclassOf(typeof(ulong))) { ulong i; if ((object)keydata != null && ulong.TryParse(keydata, out i)) { return (T)(object)i; } } else if (typeof(T) == typeof(string) || typeof(T).IsSubclassOf(typeof(string))) { // string if ((object)keydata != null) { return (T)(object)(keydata).ToString(); } } else if (typeof(T) == typeof(string[]) || typeof(T).IsSubclassOf(typeof(string[]))) { // string[] if ((object)keydata != null) { // string array data SHOULD always be saved to the environment as a string||string||string.. return (T)(object)keydata.Split(new string[] { separator }, StringSplitOptions.None); } } else if (typeof(T) == typeof(List<string>) || typeof(T).IsSubclassOf(typeof(List<string>))) { // List<string> if ((object)keydata != null) { // string array data SHOULD always be saved to the environment as a string||string||string.. return (T)(object)new List<string>(keydata.Split(new string[] { separator }, StringSplitOptions.None)); } } else { throw new InvalidOperationException("unknown or unsupported data type was requested"); } return defaultValue; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Orchard.Caching; using Orchard.Environment.Extensions.Models; using Orchard.FileSystems.WebSite; using Orchard.Localization; using Orchard.Logging; using Orchard.Utility.Extensions; namespace Orchard.Environment.Extensions.Folders { public class ExtensionHarvester : IExtensionHarvester { private const string NameSection = "name"; private const string PathSection = "path"; private const string DescriptionSection = "description"; private const string VersionSection = "version"; private const string OrchardVersionSection = "orchardversion"; private const string AuthorSection = "author"; private const string WebsiteSection = "website"; private const string TagsSection = "tags"; private const string AntiForgerySection = "antiforgery"; private const string ZonesSection = "zones"; private const string BaseThemeSection = "basetheme"; private const string DependenciesSection = "dependencies"; private const string CategorySection = "category"; private const string FeatureDescriptionSection = "featuredescription"; private const string FeatureNameSection = "featurename"; private const string PrioritySection = "priority"; private const string FeaturesSection = "features"; private const string SessionStateSection = "sessionstate"; private readonly ICacheManager _cacheManager; private readonly IWebSiteFolder _webSiteFolder; private readonly ICriticalErrorProvider _criticalErrorProvider; public ExtensionHarvester(ICacheManager cacheManager, IWebSiteFolder webSiteFolder, ICriticalErrorProvider criticalErrorProvider) { _cacheManager = cacheManager; _webSiteFolder = webSiteFolder; _criticalErrorProvider = criticalErrorProvider; Logger = NullLogger.Instance; T = NullLocalizer.Instance; } public Localizer T { get; set; } public ILogger Logger { get; set; } public bool DisableMonitoring { get; set; } public IEnumerable<ExtensionDescriptor> HarvestExtensions(IEnumerable<string> paths, string extensionType, string manifestName, bool manifestIsOptional) { return paths .SelectMany(path => HarvestExtensions(path, extensionType, manifestName, manifestIsOptional)) .ToList(); } private IEnumerable<ExtensionDescriptor> HarvestExtensions(string path, string extensionType, string manifestName, bool manifestIsOptional) { string key = string.Format("{0}-{1}-{2}", path, manifestName, extensionType); return _cacheManager.Get(key, ctx => { if (!DisableMonitoring) { Logger.Debug("Monitoring virtual path \"{0}\"", path); ctx.Monitor(_webSiteFolder.WhenPathChanges(path)); } return AvailableExtensionsInFolder(path, extensionType, manifestName, manifestIsOptional).ToReadOnlyCollection(); }); } private List<ExtensionDescriptor> AvailableExtensionsInFolder(string path, string extensionType, string manifestName, bool manifestIsOptional) { Logger.Information("Start looking for extensions in '{0}'...", path); var subfolderPaths = _webSiteFolder.ListDirectories(path); var localList = new List<ExtensionDescriptor>(); foreach (var subfolderPath in subfolderPaths) { var extensionId = Path.GetFileName(subfolderPath.TrimEnd('/', '\\')); var manifestPath = Path.Combine(subfolderPath, manifestName); try { var descriptor = GetExtensionDescriptor(path, extensionId, extensionType, manifestPath, manifestIsOptional); if (descriptor == null) continue; if (descriptor.Path != null && !descriptor.Path.IsValidUrlSegment()) { Logger.Error("The module '{0}' could not be loaded because it has an invalid Path ({1}). It was ignored. The Path if specified must be a valid URL segment. The best bet is to stick with letters and numbers with no spaces.", extensionId, descriptor.Path); _criticalErrorProvider.RegisterErrorMessage(T("The extension '{0}' could not be loaded because it has an invalid Path ({1}). It was ignored. The Path if specified must be a valid URL segment. The best bet is to stick with letters and numbers with no spaces.", extensionId, descriptor.Path)); continue; } if (descriptor.Path == null) { descriptor.Path = descriptor.Name.IsValidUrlSegment() ? descriptor.Name : descriptor.Id; } localList.Add(descriptor); } catch (Exception ex) { // Ignore invalid module manifests Logger.Error(ex, "The module '{0}' could not be loaded. It was ignored.", extensionId); _criticalErrorProvider.RegisterErrorMessage(T("The extension '{0}' manifest could not be loaded. It was ignored.", extensionId)); } } Logger.Information("Done looking for extensions in '{0}': {1}", path, string.Join(", ", localList.Select(d => d.Id))); return localList; } public static ExtensionDescriptor GetDescriptorForExtension(string locationPath, string extensionId, string extensionType, string manifestText) { Dictionary<string, string> manifest = ParseManifest(manifestText); var extensionDescriptor = new ExtensionDescriptor { Location = locationPath, Id = extensionId, ExtensionType = extensionType, Name = GetValue(manifest, NameSection) ?? extensionId, Path = GetValue(manifest, PathSection), Description = GetValue(manifest, DescriptionSection), Version = GetValue(manifest, VersionSection), OrchardVersion = GetValue(manifest, OrchardVersionSection), Author = GetValue(manifest, AuthorSection), WebSite = GetValue(manifest, WebsiteSection), Tags = GetValue(manifest, TagsSection), AntiForgery = GetValue(manifest, AntiForgerySection), Zones = GetValue(manifest, ZonesSection), BaseTheme = GetValue(manifest, BaseThemeSection), SessionState = GetValue(manifest, SessionStateSection) }; extensionDescriptor.Features = GetFeaturesForExtension(manifest, extensionDescriptor); return extensionDescriptor; } private ExtensionDescriptor GetExtensionDescriptor(string locationPath, string extensionId, string extensionType, string manifestPath, bool manifestIsOptional) { return _cacheManager.Get(manifestPath, context => { if (!DisableMonitoring) { Logger.Debug("Monitoring virtual path \"{0}\"", manifestPath); context.Monitor(_webSiteFolder.WhenPathChanges(manifestPath)); } var manifestText = _webSiteFolder.ReadFile(manifestPath); if (manifestText == null) { if (manifestIsOptional) { manifestText = string.Format("Id: {0}", extensionId); } else { return null; } } return GetDescriptorForExtension(locationPath, extensionId, extensionType, manifestText); }); } private static Dictionary<string, string> ParseManifest(string manifestText) { var manifest = new Dictionary<string, string>(); using (StringReader reader = new StringReader(manifestText)) { string line; while ((line = reader.ReadLine()) != null) { string[] field = line.Split(new[] { ":" }, 2, StringSplitOptions.None); int fieldLength = field.Length; if (fieldLength != 2) continue; for (int i = 0; i < fieldLength; i++) { field[i] = field[i].Trim(); } switch (field[0].ToLowerInvariant()) { case NameSection: manifest.Add(NameSection, field[1]); break; case PathSection: manifest.Add(PathSection, field[1]); break; case DescriptionSection: manifest.Add(DescriptionSection, field[1]); break; case VersionSection: manifest.Add(VersionSection, field[1]); break; case OrchardVersionSection: manifest.Add(OrchardVersionSection, field[1]); break; case AuthorSection: manifest.Add(AuthorSection, field[1]); break; case WebsiteSection: manifest.Add(WebsiteSection, field[1]); break; case TagsSection: manifest.Add(TagsSection, field[1]); break; case AntiForgerySection: manifest.Add(AntiForgerySection, field[1]); break; case ZonesSection: manifest.Add(ZonesSection, field[1]); break; case BaseThemeSection: manifest.Add(BaseThemeSection, field[1]); break; case DependenciesSection: manifest.Add(DependenciesSection, field[1]); break; case CategorySection: manifest.Add(CategorySection, field[1]); break; case FeatureDescriptionSection: manifest.Add(FeatureDescriptionSection, field[1]); break; case FeatureNameSection: manifest.Add(FeatureNameSection, field[1]); break; case PrioritySection: manifest.Add(PrioritySection, field[1]); break; case SessionStateSection: manifest.Add(SessionStateSection, field[1]); break; case FeaturesSection: manifest.Add(FeaturesSection, reader.ReadToEnd()); break; } } } return manifest; } private static IEnumerable<FeatureDescriptor> GetFeaturesForExtension(IDictionary<string, string> manifest, ExtensionDescriptor extensionDescriptor) { var featureDescriptors = new List<FeatureDescriptor>(); // Default feature FeatureDescriptor defaultFeature = new FeatureDescriptor { Id = extensionDescriptor.Id, Name = GetValue(manifest, FeatureNameSection) ?? extensionDescriptor.Name, Priority = GetValue(manifest, PrioritySection) != null ? int.Parse(GetValue(manifest, PrioritySection)) : 0, Description = GetValue(manifest, FeatureDescriptionSection) ?? GetValue(manifest, DescriptionSection) ?? string.Empty, Dependencies = ParseFeatureDependenciesEntry(GetValue(manifest, DependenciesSection)), Extension = extensionDescriptor, Category = GetValue(manifest, CategorySection) }; featureDescriptors.Add(defaultFeature); // Remaining features string featuresText = GetValue(manifest, FeaturesSection); if (featuresText != null) { FeatureDescriptor featureDescriptor = null; using (StringReader reader = new StringReader(featuresText)) { string line; while ((line = reader.ReadLine()) != null) { if (IsFeatureDeclaration(line)) { if (featureDescriptor != null) { if (!featureDescriptor.Equals(defaultFeature)) { featureDescriptors.Add(featureDescriptor); } featureDescriptor = null; } string[] featureDeclaration = line.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries); string featureDescriptorId = featureDeclaration[0].Trim(); if (String.Equals(featureDescriptorId, extensionDescriptor.Id, StringComparison.OrdinalIgnoreCase)) { featureDescriptor = defaultFeature; featureDescriptor.Name = extensionDescriptor.Name; } else { featureDescriptor = new FeatureDescriptor { Id = featureDescriptorId, Extension = extensionDescriptor }; } } else if (IsFeatureFieldDeclaration(line)) { if (featureDescriptor != null) { string[] featureField = line.Split(new[] { ":" }, 2, StringSplitOptions.None); int featureFieldLength = featureField.Length; if (featureFieldLength != 2) continue; for (int i = 0; i < featureFieldLength; i++) { featureField[i] = featureField[i].Trim(); } switch (featureField[0].ToLowerInvariant()) { case NameSection: featureDescriptor.Name = featureField[1]; break; case DescriptionSection: featureDescriptor.Description = featureField[1]; break; case CategorySection: featureDescriptor.Category = featureField[1]; break; case PrioritySection: featureDescriptor.Priority = int.Parse(featureField[1]); break; case DependenciesSection: featureDescriptor.Dependencies = ParseFeatureDependenciesEntry(featureField[1]); break; } } else { string message = string.Format("The line {0} in manifest for extension {1} was ignored", line, extensionDescriptor.Id); throw new ArgumentException(message); } } else { string message = string.Format("The line {0} in manifest for extension {1} was ignored", line, extensionDescriptor.Id); throw new ArgumentException(message); } } if (featureDescriptor != null && !featureDescriptor.Equals(defaultFeature)) featureDescriptors.Add(featureDescriptor); } } return featureDescriptors; } private static bool IsFeatureFieldDeclaration(string line) { if (line.StartsWith("\t\t") || line.StartsWith("\t ") || line.StartsWith(" ") || line.StartsWith(" \t")) return true; return false; } private static bool IsFeatureDeclaration(string line) { int lineLength = line.Length; if (line.StartsWith("\t") && lineLength >= 2) { return !Char.IsWhiteSpace(line[1]); } if (line.StartsWith(" ") && lineLength >= 5) return !Char.IsWhiteSpace(line[4]); return false; } private static IEnumerable<string> ParseFeatureDependenciesEntry(string dependenciesEntry) { if (string.IsNullOrEmpty(dependenciesEntry)) return Enumerable.Empty<string>(); var dependencies = new List<string>(); foreach (var s in dependenciesEntry.Split(',')) { dependencies.Add(s.Trim()); } return dependencies; } private static string GetValue(IDictionary<string, string> fields, string key) { string value; return fields.TryGetValue(key, out value) ? value : null; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; namespace System.ComponentModel { // Summary: // Provides a unified way of converting types of values to other types, as well // as for accessing standard values and subproperties. //[ComVisible(true)] public class TypeConverter { // Summary: // Initializes a new instance of the System.ComponentModel.TypeConverter class. //public TypeConverter(); // Summary: // Returns whether this converter can convert an object of the given type to // the type of this converter. // // Parameters: // sourceType: // A System.Type that represents the type you want to convert from. // // Returns: // true if this converter can perform the conversion; otherwise, false. //public bool CanConvertFrom(Type sourceType); // // Summary: // Returns whether this converter can convert an object of the given type to // the type of this converter, using the specified context. // // Parameters: // context: // An System.ComponentModel.ITypeDescriptorContext that provides a format context. // // sourceType: // A System.Type that represents the type you want to convert from. // // Returns: // true if this converter can perform the conversion; otherwise, false. //public virtual bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType); // // Summary: // Returns whether this converter can convert the object to the specified type. // // Parameters: // destinationType: // A System.Type that represents the type you want to convert to. // // Returns: // true if this converter can perform the conversion; otherwise, false. //public bool CanConvertTo(Type destinationType); // // Summary: // Returns whether this converter can convert the object to the specified type, // using the specified context. // // Parameters: // context: // An System.ComponentModel.ITypeDescriptorContext that provides a format context. // // destinationType: // A System.Type that represents the type you want to convert to. // // Returns: // true if this converter can perform the conversion; otherwise, false. //public virtual bool CanConvertTo(ITypeDescriptorContext context, Type destinationType); // // Summary: // Converts the given value to the type of this converter. // // Parameters: // value: // The System.Object to convert. // // Returns: // An System.Object that represents the converted value. // // Exceptions: // System.NotSupportedException: // The conversion cannot be performed. //public object ConvertFrom(object value); // // Summary: // Converts the given object to the type of this converter, using the specified // context and culture information. // // Parameters: // context: // An System.ComponentModel.ITypeDescriptorContext that provides a format context. // // culture: // The System.Globalization.CultureInfo to use as the current culture. // // value: // The System.Object to convert. // // Returns: // An System.Object that represents the converted value. // // Exceptions: // System.NotSupportedException: // The conversion cannot be performed. //public virtual object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value); // // Summary: // Converts the given string to the type of this converter, using the invariant // culture. // // Parameters: // text: // The System.String to convert. // // Returns: // An System.Object that represents the converted text. // // Exceptions: // System.NotSupportedException: // The conversion cannot be performed. //public object ConvertFromInvariantString(string text); // // Summary: // Converts the given string to the type of this converter, using the invariant // culture and the specified context. // // Parameters: // context: // An System.ComponentModel.ITypeDescriptorContext that provides a format context. // // text: // The System.String to convert. // // Returns: // An System.Object that represents the converted text. // // Exceptions: // System.NotSupportedException: // The conversion cannot be performed. //public object ConvertFromInvariantString(ITypeDescriptorContext context, string text); // // Summary: // Converts the specified text to an object. // // Parameters: // text: // The text representation of the object to convert. // // Returns: // An System.Object that represents the converted text. // // Exceptions: // System.NotSupportedException: // The string cannot be converted into the appropriate object. //public object ConvertFromString(string text); // // Summary: // Converts the given text to an object, using the specified context. // // Parameters: // context: // An System.ComponentModel.ITypeDescriptorContext that provides a format context. // // text: // The System.String to convert. // // Returns: // An System.Object that represents the converted text. // // Exceptions: // System.NotSupportedException: // The conversion cannot be performed. //public object ConvertFromString(ITypeDescriptorContext context, string text); // // Summary: // Converts the given text to an object, using the specified context and culture // information. // // Parameters: // context: // An System.ComponentModel.ITypeDescriptorContext that provides a format context. // // culture: // A System.Globalization.CultureInfo. If null is passed, the current culture // is assumed. // // text: // The System.String to convert. // // Returns: // An System.Object that represents the converted text. // // Exceptions: // System.NotSupportedException: // The conversion cannot be performed. //public object ConvertFromString(ITypeDescriptorContext context, CultureInfo culture, string text); // // Summary: // Converts the given value object to the specified type, using the arguments. // // Parameters: // value: // The System.Object to convert. // // destinationType: // The System.Type to convert the value parameter to. // // Returns: // An System.Object that represents the converted value. // // Exceptions: // System.ArgumentNullException: // The destinationType parameter is null. // // System.NotSupportedException: // The conversion cannot be performed. public object ConvertTo(object value, Type destinationType) { Contract.Requires(destinationType != null); return default(object); } // // Summary: // Converts the given value object to the specified type, using the specified // context and culture information. // // Parameters: // context: // An System.ComponentModel.ITypeDescriptorContext that provides a format context. // // culture: // A System.Globalization.CultureInfo. If null is passed, the current culture // is assumed. // // value: // The System.Object to convert. // // destinationType: // The System.Type to convert the value parameter to. // // Returns: // An System.Object that represents the converted value. // // Exceptions: // System.ArgumentNullException: // The destinationType parameter is null. // // System.NotSupportedException: // The conversion cannot be performed. //public virtual object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType); // // Summary: // Converts the specified value to a culture-invariant string representation. // // Parameters: // value: // The System.Object to convert. // // Returns: // A System.String that represents the converted value. // // Exceptions: // System.NotSupportedException: // The conversion cannot be performed. //public string ConvertToInvariantString(object value); // // Summary: // Converts the specified value to a culture-invariant string representation, // using the specified context. // // Parameters: // context: // An System.ComponentModel.ITypeDescriptorContext that provides a format context. // // value: // The System.Object to convert. // // Returns: // A System.String that represents the converted value. // // Exceptions: // System.NotSupportedException: // The conversion cannot be performed. //public string ConvertToInvariantString(ITypeDescriptorContext context, object value); // // Summary: // Converts the specified value to a string representation. // // Parameters: // value: // The System.Object to convert. // // Returns: // An System.Object that represents the converted value. // // Exceptions: // System.NotSupportedException: // The conversion cannot be performed. //public string ConvertToString(object value); // // Summary: // Converts the given value to a string representation, using the given context. // // Parameters: // context: // An System.ComponentModel.ITypeDescriptorContext that provides a format context. // // value: // The System.Object to convert. // // Returns: // An System.Object that represents the converted value. // // Exceptions: // System.NotSupportedException: // The conversion cannot be performed. //public string ConvertToString(ITypeDescriptorContext context, object value); // // Summary: // Converts the given value to a string representation, using the specified // context and culture information. // // Parameters: // context: // An System.ComponentModel.ITypeDescriptorContext that provides a format context. // // culture: // A System.Globalization.CultureInfo. If null is passed, the current culture // is assumed. // // value: // The System.Object to convert. // // Returns: // An System.Object that represents the converted value. // // Exceptions: // System.NotSupportedException: // The conversion cannot be performed. //public string ConvertToString(ITypeDescriptorContext context, CultureInfo culture, object value); // // Summary: // Re-creates an System.Object given a set of property values for the object. // // Parameters: // propertyValues: // An System.Collections.IDictionary that represents a dictionary of new property // values. // // Returns: // An System.Object representing the given System.Collections.IDictionary, or // null if the object cannot be created. This method always returns null. //public object CreateInstance(IDictionary propertyValues); // // Summary: // Creates an instance of the type that this System.ComponentModel.TypeConverter // is associated with, using the specified context, given a set of property // values for the object. // // Parameters: // context: // An System.ComponentModel.ITypeDescriptorContext that provides a format context. // // propertyValues: // An System.Collections.IDictionary of new property values. // // Returns: // An System.Object representing the given System.Collections.IDictionary, or // null if the object cannot be created. This method always returns null. //public virtual object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues); // // Summary: // Returns an exception to throw when a conversion cannot be performed. // // Parameters: // value: // The System.Object to convert, or null if the object is not available. // // Returns: // An System.Exception that represents the exception to throw when a conversion // cannot be performed. // // Exceptions: // System.NotSupportedException: // Automatically thrown by this method. //protected Exception GetConvertFromException(object value); // // Summary: // Returns an exception to throw when a conversion cannot be performed. // // Parameters: // value: // The System.Object to convert, or null if the object is not available. // // destinationType: // A System.Type that represents the type the conversion was trying to convert // to. // // Returns: // An System.Exception that represents the exception to throw when a conversion // cannot be performed. // // Exceptions: // System.NotSupportedException: // Automatically thrown by this method. //protected Exception GetConvertToException(object value, Type destinationType); // // Summary: // Returns whether changing a value on this object requires a call to the System.ComponentModel.TypeConverter.CreateInstance(System.Collections.IDictionary) // method to create a new value. // // Returns: // true if changing a property on this object requires a call to System.ComponentModel.TypeConverter.CreateInstance(System.Collections.IDictionary) // to create a new value; otherwise, false. //public bool GetCreateInstanceSupported(); // // Summary: // Returns whether changing a value on this object requires a call to System.ComponentModel.TypeConverter.CreateInstance(System.Collections.IDictionary) // to create a new value, using the specified context. // // Parameters: // context: // An System.ComponentModel.ITypeDescriptorContext that provides a format context. // // Returns: // true if changing a property on this object requires a call to System.ComponentModel.TypeConverter.CreateInstance(System.Collections.IDictionary) // to create a new value; otherwise, false. //public virtual bool GetCreateInstanceSupported(ITypeDescriptorContext context); // // Summary: // Returns a collection of properties for the type of array specified by the // value parameter. // // Parameters: // value: // An System.Object that specifies the type of array for which to get properties. // // Returns: // A System.ComponentModel.PropertyDescriptorCollection with the properties // that are exposed for this data type, or null if there are no properties. //public PropertyDescriptorCollection GetProperties(object value); // // Summary: // Returns a collection of properties for the type of array specified by the // value parameter, using the specified context. // // Parameters: // context: // An System.ComponentModel.ITypeDescriptorContext that provides a format context. // // value: // An System.Object that specifies the type of array for which to get properties. // // Returns: // A System.ComponentModel.PropertyDescriptorCollection with the properties // that are exposed for this data type, or null if there are no properties. //public PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value); // // Summary: // Returns a collection of properties for the type of array specified by the // value parameter, using the specified context and attributes. // // Parameters: // context: // An System.ComponentModel.ITypeDescriptorContext that provides a format context. // // value: // An System.Object that specifies the type of array for which to get properties. // // attributes: // An array of type System.Attribute that is used as a filter. // // Returns: // A System.ComponentModel.PropertyDescriptorCollection with the properties // that are exposed for this data type, or null if there are no properties. //public virtual PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes); // // Summary: // Returns whether this object supports properties. // // Returns: // true if System.ComponentModel.TypeConverter.GetProperties(System.Object) // should be called to find the properties of this object; otherwise, false. //public bool GetPropertiesSupported(); // // Summary: // Returns whether this object supports properties, using the specified context. // // Parameters: // context: // An System.ComponentModel.ITypeDescriptorContext that provides a format context. // // Returns: // true if System.ComponentModel.TypeConverter.GetProperties(System.Object) // should be called to find the properties of this object; otherwise, false. //public virtual bool GetPropertiesSupported(ITypeDescriptorContext context); // // Summary: // Returns a collection of standard values from the default context for the // data type this type converter is designed for. // // Returns: // A System.ComponentModel.TypeConverter.StandardValuesCollection containing // a standard set of valid values, or null if the data type does not support // a standard set of values. //public ICollection GetStandardValues(); // // Summary: // Returns a collection of standard values for the data type this type converter // is designed for when provided with a format context. // // Parameters: // context: // An System.ComponentModel.ITypeDescriptorContext that provides a format context // that can be used to extract additional information about the environment // from which this converter is invoked. This parameter or properties of this // parameter can be null. // // Returns: // A System.ComponentModel.TypeConverter.StandardValuesCollection that holds // a standard set of valid values, or null if the data type does not support // a standard set of values. //public virtual TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context); // // Summary: // Returns whether the collection of standard values returned from System.ComponentModel.TypeConverter.GetStandardValues() // is an exclusive list. // // Returns: // true if the System.ComponentModel.TypeConverter.StandardValuesCollection // returned from System.ComponentModel.TypeConverter.GetStandardValues() is // an exhaustive list of possible values; false if other values are possible. //public bool GetStandardValuesExclusive(); // // Summary: // Returns whether the collection of standard values returned from System.ComponentModel.TypeConverter.GetStandardValues() // is an exclusive list of possible values, using the specified context. // // Parameters: // context: // An System.ComponentModel.ITypeDescriptorContext that provides a format context. // // Returns: // true if the System.ComponentModel.TypeConverter.StandardValuesCollection // returned from System.ComponentModel.TypeConverter.GetStandardValues() is // an exhaustive list of possible values; false if other values are possible. //public virtual bool GetStandardValuesExclusive(ITypeDescriptorContext context); // // Summary: // Returns whether this object supports a standard set of values that can be // picked from a list. // // Returns: // true if System.ComponentModel.TypeConverter.GetStandardValues() should be // called to find a common set of values the object supports; otherwise, false. //public bool GetStandardValuesSupported(); // // Summary: // Returns whether this object supports a standard set of values that can be // picked from a list, using the specified context. // // Parameters: // context: // An System.ComponentModel.ITypeDescriptorContext that provides a format context. // // Returns: // true if System.ComponentModel.TypeConverter.GetStandardValues() should be // called to find a common set of values the object supports; otherwise, false. //public virtual bool GetStandardValuesSupported(ITypeDescriptorContext context); // // Summary: // Returns whether the given value object is valid for this type. // // Parameters: // value: // The object to test for validity. // // Returns: // true if the specified value is valid for this object; otherwise, false. //public bool IsValid(object value); // // Summary: // Returns whether the given value object is valid for this type and for the // specified context. // // Parameters: // context: // An System.ComponentModel.ITypeDescriptorContext that provides a format context. // // value: // The System.Object to test for validity. // // Returns: // true if the specified value is valid for this object; otherwise, false. //public virtual bool IsValid(ITypeDescriptorContext context, object value); // // Summary: // Sorts a collection of properties. // // Parameters: // props: // A System.ComponentModel.PropertyDescriptorCollection that has the properties // to sort. // // names: // An array of names in the order you want the properties to appear in the collection. // // Returns: // A System.ComponentModel.PropertyDescriptorCollection that contains the sorted // properties. //protected PropertyDescriptorCollection SortProperties(PropertyDescriptorCollection props, string[] names); #if !SILVERLIGHT // Summary: // Represents an abstract class that provides properties for objects that do // not have properties. protected abstract class SimplePropertyDescriptor //: PropertyDescriptor { // Summary: // Initializes a new instance of the System.ComponentModel.TypeConverter.SimplePropertyDescriptor // class. // // Parameters: // componentType: // A System.Type that represents the type of component to which this property // descriptor binds. // // name: // The name of the property. // // propertyType: // A System.Type that represents the data type for this property. //protected SimplePropertyDescriptor(Type componentType, string name, Type propertyType); // // Summary: // Initializes a new instance of the System.ComponentModel.TypeConverter.SimplePropertyDescriptor // class. // // Parameters: // componentType: // A System.Type that represents the type of component to which this property // descriptor binds. // // name: // The name of the property. // // propertyType: // A System.Type that represents the data type for this property. // // attributes: // An System.Attribute array with the attributes to associate with the property. //protected SimplePropertyDescriptor(Type componentType, string name, Type propertyType, Attribute[] attributes); // Summary: // Gets the type of component to which this property description binds. // // Returns: // A System.Type that represents the type of component to which this property // binds. //public override Type ComponentType { get; } // // Summary: // Gets a value indicating whether this property is read-only. // // Returns: // true if the property is read-only; false if the property is read/write. //public override bool IsReadOnly { get; } // // Summary: // Gets the type of the property. // // Returns: // A System.Type that represents the type of the property. //public override Type PropertyType { get; } // Summary: // Returns whether resetting the component changes the value of the component. // // Parameters: // component: // The component to test for reset capability. // // Returns: // true if resetting the component changes the value of the component; otherwise, // false. //public override bool CanResetValue(object component); // // Summary: // Resets the value for this property of the component. // // Parameters: // component: // The component with the property value to be reset. //public override void ResetValue(object component); // // Summary: // Returns whether the value of this property can persist. // // Parameters: // component: // The component with the property that is to be examined for persistence. // // Returns: // true if the value of the property can persist; otherwise, false. //public override bool ShouldSerializeValue(object component); } // Summary: // Represents a collection of values. public class StandardValuesCollection //: ICollection, IEnumerable { // Summary: // Initializes a new instance of the System.ComponentModel.TypeConverter.StandardValuesCollection // class. // // Parameters: // values: // An System.Collections.ICollection that represents the objects to put into // the collection. //public StandardValuesCollection(ICollection values); // Summary: // Gets the number of objects in the collection. // // Returns: // The number of objects in the collection. //public int Count { get; } // Summary: // Gets the object at the specified index number. // // Parameters: // index: // The zero-based index of the System.Object to get from the collection. // // Returns: // The System.Object with the specified index. //public object this[int index] { get; } // Summary: // Copies the contents of this collection to an array. // // Parameters: // array: // An System.Array that represents the array to copy to. // // index: // The index to start from. //public void CopyTo(Array array, int index); // // Summary: // Returns an enumerator for this collection. // // Returns: // An enumerator of type System.Collections.IEnumerator. //public IEnumerator GetEnumerator(); } #endif } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the swf-2012-01-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SimpleWorkflow.Model { /// <summary> /// Container for the parameters to the StartWorkflowExecution operation. /// Starts an execution of the workflow type in the specified domain using the provided /// <code>workflowId</code> and input data. /// /// /// <para> /// This action returns the newly started workflow execution. /// </para> /// /// <para> /// <b>Access Control</b> /// </para> /// /// <para> /// You can use IAM policies to control this action's access to Amazon SWF resources as /// follows: /// </para> /// <ul> <li>Use a <code>Resource</code> element with the domain name to limit the action /// to only specified domains.</li> <li>Use an <code>Action</code> element to allow or /// deny permission to call this action.</li> <li>Constrain the following parameters by /// using a <code>Condition</code> element with the appropriate keys. <ul> <li> <code>tagList.member.0</code>: /// The key is <code>swf:tagList.member.0</code>.</li> <li> <code>tagList.member.1</code>: /// The key is <code>swf:tagList.member.1</code>.</li> <li> <code>tagList.member.2</code>: /// The key is <code>swf:tagList.member.2</code>.</li> <li> <code>tagList.member.3</code>: /// The key is <code>swf:tagList.member.3</code>.</li> <li> <code>tagList.member.4</code>: /// The key is <code>swf:tagList.member.4</code>.</li> <li><code>taskList</code>: String /// constraint. The key is <code>swf:taskList.name</code>.</li> <li><code>workflowType.name</code>: /// String constraint. The key is <code>swf:workflowType.name</code>.</li> <li><code>workflowType.version</code>: /// String constraint. The key is <code>swf:workflowType.version</code>.</li> </ul> </li> /// </ul> /// <para> /// If the caller does not have sufficient permissions to invoke the action, or the parameter /// values fall outside the specified constraints, the action fails. The associated event /// attribute's <b>cause</b> parameter will be set to OPERATION_NOT_PERMITTED. For details /// and example IAM policies, see <a href="http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using /// IAM to Manage Access to Amazon SWF Workflows</a>. /// </para> /// </summary> public partial class StartWorkflowExecutionRequest : AmazonSimpleWorkflowRequest { private ChildPolicy _childPolicy; private string _domain; private string _executionStartToCloseTimeout; private string _input; private string _lambdaRole; private List<string> _tagList = new List<string>(); private TaskList _taskList; private string _taskPriority; private string _taskStartToCloseTimeout; private string _workflowId; private WorkflowType _workflowType; /// <summary> /// Gets and sets the property ChildPolicy. /// <para> /// If set, specifies the policy to use for the child workflow executions of this workflow /// execution if it is terminated, by calling the <a>TerminateWorkflowExecution</a> action /// explicitly or due to an expired timeout. This policy overrides the default child policy /// specified when registering the workflow type using <a>RegisterWorkflowType</a>. /// </para> /// /// <para> /// The supported child policies are: /// </para> /// <ul> <li><b>TERMINATE:</b> the child executions will be terminated.</li> <li><b>REQUEST_CANCEL:</b> /// a request to cancel will be attempted for each child execution by recording a <code>WorkflowExecutionCancelRequested</code> /// event in its history. It is up to the decider to take appropriate actions when it /// receives an execution history with this event.</li> <li><b>ABANDON:</b> no action /// will be taken. The child executions will continue to run.</li> </ul> <note>A child /// policy for this workflow execution must be specified either as a default for the workflow /// type or through this parameter. If neither this parameter is set nor a default child /// policy was specified at registration time then a fault will be returned.</note> /// </summary> public ChildPolicy ChildPolicy { get { return this._childPolicy; } set { this._childPolicy = value; } } // Check to see if ChildPolicy property is set internal bool IsSetChildPolicy() { return this._childPolicy != null; } /// <summary> /// Gets and sets the property Domain. /// <para> /// The name of the domain in which the workflow execution is created. /// </para> /// </summary> public string Domain { get { return this._domain; } set { this._domain = value; } } // Check to see if Domain property is set internal bool IsSetDomain() { return this._domain != null; } /// <summary> /// Gets and sets the property ExecutionStartToCloseTimeout. /// <para> /// The total duration for this workflow execution. This overrides the defaultExecutionStartToCloseTimeout /// specified when registering the workflow type. /// </para> /// /// <para> /// The duration is specified in seconds; an integer greater than or equal to 0. Exceeding /// this limit will cause the workflow execution to time out. Unlike some of the other /// timeout parameters in Amazon SWF, you cannot specify a value of "NONE" for this timeout; /// there is a one-year max limit on the time that a workflow execution can run. /// </para> /// <note> An execution start-to-close timeout must be specified either through this /// parameter or as a default when the workflow type is registered. If neither this parameter /// nor a default execution start-to-close timeout is specified, a fault is returned.</note> /// </summary> public string ExecutionStartToCloseTimeout { get { return this._executionStartToCloseTimeout; } set { this._executionStartToCloseTimeout = value; } } // Check to see if ExecutionStartToCloseTimeout property is set internal bool IsSetExecutionStartToCloseTimeout() { return this._executionStartToCloseTimeout != null; } /// <summary> /// Gets and sets the property Input. /// <para> /// The input for the workflow execution. This is a free form string which should be meaningful /// to the workflow you are starting. This <code>input</code> is made available to the /// new workflow execution in the <code>WorkflowExecutionStarted</code> history event. /// </para> /// </summary> public string Input { get { return this._input; } set { this._input = value; } } // Check to see if Input property is set internal bool IsSetInput() { return this._input != null; } /// <summary> /// Gets and sets the property LambdaRole. /// <para> /// The ARN of an IAM role that authorizes Amazon SWF to invoke AWS Lambda functions. /// </para> /// <note>In order for this workflow execution to invoke AWS Lambda functions, an appropriate /// IAM role must be specified either as a default for the workflow type or through this /// field.</note> /// </summary> public string LambdaRole { get { return this._lambdaRole; } set { this._lambdaRole = value; } } // Check to see if LambdaRole property is set internal bool IsSetLambdaRole() { return this._lambdaRole != null; } /// <summary> /// Gets and sets the property TagList. /// <para> /// The list of tags to associate with the workflow execution. You can specify a maximum /// of 5 tags. You can list workflow executions with a specific tag by calling <a>ListOpenWorkflowExecutions</a> /// or <a>ListClosedWorkflowExecutions</a> and specifying a <a>TagFilter</a>. /// </para> /// </summary> public List<string> TagList { get { return this._tagList; } set { this._tagList = value; } } // Check to see if TagList property is set internal bool IsSetTagList() { return this._tagList != null && this._tagList.Count > 0; } /// <summary> /// Gets and sets the property TaskList. /// <para> /// The task list to use for the decision tasks generated for this workflow execution. /// This overrides the <code>defaultTaskList</code> specified when registering the workflow /// type. /// </para> /// <note>A task list for this workflow execution must be specified either as a default /// for the workflow type or through this parameter. If neither this parameter is set /// nor a default task list was specified at registration time then a fault will be returned.</note> /// /// <para> /// The specified string must not start or end with whitespace. It must not contain a /// <code>:</code> (colon), <code>/</code> (slash), <code>|</code> (vertical bar), or /// any control characters (\u0000-\u001f | \u007f - \u009f). Also, it must not contain /// the literal string quotarnquot. /// </para> /// </summary> public TaskList TaskList { get { return this._taskList; } set { this._taskList = value; } } // Check to see if TaskList property is set internal bool IsSetTaskList() { return this._taskList != null; } /// <summary> /// Gets and sets the property TaskPriority. /// <para> /// The task priority to use for this workflow execution. This will override any default /// priority that was assigned when the workflow type was registered. If not set, then /// the default task priority for the workflow type will be used. Valid values are integers /// that range from Java's <code>Integer.MIN_VALUE</code> (-2147483648) to <code>Integer.MAX_VALUE</code> /// (2147483647). Higher numbers indicate higher priority. /// </para> /// /// <para> /// For more information about setting task priority, see <a href="http://docs.aws.amazon.com/amazonswf/latest/developerguide/programming-priority.html">Setting /// Task Priority</a> in the <i>Amazon Simple Workflow Developer Guide</i>. /// </para> /// </summary> public string TaskPriority { get { return this._taskPriority; } set { this._taskPriority = value; } } // Check to see if TaskPriority property is set internal bool IsSetTaskPriority() { return this._taskPriority != null; } /// <summary> /// Gets and sets the property TaskStartToCloseTimeout. /// <para> /// Specifies the maximum duration of decision tasks for this workflow execution. This /// parameter overrides the <code>defaultTaskStartToCloseTimout</code> specified when /// registering the workflow type using <a>RegisterWorkflowType</a>. /// </para> /// /// <para> /// The duration is specified in seconds; an integer greater than or equal to 0. The value /// "NONE" can be used to specify unlimited duration. /// </para> /// <note>A task start-to-close timeout for this workflow execution must be specified /// either as a default for the workflow type or through this parameter. If neither this /// parameter is set nor a default task start-to-close timeout was specified at registration /// time then a fault will be returned.</note> /// </summary> public string TaskStartToCloseTimeout { get { return this._taskStartToCloseTimeout; } set { this._taskStartToCloseTimeout = value; } } // Check to see if TaskStartToCloseTimeout property is set internal bool IsSetTaskStartToCloseTimeout() { return this._taskStartToCloseTimeout != null; } /// <summary> /// Gets and sets the property WorkflowId. /// <para> /// The user defined identifier associated with the workflow execution. You can use this /// to associate a custom identifier with the workflow execution. You may specify the /// same identifier if a workflow execution is logically a <i>restart</i> of a previous /// execution. You cannot have two open workflow executions with the same <code>workflowId</code> /// at the same time. /// </para> /// /// <para> /// The specified string must not start or end with whitespace. It must not contain a /// <code>:</code> (colon), <code>/</code> (slash), <code>|</code> (vertical bar), or /// any control characters (\u0000-\u001f | \u007f - \u009f). Also, it must not contain /// the literal string quotarnquot. /// </para> /// </summary> public string WorkflowId { get { return this._workflowId; } set { this._workflowId = value; } } // Check to see if WorkflowId property is set internal bool IsSetWorkflowId() { return this._workflowId != null; } /// <summary> /// Gets and sets the property WorkflowType. /// <para> /// The type of the workflow to start. /// </para> /// </summary> public WorkflowType WorkflowType { get { return this._workflowType; } set { this._workflowType = value; } } // Check to see if WorkflowType property is set internal bool IsSetWorkflowType() { return this._workflowType != null; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; namespace System.Reflection.Internal { internal static class MemoryMapLightUp { private static Type lazyMemoryMappedFileType; private static Type lazyMemoryMappedViewAccessorType; private static Type lazyMemoryMappedFileAccessType; private static Type lazyMemoryMappedFileSecurityType; private static Type lazyHandleInheritabilityType; private static MethodInfo lazyCreateFromFile; private static MethodInfo lazyCreateViewAccessor; private static PropertyInfo lazySafeMemoryMappedViewHandle; private static PropertyInfo lazyPointerOffset; private static FieldInfo lazyInternalViewField; private static PropertyInfo lazyInternalPointerOffset; private static readonly object MemoryMappedFileAccess_Read = 1; private static readonly object HandleInheritability_None = 0; private static readonly object LongZero = (long)0; private static readonly object True = true; // test only: internal static bool Test450Compat; private static bool? lazyIsAvailable; internal static bool IsAvailable { get { if (!lazyIsAvailable.HasValue) { lazyIsAvailable = TryLoadTypes(); } return lazyIsAvailable.Value; } } private static bool TryLoadType(string assemblyQualifiedName, out Type type) { try { type = Type.GetType(assemblyQualifiedName, throwOnError: false); } catch { type = null; } return type != null; } private static bool TryLoadTypes() { const string SystemCoreRef = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; return FileStreamReadLightUp.FileStreamType.Value != null && TryLoadType("System.IO.MemoryMappedFiles.MemoryMappedFile, " + SystemCoreRef, out lazyMemoryMappedFileType) && TryLoadType("System.IO.MemoryMappedFiles.MemoryMappedViewAccessor, " + SystemCoreRef, out lazyMemoryMappedViewAccessorType) && TryLoadType("System.IO.MemoryMappedFiles.MemoryMappedFileAccess, " + SystemCoreRef, out lazyMemoryMappedFileAccessType) && TryLoadType("System.IO.MemoryMappedFiles.MemoryMappedFileSecurity, " + SystemCoreRef, out lazyMemoryMappedFileSecurityType) && TryLoadType("System.IO.HandleInheritability, " + SystemCoreRef, out lazyHandleInheritabilityType) && TryLoadMembers(); } private static bool TryLoadMembers() { lazyCreateFromFile = (from m in lazyMemoryMappedFileType.GetTypeInfo().GetDeclaredMethods("CreateFromFile") let ps = m.GetParameters() where ps.Length == 7 && ps[0].ParameterType == FileStreamReadLightUp.FileStreamType.Value && ps[1].ParameterType == typeof(string) && ps[2].ParameterType == typeof(long) && ps[3].ParameterType == lazyMemoryMappedFileAccessType && ps[4].ParameterType == lazyMemoryMappedFileSecurityType && ps[5].ParameterType == lazyHandleInheritabilityType && ps[6].ParameterType == typeof(bool) select m).SingleOrDefault(); if (lazyCreateFromFile == null) { return false; } lazyCreateViewAccessor = (from m in lazyMemoryMappedFileType.GetTypeInfo().GetDeclaredMethods("CreateViewAccessor") let ps = m.GetParameters() where ps.Length == 3 && ps[0].ParameterType == typeof(long) && ps[1].ParameterType == typeof(long) && ps[2].ParameterType == lazyMemoryMappedFileAccessType select m).SingleOrDefault(); if (lazyCreateViewAccessor == null) { return false; } lazySafeMemoryMappedViewHandle = lazyMemoryMappedViewAccessorType.GetTypeInfo().GetDeclaredProperty("SafeMemoryMappedViewHandle"); if (lazySafeMemoryMappedViewHandle == null) { return false; } // Available on FW >= 4.5.1: lazyPointerOffset = Test450Compat ? null : lazyMemoryMappedViewAccessorType.GetTypeInfo().GetDeclaredProperty("PointerOffset"); if (lazyPointerOffset == null) { // FW < 4.5.1 lazyInternalViewField = lazyMemoryMappedViewAccessorType.GetTypeInfo().GetDeclaredField("m_view"); if (lazyInternalViewField == null) { return false; } lazyInternalPointerOffset = lazyInternalViewField.FieldType.GetTypeInfo().GetDeclaredProperty("PointerOffset"); if (lazyInternalPointerOffset == null) { return false; } } return true; } internal static IDisposable CreateMemoryMap(Stream stream) { Debug.Assert(lazyIsAvailable.GetValueOrDefault()); try { return (IDisposable)lazyCreateFromFile.Invoke(null, new object[7] { stream, // fileStream null, // mapName LongZero, // capacity MemoryMappedFileAccess_Read, // access null, // memoryMappedFileSecurity HandleInheritability_None, // inheritability True, // leaveOpen }); } catch (MemberAccessException) { lazyIsAvailable = false; return null; } catch (TargetInvocationException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); throw; } } internal static IDisposable CreateViewAccessor(object memoryMap, long start, int size) { Debug.Assert(lazyIsAvailable.GetValueOrDefault()); try { return (IDisposable)lazyCreateViewAccessor.Invoke(memoryMap, new object[3] { start, // start (long)size, // size MemoryMappedFileAccess_Read, // access }); } catch (MemberAccessException) { lazyIsAvailable = false; return null; } catch (TargetInvocationException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); throw; } } internal unsafe static byte* AcquirePointer(object accessor, out SafeBuffer safeBuffer) { Debug.Assert(lazyIsAvailable.GetValueOrDefault()); safeBuffer = (SafeBuffer)lazySafeMemoryMappedViewHandle.GetValue(accessor); byte* ptr = null; safeBuffer.AcquirePointer(ref ptr); long offset; if (lazyPointerOffset != null) { offset = (long)lazyPointerOffset.GetValue(accessor); } else { object internalView = lazyInternalViewField.GetValue(accessor); offset = (long)lazyInternalPointerOffset.GetValue(internalView); } return ptr + offset; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MaskStoreUInt64() { var test = new StoreBinaryOpTest__MaskStoreUInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class StoreBinaryOpTest__MaskStoreUInt64 { private struct TestStruct { public Vector128<UInt64> _fld1; public Vector128<UInt64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); return testStruct; } public void RunStructFldScenario(StoreBinaryOpTest__MaskStoreUInt64 testClass) { Avx2.MaskStore((UInt64*)testClass._dataTable.outArrayPtr, _fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static UInt64[] _data1 = new UInt64[Op1ElementCount]; private static UInt64[] _data2 = new UInt64[Op2ElementCount]; private static Vector128<UInt64> _clsVar1; private static Vector128<UInt64> _clsVar2; private Vector128<UInt64> _fld1; private Vector128<UInt64> _fld2; private SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64> _dataTable; static StoreBinaryOpTest__MaskStoreUInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); } public StoreBinaryOpTest__MaskStoreUInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64>(_data1, _data2, new UInt64[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); Avx2.MaskStore( (UInt64*)_dataTable.outArrayPtr, Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); Avx2.MaskStore( (UInt64*)_dataTable.outArrayPtr, Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); Avx2.MaskStore( (UInt64*)_dataTable.outArrayPtr, Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); typeof(Avx2).GetMethod(nameof(Avx2.MaskStore), new Type[] { typeof(UInt64*), typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(UInt64*)), Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); typeof(Avx2).GetMethod(nameof(Avx2.MaskStore), new Type[] { typeof(UInt64*), typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(UInt64*)), Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); typeof(Avx2).GetMethod(nameof(Avx2.MaskStore), new Type[] { typeof(UInt64*), typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(UInt64*)), Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); Avx2.MaskStore( (UInt64*)_dataTable.outArrayPtr, _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr); Avx2.MaskStore((UInt64*)_dataTable.outArrayPtr, left, right); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)); Avx2.MaskStore((UInt64*)_dataTable.outArrayPtr, left, right); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)); Avx2.MaskStore((UInt64*)_dataTable.outArrayPtr, left, right); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new StoreBinaryOpTest__MaskStoreUInt64(); Avx2.MaskStore((UInt64*)_dataTable.outArrayPtr, test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); Avx2.MaskStore((UInt64*)_dataTable.outArrayPtr, _fld1, _fld2); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); Avx2.MaskStore((UInt64*)_dataTable.outArrayPtr, test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt64> left, Vector128<UInt64> right, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (((left[0] & (1UL << 63)) != 0) ? right[0] : result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (((left[i] & (1UL << 63)) != 0) ? right[i] : result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.MaskStore)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Editor.CSharp.Interactive; using Microsoft.CodeAnalysis.Interactive; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Traits = Roslyn.Test.Utilities.Traits; namespace Microsoft.CodeAnalysis.UnitTests.Interactive { [Trait(Traits.Feature, Traits.Features.InteractiveHost)] public sealed class InteractiveHostTests : AbstractInteractiveHostTests { #region Utils private SynchronizedStringWriter _synchronizedOutput; private SynchronizedStringWriter _synchronizedErrorOutput; private int[] _outputReadPosition = new int[] { 0, 0 }; private readonly InteractiveHost Host; private static readonly string s_fxDir = FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory()); private static readonly string s_homeDir = FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); public InteractiveHostTests() { Host = new InteractiveHost(typeof(CSharpReplServiceProvider), GetInteractiveHostPath(), ".", millisecondsTimeout: -1); RedirectOutput(); Host.ResetAsync(InteractiveHostOptions.Default).Wait(); var remoteService = Host.TryGetService(); Assert.NotNull(remoteService); remoteService.SetTestObjectFormattingOptions(); Host.SetPathsAsync(new[] { s_fxDir }, new[] { s_homeDir }, s_homeDir).Wait(); // assert and remove logo: var output = SplitLines(ReadOutputToEnd()); var errorOutput = ReadErrorOutputToEnd(); Assert.Equal("", errorOutput); Assert.Equal(2, output.Length); Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(Host.GetType().Assembly.Location).FileVersion, output[0]); // "Type "#help" for more information." Assert.Equal(FeaturesResources.TypeHelpForMoreInformation, output[1]); // remove logo: ClearOutput(); } public override void Dispose() { try { Process process = Host.TryGetProcess(); DisposeInteractiveHostProcess(Host); // the process should be terminated if (process != null && !process.HasExited) { process.WaitForExit(); } } finally { // Dispose temp files only after the InteractiveHost exits, // so that assemblies are unloaded. base.Dispose(); } } private void RedirectOutput() { _synchronizedOutput = new SynchronizedStringWriter(); _synchronizedErrorOutput = new SynchronizedStringWriter(); ClearOutput(); Host.Output = _synchronizedOutput; Host.ErrorOutput = _synchronizedErrorOutput; } private bool LoadReference(string reference) { return Execute($"#r \"{reference}\""); } private bool Execute(string code) { var task = Host.ExecuteAsync(code); task.Wait(); return task.Result.Success; } private bool IsShadowCopy(string path) { return Host.TryGetService().IsShadowCopy(path); } public string ReadErrorOutputToEnd() { return ReadOutputToEnd(isError: true); } public void ClearOutput() { _outputReadPosition = new int[] { 0, 0 }; _synchronizedOutput.Clear(); _synchronizedErrorOutput.Clear(); } public void RestartHost(string rspFile = null) { ClearOutput(); var initTask = Host.ResetAsync(InteractiveHostOptions.Default.WithInitializationFile(rspFile)); initTask.Wait(); } public string ReadOutputToEnd(bool isError = false) { var writer = isError ? _synchronizedErrorOutput : _synchronizedOutput; var markPrefix = '\uFFFF'; var mark = markPrefix + Guid.NewGuid().ToString(); // writes mark to the STDOUT/STDERR pipe in the remote process: Host.TryGetService().RemoteConsoleWrite(Encoding.UTF8.GetBytes(mark), isError); while (true) { var data = writer.Prefix(mark, ref _outputReadPosition[isError ? 0 : 1]); if (data != null) { return data; } Thread.Sleep(10); } } private class CompiledFile { public string Path; public ImmutableArray<byte> Image; } private static CompiledFile CompileLibrary(TempDirectory dir, string fileName, string assemblyName, string source, params MetadataReference[] references) { var file = dir.CreateFile(fileName); var compilation = CreateCompilation( new[] { source }, assemblyName: assemblyName, references: references.Concat(new[] { MetadataReference.CreateFromAssemblyInternal(typeof(object).Assembly) }), options: fileName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) ? TestOptions.ReleaseExe : TestOptions.ReleaseDll); var image = compilation.EmitToArray(); file.WriteAllBytes(image); return new CompiledFile { Path = file.Path, Image = image }; } #endregion [Fact] public void OutputRedirection() { Execute(@" System.Console.WriteLine(""hello-\u4567!""); System.Console.Error.WriteLine(""error-\u7890!""); 1+1 "); var output = ReadOutputToEnd(); var error = ReadErrorOutputToEnd(); Assert.Equal("hello-\u4567!\r\n2\r\n", output); Assert.Equal("error-\u7890!\r\n", error); } [Fact] public void OutputRedirection2() { Execute(@"System.Console.WriteLine(1);"); Execute(@"System.Console.Error.WriteLine(2);"); var output = ReadOutputToEnd(); var error = ReadErrorOutputToEnd(); Assert.Equal("1\r\n", output); Assert.Equal("2\r\n", error); RedirectOutput(); Execute(@"System.Console.WriteLine(3);"); Execute(@"System.Console.Error.WriteLine(4);"); output = ReadOutputToEnd(); error = ReadErrorOutputToEnd(); Assert.Equal("3\r\n", output); Assert.Equal("4\r\n", error); } [Fact] public void StackOverflow() { // Windows Server 2008 (OS v6.0), Vista (OS v6.0) and XP (OS v5.1) ignores SetErrorMode and shows crash dialog, which would hang the test: if (Environment.OSVersion.Version < new Version(6, 1, 0, 0)) { return; } Execute(@" int foo(int a0, int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9) { return foo(0,1,2,3,4,5,6,7,8,9) + foo(0,1,2,3,4,5,6,7,8,9); } foo(0,1,2,3,4,5,6,7,8,9) "); Assert.Equal("", ReadOutputToEnd()); // Hosting process exited with exit code -1073741571. Assert.Equal("Process is terminated due to StackOverflowException.\n" + string.Format(FeaturesResources.HostingProcessExitedWithExitCode, -1073741571), ReadErrorOutputToEnd().Trim()); Execute(@"1+1"); Assert.Equal("2\r\n", ReadOutputToEnd().ToString()); } private const string MethodWithInfiniteLoop = @" void foo() { int i = 0; while (true) { if (i < 10) { i = i + 1; } else if (i == 10) { System.Console.Error.WriteLine(""in the loop""); i = i + 1; } } } "; [Fact] public void AsyncExecute_InfiniteLoop() { var mayTerminate = new ManualResetEvent(false); Host.ErrorOutputReceived += (_, __) => mayTerminate.Set(); var executeTask = Host.ExecuteAsync(MethodWithInfiniteLoop + "\r\nfoo()"); Assert.True(mayTerminate.WaitOne()); RestartHost(); executeTask.Wait(); Assert.True(Execute(@"1+1")); Assert.Equal("2\r\n", ReadOutputToEnd()); } [Fact(Skip = "529027")] public void AsyncExecute_HangingForegroundThreads() { var mayTerminate = new ManualResetEvent(false); Host.OutputReceived += (_, __) => { mayTerminate.Set(); }; var executeTask = Host.ExecuteAsync(@" using System.Threading; int i1 = 0; Thread t1 = new Thread(() => { while(true) { i1++; } }); t1.Name = ""TestThread-1""; t1.IsBackground = false; t1.Start(); int i2 = 0; Thread t2 = new Thread(() => { while(true) { i2++; } }); t2.Name = ""TestThread-2""; t2.IsBackground = true; t2.Start(); Thread t3 = new Thread(() => Thread.Sleep(Timeout.Infinite)); t3.Name = ""TestThread-3""; t3.Start(); while (i1 < 2 || i2 < 2 || t3.ThreadState != System.Threading.ThreadState.WaitSleepJoin) { } System.Console.WriteLine(""terminate!""); while(true) {} "); Assert.Equal("", ReadErrorOutputToEnd()); Assert.True(mayTerminate.WaitOne()); var service = Host.TryGetService(); Assert.NotNull(service); var process = Host.TryGetProcess(); Assert.NotNull(process); service.EmulateClientExit(); // the process should terminate with exit code 0: process.WaitForExit(); Assert.Equal(0, process.ExitCode); } [Fact] public void AsyncExecuteFile_InfiniteLoop() { var file = Temp.CreateFile().WriteAllText(MethodWithInfiniteLoop + "\r\nfoo();").Path; var mayTerminate = new ManualResetEvent(false); Host.ErrorOutputReceived += (_, __) => mayTerminate.Set(); var executeTask = Host.ExecuteFileAsync(file); mayTerminate.WaitOne(); RestartHost(); executeTask.Wait(); Assert.True(Execute(@"1+1")); Assert.Equal("2\r\n", ReadOutputToEnd()); } [Fact] public void AsyncExecuteFile_SourceKind() { var file = Temp.CreateFile().WriteAllText("1+1").Path; var task = Host.ExecuteFileAsync(file); task.Wait(); Assert.False(task.Result.Success); var errorOut = ReadErrorOutputToEnd().Trim(); Assert.True(errorOut.StartsWith(file + "(1,4):", StringComparison.Ordinal), "Error output should start with file name, line and column"); Assert.True(errorOut.Contains("CS1002"), "Error output should include error CS1002"); } [Fact] public void AsyncExecuteFile_NonExistingFile() { var task = Host.ExecuteFileAsync("non existing file"); task.Wait(); Assert.False(task.Result.Success); var errorOut = ReadErrorOutputToEnd().Trim(); Assert.Contains(FeaturesResources.SpecifiedFileNotFound, errorOut, StringComparison.Ordinal); Assert.Contains(FeaturesResources.SearchedInDirectory, errorOut, StringComparison.Ordinal); } [Fact] public void AsyncExecuteFile() { var file = Temp.CreateFile().WriteAllText(@" using static System.Console; public class C { public int field = 4; public int Foo(int i) { return i; } } public int Foo(int i) { return i; } WriteLine(5); ").Path; var task = Host.ExecuteFileAsync(file); task.Wait(); Assert.True(task.Result.Success); Assert.Equal("5", ReadOutputToEnd().Trim()); Execute("Foo(2)"); Assert.Equal("2", ReadOutputToEnd().Trim()); Execute("new C().Foo(3)"); Assert.Equal("3", ReadOutputToEnd().Trim()); Execute("new C().field"); Assert.Equal("4", ReadOutputToEnd().Trim()); } [Fact] public void AsyncExecuteFile_InvalidFileContent() { var executeTask = Host.ExecuteFileAsync(typeof(Process).Assembly.Location); executeTask.Wait(); var errorOut = ReadErrorOutputToEnd().Trim(); Assert.True(errorOut.StartsWith(typeof(Process).Assembly.Location + "(1,3):", StringComparison.Ordinal), "Error output should start with file name, line and column"); Assert.True(errorOut.Contains("CS1056"), "Error output should include error CS1056"); Assert.True(errorOut.Contains("CS1002"), "Error output should include error CS1002"); } [Fact] public void AsyncExecuteFile_ScriptFileWithBuildErrors() { var file = Temp.CreateFile().WriteAllText("#load blah.csx" + "\r\n" + "class C {}"); Host.ExecuteFileAsync(file.Path).Wait(); var errorOut = ReadErrorOutputToEnd().Trim(); Assert.True(errorOut.StartsWith(file.Path + "(1,7):", StringComparison.Ordinal), "Error output should start with file name, line and column"); Assert.True(errorOut.Contains("CS7010"), "Error output should include error CS7010"); } /// <summary> /// Check that the assembly resolve event doesn't cause any harm. It shouldn't actually be /// even invoked since we resolve the assembly via Fusion. /// </summary> [Fact(Skip = "987032")] public void UserDefinedAssemblyResolve_InfiniteLoop() { var mayTerminate = new ManualResetEvent(false); Host.ErrorOutputReceived += (_, __) => mayTerminate.Set(); Host.TryGetService().HookMaliciousAssemblyResolve(); var executeTask = Host.AddReferenceAsync("nonexistingassembly" + Guid.NewGuid()); Assert.True(mayTerminate.WaitOne()); executeTask.Wait(); Assert.True(Execute(@"1+1")); var output = ReadOutputToEnd(); Assert.Equal("2\r\n", output); } [Fact] public void AddReference_PartialName() { Assert.False(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited")); Assert.True(LoadReference("System")); Assert.True(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited")); } [Fact] public void AddReference_PartialName_LatestVersion() { // there might be two versions of System.Data - v2 and v4, we should get the latter: Assert.True(LoadReference("System.Data")); Assert.True(LoadReference("System")); Assert.True(LoadReference("System.Xml")); Execute(@"new System.Data.DataSet().GetType().Assembly.GetName().Version"); var output = ReadOutputToEnd(); Assert.Equal("[4.0.0.0]\r\n", output); } [Fact] public void AddReference_FullName() { Assert.False(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited")); Assert.True(LoadReference(typeof(Process).Assembly.FullName)); Assert.True(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited")); } [ConditionalFact(typeof(Framework35Installed), Skip="https://github.com/dotnet/roslyn/issues/5167")] public void AddReference_VersionUnification1() { // V3.5 unifies with the current Framework version: var result = LoadReference("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); Assert.True(result); result = LoadReference("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); Assert.True(result); result = LoadReference("System.Core"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); Assert.True(result); } [Fact] public void AddReference_AssemblyAlreadyLoaded() { var result = LoadReference("System.Core"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); Assert.True(result); result = LoadReference("System.Core.dll"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); Assert.True(result); } [Fact] public void AddReference_Path() { Assert.False(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited")); Assert.True(LoadReference(typeof(Process).Assembly.Location)); Assert.True(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited")); } [Fact(Skip = "530414")] public void AddReference_ShadowCopy() { var dir = Temp.CreateDirectory(); // create C.dll var c = CompileLibrary(dir, "c.dll", "c", @"public class C { }"); // load C.dll: Assert.True(LoadReference(c.Path)); Assert.True(Execute("new C()")); Assert.Equal("C { }", ReadOutputToEnd().Trim()); // rewrite C.dll: File.WriteAllBytes(c.Path, new byte[] { 1, 2, 3 }); // we can still run code: var result = Execute("new C()"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("C { }", ReadOutputToEnd().Trim()); Assert.True(result); } #if TODO /// <summary> /// Tests that a dependency is correctly resolved and loaded at runtime. /// A depends on B, which depends on C. When CallB is jitted B is loaded. When CallC is jitted C is loaded. /// </summary> [Fact(Skip = "https://github.com/dotnet/roslyn/issues/860")] public void AddReference_Dependencies() { var dir = Temp.CreateDirectory(); var c = CompileLibrary(dir, "c.dll", "c", @"public class C { }"); var b = CompileLibrary(dir, "b.dll", "b", @"public class B { public static int CallC() { new C(); return 1; } }", MetadataReference.CreateFromImage(c.Image)); var a = CompileLibrary(dir, "a.dll", "a", @"public class A { public static int CallB() { B.CallC(); return 1; } }", MetadataReference.CreateFromImage(b.Image)); AssemblyLoadResult result; result = LoadReference(a.Path); Assert.Equal(a.Path, result.OriginalPath); Assert.True(IsShadowCopy(result.Path)); Assert.True(result.IsSuccessful); Assert.True(Execute("A.CallB()")); // c.dll is loaded as a dependency, so #r should be successful: result = LoadReference(c.Path); Assert.Equal(c.Path, result.OriginalPath); Assert.True(IsShadowCopy(result.Path)); Assert.True(result.IsSuccessful); // c.dll was already loaded explicitly via #r so we should fail now: result = LoadReference(c.Path); Assert.False(result.IsSuccessful); Assert.Equal(c.Path, result.OriginalPath); Assert.True(IsShadowCopy(result.Path)); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("1", ReadOutputToEnd().Trim()); } #endif /// <summary> /// When two files of the same version are in the same directory, prefer .dll over .exe. /// </summary> [Fact] public void AddReference_Dependencies_DllExe() { var dir = Temp.CreateDirectory(); var dll = CompileLibrary(dir, "c.dll", "C", @"public class C { public static int Main() { return 1; } }"); var exe = CompileLibrary(dir, "c.exe", "C", @"public class C { public static int Main() { return 2; } }"); var main = CompileLibrary(dir, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }", MetadataReference.CreateFromImage(dll.Image)); Assert.True(LoadReference(main.Path)); Assert.True(Execute("Program.Main()")); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("1", ReadOutputToEnd().Trim()); } [Fact] public void AddReference_Dependencies_Versions() { var dir1 = Temp.CreateDirectory(); var dir2 = Temp.CreateDirectory(); var dir3 = Temp.CreateDirectory(); // [assembly:AssemblyVersion("1.0.0.0")] public class C { public static int Main() { return 1; } }"); var file1 = dir1.CreateFile("c.dll").WriteAllBytes(TestResources.General.C1); // [assembly:AssemblyVersion("2.0.0.0")] public class C { public static int Main() { return 2; } }"); var file2 = dir2.CreateFile("c.dll").WriteAllBytes(TestResources.General.C2); Assert.True(LoadReference(file1.Path)); Assert.True(LoadReference(file2.Path)); var main = CompileLibrary(dir3, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }", MetadataReference.CreateFromImage(TestResources.General.C2.AsImmutableOrNull())); Assert.True(LoadReference(main.Path)); Assert.True(Execute("Program.Main()")); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("2", ReadOutputToEnd().Trim()); } [Fact] public void AddReference_AlreadyLoadedDependencies() { var dir = Temp.CreateDirectory(); var lib1 = CompileLibrary(dir, "lib1.dll", "lib1", @"public interface I { int M(); }"); var lib2 = CompileLibrary(dir, "lib2.dll", "lib2", @"public class C : I { public int M() { return 1; } }", MetadataReference.CreateFromFile(lib1.Path)); Execute("#r \"" + lib1.Path + "\""); Execute("#r \"" + lib2.Path + "\""); Execute("new C().M()"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("1", ReadOutputToEnd().Trim()); } [Fact(Skip = "530414")] public void AddReference_LoadUpdatedReference() { var dir = Temp.CreateDirectory(); var source1 = "public class C { public int X = 1; }"; var c1 = CreateCompilationWithMscorlib(source1, assemblyName: "C"); var file = dir.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray()); // use: Execute(@" #r """ + file.Path + @""" C foo() { return new C(); } new C().X "); // update: var source2 = "public class D { public int Y = 2; }"; var c2 = CreateCompilationWithMscorlib(source2, assemblyName: "C"); file.WriteAllBytes(c2.EmitToArray()); // add the reference again: Execute(@" #r """ + file.Path + @""" new D().Y "); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal( @"1 2", ReadOutputToEnd().Trim()); } [Fact(Skip = "987032")] public void AddReference_MultipleReferencesWithSameWeakIdentity() { var dir = Temp.CreateDirectory(); var dir1 = dir.CreateDirectory("1"); var dir2 = dir.CreateDirectory("2"); var source1 = "public class C1 { }"; var c1 = CreateCompilationWithMscorlib(source1, assemblyName: "C"); var file1 = dir1.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray()); var source2 = "public class C2 { }"; var c2 = CreateCompilationWithMscorlib(source2, assemblyName: "C"); var file2 = dir2.CreateFile("c.dll").WriteAllBytes(c2.EmitToArray()); Execute(@" #r """ + file1.Path + @""" #r """ + file2.Path + @""" "); Execute("new C1()"); Execute("new C2()"); Assert.Equal( @"(2,1): error CS1704: An assembly with the same simple name 'C' has already been imported. Try removing one of the references (e.g. '" + file1.Path + @"') or sign them to enable side-by-side. (1,5): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?) (1,5): error CS0246: The type or namespace name 'C2' could not be found (are you missing a using directive or an assembly reference?)", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); } //// TODO (987032): //// [Fact] //// public void AsyncInitializeContextWithDotNETLibraries() //// { //// var rspFile = Temp.CreateFile(); //// var rspDisplay = Path.GetFileName(rspFile.Path); //// var initScript = Temp.CreateFile(); //// rspFile.WriteAllText(@" /////r:System.Core ////""" + initScript.Path + @""" ////"); //// initScript.WriteAllText(@" ////using static System.Console; ////using System.Linq.Expressions; ////WriteLine(Expression.Constant(123)); ////"); //// // override default "is restarting" behavior (the REPL is already initialized): //// var task = Host.InitializeContextAsync(rspFile.Path, isRestarting: false, killProcess: true); //// task.Wait(); //// var output = SplitLines(ReadOutputToEnd()); //// var errorOutput = ReadErrorOutputToEnd(); //// Assert.Equal(4, output.Length); //// Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(typeof(Compilation).Assembly.Location).FileVersion, output[0]); //// Assert.Equal("Loading context from '" + rspDisplay + "'.", output[1]); //// Assert.Equal("Type \"#help\" for more information.", output[2]); //// Assert.Equal("123", output[3]); //// Assert.Equal("", errorOutput); //// Host.InitializeContextAsync(rspFile.Path).Wait(); //// output = SplitLines(ReadOutputToEnd()); //// errorOutput = ReadErrorOutputToEnd(); //// Assert.True(2 == output.Length, "Output is: '" + string.Join("<NewLine>", output) + "'. Expecting 2 lines."); //// Assert.Equal("Loading context from '" + rspDisplay + "'.", output[0]); //// Assert.Equal("123", output[1]); //// Assert.Equal("", errorOutput); //// } //// [Fact] //// public void AsyncInitializeContextWithBothUserDefinedAndDotNETLibraries() //// { //// var dir = Temp.CreateDirectory(); //// var rspFile = Temp.CreateFile(); //// var initScript = Temp.CreateFile(); //// var dll = CompileLibrary(dir, "c.dll", "C", @"public class C { public static int Main() { return 1; } }"); //// rspFile.WriteAllText(@" /////r:System.Numerics /////r:" + dll.Path + @" ////""" + initScript.Path + @""" ////"); //// initScript.WriteAllText(@" ////using static System.Console; ////using System.Numerics; ////WriteLine(new Complex(12, 6).Real + C.Main()); ////"); //// // override default "is restarting" behavior (the REPL is already initialized): //// var task = Host.InitializeContextAsync(rspFile.Path, isRestarting: false, killProcess: true); //// task.Wait(); //// var errorOutput = ReadErrorOutputToEnd(); //// Assert.Equal("", errorOutput); //// var output = SplitLines(ReadOutputToEnd()); //// Assert.Equal(4, output.Length); //// Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(Host.GetType().Assembly.Location).FileVersion, output[0]); //// Assert.Equal("Loading context from '" + Path.GetFileName(rspFile.Path) + "'.", output[1]); //// Assert.Equal("Type \"#help\" for more information.", output[2]); //// Assert.Equal("13", output[3]); //// } [Fact] public void ReferencePaths() { var directory = Temp.CreateDirectory(); var assemblyName = GetUniqueName(); CompileLibrary(directory, assemblyName + ".dll", assemblyName, @"public class C { }"); var rspFile = Temp.CreateFile(); rspFile.WriteAllText("/rp:" + directory.Path); var task = Host.ResetAsync(InteractiveHostOptions.Default.WithInitializationFile(rspFile.Path)); task.Wait(); Execute( $@"#r ""{assemblyName}.dll"" typeof(C).Assembly.GetName()"); var output = SplitLines(ReadOutputToEnd()); Assert.Equal(2, output.Length); Assert.Equal("Loading context from '" + Path.GetFileName(rspFile.Path) + "'.", output[0]); Assert.Equal($"[{assemblyName}, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", output[1]); } [Fact] public void ReferenceDirectives() { Execute(@" #r ""System.Numerics"" #r """ + typeof(System.Linq.Expressions.Expression).Assembly.Location + @""" using static System.Console; using System.Linq.Expressions; using System.Numerics; WriteLine(Expression.Constant(1)); WriteLine(new Complex(2, 6).Real); "); var output = ReadOutputToEnd(); Assert.Equal("1\r\n2\r\n", output); } [Fact] public void ExecutesOnStaThread() { Execute(@" #r ""System"" #r ""System.Xaml"" #r ""WindowsBase"" #r ""PresentationCore"" #r ""PresentationFramework"" new System.Windows.Window(); System.Console.WriteLine(""OK""); "); var error = ReadErrorOutputToEnd(); Assert.Equal("", error); var output = ReadOutputToEnd(); Assert.Equal("OK\r\n", output); } /// <summary> /// Execution of expressions should be /// sequential, even await expressions. /// </summary> [Fact] public void ExecuteSequentially() { Execute(@"using System; using System.Threading.Tasks;"); Execute(@"await Task.Delay(1000).ContinueWith(t => 1)"); Execute(@"await Task.Delay(500).ContinueWith(t => 2)"); Execute(@"3"); var output = ReadOutputToEnd(); Assert.Equal("1\r\n2\r\n3\r\n", output); } [Fact] public void MultiModuleAssembly() { var dir = Temp.CreateDirectory(); var dll = dir.CreateFile("MultiModule.dll").WriteAllBytes(TestResources.SymbolsTests.MultiModule.MultiModuleDll); dir.CreateFile("mod2.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod2); dir.CreateFile("mod3.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod3); Execute(@" #r """ + dll.Path + @""" new object[] { new Class1(), new Class2(), new Class3() } "); var error = ReadErrorOutputToEnd(); Assert.Equal("", error); var output = ReadOutputToEnd(); Assert.Equal("object[3] { Class1 { }, Class2 { }, Class3 { } }\r\n", output); } [Fact] public void SearchPaths1() { var dll = Temp.CreateFile(extension: ".dll").WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSInterfaces01); var srcDir = Temp.CreateDirectory(); var dllDir = Path.GetDirectoryName(dll.Path); srcDir.CreateFile("foo.csx").WriteAllText("ReferencePaths.Add(@\"" + dllDir + "\");"); Func<string, string> normalizeSeparatorsAndFrameworkFolders = (s) => s.Replace("\\", "\\\\").Replace("Framework64", "Framework"); // print default: Host.ExecuteAsync(@"ReferencePaths").Wait(); var output = ReadOutputToEnd(); Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", new[] { s_fxDir })) + "\" }\r\n", output); Host.ExecuteAsync(@"SourcePaths").Wait(); output = ReadOutputToEnd(); Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", new[] { s_homeDir })) + "\" }\r\n", output); // add and test if added: Host.ExecuteAsync("SourcePaths.Add(@\"" + srcDir + "\");").Wait(); Host.ExecuteAsync(@"SourcePaths").Wait(); output = ReadOutputToEnd(); Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", new[] { s_homeDir, srcDir.Path })) + "\" }\r\n", output); // execute file (uses modified search paths), the file adds a reference path Host.ExecuteFileAsync("foo.csx").Wait(); Host.ExecuteAsync(@"ReferencePaths").Wait(); output = ReadOutputToEnd(); Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", new[] { s_fxDir, dllDir })) + "\" }\r\n", output); Host.AddReferenceAsync(Path.GetFileName(dll.Path)).Wait(); Host.ExecuteAsync(@"typeof(Metadata.ICSProp)").Wait(); var error = ReadErrorOutputToEnd(); Assert.Equal("", error); output = ReadOutputToEnd(); Assert.Equal("[Metadata.ICSProp]\r\n", output); } #region Submission result printing - null/void/value. [Fact] public void SubmissionResult_PrintingNull() { Execute(@" string s; s "); var output = ReadOutputToEnd(); Assert.Equal("null\r\n", output); } [Fact] public void SubmissionResult_PrintingVoid() { Execute(@"System.Console.WriteLine(2)"); var output = ReadOutputToEnd(); Assert.Equal("2\r\n<void>\r\n", output); Execute(@" void foo() { } foo() "); output = ReadOutputToEnd(); Assert.Equal("<void>\r\n", output); } #endregion private static ImmutableArray<string> SplitLines(string text) { return ImmutableArray.Create(text.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)); } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using ASC.Common.Logging; using ASC.Core; using ASC.Mail.Core.Dao.Expressions.Contact; using ASC.Mail.Core.Entities; using ASC.Mail.Data.Search; using ASC.Mail.Enums; using ASC.Mail.Utils; using ASC.Web.Core; namespace ASC.Mail.Core.Engine { public class ContactEngine { public int Tenant { get; private set; } public string User { get; private set; } public ILog Log { get; private set; } public ContactEngine(int tenant, string user, ILog log = null) { Tenant = tenant; User = user; Log = log ?? LogManager.GetLogger("ASC.Mail.ContactEngine"); } public List<ContactCard> GetContactCards(IContactsExp exp) { if (exp == null) throw new ArgumentNullException("exp"); using (var daoFactory = new DaoFactory()) { var daoContacts = daoFactory.CreateContactCardDao(Tenant, User); var list = daoContacts.GetContactCards(exp); return list; } } public int GetContactCardsCount(IContactsExp exp) { if (exp == null) throw new ArgumentNullException("exp"); using (var daoFactory = new DaoFactory()) { var daoContacts = daoFactory.CreateContactCardDao(Tenant, User); var count = daoContacts.GetContactCardsCount(exp); return count; } } public ContactCard GetContactCard(int id) { using (var daoFactory = new DaoFactory()) { var daoContacts = daoFactory.CreateContactCardDao(Tenant, User); var contactCard = daoContacts.GetContactCard(id); return contactCard; } } public ContactCard SaveContactCard(ContactCard contactCard) { using (var daoFactory = new DaoFactory()) { using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted)) { var daoContact = daoFactory.CreateContactDao(Tenant, User); var daoContactInfo = daoFactory.CreateContactInfoDao(Tenant, User); var contactId = daoContact.SaveContact(contactCard.ContactInfo); contactCard.ContactInfo.Id = contactId; foreach (var contactItem in contactCard.ContactItems) { contactItem.ContactId = contactId; var contactItemId = daoContactInfo.SaveContactInfo(contactItem); contactItem.Id = contactItemId; } tx.Commit(); } } var factory = new EngineFactory(Tenant, User, Log); Log.Debug("IndexEngine->SaveContactCard()"); factory.IndexEngine.Add(contactCard.ToMailContactWrapper()); return contactCard; } public ContactCard UpdateContactCard(ContactCard newContactCard) { var contactId = newContactCard.ContactInfo.Id; if (contactId < 0) throw new ArgumentException("Invalid contact id"); var contactCard = GetContactCard(contactId); if (null == contactCard) throw new ArgumentException("Contact not found"); var contactChanged = !contactCard.ContactInfo.Equals(newContactCard.ContactInfo); var newContactItems = newContactCard.ContactItems.Where(c => !contactCard.ContactItems.Contains(c)).ToList(); var removedContactItems = contactCard.ContactItems.Where(c => !newContactCard.ContactItems.Contains(c)).ToList(); if (!contactChanged && !newContactItems.Any() && !removedContactItems.Any()) return contactCard; using (var daoFactory = new DaoFactory()) { using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted)) { if (contactChanged) { var daoContact = daoFactory.CreateContactDao(Tenant, User); daoContact.SaveContact(newContactCard.ContactInfo); contactCard.ContactInfo = newContactCard.ContactInfo; } var daoContactInfo = daoFactory.CreateContactInfoDao(Tenant, User); if (newContactItems.Any()) { foreach (var contactItem in newContactItems) { contactItem.ContactId = contactId; var contactItemId = daoContactInfo.SaveContactInfo(contactItem); contactItem.Id = contactItemId; contactCard.ContactItems.Add(contactItem); } } if (removedContactItems.Any()) { foreach (var contactItem in removedContactItems) { daoContactInfo.RemoveContactInfo(contactItem.Id); contactCard.ContactItems.Remove(contactItem); } } tx.Commit(); } } var factory = new EngineFactory(Tenant, User, Log); Log.Debug("IndexEngine->UpdateContactCard()"); factory.IndexEngine.Update(new List<MailContactWrapper> { contactCard.ToMailContactWrapper() }); return contactCard; } public void RemoveContacts(List<int> ids) { if (!ids.Any()) throw new ArgumentNullException("ids"); using (var daoFactory = new DaoFactory()) { using (var tx = daoFactory.DbManager.BeginTransaction()) { var daoContact = daoFactory.CreateContactDao(Tenant, User); daoContact.RemoveContacts(ids); var daoContactInfo = daoFactory.CreateContactInfoDao(Tenant, User); daoContactInfo.RemoveByContactIds(ids); tx.Commit(); } } var factory = new EngineFactory(Tenant, User, Log); Log.Debug("IndexEngine->RemoveContacts()"); factory.IndexEngine.RemoveContacts(ids, Tenant, new Guid(User)); } /// <summary> /// Search emails in Accounts, Mail, CRM, Peaople Contact System /// </summary> /// <param name="tenant">Tenant id</param> /// <param name="userName">User id</param> /// <param name="term">Search word</param> /// <param name="maxCountPerSystem">limit result per Contact System</param> /// <param name="timeout">Timeout in milliseconds</param> /// <param name="httpContextScheme"></param> /// <returns></returns> public List<string> SearchEmails(int tenant, string userName, string term, int maxCountPerSystem, string httpContextScheme, int timeout = -1) { var equality = new ContactEqualityComparer(); var contacts = new List<string>(); var userGuid = new Guid(userName); var watch = new Stopwatch(); watch.Start(); var apiHelper = new ApiHelper(httpContextScheme, Log); var taskList = new List<Task<List<string>>>() { Task.Run(() => { CoreContext.TenantManager.SetCurrentTenant(tenant); SecurityContext.AuthenticateMe(userGuid); var engine = new EngineFactory(tenant, userName); var exp = new FullFilterContactsExp(tenant, userName, term, infoType: ContactInfoType.Email, orderAsc: true, limit: maxCountPerSystem); var contactCards = engine.ContactEngine.GetContactCards(exp); return (from contactCard in contactCards from contactItem in contactCard.ContactItems select string.IsNullOrEmpty(contactCard.ContactInfo.ContactName) ? contactItem.Data : MailUtil.CreateFullEmail(contactCard.ContactInfo.ContactName, contactItem.Data)) .ToList(); }), Task.Run(() => { CoreContext.TenantManager.SetCurrentTenant(tenant); SecurityContext.AuthenticateMe(userGuid); var engine = new EngineFactory(tenant, userGuid.ToString()); return engine.AccountEngine.SearchAccountEmails(term); }), Task.Run(() => { CoreContext.TenantManager.SetCurrentTenant(tenant); SecurityContext.AuthenticateMe(userGuid); return WebItemSecurity.IsAvailableForMe(WebItemManager.CRMProductID) ? apiHelper.SearchCrmEmails(term, maxCountPerSystem) : new List<string>(); }), Task.Run(() => { CoreContext.TenantManager.SetCurrentTenant(tenant); SecurityContext.AuthenticateMe(userGuid); return WebItemSecurity.IsAvailableForMe(WebItemManager.PeopleProductID) ? apiHelper.SearchPeopleEmails(term, 0, maxCountPerSystem) : new List<string>(); }) }; try { var taskArray = taskList.ToArray<Task>(); Task.WaitAll(taskArray, timeout); watch.Stop(); } catch (AggregateException e) { watch.Stop(); var errorText = new StringBuilder("SearchEmails: \nThe following exceptions have been thrown by WaitAll():"); foreach (var t in e.InnerExceptions) { errorText .AppendFormat("\n-------------------------------------------------\n{0}", t); } Log.Error(errorText.ToString()); } contacts = taskList.Aggregate(contacts, (current, task) => !task.IsFaulted && task.IsCompleted && !task.IsCanceled ? current.Concat(task.Result).ToList() : current) .Distinct(equality) .ToList(); Log.DebugFormat("SearchEmails (term = '{0}'): {1} sec / {2} items", term, watch.Elapsed.TotalSeconds, contacts.Count); return contacts; } public class ContactEqualityComparer : IEqualityComparer<string> { public bool Equals(string contact1, string contact2) { if (contact1 == null && contact2 == null) return true; if (contact1 == null || contact2 == null) return false; var contact1Parts = contact1.Split('<'); var contact2Parts = contact2.Split('<'); return contact1Parts.Last().Replace(">", "") == contact2Parts.Last().Replace(">", ""); } public int GetHashCode(string str) { var strParts = str.Split('<'); return strParts.Last().Replace(">", "").GetHashCode(); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.Script.Services; using System.Web.Services; using System.Web.UI; using System.Xml; using System.Xml.Xsl; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.IO; using Umbraco.Web.WebServices; using umbraco.BusinessLogic; using umbraco.cms.businesslogic.macro; using umbraco.cms.businesslogic.template; using umbraco.cms.businesslogic.web; using System.Net; using System.Collections; using umbraco.NodeFactory; namespace umbraco.presentation.webservices { /// <summary> /// Summary description for codeEditorSave /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] [ScriptService] public class codeEditorSave : UmbracoAuthorizedWebService { [Obsolete("This method has been superceded by the REST service /Umbraco/RestServices/SaveFile/SaveStylesheet which is powered by the SaveFileController.")] [WebMethod] public string SaveCss(string fileName, string oldName, string fileContents, int fileID) { if (AuthorizeRequest(DefaultApps.settings.ToString())) { var stylesheet = Services.FileService.GetStylesheetByName(oldName.EnsureEndsWith(".css")); if (stylesheet == null) throw new InvalidOperationException("No stylesheet found with name " + oldName); stylesheet.Content = fileContents; if (fileName.InvariantEquals(oldName) == false) { //it's changed which means we need to change the path stylesheet.Path = stylesheet.Path.TrimEnd(oldName.EnsureEndsWith(".css")) + fileName.EnsureEndsWith(".css"); } Services.FileService.SaveStylesheet(stylesheet, Security.CurrentUser.Id); return "true"; } return "false"; } [WebMethod] public string SaveXslt(string fileName, string oldName, string fileContents, bool ignoreDebugging) { fileName = fileName.CleanForXss(); if (AuthorizeRequest(DefaultApps.developer.ToString())) { IOHelper.EnsurePathExists(SystemDirectories.Xslt); // validate file IOHelper.ValidateEditPath(IOHelper.MapPath(SystemDirectories.Xslt + "/" + fileName), SystemDirectories.Xslt); // validate extension IOHelper.ValidateFileExtension(IOHelper.MapPath(SystemDirectories.Xslt + "/" + fileName), new List<string>() { "xsl", "xslt" }); StreamWriter SW; string tempFileName = IOHelper.MapPath(SystemDirectories.Xslt + "/" + DateTime.Now.Ticks + "_temp.xslt"); SW = File.CreateText(tempFileName); SW.Write(fileContents); SW.Close(); // Test the xslt string errorMessage = ""; if (!ignoreDebugging) { try { // Check if there's any documents yet string xpath = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "/root/node" : "/root/*"; if (content.Instance.XmlContent.SelectNodes(xpath).Count > 0) { var macroXML = new XmlDocument(); macroXML.LoadXml("<macro/>"); var macroXSLT = new XslCompiledTransform(); var umbPage = new page(content.Instance.XmlContent.SelectSingleNode("//* [@parentID = -1]")); var xslArgs = macro.AddMacroXsltExtensions(); var lib = new library(umbPage); xslArgs.AddExtensionObject("urn:umbraco.library", lib); HttpContext.Current.Trace.Write("umbracoMacro", "After adding extensions"); // Add the current node xslArgs.AddParam("currentPage", "", library.GetXmlNodeById(umbPage.PageID.ToString())); HttpContext.Current.Trace.Write("umbracoMacro", "Before performing transformation"); // Create reader and load XSL file // We need to allow custom DTD's, useful for defining an ENTITY var readerSettings = new XmlReaderSettings(); readerSettings.ProhibitDtd = false; using (var xmlReader = XmlReader.Create(tempFileName, readerSettings)) { var xslResolver = new XmlUrlResolver(); xslResolver.Credentials = CredentialCache.DefaultCredentials; macroXSLT.Load(xmlReader, XsltSettings.TrustedXslt, xslResolver); xmlReader.Close(); // Try to execute the transformation var macroResult = new HtmlTextWriter(new StringWriter()); macroXSLT.Transform(macroXML, xslArgs, macroResult); macroResult.Close(); File.Delete(tempFileName); } } else { //errorMessage = ui.Text("developer", "xsltErrorNoNodesPublished"); File.Delete(tempFileName); //base.speechBubble(speechBubbleIcon.info, ui.Text("errors", "xsltErrorHeader", base.getUser()), "Unable to validate xslt as no published content nodes exist."); } } catch (Exception errorXslt) { File.Delete(tempFileName); errorMessage = (errorXslt.InnerException ?? errorXslt).ToString(); // Full error message errorMessage = errorMessage.Replace("\n", "<br/>\n"); //closeErrorMessage.Visible = true; // Find error var m = Regex.Matches(errorMessage, @"\d*[^,],\d[^\)]", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); foreach (Match mm in m) { string[] errorLine = mm.Value.Split(','); if (errorLine.Length > 0) { var theErrorLine = int.Parse(errorLine[0]); var theErrorChar = int.Parse(errorLine[1]); errorMessage = "Error in XSLT at line " + errorLine[0] + ", char " + errorLine[1] + "<br/>"; errorMessage += "<span style=\"font-family: courier; font-size: 11px;\">"; var xsltText = fileContents.Split("\n".ToCharArray()); for (var i = 0; i < xsltText.Length; i++) { if (i >= theErrorLine - 3 && i <= theErrorLine + 1) if (i + 1 == theErrorLine) { errorMessage += "<b>" + (i + 1) + ": &gt;&gt;&gt;&nbsp;&nbsp;" + Server.HtmlEncode(xsltText[i].Substring(0, theErrorChar)); errorMessage += "<span style=\"text-decoration: underline; border-bottom: 1px solid red\">" + Server.HtmlEncode( xsltText[i].Substring(theErrorChar, xsltText[i].Length - theErrorChar)). Trim() + "</span>"; errorMessage += " &lt;&lt;&lt;</b><br/>"; } else errorMessage += (i + 1) + ": &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + Server.HtmlEncode(xsltText[i]) + "<br/>"; } errorMessage += "</span>"; } } } } if (errorMessage == "" && fileName.ToLower().EndsWith(".xslt")) { //Hardcoded security-check... only allow saving files in xslt directory... var savePath = IOHelper.MapPath(SystemDirectories.Xslt + "/" + fileName); if (savePath.StartsWith(IOHelper.MapPath(SystemDirectories.Xslt + "/"))) { //deletes the old xslt file if (fileName != oldName) { var p = IOHelper.MapPath(SystemDirectories.Xslt + "/" + oldName); if (File.Exists(p)) File.Delete(p); } SW = File.CreateText(savePath); SW.Write(fileContents); SW.Close(); errorMessage = "true"; } else { errorMessage = "Illegal path"; } } File.Delete(tempFileName); return errorMessage; } return "false"; } [WebMethod] public string SaveDLRScript(string fileName, string oldName, string fileContents, bool ignoreDebugging) { if (AuthorizeRequest(DefaultApps.developer.ToString())) { if (string.IsNullOrEmpty(fileName)) throw new ArgumentNullException("fileName"); var allowedExtensions = new List<string>(); foreach (var lang in MacroEngineFactory.GetSupportedUILanguages()) { if (!allowedExtensions.Contains(lang.Extension)) allowedExtensions.Add(lang.Extension); } // validate file IOHelper.ValidateEditPath(IOHelper.MapPath(SystemDirectories.MacroScripts + "/" + fileName), SystemDirectories.MacroScripts); // validate extension IOHelper.ValidateFileExtension(IOHelper.MapPath(SystemDirectories.MacroScripts + "/" + fileName), allowedExtensions); //As Files Can Be Stored In Sub Directories, So We Need To Get The Exeuction Directory Correct var lastOccurance = fileName.LastIndexOf('/') + 1; var directory = fileName.Substring(0, lastOccurance); var fileNameWithExt = fileName.Substring(lastOccurance); var tempFileName = IOHelper.MapPath(SystemDirectories.MacroScripts + "/" + directory + DateTime.Now.Ticks + "_" + fileNameWithExt); using (var sw = new StreamWriter(tempFileName, false, Encoding.UTF8)) { sw.Write(fileContents); sw.Close(); } var errorMessage = ""; if (!ignoreDebugging) { var root = Document.GetRootDocuments().FirstOrDefault(); if (root != null) { var args = new Hashtable(); var n = new Node(root.Id); args.Add("currentPage", n); try { var engine = MacroEngineFactory.GetByFilename(tempFileName); var tempErrorMessage = ""; var xpath = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "/root/node" : "/root/*"; if ( !engine.Validate(fileContents, tempFileName, Node.GetNodeByXpath(xpath), out tempErrorMessage)) errorMessage = tempErrorMessage; } catch (Exception err) { errorMessage = err.ToString(); } } } if (errorMessage == "") { var savePath = IOHelper.MapPath(SystemDirectories.MacroScripts + "/" + fileName); //deletes the file if (fileName != oldName) { var p = IOHelper.MapPath(SystemDirectories.MacroScripts + "/" + oldName); if (File.Exists(p)) File.Delete(p); } using (var sw = new StreamWriter(savePath, false, Encoding.UTF8)) { sw.Write(fileContents); sw.Close(); } errorMessage = "true"; } File.Delete(tempFileName); return errorMessage.Replace("\n", "<br/>\n"); } return "false"; } //[WebMethod] //public string SavePartialView(string filename, string oldName, string contents) //{ // if (BasePage.ValidateUserContextID(BasePage.umbracoUserContextID)) // { // var folderPath = SystemDirectories.MvcViews + "/Partials/"; // // validate file // IOHelper.ValidateEditPath(IOHelper.MapPath(folderPath + filename), folderPath); // // validate extension // IOHelper.ValidateFileExtension(IOHelper.MapPath(folderPath + filename), new[] {"cshtml"}.ToList()); // var val = contents; // string returnValue; // var saveOldPath = oldName.StartsWith("~/") ? IOHelper.MapPath(oldName) : IOHelper.MapPath(folderPath + oldName); // var savePath = filename.StartsWith("~/") ? IOHelper.MapPath(filename) : IOHelper.MapPath(folderPath + filename); // //Directory check.. only allow files in script dir and below to be edited // if (savePath.StartsWith(IOHelper.MapPath(folderPath))) // { // //deletes the old file // if (savePath != saveOldPath) // { // if (File.Exists(saveOldPath)) // File.Delete(saveOldPath); // } // using (var sw = File.CreateText(savePath)) // { // sw.Write(val); // } // returnValue = "true"; // } // else // { // returnValue = "illegalPath"; // } // return returnValue; // } // return "false"; //} [Obsolete("This method has been superceded by the REST service /Umbraco/RestServices/SaveFile/SaveScript which is powered by the SaveFileController.")] [WebMethod] public string SaveScript(string filename, string oldName, string contents) { if (AuthorizeRequest(DefaultApps.settings.ToString())) { // validate file IOHelper.ValidateEditPath(IOHelper.MapPath(SystemDirectories.Scripts + "/" + filename), SystemDirectories.Scripts); // validate extension IOHelper.ValidateFileExtension(IOHelper.MapPath(SystemDirectories.Scripts + "/" + filename), UmbracoConfig.For.UmbracoSettings().Content.ScriptFileTypes.ToList()); var val = contents; string returnValue; try { var saveOldPath = ""; saveOldPath = oldName.StartsWith("~/") ? IOHelper.MapPath(oldName) : IOHelper.MapPath(SystemDirectories.Scripts + "/" + oldName); var savePath = ""; savePath = filename.StartsWith("~/") ? IOHelper.MapPath(filename) : IOHelper.MapPath(SystemDirectories.Scripts + "/" + filename); //Directory check.. only allow files in script dir and below to be edited if (savePath.StartsWith(IOHelper.MapPath(SystemDirectories.Scripts + "/")) || savePath.StartsWith(IOHelper.MapPath(SystemDirectories.Masterpages + "/"))) { //deletes the old file if (savePath != saveOldPath) { if (File.Exists(saveOldPath)) File.Delete(saveOldPath); } //ensure the folder exists before saving Directory.CreateDirectory(Path.GetDirectoryName(savePath)); using (var sw = File.CreateText(savePath)) { sw.Write(val); sw.Close(); } returnValue = "true"; } else { returnValue = "illegalPath"; } } catch { returnValue = "false"; } return returnValue; } return "false"; } [Obsolete("This method has been superceded by the REST service /Umbraco/RestServices/SaveFile/SaveTemplate which is powered by the SaveFileController.")] [WebMethod] public string SaveTemplate(string templateName, string templateAlias, string templateContents, int templateID, int masterTemplateID) { if (AuthorizeRequest(DefaultApps.settings.ToString())) { var _template = new Template(templateID); string retVal = "false"; if (_template != null) { _template.Text = templateName; _template.Alias = templateAlias; _template.MasterTemplate = masterTemplateID; _template.Design = templateContents; _template.Save(); retVal = "true"; } return retVal; } return "false"; } } }
#pragma warning disable MA0028 // Optimize StringBuilder would make the code harder to read #pragma warning disable MA0101 // String contains an implicit end of line character using System.Globalization; using System.Text; using System.Text.RegularExpressions; using System.Xml.Linq; using System.Xml.XPath; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Meziantou.Framework.ResxSourceGenerator; [Generator] public sealed class ResxGenerator : IIncrementalGenerator { private static readonly DiagnosticDescriptor s_invalidResx = new( id: "MFRG0001", title: "Couldn't parse Resx file", messageFormat: "Couldn't parse Resx file '{0}'", category: "ResxGenerator", DiagnosticSeverity.Warning, isEnabledByDefault: true); private static readonly DiagnosticDescriptor s_invalidPropertiesForNamespace = new( id: "MFRG0002", title: "Couldn't compute namespace", messageFormat: "Couldn't compute namespace for file '{0}'", category: "ResxGenerator", DiagnosticSeverity.Warning, isEnabledByDefault: true); private static readonly DiagnosticDescriptor s_invalidPropertiesForResourceName = new( id: "MFRG0003", title: "Couldn't compute resource name", messageFormat: "Couldn't compute resource name for file '{0}'", category: "ResxGenerator", DiagnosticSeverity.Warning, isEnabledByDefault: true); private static readonly DiagnosticDescriptor s_inconsistentProperties = new( id: "MFRG0004", title: "Inconsistent properties", messageFormat: "Property '{0}' values for '{1}' are inconsistent", category: "ResxGenerator", DiagnosticSeverity.Warning, isEnabledByDefault: true); public void Initialize(IncrementalGeneratorInitializationContext context) { context.RegisterSourceOutput( source: context.AnalyzerConfigOptionsProvider.Combine(context.CompilationProvider.Combine(context.AdditionalTextsProvider.Where(text => text.Path.EndsWith(".resx", StringComparison.OrdinalIgnoreCase)).Collect())), action: (ctx, source) => Execute(ctx, source.Left, source.Right.Left, source.Right.Right)); } private static void Execute(SourceProductionContext context, AnalyzerConfigOptionsProvider options, Compilation compilation, System.Collections.Immutable.ImmutableArray<AdditionalText> files) { var hasNotNullIfNotNullAttribute = compilation.GetTypeByMetadataName("System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute") != null; // Group additional file by resource kind ((a.resx, a.en.resx, a.en-us.resx), (b.resx, b.en-us.resx)) var resxGroups = files .GroupBy(file => GetResourceName(file.Path), StringComparer.OrdinalIgnoreCase) .ToList(); foreach (var resxGroug in resxGroups) { var rootNamespaceConfiguration = GetMetadataValue(context, options, "RootNamespace", resxGroug); var projectDirConfiguration = GetMetadataValue(context, options, "ProjectDir", resxGroug); var namespaceConfiguration = GetMetadataValue(context, options, "Namespace", "DefaultResourcesNamespace", resxGroug); var resourceNameConfiguration = GetMetadataValue(context, options, "ResourceName", globalName: null, resxGroug); var classNameConfiguration = GetMetadataValue(context, options, "ClassName", globalName: null, resxGroug); var assemblyName = compilation.AssemblyName; var rootNamespace = rootNamespaceConfiguration ?? assemblyName ?? ""; var projectDir = projectDirConfiguration ?? assemblyName ?? ""; var defaultResourceName = ComputeResourceName(rootNamespace, projectDir, resxGroug.Key); var defaultNamespace = ComputeNamespace(rootNamespace, projectDir, resxGroug.Key); var ns = namespaceConfiguration ?? defaultNamespace; var resourceName = resourceNameConfiguration ?? defaultResourceName; var className = classNameConfiguration ?? ToCSharpNameIdentifier(Path.GetFileName(resxGroug.Key)); if (ns == null) { context.ReportDiagnostic(Diagnostic.Create(s_invalidPropertiesForNamespace, location: null, resxGroug.First().Path)); } if (resourceName == null) { context.ReportDiagnostic(Diagnostic.Create(s_invalidPropertiesForResourceName, location: null, resxGroug.First().Path)); } var entries = LoadResourceFiles(context, resxGroug); var content = $@" // Debug info: // key: {resxGroug.Key} // files: {string.Join(", ", resxGroug.Select(f => f.Path))} // RootNamespace (metadata): {rootNamespaceConfiguration} // ProjectDir (metadata): {projectDirConfiguration} // Namespace / DefaultResourcesNamespace (metadata): {namespaceConfiguration} // ResourceName (metadata): {resourceNameConfiguration} // ClassName (metadata): {classNameConfiguration} // AssemblyName: {assemblyName} // RootNamespace (computed): {rootNamespace} // ProjectDir (computed): {projectDir} // defaultNamespace: {defaultNamespace} // defaultResourceName: {defaultResourceName} // Namespace: {ns} // ResourceName: {resourceName} // ClassName: {className} "; if (resourceName != null && entries != null) { content += GenerateCode(ns, className, resourceName, entries, hasNotNullIfNotNullAttribute); } context.AddSource($"{Path.GetFileName(resxGroug.Key)}.resx.g.cs", SourceText.From(content, Encoding.UTF8)); } } private static string GenerateCode(string? ns, string className, string resourceName, List<ResxEntry> entries, bool enableNullableAttributes) { var sb = new StringBuilder(); sb.AppendLine(); sb.AppendLine("#nullable enable"); if (ns != null) { sb.AppendLine("namespace " + ns); sb.AppendLine("{"); } sb.AppendLine(" internal partial class " + className); sb.AppendLine(" {"); sb.AppendLine(" private static global::System.Resources.ResourceManager? resourceMan;"); sb.AppendLine(); sb.AppendLine(" public " + className + "() { }"); sb.AppendLine(@" /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (resourceMan is null) { resourceMan = new global::System.Resources.ResourceManager(""" + resourceName + @""", typeof(" + className + @").Assembly); } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo? Culture { get; set; } " + AppendNotNullIfNotNull("defaultValue") + @" public static object? GetObject(global::System.Globalization.CultureInfo? culture, string name, object? defaultValue) { culture ??= Culture; object? obj = ResourceManager.GetObject(name, culture); if (obj == null) { return defaultValue; } return obj; } public static object? GetObject(global::System.Globalization.CultureInfo? culture, string name) { return GetObject(culture: culture, name: name, defaultValue: null); } public static object? GetObject(string name) { return GetObject(culture: null, name: name, defaultValue: null); } " + AppendNotNullIfNotNull("defaultValue") + @" public static object? GetObject(string name, object? defaultValue) { return GetObject(culture: null, name: name, defaultValue: defaultValue); } public static global::System.IO.Stream? GetStream(string name) { return GetStream(culture: null, name: name); } public static global::System.IO.Stream? GetStream(global::System.Globalization.CultureInfo? culture, string name) { culture ??= Culture; return ResourceManager.GetStream(name, culture); } public static string? GetString(global::System.Globalization.CultureInfo? culture, string name) { return GetString(culture: culture, name: name, args: null); } public static string? GetString(global::System.Globalization.CultureInfo? culture, string name, params object?[]? args) { culture ??= Culture; string? str = ResourceManager.GetString(name, culture); if (str == null) { return null; } if (args != null) { return string.Format(culture, str, args); } else { return str; } } public static string? GetString(string name, params object?[]? args) { return GetString(culture: null, name: name, args: args); } " + AppendNotNullIfNotNull("defaultValue") + @" public static string? GetString(string name, string? defaultValue) { return GetStringWithDefault(culture: null, name: name, defaultValue: defaultValue, args: null); } public static string? GetString(string name) { return GetStringWithDefault(culture: null, name: name, defaultValue: null, args: null); } " + AppendNotNullIfNotNull("defaultValue") + @" public static string? GetStringWithDefault(global::System.Globalization.CultureInfo? culture, string name, string? defaultValue) { return GetStringWithDefault(culture: culture, name: name, defaultValue: defaultValue, args: null); } " + AppendNotNullIfNotNull("defaultValue") + @" public static string? GetStringWithDefault(global::System.Globalization.CultureInfo? culture, string name, string? defaultValue, params object?[]? args) { culture ??= Culture; string? str = ResourceManager.GetString(name, culture); if (str == null) { if (defaultValue == null || args == null) { return defaultValue; } else { return string.Format(culture, defaultValue, args); } } if (args != null) { return string.Format(culture, str, args); } else { return str; } } " + AppendNotNullIfNotNull("defaultValue") + @" public static string? GetStringWithDefault(string name, string? defaultValue, params object?[]? args) { return GetStringWithDefault(culture: null, name: name, defaultValue: defaultValue, args: args); } " + AppendNotNullIfNotNull("defaultValue") + @" public static string? GetStringWithDefault(string name, string? defaultValue) { return GetStringWithDefault(culture: null, name: name, defaultValue: defaultValue, args: null); } "); foreach (var entry in entries.OrderBy(e => e.Name)) { if (string.IsNullOrEmpty(entry.Name)) continue; if (entry.IsText) { var summary = new XElement("summary", new XElement("para", $"Looks up a localized string for \"{entry.Name}\".")); if (!string.IsNullOrWhiteSpace(entry.Comment)) { summary.Add(new XElement("para", entry.Comment)); } if (!entry.IsFileRef) { summary.Add(new XElement("para", $"Value: \"{entry.Value}\".")); } var comment = summary.ToString().Replace(Environment.NewLine, Environment.NewLine + " /// ", StringComparison.Ordinal); sb.AppendLine(@" /// " + comment + @" public static string? @" + ToCSharpNameIdentifier(entry.Name) + @" { get { return GetString(""" + entry.Name + @"""); } } "); if (entry.Value != null) { var args = Regex.Matches(entry.Value, "\\{(?<num>[0-9]+)(\\:[^}]*)?\\}", RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant, TimeSpan.FromSeconds(1)) .Cast<Match>() .Select(m => int.Parse(m.Groups["num"].Value, CultureInfo.InvariantCulture)) .Distinct() .DefaultIfEmpty(-1) .Max(); if (args >= 0) { var inParams = string.Join(", ", Enumerable.Range(0, args + 1).Select(arg => "object? arg" + arg.ToString(CultureInfo.InvariantCulture))); var callParams = string.Join(", ", Enumerable.Range(0, args + 1).Select(arg => "arg" + arg.ToString(CultureInfo.InvariantCulture))); sb.AppendLine(@" /// " + comment + @" public static string? Format" + ToCSharpNameIdentifier(entry.Name) + "(global::System.Globalization.CultureInfo? provider, " + inParams + @") { return GetString(provider, """ + entry.Name + "\", " + callParams + @"); } "); sb.AppendLine(@" /// " + comment + @" public static string? Format" + ToCSharpNameIdentifier(entry.Name) + "(" + inParams + @") { return GetString(""" + entry.Name + "\", " + callParams + @"); } "); } } } else { sb.AppendLine(@" public static global::" + entry.FullTypeName + "? @" + ToCSharpNameIdentifier(entry.Name) + @" { get { return (global::" + entry.FullTypeName + @"?)GetObject(""" + entry.Name + @"""); } } "); } } sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" internal partial class " + className + "Names"); sb.AppendLine(" {"); foreach (var entry in entries) { if (string.IsNullOrEmpty(entry.Name)) continue; sb.AppendLine(" public const string @" + ToCSharpNameIdentifier(entry.Name) + " = \"" + entry.Name + "\";"); } sb.AppendLine(" }"); if (ns != null) { sb.AppendLine("}"); } return sb.ToString(); string? AppendNotNullIfNotNull(string paramName) { if (!enableNullableAttributes) return null; return "[return: global::System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute(\"" + paramName + "\")]\n"; } } private static string? ComputeResourceName(string rootNamespace, string projectDir, string resourcePath) { var fullProjectDir = EnsureEndSeparator(Path.GetFullPath(projectDir)); var fullResourcePath = Path.GetFullPath(resourcePath); if (fullProjectDir == fullResourcePath) return rootNamespace; if (fullResourcePath.StartsWith(fullProjectDir, StringComparison.Ordinal)) { var relativePath = fullResourcePath[fullProjectDir.Length..]; return rootNamespace + '.' + relativePath.Replace('/', '.').Replace('\\', '.'); } return null; } private static string? ComputeNamespace(string rootNamespace, string projectDir, string resourcePath) { var fullProjectDir = EnsureEndSeparator(Path.GetFullPath(projectDir)); var fullResourcePath = EnsureEndSeparator(Path.GetDirectoryName(Path.GetFullPath(resourcePath))!); if (fullProjectDir == fullResourcePath) return rootNamespace; if (fullResourcePath.StartsWith(fullProjectDir, StringComparison.Ordinal)) { var relativePath = fullResourcePath[fullProjectDir.Length..]; return rootNamespace + '.' + relativePath.Replace('/', '.').Replace('\\', '.').TrimEnd('.'); } return null; } private static List<ResxEntry>? LoadResourceFiles(SourceProductionContext context, IGrouping<string, AdditionalText> resxGroug) { var entries = new List<ResxEntry>(); foreach (var entry in resxGroug.OrderBy(file => file.Path, StringComparer.Ordinal)) { var content = entry.GetText(context.CancellationToken); if (content == null) continue; try { var document = XDocument.Parse(content.ToString()); foreach (var element in document.XPathSelectElements("/root/data")) { var name = element.Attribute("name")?.Value; var type = element.Attribute("type")?.Value; var comment = element.Attribute("comment")?.Value; var value = element.Element("value")?.Value; var existingEntry = entries.Find(e => e.Name == name); if (existingEntry != null) { if (existingEntry.Comment == null) { existingEntry.Comment = comment; } } else { entries.Add(new ResxEntry { Name = name, Value = value, Comment = comment, Type = type }); } } } catch { context.ReportDiagnostic(Diagnostic.Create(s_invalidResx, location: null, entry.Path)); return null; } } return entries; } private static string? GetMetadataValue(SourceProductionContext context, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider, string name, IEnumerable<AdditionalText> additionalFiles) { return GetMetadataValue(context, analyzerConfigOptionsProvider, name, name, additionalFiles); } private static string? GetMetadataValue(SourceProductionContext context, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider, string name, string? globalName, IEnumerable<AdditionalText> additionalFiles) { string? result = null; foreach (var file in additionalFiles) { if (analyzerConfigOptionsProvider.GetOptions(file).TryGetValue("build_metadata.AdditionalFiles." + name, out var value)) { if (result != null && value != result) { context.ReportDiagnostic(Diagnostic.Create(s_inconsistentProperties, location: null, name, file.Path)); return null; } result = value; } } if (!string.IsNullOrEmpty(result)) return result; if (globalName != null && analyzerConfigOptionsProvider.GlobalOptions.TryGetValue("build_property." + globalName, out var globalValue) && !string.IsNullOrEmpty(globalValue)) return globalValue; return null; } private static string ToCSharpNameIdentifier(string name) { // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure#identifiers // https://docs.microsoft.com/en-us/dotnet/api/system.globalization.unicodecategory?view=net-5.0 var sb = new StringBuilder(); foreach (var c in name) { var category = char.GetUnicodeCategory(c); switch (category) { case UnicodeCategory.UppercaseLetter: case UnicodeCategory.LowercaseLetter: case UnicodeCategory.TitlecaseLetter: case UnicodeCategory.ModifierLetter: case UnicodeCategory.OtherLetter: case UnicodeCategory.LetterNumber: sb.Append(c); break; case UnicodeCategory.DecimalDigitNumber: case UnicodeCategory.ConnectorPunctuation: case UnicodeCategory.Format: if (sb.Length == 0) { sb.Append('_'); } sb.Append(c); break; default: sb.Append('_'); break; } } return sb.ToString(); } private static string EnsureEndSeparator(string path) { if (path[^1] == Path.DirectorySeparatorChar) return path; return path + Path.DirectorySeparatorChar; } private static string GetResourceName(string path) { var pathWithoutExtension = Path.Combine(Path.GetDirectoryName(path)!, Path.GetFileNameWithoutExtension(path)); var indexOf = pathWithoutExtension.LastIndexOf('.'); if (indexOf < 0) return pathWithoutExtension; return Regex.IsMatch(pathWithoutExtension[(indexOf + 1)..], "^[a-zA-Z]{2}(-[a-zA-Z]{2})?$", RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant, TimeSpan.FromSeconds(1)) ? pathWithoutExtension[0..indexOf] : pathWithoutExtension; } private sealed class ResxEntry { public string? Name { get; set; } public string? Value { get; set; } public string? Comment { get; set; } public string? Type { get; set; } public bool IsText { get { if (Type == null) return true; if (Value != null) { var parts = Value.Split(';'); if (parts.Length > 1) { var type = parts[1]; if (type.StartsWith("System.String,", StringComparison.Ordinal)) return true; } } return false; } } public string? FullTypeName { get { if (IsText) return "string"; if (Value != null) { var parts = Value.Split(';'); if (parts.Length > 1) { var type = parts[1]; return type.Split(',')[0]; } } return null; } } public bool IsFileRef => Type != null && Type.StartsWith("System.Resources.ResXFileRef,", StringComparison.Ordinal); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FlatRedBall.Graphics; using FlatRedBall.Math; using FlatRedBall.Math.Collision; using FlatRedBall.Math.Geometry; #if WINDOWS_PHONE using Microsoft.Phone.Info; #endif namespace FlatRedBall.Debugging { #region CountedCategory class class CountedCategory { public string String; public int Count; public int Invisible; public override string ToString() { return String; } } #endregion public static class Debugger { #region Enums public enum Corner { TopLeft, TopRight, BottomLeft, BottomRight } #endregion #region Fields static Text mText; static Layer mLayer; static string MemoryInformation; static double LastCalculationTime; public static Corner TextCorner = Corner.TopLeft; public static float TextRed = 1; public static float TextGreen = 1; public static float TextBlue = 1; public static int NumberOfLinesInCommandLine = 5; static List<string> mCommandLineOutput = new List<string>(); #if DEBUG static RollingAverage mAllocationAverage = new RollingAverage(4); static long mLastMemoryUse = -1; #endif #if WINDOWS_PHONE static double mMemoryUpdateFrequency = 1; #else static double mMemoryUpdateFrequency = .25; #endif #endregion #region Properties public static double MemoryUpdateFrequency { get { return mMemoryUpdateFrequency; } set { mMemoryUpdateFrequency = value; } } public static AutomaticDebuggingBehavior AutomaticDebuggingBehavior { get; set; } #endregion #region Constructor static Debugger() { AutomaticDebuggingBehavior = new AutomaticDebuggingBehavior(); } #endregion #region Methods static void CreateTextIfNecessary() { if (mText == null) { mText = TextManager.AddText(""); mText.Name = "Debugger rendering text"; mLayer = SpriteManager.TopLayer; TextManager.AddToLayer(mText, mLayer); mText.AttachTo(SpriteManager.Camera, false); mText.VerticalAlignment = VerticalAlignment.Top; mText.AdjustPositionForPixelPerfectDrawing = true; } } public static void DestroyText() { if (mText != null) { SpriteManager.RemoveLayer(mLayer); TextManager.RemoveText(mText); mLayer = null; mText = null; } } public static void ClearCommandLine() { mCommandLineOutput.Clear(); } public static void CommandLineWrite(string stringToWrite) { mCommandLineOutput.Add(stringToWrite); if (mCommandLineOutput.Count > NumberOfLinesInCommandLine) { mCommandLineOutput.RemoveAt(0); } } public static void CommandLineWrite(object objectToWrite) { if (objectToWrite != null) { CommandLineWrite(objectToWrite.ToString()); } else { CommandLineWrite("<null>"); } } public static void Write(string stringToWrite) { CreateTextIfNecessary(); mText.DisplayText = stringToWrite; //position the text each frame in case of camera changes AdjustTextPosition(); mText.Red = TextRed; mText.Green = TextGreen; mText.Blue = TextBlue; mText.SetPixelPerfectScale(mLayer); } public static void Write(object objectToWrite) { if (objectToWrite == null) { Write("<NULL>"); } else { Write(objectToWrite.ToString()); } } public static void WriteMemoryInformation() { if (TimeManager.SecondsSince(LastCalculationTime) > mMemoryUpdateFrequency) { MemoryInformation = ForceGetMemoryInformation(); } Write(MemoryInformation); } public static string ForceGetMemoryInformation() { string memoryInformation; long currentUsage; #if WINDOWS_PHONE currentUsage = (long)DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage"); memoryInformation = DeviceExtendedProperties.GetValue("DeviceTotalMemory") + "\n" + currentUsage + "\n" + DeviceExtendedProperties.GetValue("ApplicationPeakMemoryUsage"); #else currentUsage = GC.GetTotalMemory(false); memoryInformation = "Total Memory: " + currentUsage; #endif #if DEBUG if (mLastMemoryUse >= 0) { long difference = currentUsage - mLastMemoryUse; if (difference >= 0) { mAllocationAverage.AddValue((float)(difference / mMemoryUpdateFrequency)); } } memoryInformation += "\nAverage Growth per second: " + mAllocationAverage.Average.ToString("0,000"); #endif LastCalculationTime = TimeManager.CurrentTime; #if DEBUG mLastMemoryUse = currentUsage; #endif return memoryInformation; } public static void WriteAutomaticallyUpdatedObjectInformation() { string result = GetAutomaticallyUpdatedObjectInformation(); Write(result); } public static string GetAutomaticallyUpdatedObjectInformation() { const string indentString = " * "; StringBuilder stringBuilder = new StringBuilder(); int total = 0; // SpriteManager stringBuilder.AppendLine(SpriteManager.ManagedPositionedObjects.Count + " PositionedObjects"); var entityCount = SpriteManager.ManagedPositionedObjects.Where(item => item.GetType().FullName.Contains(".Entities")).Count(); stringBuilder.AppendLine($"{indentString} {entityCount} Entities"); total += SpriteManager.ManagedPositionedObjects.Count; var totalSpriteCount = SpriteManager.AutomaticallyUpdatedSprites.Count; stringBuilder.AppendLine(totalSpriteCount + " Sprites"); var spriteNonParticleEntityCount = SpriteManager.AutomaticallyUpdatedSprites.Where(item => item.GetType().FullName.Contains(".Entities")).Count(); stringBuilder.AppendLine(indentString + spriteNonParticleEntityCount + " Entity Sprites"); stringBuilder.AppendLine(indentString + SpriteManager.ParticleCount + " Particles"); var normalSpriteCount = SpriteManager.AutomaticallyUpdatedSprites.Count - spriteNonParticleEntityCount - SpriteManager.ParticleCount; stringBuilder.AppendLine(indentString + (normalSpriteCount) + " Normal Sprites"); total += SpriteManager.AutomaticallyUpdatedSprites.Count; stringBuilder.AppendLine(SpriteManager.SpriteFrames.Count + " SpriteFrames"); total += SpriteManager.SpriteFrames.Count; stringBuilder.AppendLine(SpriteManager.Cameras.Count + " Cameras"); total += SpriteManager.Cameras.Count; stringBuilder.AppendLine(SpriteManager.Emitters.Count + " Emitters"); total += SpriteManager.Emitters.Count; // ShapeManager stringBuilder.AppendLine(ShapeManager.AutomaticallyUpdatedShapes.Count + " Shapes"); total += ShapeManager.AutomaticallyUpdatedShapes.Count; // TextManager stringBuilder.AppendLine(TextManager.AutomaticallyUpdatedTexts.Count + " Texts"); total += TextManager.AutomaticallyUpdatedTexts.Count; stringBuilder.AppendLine("---------------"); stringBuilder.AppendLine(total + " Total"); string result = stringBuilder.ToString(); return result; } public static string GetAutomaticallyUpdatedEntityInformation() { Dictionary<Type, int> countDictionary = new Dictionary<Type, int>(); var entities = SpriteManager.ManagedPositionedObjects.Where(item => item.GetType().FullName.Contains(".Entities")); foreach(var entity in entities) { var type = entity.GetType(); if (countDictionary.ContainsKey(type)) { countDictionary[type]++; } else { countDictionary[type] = 1; } } StringBuilder builder = new StringBuilder(); foreach(var kvp in countDictionary.OrderByDescending(item =>item.Value)) { builder.AppendLine($"{kvp.Value} {kvp.Key.Name}"); } return builder.ToString(); } public static void WriteAutomaticallyUpdatedSpriteFrameBreakdown() { string result = GetAutomaticallyUpdatedBreakdownFromList<FlatRedBall.ManagedSpriteGroups.SpriteFrame>(SpriteManager.SpriteFrames); Write(result); } public static void WriteAutomaticallyUpdatedShapeBreakdown() { var result = GetShapeBreakdown(); Write(result); } public static void WriteAutomaticallyUpdatedSpriteBreakdown() { string result = GetAutomaticallyUpdatedSpriteBreakdown(); Write(result); } public static string GetAutomaticallyUpdatedSpriteBreakdown() { return GetAutomaticallyUpdatedBreakdownFromList<Sprite>(SpriteManager.AutomaticallyUpdatedSprites); } public static string GetAutomaticallyUpdatedBreakdownFromList<T>(IEnumerable<T> list) where T : PositionedObject { Dictionary<string, CountedCategory> typeDictionary = new Dictionary<string, CountedCategory>(); bool isIVisible = false; if (list.Count() != 0) { isIVisible = list.First() is IVisible; } foreach(var atI in list) { string typeName = "Unparented"; if (typeof(T) != atI.GetType()) { typeName = atI.GetType().Name; } else if (atI.Parent != null) { typeName = atI.Parent.GetType().Name; } if (typeDictionary.ContainsKey(typeName) == false) { var toAdd = new CountedCategory(); toAdd.String = typeName; typeDictionary.Add(typeName, toAdd); } typeDictionary[typeName].Count++; if (isIVisible && !((IVisible)atI).AbsoluteVisible) { typeDictionary[typeName].Invisible++; } } string toReturn = "Total: " + list.Count() + " " + typeof(T).Name + "s\n" + GetFilledStringBuilderWithNumberedTypes(typeDictionary).ToString(); if (list.Count() == 0) { toReturn = "No automatically updated " + typeof(T).Name + "s"; } return toReturn; } static StringBuilder stringBuilder = new StringBuilder(); public static string GetFullPerformanceInformation() { if(Renderer.RecordRenderBreaks == false) { Renderer.RecordRenderBreaks = true; } stringBuilder.Clear(); var objectCount = GetAutomaticallyUpdatedObjectInformation(); stringBuilder.AppendLine(objectCount); stringBuilder.AppendLine(); stringBuilder.Append(GetInstructionInformation()); stringBuilder.AppendLine(); stringBuilder.AppendLine($"Render breaks: {Renderer.LastFrameRenderBreakList.Count}"); foreach(var renderBreak in Renderer.LastFrameRenderBreakList) { stringBuilder.AppendLine(renderBreak.ToString()); } stringBuilder.AppendLine(); var collisionInformation = GetCollisionInformation(); stringBuilder.AppendLine(collisionInformation); stringBuilder.AppendLine(); if (TimeManager.SecondsSince(LastCalculationTime) > mMemoryUpdateFrequency) { MemoryInformation = ForceGetMemoryInformation(); } stringBuilder.Append(MemoryInformation); return stringBuilder.ToString(); } private static string GetCollisionInformation() { var collisionManager = Math.Collision.CollisionManager.Self; int numberOfCollisions = 0; int? maxCollisions = null; CollisionRelationship collisionRelationshipWithMost = null; foreach (var relationship in collisionManager.Relationships) { numberOfCollisions += relationship.DeepCollisionsThisFrame; if(relationship.DeepCollisionsThisFrame > maxCollisions || maxCollisions == null) { maxCollisions = numberOfCollisions; collisionRelationshipWithMost = relationship; } } var collisionsThisFrame = $"Deep collisions: {Math.Collision.CollisionManager.Self.DeepCollisionsThisFrame}"; if(collisionRelationshipWithMost != null) { collisionsThisFrame += $"\nHighest Relationship: {collisionRelationshipWithMost.Name} with {collisionRelationshipWithMost.DeepCollisionsThisFrame}"; } return collisionsThisFrame; } public static void WritePositionedObjectBreakdown() { string result = GetPositionedObjectBreakdown(); Write(result); } public static string GetPositionedObjectBreakdown() { Dictionary<string, CountedCategory> typeDictionary = new Dictionary<string, CountedCategory>(); int count = SpriteManager.ManagedPositionedObjects.Count; for (int i = 0; i < count; i++) { var atI = SpriteManager.ManagedPositionedObjects[i]; Type type = atI.GetType(); if (typeDictionary.ContainsKey(type.Name) == false) { var countedCategory = new CountedCategory(); countedCategory.String = type.Name; typeDictionary.Add(type.Name, countedCategory); } typeDictionary[type.Name].Count++; } StringBuilder stringBuilder = GetFilledStringBuilderWithNumberedTypes(typeDictionary); string toReturn = "Total: " + count + "\n" + stringBuilder.ToString(); if (count == 0) { toReturn = "No automatically updated PositionedObjects"; } return toReturn; } public static string GetShapeBreakdown() { Dictionary<string, CountedCategory> typeDictionary = new Dictionary<string, CountedCategory>(); foreach(PositionedObject shape in ShapeManager.AutomaticallyUpdatedShapes) { var parent = shape.Parent; string parentType = "<null>"; if(parent != null) { parentType = parent.GetType().Name; } if (typeDictionary.ContainsKey(parentType) == false) { var countedCategory = new CountedCategory(); countedCategory.String = parentType; typeDictionary.Add(parentType, countedCategory); } typeDictionary[parentType].Count++; } StringBuilder stringBuilder = GetFilledStringBuilderWithNumberedTypes(typeDictionary); var count = ShapeManager.AutomaticallyUpdatedShapes.Count; string toReturn = "Total: " + count + "\n" + stringBuilder.ToString(); if (count == 0) { toReturn = "No automatically updated Shapes"; } return toReturn; } public static string GetInstructionInformation() { return $"Instruction Count: {Instructions.InstructionManager.Instructions.Count}\n" + $"Unpause Instructions Count: {Instructions.InstructionManager.UnpauseInstructionCount}"; } private static StringBuilder GetFilledStringBuilderWithNumberedTypes(Dictionary<string, CountedCategory> typeDictionary) { List<CountedCategory> listOfItems = new List<CountedCategory>(); foreach (var kvp in typeDictionary) { listOfItems.Add(kvp.Value); } listOfItems.Sort((first, second) => second.Count.CompareTo(first.Count)); StringBuilder stringBuilder = new StringBuilder(); foreach (var item in listOfItems) { if (item.Invisible != 0) { string whatToAdd = item.Count + " (" + item.Invisible + " invisible)" + " " + item.String; stringBuilder.AppendLine(whatToAdd); } else { stringBuilder.AppendLine(item.Count + " " + item.String); } } return stringBuilder; } public static void Update() { if (mText != null) { mText.DisplayText = ""; mText.Red = TextRed; mText.Green = TextGreen; mText.Blue = TextBlue; if (mCommandLineOutput.Count != 0) { for (int i = 0; i < mCommandLineOutput.Count; i++) { mText.DisplayText += mCommandLineOutput[i] + '\n'; } } } else if(mCommandLineOutput.Count != 0) { Write("Command Line..."); } } internal static void UpdateDependencies() { if (mText != null) { AdjustTextPosition(); mText.UpdateDependencies(TimeManager.CurrentTime); mText.SetPixelPerfectScale(mLayer); bool orthogonal = true; if (mLayer.LayerCameraSettings != null) { orthogonal = mLayer.LayerCameraSettings.Orthogonal; } else { orthogonal = Camera.Main.Orthogonal; } mText.AdjustPositionForPixelPerfectDrawing = orthogonal; } } private static void AdjustTextPosition() { switch(TextCorner) { case Corner.TopLeft: mText.RelativeX = -SpriteManager.Camera.RelativeXEdgeAt(SpriteManager.Camera.Z -40) * .95f;// -15; mText.RelativeY = SpriteManager.Camera.RelativeYEdgeAt(SpriteManager.Camera.Z - 40) * .95f; mText.HorizontalAlignment = HorizontalAlignment.Left; break; case Corner.TopRight: mText.RelativeX = SpriteManager.Camera.RelativeXEdgeAt(SpriteManager.Camera.Z -40) * .95f;// -15; mText.RelativeY = SpriteManager.Camera.RelativeYEdgeAt(SpriteManager.Camera.Z - 40) * .95f; mText.HorizontalAlignment = HorizontalAlignment.Right; break; case Corner.BottomLeft: mText.RelativeX = -SpriteManager.Camera.RelativeXEdgeAt(SpriteManager.Camera.Z -40) * .95f;// -15; mText.RelativeY = -SpriteManager.Camera.RelativeYEdgeAt(SpriteManager.Camera.Z - 40) * .95f + mText.NumberOfLines * mText.NewLineDistance; mText.HorizontalAlignment = HorizontalAlignment.Left; break; case Corner.BottomRight: mText.RelativeX = SpriteManager.Camera.RelativeXEdgeAt(SpriteManager.Camera.Z - 40) * .95f;// -15; mText.RelativeY = -SpriteManager.Camera.RelativeYEdgeAt(SpriteManager.Camera.Z - 40) * .95f + NumberOfLinesInCommandLine * mText.NewLineDistance; mText.HorizontalAlignment = HorizontalAlignment.Right; break; } mText.RelativeZ = -40; if (float.IsNaN(mText.RelativeX) || float.IsPositiveInfinity(mText.RelativeX) || float.IsNegativeInfinity(mText.RelativeX)) { mText.RelativeX = 0; } if (float.IsNaN(mText.RelativeY) || float.IsPositiveInfinity(mText.RelativeY) || float.IsNegativeInfinity(mText.RelativeY)) { mText.RelativeY = 0; } } #endregion } }
#region File Description //----------------------------------------------------------------------------- // SpriteSheetGame.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Graphics; using SpriteSheetRuntime; using System; #endregion namespace SpriteSheetSampleWindowsPhone { /// <summary> /// This is the main type for your game /// </summary> public class SpriteSheetGame : Microsoft.Xna.Framework.Game { #region Fields GraphicsDeviceManager graphics; SpriteBatch spriteBatch; SpriteSheet spriteSheet; SpriteFont spriteFont; Texture2D checker; #if WINDOWS_PHONE RenderTarget2D renderTarget; #endif #endregion #region Initialization public SpriteSheetGame() { Content.RootDirectory = "Content"; graphics = new GraphicsDeviceManager(this); #if (!WINDOWS_PHONE) graphics.PreferredBackBufferWidth = 853; graphics.PreferredBackBufferHeight = 480; #else // Frame rate is 30 fps by default for Windows Phone. TargetElapsedTime = TimeSpan.FromTicks(333333); // Pre-autoscale settings. graphics.PreferredBackBufferWidth = 480; graphics.PreferredBackBufferHeight = 800; graphics.SupportedOrientations = DisplayOrientation.Default; graphics.IsFullScreen = true; #endif } #if (WINDOWS_PHONE) /// <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 #if WINDOWS_PHONE renderTarget = new RenderTarget2D(graphics.GraphicsDevice, 800, 480); #endif base.Initialize(); } #endif /// <summary> /// Load your content. /// </summary> protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); spriteSheet = Content.Load<SpriteSheet>("SpriteSheet"); spriteFont = Content.Load<SpriteFont>("hudFont"); checker = Content.Load<Texture2D>("Checker"); } #endregion #region Update and Draw /// <summary> /// Allows the game to run logic. /// </summary> protected override void Update(GameTime gameTime) { HandleInput(); base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> protected override void Draw(GameTime gameTime) { #if WINDOWS_PHONE GraphicsDevice.SetRenderTarget(renderTarget); #endif float time = (float)gameTime.TotalGameTime.TotalSeconds; GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); // Draw a text label. spriteBatch.DrawString(spriteFont, "Here are some individual sprites,\n" + "all stored in a single sprite sheet:", new Vector2(100, 80), Color.White); // Draw a spinning cat sprite, looking it up from the sprite sheet by name. spriteBatch.Draw(spriteSheet.Texture, new Vector2(200, 250), spriteSheet.SourceRectangle("cat"), Color.White, time, new Vector2(50, 50), 1, SpriteEffects.None, 0); // Draw an animating glow effect, by rapidly cycling // through 7 slightly different sprite images. const int animationFramesPerSecond = 20; const int animationFrameCount = 7; // Look up the index of the first glow sprite. int glowIndex = spriteSheet.GetIndex("glow1"); // Modify the index to select the current frame of the animation. glowIndex += (int)(time * animationFramesPerSecond) % animationFrameCount; // Draw the current glow sprite. spriteBatch.Draw(spriteSheet.Texture, new Rectangle(100, 150, 200, 200), spriteSheet.SourceRectangle(glowIndex), Color.White); spriteBatch.End(); DrawEntireSpriteSheetTexture(); base.Draw(gameTime); #if WINDOWS_PHONE GraphicsDevice.SetRenderTarget(null); spriteBatch.Begin(); spriteBatch.Draw(renderTarget as Texture2D, new Vector2(240, 400), null, Color.White, MathHelper.PiOver2, new Vector2(400, 240), 1f, SpriteEffects.None, 0); spriteBatch.End(); #endif } /// <summary> /// A real game would never do this, but when debugging, it is /// useful to draw the entire sprite sheet texture, so you can /// see how the individual sprite images have been arranged. /// </summary> void DrawEntireSpriteSheetTexture() { #if WINDOWS_PHONE Vector2 location = new Vector2(500, 80); #else Vector2 location = new Vector2(500, 80); #endif // use linear wrapping for our checkerboard, but retain defaults for other arguments by passing null spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.LinearWrap, null, null); int w = spriteSheet.Texture.Width; int h = spriteSheet.Texture.Height; Rectangle rect = new Rectangle((int)location.X, (int)(location.Y + 70), w, h); // Draw a tiled checkerboard pattern in the background. spriteBatch.Draw(checker, rect, new Rectangle(0, 0, w, h), Color.White); spriteBatch.End(); // start a new batch for the text and tile sheet since we don't want to use wrapping spriteBatch.Begin(); // Draw a text label. spriteBatch.DrawString(spriteFont, "And here is the combined\n" + "sprite sheet texture:", location, Color.White); // Draw the (alphablended) sprite sheet texture over the top. spriteBatch.Draw(spriteSheet.Texture, rect, Color.White); spriteBatch.End(); } #endregion #region Handle Input /// <summary> /// Handles input for quitting the game. /// </summary> private void HandleInput() { // Allows the game to exit if ((GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) || Keyboard.GetState().IsKeyDown(Keys.Escape)) this.Exit(); } #endregion } }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://openapi-generator.tech */ using System; using System.Linq; using System.Text; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; using Newtonsoft.Json; using Org.OpenAPITools.Converters; namespace Org.OpenAPITools.Models { /// <summary> /// /// </summary> [DataContract] public partial class GithubRepository : IEquatable<GithubRepository> { /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name="_class", EmitDefaultValue=false)] public string Class { get; set; } /// <summary> /// Gets or Sets Links /// </summary> [DataMember(Name="_links", EmitDefaultValue=false)] public GithubRepositorylinks Links { get; set; } /// <summary> /// Gets or Sets DefaultBranch /// </summary> [DataMember(Name="defaultBranch", EmitDefaultValue=false)] public string DefaultBranch { get; set; } /// <summary> /// Gets or Sets Description /// </summary> [DataMember(Name="description", EmitDefaultValue=false)] public string Description { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets Permissions /// </summary> [DataMember(Name="permissions", EmitDefaultValue=false)] public GithubRepositorypermissions Permissions { get; set; } /// <summary> /// Gets or Sets Private /// </summary> [DataMember(Name="private", EmitDefaultValue=false)] public bool Private { get; set; } /// <summary> /// Gets or Sets FullName /// </summary> [DataMember(Name="fullName", EmitDefaultValue=false)] public string FullName { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class GithubRepository {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" Links: ").Append(Links).Append("\n"); sb.Append(" DefaultBranch: ").Append(DefaultBranch).Append("\n"); sb.Append(" Description: ").Append(Description).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Permissions: ").Append(Permissions).Append("\n"); sb.Append(" Private: ").Append(Private).Append("\n"); sb.Append(" FullName: ").Append(FullName).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (obj is null) return false; if (ReferenceEquals(this, obj)) return true; return obj.GetType() == GetType() && Equals((GithubRepository)obj); } /// <summary> /// Returns true if GithubRepository instances are equal /// </summary> /// <param name="other">Instance of GithubRepository to be compared</param> /// <returns>Boolean</returns> public bool Equals(GithubRepository other) { if (other is null) return false; if (ReferenceEquals(this, other)) return true; return ( Class == other.Class || Class != null && Class.Equals(other.Class) ) && ( Links == other.Links || Links != null && Links.Equals(other.Links) ) && ( DefaultBranch == other.DefaultBranch || DefaultBranch != null && DefaultBranch.Equals(other.DefaultBranch) ) && ( Description == other.Description || Description != null && Description.Equals(other.Description) ) && ( Name == other.Name || Name != null && Name.Equals(other.Name) ) && ( Permissions == other.Permissions || Permissions != null && Permissions.Equals(other.Permissions) ) && ( Private == other.Private || Private.Equals(other.Private) ) && ( FullName == other.FullName || FullName != null && FullName.Equals(other.FullName) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (Class != null) hashCode = hashCode * 59 + Class.GetHashCode(); if (Links != null) hashCode = hashCode * 59 + Links.GetHashCode(); if (DefaultBranch != null) hashCode = hashCode * 59 + DefaultBranch.GetHashCode(); if (Description != null) hashCode = hashCode * 59 + Description.GetHashCode(); if (Name != null) hashCode = hashCode * 59 + Name.GetHashCode(); if (Permissions != null) hashCode = hashCode * 59 + Permissions.GetHashCode(); hashCode = hashCode * 59 + Private.GetHashCode(); if (FullName != null) hashCode = hashCode * 59 + FullName.GetHashCode(); return hashCode; } } #region Operators #pragma warning disable 1591 public static bool operator ==(GithubRepository left, GithubRepository right) { return Equals(left, right); } public static bool operator !=(GithubRepository left, GithubRepository right) { return !Equals(left, right); } #pragma warning restore 1591 #endregion Operators } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Concurrent; using System.Collections.Generic; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Threading; namespace System.Net { public class ServicePointManager { public const int DefaultNonPersistentConnectionLimit = 4; public const int DefaultPersistentConnectionLimit = 2; private static readonly ConcurrentDictionary<string, WeakReference<ServicePoint>> s_servicePointTable = new ConcurrentDictionary<string, WeakReference<ServicePoint>>(); private static SecurityProtocolType s_securityProtocolType = SecurityProtocolType.SystemDefault; private static int s_connectionLimit = 2; private static int s_maxServicePoints = 0; private static int s_maxServicePointIdleTime = 100 * 1000; private static int s_dnsRefreshTimeout = 2 * 60 * 1000; private ServicePointManager() { } public static SecurityProtocolType SecurityProtocol { get { return s_securityProtocolType; } set { ValidateSecurityProtocol(value); s_securityProtocolType = value; } } private static void ValidateSecurityProtocol(SecurityProtocolType value) { SecurityProtocolType allowed = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; if ((value & ~allowed) != 0) { throw new NotSupportedException(SR.net_securityprotocolnotsupported); } } public static int MaxServicePoints { get { return s_maxServicePoints; } set { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value)); } s_maxServicePoints = value; } } public static int DefaultConnectionLimit { get { return s_connectionLimit; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value)); } s_connectionLimit = value; } } public static int MaxServicePointIdleTime { get { return s_maxServicePointIdleTime; } set { if (value < Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(value)); } s_maxServicePointIdleTime = value; } } public static bool UseNagleAlgorithm { get; set; } = true; public static bool Expect100Continue { get; set; } = true; public static bool EnableDnsRoundRobin { get; set; } public static int DnsRefreshTimeout { get { return s_dnsRefreshTimeout; } set { s_dnsRefreshTimeout = Math.Max(-1, value); } } public static RemoteCertificateValidationCallback ServerCertificateValidationCallback { get; set; } public static bool ReusePort { get; set; } public static bool CheckCertificateRevocationList { get; set; } public static EncryptionPolicy EncryptionPolicy { get; } = EncryptionPolicy.RequireEncryption; public static ServicePoint FindServicePoint(Uri address) => FindServicePoint(address, null); public static ServicePoint FindServicePoint(string uriString, IWebProxy proxy) => FindServicePoint(new Uri(uriString), proxy); public static ServicePoint FindServicePoint(Uri address, IWebProxy proxy) { if (address == null) { throw new ArgumentNullException(nameof(address)); } // If there's a proxy for this address, get the "real" address. bool isProxyServicePoint = ProxyAddressIfNecessary(ref address, proxy); // Create a lookup key to find the service point string tableKey = MakeQueryString(address, isProxyServicePoint); // Get an existing service point or create a new one ServicePoint sp; // outside of loop to keep references alive from one iteration to the next while (true) { // The table maps lookup key to a weak reference to a service point. If the table // contains a weak ref for the key and that weak ref points to a valid ServicePoint, // simply return it (after updating its last used time). WeakReference<ServicePoint> wr; if (s_servicePointTable.TryGetValue(tableKey, out wr) && wr.TryGetTarget(out sp)) { sp.IdleSince = DateTime.Now; return sp; } // Any time we don't find what we're looking for in the table, take that as an opportunity // to scavenge the table looking for entries that have lost their service point and removing them. foreach (KeyValuePair<string, WeakReference<ServicePoint>> entry in s_servicePointTable) { ServicePoint ignored; if (!entry.Value.TryGetTarget(out ignored)) { // We use the IDictionary.Remove method rather than TryRemove as it will only // remove the entry from the table if both the key/value in the pair match. // This avoids a race condition where another thread concurrently sets a new // weak reference value for the same key, and is why when adding the new // service point below, we don't use any weak reference object we may already // have from the initial retrieval above. ((IDictionary<string, WeakReference<ServicePoint>>)s_servicePointTable).Remove(entry); } } // There wasn't a service point in the table. Create a new one, and then store // it back into the table. We create a new weak reference object even if we were // able to get one above so that when we scavenge the table, we can rely on // weak reference reference equality to know whether we're removing the same // weak reference we saw when we enumerated. sp = new ServicePoint(address) { ConnectionLimit = DefaultConnectionLimit, IdleSince = DateTime.Now, Expect100Continue = Expect100Continue, UseNagleAlgorithm = UseNagleAlgorithm }; s_servicePointTable[tableKey] = new WeakReference<ServicePoint>(sp); // It's possible there's a race between two threads both updating the table // at the same time. We don't want to just use GetOrAdd, as with the weak // reference we may end up getting back a weak ref that no longer has a target. // So we simply loop around again; in all but the most severe of circumstances, the // next iteration will find it in the table and return it. } } private static bool ProxyAddressIfNecessary(ref Uri address, IWebProxy proxy) { if (proxy != null && !address.IsLoopback) { Uri proxyAddress = proxy.GetProxy(address); if (proxyAddress != null) { if (proxyAddress.Scheme != Uri.UriSchemeHttp) { throw new NotSupportedException(SR.Format(SR.net_proxyschemenotsupported, address.Scheme)); } address = proxyAddress; return true; } } return false; } private static string MakeQueryString(Uri address) => address.IsDefaultPort ? address.Scheme + "://" + address.DnsSafeHost : address.Scheme + "://" + address.DnsSafeHost + ":" + address.Port.ToString(); private static string MakeQueryString(Uri address, bool isProxy) { string queryString = MakeQueryString(address); return isProxy ? queryString + "://proxy" : queryString; } public static void SetTcpKeepAlive(bool enabled, int keepAliveTime, int keepAliveInterval) { if (enabled) { if (keepAliveTime <= 0) { throw new ArgumentOutOfRangeException(nameof(keepAliveTime)); } if (keepAliveInterval <= 0) { throw new ArgumentOutOfRangeException(nameof(keepAliveInterval)); } } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Net; using System.Xml; using System.Reflection; using System.Text; using System.Threading; using OpenSim.Framework; using OpenSim.Framework.Capabilities; using OpenSim.Framework.Client; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenMetaverse; using log4net; using Nini.Config; using Mono.Addins; namespace OpenSim.Region.CoreModules.Framework.InventoryAccess { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "BasicInventoryAccessModule")] public class BasicInventoryAccessModule : INonSharedRegionModule, IInventoryAccessModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected bool m_Enabled = false; protected Scene m_Scene; protected IUserManagement m_UserManagement; protected IUserManagement UserManagementModule { get { if (m_UserManagement == null) m_UserManagement = m_Scene.RequestModuleInterface<IUserManagement>(); return m_UserManagement; } } public bool CoalesceMultipleObjectsToInventory { get; set; } #region INonSharedRegionModule public Type ReplaceableInterface { get { return null; } } public virtual string Name { get { return "BasicInventoryAccessModule"; } } public virtual void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("InventoryAccessModule", ""); if (name == Name) { m_Enabled = true; InitialiseCommon(source); m_log.InfoFormat("[INVENTORY ACCESS MODULE]: {0} enabled.", Name); } } } /// <summary> /// Common module config for both this and descendant classes. /// </summary> /// <param name="source"></param> protected virtual void InitialiseCommon(IConfigSource source) { IConfig inventoryConfig = source.Configs["Inventory"]; if (inventoryConfig != null) CoalesceMultipleObjectsToInventory = inventoryConfig.GetBoolean("CoalesceMultipleObjectsToInventory", true); else CoalesceMultipleObjectsToInventory = true; } public virtual void PostInitialise() { } public virtual void AddRegion(Scene scene) { if (!m_Enabled) return; m_Scene = scene; scene.RegisterModuleInterface<IInventoryAccessModule>(this); scene.EventManager.OnNewClient += OnNewClient; } protected virtual void OnNewClient(IClientAPI client) { client.OnCreateNewInventoryItem += CreateNewInventoryItem; } public virtual void Close() { if (!m_Enabled) return; } public virtual void RemoveRegion(Scene scene) { if (!m_Enabled) return; m_Scene = null; } public virtual void RegionLoaded(Scene scene) { if (!m_Enabled) return; } #endregion #region Inventory Access /// <summary> /// Create a new inventory item. Called when the client creates a new item directly within their /// inventory (e.g. by selecting a context inventory menu option). /// </summary> /// <param name="remoteClient"></param> /// <param name="transactionID"></param> /// <param name="folderID"></param> /// <param name="callbackID"></param> /// <param name="description"></param> /// <param name="name"></param> /// <param name="invType"></param> /// <param name="type"></param> /// <param name="wearableType"></param> /// <param name="nextOwnerMask"></param> public void CreateNewInventoryItem(IClientAPI remoteClient, UUID transactionID, UUID folderID, uint callbackID, string description, string name, sbyte invType, sbyte assetType, byte wearableType, uint nextOwnerMask, int creationDate) { m_log.DebugFormat("[INVENTORY ACCESS MODULE]: Received request to create inventory item {0} in folder {1}", name, folderID); if (!m_Scene.Permissions.CanCreateUserInventory(invType, remoteClient.AgentId)) return; if (transactionID == UUID.Zero) { ScenePresence presence; if (m_Scene.TryGetScenePresence(remoteClient.AgentId, out presence)) { byte[] data = null; if (invType == (sbyte)InventoryType.Landmark && presence != null) { string suffix = string.Empty, prefix = string.Empty; string strdata = GenerateLandmark(presence, out prefix, out suffix); data = Encoding.ASCII.GetBytes(strdata); name = prefix + name; description += suffix; } AssetBase asset = m_Scene.CreateAsset(name, description, assetType, data, remoteClient.AgentId); m_Scene.AssetService.Store(asset); m_Scene.CreateNewInventoryItem( remoteClient, remoteClient.AgentId.ToString(), string.Empty, folderID, name, description, 0, callbackID, asset, invType, nextOwnerMask, creationDate); } else { m_log.ErrorFormat( "[INVENTORY ACCESS MODULE]: ScenePresence for agent uuid {0} unexpectedly not found in CreateNewInventoryItem", remoteClient.AgentId); } } else { IAgentAssetTransactions agentTransactions = m_Scene.AgentTransactionsModule; if (agentTransactions != null) { agentTransactions.HandleItemCreationFromTransaction( remoteClient, transactionID, folderID, callbackID, description, name, invType, assetType, wearableType, nextOwnerMask); } } } protected virtual string GenerateLandmark(ScenePresence presence, out string prefix, out string suffix) { prefix = string.Empty; suffix = string.Empty; Vector3 pos = presence.AbsolutePosition; return String.Format("Landmark version 2\nregion_id {0}\nlocal_pos {1} {2} {3}\nregion_handle {4}\n", presence.Scene.RegionInfo.RegionID, pos.X, pos.Y, pos.Z, presence.RegionHandle); } /// <summary> /// Capability originating call to update the asset of an item in an agent's inventory /// </summary> /// <param name="remoteClient"></param> /// <param name="itemID"></param> /// <param name="data"></param> /// <returns></returns> public virtual UUID CapsUpdateInventoryItemAsset(IClientAPI remoteClient, UUID itemID, byte[] data) { InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId); item = m_Scene.InventoryService.GetItem(item); if (item.Owner != remoteClient.AgentId) return UUID.Zero; if (item != null) { if ((InventoryType)item.InvType == InventoryType.Notecard) { if (!m_Scene.Permissions.CanEditNotecard(itemID, UUID.Zero, remoteClient.AgentId)) { remoteClient.SendAgentAlertMessage("Insufficient permissions to edit notecard", false); return UUID.Zero; } remoteClient.SendAgentAlertMessage("Notecard saved", false); } else if ((InventoryType)item.InvType == InventoryType.LSL) { if (!m_Scene.Permissions.CanEditScript(itemID, UUID.Zero, remoteClient.AgentId)) { remoteClient.SendAgentAlertMessage("Insufficient permissions to edit script", false); return UUID.Zero; } remoteClient.SendAgentAlertMessage("Script saved", false); } AssetBase asset = CreateAsset(item.Name, item.Description, (sbyte)item.AssetType, data, remoteClient.AgentId.ToString()); item.AssetID = asset.FullID; m_Scene.AssetService.Store(asset); m_Scene.InventoryService.UpdateItem(item); // remoteClient.SendInventoryItemCreateUpdate(item); return (asset.FullID); } else { m_log.ErrorFormat( "[INVENTORY ACCESS MODULE]: Could not find item {0} for caps inventory update", itemID); } return UUID.Zero; } public virtual List<InventoryItemBase> CopyToInventory( DeRezAction action, UUID folderID, List<SceneObjectGroup> objectGroups, IClientAPI remoteClient, bool asAttachment) { List<InventoryItemBase> copiedItems = new List<InventoryItemBase>(); Dictionary<UUID, List<SceneObjectGroup>> bundlesToCopy = new Dictionary<UUID, List<SceneObjectGroup>>(); if (CoalesceMultipleObjectsToInventory) { // The following code groups the SOG's by owner. No objects // belonging to different people can be coalesced, for obvious // reasons. foreach (SceneObjectGroup g in objectGroups) { if (!bundlesToCopy.ContainsKey(g.OwnerID)) bundlesToCopy[g.OwnerID] = new List<SceneObjectGroup>(); bundlesToCopy[g.OwnerID].Add(g); } } else { // If we don't want to coalesce then put every object in its own bundle. foreach (SceneObjectGroup g in objectGroups) { List<SceneObjectGroup> bundle = new List<SceneObjectGroup>(); bundle.Add(g); bundlesToCopy[g.UUID] = bundle; } } // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: Copying {0} object bundles to folder {1} action {2} for {3}", // bundlesToCopy.Count, folderID, action, remoteClient.Name); // Each iteration is really a separate asset being created, // with distinct destinations as well. foreach (List<SceneObjectGroup> bundle in bundlesToCopy.Values) copiedItems.Add(CopyBundleToInventory(action, folderID, bundle, remoteClient, asAttachment)); return copiedItems; } /// <summary> /// Copy a bundle of objects to inventory. If there is only one object, then this will create an object /// item. If there are multiple objects then these will be saved as a single coalesced item. /// </summary> /// <param name="action"></param> /// <param name="folderID"></param> /// <param name="objlist"></param> /// <param name="remoteClient"></param> /// <param name="asAttachment">Should be true if the bundle is being copied as an attachment. This prevents /// attempted serialization of any script state which would abort any operating scripts.</param> /// <returns>The inventory item created by the copy</returns> protected InventoryItemBase CopyBundleToInventory( DeRezAction action, UUID folderID, List<SceneObjectGroup> objlist, IClientAPI remoteClient, bool asAttachment) { CoalescedSceneObjects coa = new CoalescedSceneObjects(UUID.Zero); Dictionary<UUID, Vector3> originalPositions = new Dictionary<UUID, Vector3>(); foreach (SceneObjectGroup objectGroup in objlist) { Vector3 inventoryStoredPosition = new Vector3 (((objectGroup.AbsolutePosition.X > (int)Constants.RegionSize) ? 250 : objectGroup.AbsolutePosition.X) , (objectGroup.AbsolutePosition.Y > (int)Constants.RegionSize) ? 250 : objectGroup.AbsolutePosition.Y, objectGroup.AbsolutePosition.Z); originalPositions[objectGroup.UUID] = objectGroup.AbsolutePosition; objectGroup.AbsolutePosition = inventoryStoredPosition; // Make sure all bits but the ones we want are clear // on take. // This will be applied to the current perms, so // it will do what we want. objectGroup.RootPart.NextOwnerMask &= ((uint)PermissionMask.Copy | (uint)PermissionMask.Transfer | (uint)PermissionMask.Modify); objectGroup.RootPart.NextOwnerMask |= (uint)PermissionMask.Move; coa.Add(objectGroup); } string itemXml; // If we're being called from a script, then trying to serialize that same script's state will not complete // in any reasonable time period. Therefore, we'll avoid it. The worst that can happen is that if // the client/server crashes rather than logging out normally, the attachment's scripts will resume // without state on relog. Arguably, this is what we want anyway. if (objlist.Count > 1) itemXml = CoalescedSceneObjectsSerializer.ToXml(coa, !asAttachment); else itemXml = SceneObjectSerializer.ToOriginalXmlFormat(objlist[0], !asAttachment); // Restore the position of each group now that it has been stored to inventory. foreach (SceneObjectGroup objectGroup in objlist) objectGroup.AbsolutePosition = originalPositions[objectGroup.UUID]; InventoryItemBase item = CreateItemForObject(action, remoteClient, objlist[0], folderID); // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: Created item is {0}", // item != null ? item.ID.ToString() : "NULL"); if (item == null) return null; // Can't know creator is the same, so null it in inventory if (objlist.Count > 1) { item.CreatorId = UUID.Zero.ToString(); item.Flags = (uint)InventoryItemFlags.ObjectHasMultipleItems; } else { item.CreatorId = objlist[0].RootPart.CreatorID.ToString(); item.CreatorData = objlist[0].RootPart.CreatorData; item.SaleType = objlist[0].RootPart.ObjectSaleType; item.SalePrice = objlist[0].RootPart.SalePrice; } AssetBase asset = CreateAsset( objlist[0].GetPartName(objlist[0].RootPart.LocalId), objlist[0].GetPartDescription(objlist[0].RootPart.LocalId), (sbyte)AssetType.Object, Utils.StringToBytes(itemXml), objlist[0].OwnerID.ToString()); m_Scene.AssetService.Store(asset); item.AssetID = asset.FullID; if (DeRezAction.SaveToExistingUserInventoryItem == action) { m_Scene.InventoryService.UpdateItem(item); } else { AddPermissions(item, objlist[0], objlist, remoteClient); item.CreationDate = Util.UnixTimeSinceEpoch(); item.Description = asset.Description; item.Name = asset.Name; item.AssetType = asset.Type; m_Scene.AddInventoryItem(item); if (remoteClient != null && item.Owner == remoteClient.AgentId) { remoteClient.SendInventoryItemCreateUpdate(item, 0); } else { ScenePresence notifyUser = m_Scene.GetScenePresence(item.Owner); if (notifyUser != null) { notifyUser.ControllingClient.SendInventoryItemCreateUpdate(item, 0); } } } // This is a hook to do some per-asset post-processing for subclasses that need that if (remoteClient != null) ExportAsset(remoteClient.AgentId, asset.FullID); return item; } protected virtual void ExportAsset(UUID agentID, UUID assetID) { // nothing to do here } /// <summary> /// Add relevant permissions for an object to the item. /// </summary> /// <param name="item"></param> /// <param name="so"></param> /// <param name="objsForEffectivePermissions"></param> /// <param name="remoteClient"></param> /// <returns></returns> protected InventoryItemBase AddPermissions( InventoryItemBase item, SceneObjectGroup so, List<SceneObjectGroup> objsForEffectivePermissions, IClientAPI remoteClient) { uint effectivePerms = (uint)(PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify | PermissionMask.Move) | 7; foreach (SceneObjectGroup grp in objsForEffectivePermissions) effectivePerms &= grp.GetEffectivePermissions(); effectivePerms |= (uint)PermissionMask.Move; if (remoteClient != null && (remoteClient.AgentId != so.RootPart.OwnerID) && m_Scene.Permissions.PropagatePermissions()) { uint perms = effectivePerms; uint nextPerms = (perms & 7) << 13; if ((nextPerms & (uint)PermissionMask.Copy) == 0) perms &= ~(uint)PermissionMask.Copy; if ((nextPerms & (uint)PermissionMask.Transfer) == 0) perms &= ~(uint)PermissionMask.Transfer; if ((nextPerms & (uint)PermissionMask.Modify) == 0) perms &= ~(uint)PermissionMask.Modify; item.BasePermissions = perms & so.RootPart.NextOwnerMask; item.CurrentPermissions = item.BasePermissions; item.NextPermissions = perms & so.RootPart.NextOwnerMask; item.EveryOnePermissions = so.RootPart.EveryoneMask & so.RootPart.NextOwnerMask; item.GroupPermissions = so.RootPart.GroupMask & so.RootPart.NextOwnerMask; // Magic number badness. Maybe this deserves an enum. // bit 4 (16) is the "Slam" bit, it means treat as passed // and apply next owner perms on rez item.CurrentPermissions |= 16; // Slam! } else { item.BasePermissions = effectivePerms; item.CurrentPermissions = effectivePerms; item.NextPermissions = so.RootPart.NextOwnerMask & effectivePerms; item.EveryOnePermissions = so.RootPart.EveryoneMask & effectivePerms; item.GroupPermissions = so.RootPart.GroupMask & effectivePerms; item.CurrentPermissions &= ((uint)PermissionMask.Copy | (uint)PermissionMask.Transfer | (uint)PermissionMask.Modify | (uint)PermissionMask.Move | 7); // Preserve folded permissions } return item; } /// <summary> /// Create an item using details for the given scene object. /// </summary> /// <param name="action"></param> /// <param name="remoteClient"></param> /// <param name="so"></param> /// <param name="folderID"></param> /// <returns></returns> protected InventoryItemBase CreateItemForObject( DeRezAction action, IClientAPI remoteClient, SceneObjectGroup so, UUID folderID) { // Get the user info of the item destination // UUID userID = UUID.Zero; if (action == DeRezAction.Take || action == DeRezAction.TakeCopy || action == DeRezAction.SaveToExistingUserInventoryItem) { // Take or take copy require a taker // Saving changes requires a local user // if (remoteClient == null) return null; userID = remoteClient.AgentId; // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: Target of {0} in CreateItemForObject() is {1} {2}", // action, remoteClient.Name, userID); } else if (so.RootPart.OwnerID == so.RootPart.GroupID) { // Group owned objects go to the last owner before the object was transferred. userID = so.RootPart.LastOwnerID; } else { // Other returns / deletes go to the object owner // userID = so.RootPart.OwnerID; // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: Target of {0} in CreateItemForObject() is object owner {1}", // action, userID); } if (userID == UUID.Zero) // Can't proceed { return null; } // If we're returning someone's item, it goes back to the // owner's Lost And Found folder. // Delete is treated like return in this case // Deleting your own items makes them go to trash // InventoryFolderBase folder = null; InventoryItemBase item = null; if (DeRezAction.SaveToExistingUserInventoryItem == action) { item = new InventoryItemBase(so.RootPart.FromUserInventoryItemID, userID); item = m_Scene.InventoryService.GetItem(item); //item = userInfo.RootFolder.FindItem( // objectGroup.RootPart.FromUserInventoryItemID); if (null == item) { m_log.DebugFormat( "[INVENTORY ACCESS MODULE]: Object {0} {1} scheduled for save to inventory has already been deleted.", so.Name, so.UUID); return null; } } else { // Folder magic // if (action == DeRezAction.Delete) { // Deleting someone else's item // if (remoteClient == null || so.OwnerID != remoteClient.AgentId) { folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder); } else { folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.TrashFolder); } } else if (action == DeRezAction.Return) { // Dump to lost + found unconditionally // folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder); } if (folderID == UUID.Zero && folder == null) { if (action == DeRezAction.Delete) { // Deletes go to trash by default // folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.TrashFolder); } else { if (remoteClient == null || so.OwnerID != remoteClient.AgentId) { // Taking copy of another person's item. Take to // Objects folder. folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.Object); } else { // Catch all. Use lost & found // folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder); } } } // Override and put into where it came from, if it came // from anywhere in inventory and the owner is taking it back. // if (action == DeRezAction.Take || action == DeRezAction.TakeCopy) { if (so.FromFolderID != UUID.Zero && userID == remoteClient.AgentId) { InventoryFolderBase f = new InventoryFolderBase(so.FromFolderID, userID); folder = m_Scene.InventoryService.GetFolder(f); } } if (folder == null) // None of the above { folder = new InventoryFolderBase(folderID); if (folder == null) // Nowhere to put it { return null; } } item = new InventoryItemBase(); item.ID = UUID.Random(); item.InvType = (int)InventoryType.Object; item.Folder = folder.ID; item.Owner = userID; } return item; } public virtual SceneObjectGroup RezObject( IClientAPI remoteClient, UUID itemID, Vector3 RayEnd, Vector3 RayStart, UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection, bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment) { // m_log.DebugFormat("[INVENTORY ACCESS MODULE]: RezObject for {0}, item {1}", remoteClient.Name, itemID); InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId); item = m_Scene.InventoryService.GetItem(item); if (item == null) { m_log.WarnFormat( "[INVENTORY ACCESS MODULE]: Could not find item {0} for {1} in RezObject()", itemID, remoteClient.Name); return null; } item.Owner = remoteClient.AgentId; return RezObject( remoteClient, item, item.AssetID, RayEnd, RayStart, RayTargetID, BypassRayCast, RayEndIsIntersection, RezSelected, RemoveItem, fromTaskID, attachment); } public virtual SceneObjectGroup RezObject( IClientAPI remoteClient, InventoryItemBase item, UUID assetID, Vector3 RayEnd, Vector3 RayStart, UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection, bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment) { AssetBase rezAsset = m_Scene.AssetService.Get(assetID.ToString()); if (rezAsset == null) { if (item != null) { m_log.WarnFormat( "[InventoryAccessModule]: Could not find asset {0} for item {1} {2} for {3} in RezObject()", assetID, item.Name, item.ID, remoteClient.Name); } else { m_log.WarnFormat( "[INVENTORY ACCESS MODULE]: Could not find asset {0} for {1} in RezObject()", assetID, remoteClient.Name); } return null; } SceneObjectGroup group = null; string xmlData = Utils.BytesToString(rezAsset.Data); List<SceneObjectGroup> objlist = new List<SceneObjectGroup>(); List<Vector3> veclist = new List<Vector3>(); byte bRayEndIsIntersection = (byte)(RayEndIsIntersection ? 1 : 0); Vector3 pos; XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlData); XmlElement e = (XmlElement)doc.SelectSingleNode("/CoalescedObject"); if (e == null || attachment) // Single { SceneObjectGroup g = SceneObjectSerializer.FromOriginalXmlFormat(xmlData); objlist.Add(g); veclist.Add(new Vector3(0, 0, 0)); float offsetHeight = 0; pos = m_Scene.GetNewRezLocation( RayStart, RayEnd, RayTargetID, Quaternion.Identity, BypassRayCast, bRayEndIsIntersection, true, g.GetAxisAlignedBoundingBox(out offsetHeight), false); pos.Z += offsetHeight; } else { XmlElement coll = (XmlElement)e; float bx = Convert.ToSingle(coll.GetAttribute("x")); float by = Convert.ToSingle(coll.GetAttribute("y")); float bz = Convert.ToSingle(coll.GetAttribute("z")); Vector3 bbox = new Vector3(bx, by, bz); pos = m_Scene.GetNewRezLocation(RayStart, RayEnd, RayTargetID, Quaternion.Identity, BypassRayCast, bRayEndIsIntersection, true, bbox, false); pos -= bbox / 2; XmlNodeList groups = e.SelectNodes("SceneObjectGroup"); foreach (XmlNode n in groups) { SceneObjectGroup g = SceneObjectSerializer.FromOriginalXmlFormat(n.OuterXml); objlist.Add(g); XmlElement el = (XmlElement)n; string rawX = el.GetAttribute("offsetx"); string rawY = el.GetAttribute("offsety"); string rawZ = el.GetAttribute("offsetz"); // // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: Converting coalesced object {0} offset <{1}, {2}, {3}>", // g.Name, rawX, rawY, rawZ); float x = Convert.ToSingle(rawX); float y = Convert.ToSingle(rawY); float z = Convert.ToSingle(rawZ); veclist.Add(new Vector3(x, y, z)); } } if (item != null && !DoPreRezWhenFromItem(remoteClient, item, objlist, pos, attachment)) return null; for (int i = 0; i < objlist.Count; i++) { group = objlist[i]; // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: Preparing to rez {0} {1} {2} ownermask={3:X} nextownermask={4:X} groupmask={5:X} everyonemask={6:X} for {7}", // group.Name, group.LocalId, group.UUID, // group.RootPart.OwnerMask, group.RootPart.NextOwnerMask, group.RootPart.GroupMask, group.RootPart.EveryoneMask, // remoteClient.Name); // Vector3 storedPosition = group.AbsolutePosition; if (group.UUID == UUID.Zero) { m_log.Debug("[INVENTORY ACCESS MODULE]: Object has UUID.Zero! Position 3"); } foreach (SceneObjectPart part in group.Parts) { // Make the rezzer the owner, as this is not necessarily set correctly in the serialized asset. part.LastOwnerID = part.OwnerID; part.OwnerID = remoteClient.AgentId; } if (!attachment) { // If it's rezzed in world, select it. Much easier to // find small items. // foreach (SceneObjectPart part in group.Parts) { part.CreateSelected = true; } } group.ResetIDs(); if (attachment) { group.RootPart.Flags |= PrimFlags.Phantom; group.IsAttachment = true; } // If we're rezzing an attachment then don't ask // AddNewSceneObject() to update the client since // we'll be doing that later on. Scheduling more than // one full update during the attachment // process causes some clients to fail to display the // attachment properly. m_Scene.AddNewSceneObject(group, true, false); // if attachment we set it's asset id so object updates // can reflect that, if not, we set it's position in world. if (!attachment) { group.ScheduleGroupForFullUpdate(); group.AbsolutePosition = pos + veclist[i]; } group.SetGroup(remoteClient.ActiveGroupId, remoteClient); if (!attachment) { SceneObjectPart rootPart = group.RootPart; if (rootPart.Shape.PCode == (byte)PCode.Prim) group.ClearPartAttachmentData(); // Fire on_rez group.CreateScriptInstances(0, true, m_Scene.DefaultScriptEngine, 1); rootPart.ParentGroup.ResumeScripts(); rootPart.ScheduleFullUpdate(); } // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: Rezzed {0} {1} {2} ownermask={3:X} nextownermask={4:X} groupmask={5:X} everyonemask={6:X} for {7}", // group.Name, group.LocalId, group.UUID, // group.RootPart.OwnerMask, group.RootPart.NextOwnerMask, group.RootPart.GroupMask, group.RootPart.EveryoneMask, // remoteClient.Name); } if (item != null) DoPostRezWhenFromItem(item, attachment); return group; } /// <summary> /// Do pre-rez processing when the object comes from an item. /// </summary> /// <param name="remoteClient"></param> /// <param name="item"></param> /// <param name="objlist"></param> /// <param name="pos"></param> /// <param name="isAttachment"></param> /// <returns>true if we can processed with rezzing, false if we need to abort</returns> private bool DoPreRezWhenFromItem( IClientAPI remoteClient, InventoryItemBase item, List<SceneObjectGroup> objlist, Vector3 pos, bool isAttachment) { UUID fromUserInventoryItemId = UUID.Zero; // If we have permission to copy then link the rezzed object back to the user inventory // item that it came from. This allows us to enable 'save object to inventory' if (!m_Scene.Permissions.BypassPermissions()) { if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == (uint)PermissionMask.Copy && (item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) == 0) { fromUserInventoryItemId = item.ID; } } else { if ((item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) == 0) { // Brave new fullperm world fromUserInventoryItemId = item.ID; } } int primcount = 0; foreach (SceneObjectGroup g in objlist) primcount += g.PrimCount; if (!m_Scene.Permissions.CanRezObject( primcount, remoteClient.AgentId, pos) && !isAttachment) { // The client operates in no fail mode. It will // have already removed the item from the folder // if it's no copy. // Put it back if it's not an attachment // if (((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) && (!isAttachment)) remoteClient.SendBulkUpdateInventory(item); ILandObject land = m_Scene.LandChannel.GetLandObject(pos.X, pos.Y); remoteClient.SendAlertMessage(string.Format( "Can't rez object '{0}' at <{1:F3}, {2:F3}, {3:F3}> on parcel '{4}' in region {5}.", item.Name, pos.X, pos.Y, pos.Z, land != null ? land.LandData.Name : "Unknown", m_Scene.RegionInfo.RegionName)); return false; } for (int i = 0; i < objlist.Count; i++) { SceneObjectGroup so = objlist[i]; SceneObjectPart rootPart = so.RootPart; // Since renaming the item in the inventory does not // affect the name stored in the serialization, transfer // the correct name from the inventory to the // object itself before we rez. // // Only do these for the first object if we are rezzing a coalescence. if (i == 0) { rootPart.Name = item.Name; rootPart.Description = item.Description; rootPart.ObjectSaleType = item.SaleType; rootPart.SalePrice = item.SalePrice; } so.FromFolderID = item.Folder; // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: rootPart.OwnedID {0}, item.Owner {1}, item.CurrentPermissions {2:X}", // rootPart.OwnerID, item.Owner, item.CurrentPermissions); if ((rootPart.OwnerID != item.Owner) || (item.CurrentPermissions & 16) != 0) { //Need to kill the for sale here rootPart.ObjectSaleType = 0; rootPart.SalePrice = 10; if (m_Scene.Permissions.PropagatePermissions()) { foreach (SceneObjectPart part in so.Parts) { if ((item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) == 0) { part.EveryoneMask = item.EveryOnePermissions; part.NextOwnerMask = item.NextPermissions; } part.GroupMask = 0; // DO NOT propagate here } so.ApplyNextOwnerPermissions(); } } foreach (SceneObjectPart part in so.Parts) { part.FromUserInventoryItemID = fromUserInventoryItemId; if ((part.OwnerID != item.Owner) || (item.CurrentPermissions & 16) != 0) { part.Inventory.ChangeInventoryOwner(item.Owner); part.GroupMask = 0; // DO NOT propagate here } part.EveryoneMask = item.EveryOnePermissions; part.NextOwnerMask = item.NextPermissions; } rootPart.TrimPermissions(); if (isAttachment) so.FromItemID = item.ID; } return true; } /// <summary> /// Do post-rez processing when the object comes from an item. /// </summary> /// <param name="item"></param> /// <param name="isAttachment"></param> private void DoPostRezWhenFromItem(InventoryItemBase item, bool isAttachment) { if (!m_Scene.Permissions.BypassPermissions()) { if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) { // If this is done on attachments, no // copy ones will be lost, so avoid it // if (!isAttachment) { List<UUID> uuids = new List<UUID>(); uuids.Add(item.ID); m_Scene.InventoryService.DeleteItems(item.Owner, uuids); } } } } protected void AddUserData(SceneObjectGroup sog) { UserManagementModule.AddUser(sog.RootPart.CreatorID, sog.RootPart.CreatorData); foreach (SceneObjectPart sop in sog.Parts) UserManagementModule.AddUser(sop.CreatorID, sop.CreatorData); } public virtual void TransferInventoryAssets(InventoryItemBase item, UUID sender, UUID receiver) { } public virtual bool CanGetAgentInventoryItem(IClientAPI remoteClient, UUID itemID, UUID requestID) { InventoryItemBase assetRequestItem = GetItem(remoteClient.AgentId, itemID); if (assetRequestItem == null) { ILibraryService lib = m_Scene.RequestModuleInterface<ILibraryService>(); if (lib != null) assetRequestItem = lib.LibraryRootFolder.FindItem(itemID); if (assetRequestItem == null) return false; } // At this point, we need to apply perms // only to notecards and scripts. All // other asset types are always available // if (assetRequestItem.AssetType == (int)AssetType.LSLText) { if (!m_Scene.Permissions.CanViewScript(itemID, UUID.Zero, remoteClient.AgentId)) { remoteClient.SendAgentAlertMessage("Insufficient permissions to view script", false); return false; } } else if (assetRequestItem.AssetType == (int)AssetType.Notecard) { if (!m_Scene.Permissions.CanViewNotecard(itemID, UUID.Zero, remoteClient.AgentId)) { remoteClient.SendAgentAlertMessage("Insufficient permissions to view notecard", false); return false; } } if (assetRequestItem.AssetID != requestID) { m_log.WarnFormat( "[INVENTORY ACCESS MODULE]: {0} requested asset {1} from item {2} but this does not match item's asset {3}", Name, requestID, itemID, assetRequestItem.AssetID); return false; } return true; } public virtual bool IsForeignUser(UUID userID, out string assetServerURL) { assetServerURL = string.Empty; return false; } #endregion #region Misc /// <summary> /// Create a new asset data structure. /// </summary> /// <param name="name"></param> /// <param name="description"></param> /// <param name="invType"></param> /// <param name="assetType"></param> /// <param name="data"></param> /// <returns></returns> private AssetBase CreateAsset(string name, string description, sbyte assetType, byte[] data, string creatorID) { AssetBase asset = new AssetBase(UUID.Random(), name, assetType, creatorID); asset.Description = description; asset.Data = (data == null) ? new byte[1] : data; return asset; } protected virtual InventoryItemBase GetItem(UUID agentID, UUID itemID) { IInventoryService invService = m_Scene.RequestModuleInterface<IInventoryService>(); InventoryItemBase item = new InventoryItemBase(itemID, agentID); item = invService.GetItem(item); if (item != null && item.CreatorData != null && item.CreatorData != string.Empty) UserManagementModule.AddUser(item.CreatorIdAsUuid, item.CreatorData); return item; } #endregion } }
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace ZXing.Datamatrix.Internal { /// <summary> /// The Version object encapsulates attributes about a particular /// size Data Matrix Code. /// /// <author>bbrown@google.com (Brian Brown)</author> /// </summary> public sealed class Version { private static readonly Version[] VERSIONS = buildVersions(); private readonly int versionNumber; private readonly int symbolSizeRows; private readonly int symbolSizeColumns; private readonly int dataRegionSizeRows; private readonly int dataRegionSizeColumns; private readonly ECBlocks ecBlocks; private readonly int totalCodewords; internal Version(int versionNumber, int symbolSizeRows, int symbolSizeColumns, int dataRegionSizeRows, int dataRegionSizeColumns, ECBlocks ecBlocks) { this.versionNumber = versionNumber; this.symbolSizeRows = symbolSizeRows; this.symbolSizeColumns = symbolSizeColumns; this.dataRegionSizeRows = dataRegionSizeRows; this.dataRegionSizeColumns = dataRegionSizeColumns; this.ecBlocks = ecBlocks; // Calculate the total number of codewords int total = 0; int ecCodewords = ecBlocks.ECCodewords; ECB[] ecbArray = ecBlocks.ECBlocksValue; foreach (ECB ecBlock in ecbArray) { total += ecBlock.Count * (ecBlock.DataCodewords + ecCodewords); } this.totalCodewords = total; } /// <summary> /// returns the version numer /// </summary> /// <returns></returns> public int getVersionNumber() { return versionNumber; } /// <summary> /// returns the symbol size rows /// </summary> /// <returns></returns> public int getSymbolSizeRows() { return symbolSizeRows; } /// <summary> /// returns the symbols size columns /// </summary> /// <returns></returns> public int getSymbolSizeColumns() { return symbolSizeColumns; } /// <summary> /// retursn the data region size rows /// </summary> /// <returns></returns> public int getDataRegionSizeRows() { return dataRegionSizeRows; } /// <summary> /// returns the data region size columns /// </summary> /// <returns></returns> public int getDataRegionSizeColumns() { return dataRegionSizeColumns; } /// <summary> /// returns the total codewords count /// </summary> /// <returns></returns> public int getTotalCodewords() { return totalCodewords; } internal ECBlocks getECBlocks() { return ecBlocks; } /// <summary> /// <p>Deduces version information from Data Matrix dimensions.</p> /// /// <param name="numRows">Number of rows in modules</param> /// <param name="numColumns">Number of columns in modules</param> /// <returns>Version for a Data Matrix Code of those dimensions</returns> /// <exception cref="FormatException">if dimensions do correspond to a valid Data Matrix size</exception> /// </summary> public static Version getVersionForDimensions(int numRows, int numColumns) { if ((numRows & 0x01) != 0 || (numColumns & 0x01) != 0) { return null; } foreach (var version in VERSIONS) { if (version.symbolSizeRows == numRows && version.symbolSizeColumns == numColumns) { return version; } } return null; } /// <summary> /// <p>Encapsulates a set of error-correction blocks in one symbol version. Most versions will /// use blocks of differing sizes within one version, so, this encapsulates the parameters for /// each set of blocks. It also holds the number of error-correction codewords per block since it /// will be the same across all blocks within one version.</p> /// </summary> internal sealed class ECBlocks { private readonly int ecCodewords; private readonly ECB[] _ecBlocksValue; internal ECBlocks(int ecCodewords, ECB ecBlocks) { this.ecCodewords = ecCodewords; this._ecBlocksValue = new ECB[] { ecBlocks }; } internal ECBlocks(int ecCodewords, ECB ecBlocks1, ECB ecBlocks2) { this.ecCodewords = ecCodewords; this._ecBlocksValue = new ECB[] { ecBlocks1, ecBlocks2 }; } internal int ECCodewords { get { return ecCodewords; } } internal ECB[] ECBlocksValue { get { return _ecBlocksValue; } } } /// <summary> /// <p>Encapsulates the parameters for one error-correction block in one symbol version. /// This includes the number of data codewords, and the number of times a block with these /// parameters is used consecutively in the Data Matrix code version's format.</p> /// </summary> internal sealed class ECB { private readonly int count; private readonly int dataCodewords; internal ECB(int count, int dataCodewords) { this.count = count; this.dataCodewords = dataCodewords; } internal int Count { get { return count; } } internal int DataCodewords { get { return dataCodewords; } } } /// <summary> /// returns the version number as string /// </summary> /// <returns></returns> public override String ToString() { return versionNumber.ToString(); } /// <summary> /// See ISO 16022:2006 5.5.1 Table 7 /// </summary> private static Version[] buildVersions() { return new Version[] { new Version(1, 10, 10, 8, 8, new ECBlocks(5, new ECB(1, 3))), new Version(2, 12, 12, 10, 10, new ECBlocks(7, new ECB(1, 5))), new Version(3, 14, 14, 12, 12, new ECBlocks(10, new ECB(1, 8))), new Version(4, 16, 16, 14, 14, new ECBlocks(12, new ECB(1, 12))), new Version(5, 18, 18, 16, 16, new ECBlocks(14, new ECB(1, 18))), new Version(6, 20, 20, 18, 18, new ECBlocks(18, new ECB(1, 22))), new Version(7, 22, 22, 20, 20, new ECBlocks(20, new ECB(1, 30))), new Version(8, 24, 24, 22, 22, new ECBlocks(24, new ECB(1, 36))), new Version(9, 26, 26, 24, 24, new ECBlocks(28, new ECB(1, 44))), new Version(10, 32, 32, 14, 14, new ECBlocks(36, new ECB(1, 62))), new Version(11, 36, 36, 16, 16, new ECBlocks(42, new ECB(1, 86))), new Version(12, 40, 40, 18, 18, new ECBlocks(48, new ECB(1, 114))), new Version(13, 44, 44, 20, 20, new ECBlocks(56, new ECB(1, 144))), new Version(14, 48, 48, 22, 22, new ECBlocks(68, new ECB(1, 174))), new Version(15, 52, 52, 24, 24, new ECBlocks(42, new ECB(2, 102))), new Version(16, 64, 64, 14, 14, new ECBlocks(56, new ECB(2, 140))), new Version(17, 72, 72, 16, 16, new ECBlocks(36, new ECB(4, 92))), new Version(18, 80, 80, 18, 18, new ECBlocks(48, new ECB(4, 114))), new Version(19, 88, 88, 20, 20, new ECBlocks(56, new ECB(4, 144))), new Version(20, 96, 96, 22, 22, new ECBlocks(68, new ECB(4, 174))), new Version(21, 104, 104, 24, 24, new ECBlocks(56, new ECB(6, 136))), new Version(22, 120, 120, 18, 18, new ECBlocks(68, new ECB(6, 175))), new Version(23, 132, 132, 20, 20, new ECBlocks(62, new ECB(8, 163))), new Version(24, 144, 144, 22, 22, new ECBlocks(62, new ECB(8, 156), new ECB(2, 155))), new Version(25, 8, 18, 6, 16, new ECBlocks(7, new ECB(1, 5))), new Version(26, 8, 32, 6, 14, new ECBlocks(11, new ECB(1, 10))), new Version(27, 12, 26, 10, 24, new ECBlocks(14, new ECB(1, 16))), new Version(28, 12, 36, 10, 16, new ECBlocks(18, new ECB(1, 22))), new Version(29, 16, 36, 14, 16, new ECBlocks(24, new ECB(1, 32))), new Version(30, 16, 48, 14, 22, new ECBlocks(28, new ECB(1, 49))) }; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace StorageDemo.Api.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Input; namespace Avalonia.Controls { /// <summary> /// A control scrolls its content if the content is bigger than the space available. /// </summary> public class ScrollViewer : ContentControl, IScrollable { /// <summary> /// Defines the <see cref="CanHorizontallyScroll"/> property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, bool> CanHorizontallyScrollProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, bool>( nameof(CanHorizontallyScroll), o => o.CanHorizontallyScroll); /// <summary> /// Defines the <see cref="CanVerticallyScroll"/> property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, bool> CanVerticallyScrollProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, bool>( nameof(CanVerticallyScroll), o => o.CanVerticallyScroll); /// <summary> /// Defines the <see cref="Extent"/> property. /// </summary> public static readonly DirectProperty<ScrollViewer, Size> ExtentProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, Size>(nameof(Extent), o => o.Extent, (o, v) => o.Extent = v); /// <summary> /// Defines the <see cref="Offset"/> property. /// </summary> public static readonly DirectProperty<ScrollViewer, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, Vector>( nameof(Offset), o => o.Offset, (o, v) => o.Offset = v); /// <summary> /// Defines the <see cref="Viewport"/> property. /// </summary> public static readonly DirectProperty<ScrollViewer, Size> ViewportProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, Size>(nameof(Viewport), o => o.Viewport, (o, v) => o.Viewport = v); /// <summary> /// Defines the HorizontalScrollBarMaximum property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> HorizontalScrollBarMaximumProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(HorizontalScrollBarMaximum), o => o.HorizontalScrollBarMaximum); /// <summary> /// Defines the HorizontalScrollBarValue property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> HorizontalScrollBarValueProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(HorizontalScrollBarValue), o => o.HorizontalScrollBarValue, (o, v) => o.HorizontalScrollBarValue = v); /// <summary> /// Defines the HorizontalScrollBarViewportSize property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> HorizontalScrollBarViewportSizeProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(HorizontalScrollBarViewportSize), o => o.HorizontalScrollBarViewportSize); /// <summary> /// Defines the <see cref="HorizontalScrollBarVisibility"/> property. /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = AvaloniaProperty.RegisterAttached<ScrollViewer, Control, ScrollBarVisibility>( nameof(HorizontalScrollBarVisibility), ScrollBarVisibility.Hidden); /// <summary> /// Defines the VerticalScrollBarMaximum property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> VerticalScrollBarMaximumProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(VerticalScrollBarMaximum), o => o.VerticalScrollBarMaximum); /// <summary> /// Defines the VerticalScrollBarValue property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> VerticalScrollBarValueProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(VerticalScrollBarValue), o => o.VerticalScrollBarValue, (o, v) => o.VerticalScrollBarValue = v); /// <summary> /// Defines the VerticalScrollBarViewportSize property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> VerticalScrollBarViewportSizeProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(VerticalScrollBarViewportSize), o => o.VerticalScrollBarViewportSize); /// <summary> /// Defines the <see cref="VerticalScrollBarVisibility"/> property. /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = AvaloniaProperty.RegisterAttached<ScrollViewer, Control, ScrollBarVisibility>( nameof(VerticalScrollBarVisibility), ScrollBarVisibility.Auto); private Size _extent; private Vector _offset; private Size _viewport; /// <summary> /// Initializes static members of the <see cref="ScrollViewer"/> class. /// </summary> static ScrollViewer() { AffectsValidation(ExtentProperty, OffsetProperty); AffectsValidation(ViewportProperty, OffsetProperty); HorizontalScrollBarVisibilityProperty.Changed.AddClassHandler<ScrollViewer>(x => x.ScrollBarVisibilityChanged); VerticalScrollBarVisibilityProperty.Changed.AddClassHandler<ScrollViewer>(x => x.ScrollBarVisibilityChanged); } /// <summary> /// Initializes a new instance of the <see cref="ScrollViewer"/> class. /// </summary> public ScrollViewer() { } /// <summary> /// Gets the extent of the scrollable content. /// </summary> public Size Extent { get { return _extent; } private set { if (SetAndRaise(ExtentProperty, ref _extent, value)) { CalculatedPropertiesChanged(); } } } /// <summary> /// Gets or sets the current scroll offset. /// </summary> public Vector Offset { get { return _offset; } set { value = ValidateOffset(this, value); if (SetAndRaise(OffsetProperty, ref _offset, value)) { CalculatedPropertiesChanged(); } } } /// <summary> /// Gets the size of the viewport on the scrollable content. /// </summary> public Size Viewport { get { return _viewport; } private set { if (SetAndRaise(ViewportProperty, ref _viewport, value)) { CalculatedPropertiesChanged(); } } } /// <summary> /// Gets or sets the horizontal scrollbar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get { return GetValue(HorizontalScrollBarVisibilityProperty); } set { SetValue(HorizontalScrollBarVisibilityProperty, value); } } /// <summary> /// Gets or sets the vertical scrollbar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get { return GetValue(VerticalScrollBarVisibilityProperty); } set { SetValue(VerticalScrollBarVisibilityProperty, value); } } /// <summary> /// Gets a value indicating whether the viewer can scroll horizontally. /// </summary> protected bool CanHorizontallyScroll { get { return HorizontalScrollBarVisibility != ScrollBarVisibility.Disabled; } } /// <summary> /// Gets a value indicating whether the viewer can scroll vertically. /// </summary> protected bool CanVerticallyScroll { get { return VerticalScrollBarVisibility != ScrollBarVisibility.Disabled; } } /// <summary> /// Gets the maximum horizontal scrollbar value. /// </summary> protected double HorizontalScrollBarMaximum { get { return Max(_extent.Width - _viewport.Width, 0); } } /// <summary> /// Gets or sets the horizontal scrollbar value. /// </summary> protected double HorizontalScrollBarValue { get { return _offset.X; } set { if (_offset.X != value) { var old = Offset.X; Offset = Offset.WithX(value); RaisePropertyChanged(HorizontalScrollBarValueProperty, old, value); } } } /// <summary> /// Gets the size of the horizontal scrollbar viewport. /// </summary> protected double HorizontalScrollBarViewportSize { get { return _viewport.Width; } } /// <summary> /// Gets the maximum vertical scrollbar value. /// </summary> protected double VerticalScrollBarMaximum { get { return Max(_extent.Height - _viewport.Height, 0); } } /// <summary> /// Gets or sets the vertical scrollbar value. /// </summary> protected double VerticalScrollBarValue { get { return _offset.Y; } set { if (_offset.Y != value) { var old = Offset.Y; Offset = Offset.WithY(value); RaisePropertyChanged(VerticalScrollBarValueProperty, old, value); } } } /// <summary> /// Gets the size of the vertical scrollbar viewport. /// </summary> protected double VerticalScrollBarViewportSize { get { return _viewport.Height; } } /// <summary> /// Gets the value of the HorizontalScrollBarVisibility attached property. /// </summary> /// <param name="control">The control to read the value from.</param> /// <returns>The value of the property.</returns> public static ScrollBarVisibility GetHorizontalScrollBarVisibility(Control control) { return control.GetValue(HorizontalScrollBarVisibilityProperty); } /// <summary> /// Gets the value of the HorizontalScrollBarVisibility attached property. /// </summary> /// <param name="control">The control to set the value on.</param> /// <param name="value">The value of the property.</param> public static void SetHorizontalScrollBarVisibility(Control control, ScrollBarVisibility value) { control.SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Gets the value of the VerticalScrollBarVisibility attached property. /// </summary> /// <param name="control">The control to read the value from.</param> /// <returns>The value of the property.</returns> public static ScrollBarVisibility GetVerticalScrollBarVisibility(Control control) { return control.GetValue(VerticalScrollBarVisibilityProperty); } /// <summary> /// Gets the value of the VerticalScrollBarVisibility attached property. /// </summary> /// <param name="control">The control to set the value on.</param> /// <param name="value">The value of the property.</param> public static void SetVerticalScrollBarVisibility(Control control, ScrollBarVisibility value) { control.SetValue(VerticalScrollBarVisibilityProperty, value); } internal static Vector CoerceOffset(Size extent, Size viewport, Vector offset) { var maxX = Math.Max(extent.Width - viewport.Width, 0); var maxY = Math.Max(extent.Height - viewport.Height, 0); return new Vector(Clamp(offset.X, 0, maxX), Clamp(offset.Y, 0, maxY)); } private static double Clamp(double value, double min, double max) { return (value < min) ? min : (value > max) ? max : value; } private static double Max(double x, double y) { var result = Math.Max(x, y); return double.IsNaN(result) ? 0 : result; } private static Vector ValidateOffset(AvaloniaObject o, Vector value) { ScrollViewer scrollViewer = o as ScrollViewer; if (scrollViewer != null) { var extent = scrollViewer.Extent; var viewport = scrollViewer.Viewport; return CoerceOffset(extent, viewport, value); } else { return value; } } private void ScrollBarVisibilityChanged(AvaloniaPropertyChangedEventArgs e) { var wasEnabled = !ScrollBarVisibility.Disabled.Equals(e.OldValue); var isEnabled = !ScrollBarVisibility.Disabled.Equals(e.NewValue); if (wasEnabled != isEnabled) { if (e.Property == HorizontalScrollBarVisibilityProperty) { RaisePropertyChanged( CanHorizontallyScrollProperty, wasEnabled, isEnabled); } else if (e.Property == VerticalScrollBarVisibilityProperty) { RaisePropertyChanged( CanVerticallyScrollProperty, wasEnabled, isEnabled); } } } private void CalculatedPropertiesChanged() { // Pass old values of 0 here because we don't have the old values at this point, // and it shouldn't matter as only the template uses these properies. RaisePropertyChanged(HorizontalScrollBarMaximumProperty, 0, HorizontalScrollBarMaximum); RaisePropertyChanged(HorizontalScrollBarValueProperty, 0, HorizontalScrollBarValue); RaisePropertyChanged(HorizontalScrollBarViewportSizeProperty, 0, HorizontalScrollBarViewportSize); RaisePropertyChanged(VerticalScrollBarMaximumProperty, 0, VerticalScrollBarMaximum); RaisePropertyChanged(VerticalScrollBarValueProperty, 0, VerticalScrollBarValue); RaisePropertyChanged(VerticalScrollBarViewportSizeProperty, 0, VerticalScrollBarViewportSize); } protected override void OnKeyDown(KeyEventArgs e) { if (e.Key == Key.PageUp) { VerticalScrollBarValue = Math.Max(_offset.Y - _viewport.Height, 0); e.Handled = true; } else if (e.Key == Key.PageDown) { VerticalScrollBarValue = Math.Min(_offset.Y + _viewport.Height, VerticalScrollBarMaximum); e.Handled = true; } } } }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Tencent is pleased to support the open source community by making behaviac available. // // Copyright (C) 2015-2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause // // 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. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// #if !BEHAVIAC_RELEASE // Setting this to true makes sure that messages sent in one batch // are ordered same as they were generated (when they come from different threads). // It has a slight memory/performance overhead. #define USING_BEHAVIAC_SEQUENTIAL using System; using System.Collections; using System.Collections.Generic; using System.Net.Sockets; using System.Runtime.InteropServices; namespace behaviac { public struct Atomic32 { private ulong m_value; public Atomic32(ulong v) { m_value = v; } public void Set(ulong v) { m_value = v; } public ulong Get() { return m_value; } public ulong AtomicInc() { m_value++; return m_value; } public ulong AtomicDec() { m_value--; return m_value; } } public static class SocketConnection { #if USING_BEHAVIAC_SEQUENTIAL public class Seq { public Seq() { //m_seq = 0; } public ulong Next() { ulong v = m_seq.AtomicInc(); return v - 1; } public Atomic32 m_seq; }; #else struct Seq { behaviac.Atomic32 Next() { return 0; } }; #endif // USING_BEHAVIAC_SEQUENTIAL private static Seq s_seq = new Seq(); public static Seq GetNextSeq() { return s_seq; } public const int kMaxPacketDataSize = 230; public const int kMaxPacketSize = 256; public const int kSocketBufferSize = 16384 * 10; public const int kGlobalQueueSize = (1024 * 32); public const int kLocalQueueSize = (1024 * 8); public static uint ByteSwap32(uint i) { return (0xFF & i) << 24 | (0xFF00 & i) << 8 | (0xFF0000 & i) >> 8 | (0xFF000000 & i) >> 24; } public static ulong ByteSwap64(ulong i) { //return (0xFF & i) << 24 | (0xFF00 & i) << 8 | (0xFF0000 & i) >> 8 | (0xFF000000 & i) >> 24; Debug.Check(false, "unimplemented"); return i; } // For the time being only 32-bit pointers are supported. // Compile time error for other architectures. public static UIntPtr ByteSwapAddress(UIntPtr a) { return (UIntPtr)ByteSwap32((uint)a); } #if BEHAVIAC_COMPILER_64BITS static UIntPtr ByteSwapAddress(UIntPtr a) { return (UIntPtr)ByteSwap64((ulong)a); } #endif//#if BEHAVIAC_OS_WIN64 } internal enum CommandId { CMDID_INITIAL_SETTINGS = 1, CMDID_TEXT }; [StructLayout(LayoutKind.Sequential)] internal struct Text { private const int kMaxTextLength = 228; //public string buffer; [MarshalAs(UnmanagedType.ByValArray, SizeConst = kMaxTextLength + 1)] private byte[] buffer; }; [StructLayout(LayoutKind.Sequential)] public class Packet { public Packet() { } public Packet(byte commandId, ulong seq_) { this.Init(commandId, seq_); } public void Init(byte commandId, ulong seq_) { this.messageSize = 0; this.command = commandId; #if USING_BEHAVIAC_SEQUENTIAL this.seq.Set(seq_); #else (void)sizeof(seq_); #endif } public int CalcPacketSize() { int packetSize = (0); if (command == (byte)CommandId.CMDID_TEXT) { if (this.data != null) { packetSize = this.data.Length; } else { packetSize = Marshal.SizeOf(typeof(Text)); } } else { Debug.Check(false, "Unknown command"); } packetSize += Marshal.SizeOf(command); return packetSize; } public void SetData(string text) { byte[] ascII = System.Text.Encoding.ASCII.GetBytes(text); Debug.Check(ascII.Length < SocketConnection.kMaxPacketDataSize); this.data = new byte[ascII.Length]; System.Buffer.BlockCopy(ascII, 0, this.data, 0, ascII.Length); } public byte[] GetData() { int len = this.PrepareToSend(); byte[] da = new byte[len]; da[0] = messageSize; da[1] = command; Array.Copy(this.data, 0, da, 2, this.data.Length); return da; } public int PrepareToSend() { int packetSize = CalcPacketSize(); Debug.Check(packetSize < SocketConnection.kMaxPacketSize); messageSize = (byte)packetSize; return messageSize + 1; } private byte messageSize; private byte command; //[MarshalAs(UnmanagedType.ByValArray, SizeConst = SocketConnection.kMaxPacketDataSize)] private byte[] data; // IMPORTANT: has to be the last member variable, it's not being sent // to tracer application. #if USING_BEHAVIAC_SEQUENTIAL public Atomic32 seq; #endif }; //public static class StructExtentsion //{ // private static T ReadStruct<T>(this BinaryReader reader) where T : struct // { // Byte[] buffer = new Byte[Marshal.SizeOf(typeof(T))]; // reader.Read(buffer, 0, buffer.Length); // GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); // T result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); // handle.Free(); // return result; // } //} // Minimal subset of functionality that we need. public static class SocketBase { public static bool InitSockets() { return true; } public static void ShutdownSockets() { } public static Socket Create(bool blocking) { Socket h = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); if (h == null) { return null; } h.Blocking = blocking; return h; } public static void Close(ref Socket h) { if (h != null) { h.Close(); h = null; } } public static bool Listen(Socket h, ushort port, int maxConnections) { try { System.Net.IPEndPoint ipe = new System.Net.IPEndPoint(System.Net.IPAddress.Any, port); h.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //h.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000); h.Bind(ipe); h.Listen(maxConnections); return true; } catch { } return false; } public static bool TestConnection(Socket h) { bool hasRead = h.Poll(17000, SelectMode.SelectRead); if (hasRead) { return true; } return false; } public static Socket Accept(Socket listeningSocket, int bufferSize) { Socket outSocket = listeningSocket.Accept(); if (outSocket != null) { outSocket.ReceiveBufferSize = bufferSize; outSocket.SendBufferSize = bufferSize; return outSocket; } return null; } private static uint gs_packetsSent = 0; private static uint gs_packetsReceived = 0; public static bool Write(Socket h, byte[] buffer, ref int outBytesWritten) { int bytes = buffer != null ? buffer.Length : 0; if (bytes == 0 || h == null) { return bytes == 0; } try { int res = h.Send(buffer); if (res == -1) { outBytesWritten = 0; if (!h.Connected) { Close(ref h); } } else { outBytesWritten = res; gs_packetsSent++; } } catch (Exception ex) { Debug.Log(ex.Message); } return outBytesWritten != 0; } public static int Read(ref Socket h, byte[] buffer, int bytesMax) { int bytesRead = 0; if (bytesMax == 0 || h == null) { return bytesRead; } else if (!h.Connected) { Close(ref h); return 0; } bool hasData = h.Poll(1000, SelectMode.SelectRead); if (hasData) { if (h.Available == 0) { //disconnected Close(ref h); return 0; } int res = h.Receive(buffer, bytesMax, SocketFlags.None); if (res == -1) { Close(ref h); } else { bytesRead = res; gs_packetsReceived++; } return bytesRead; } return 0; } public static uint GetPacketsSent() { return gs_packetsSent; } public static uint GetPacketsReceived() { return gs_packetsReceived; } }// namespace Socket internal enum Platform { WINDOWS }; #if USING_BEHAVIAC_SEQUENTIAL public class PacketCollection { public PacketCollection() { m_packets = null; m_packetsEnd = (0); m_packetsCapacity = (0); } //~PacketCollection( //{ // Close(); //} public void Init(int capacity) { Debug.Check(m_packets == null); m_packets = new Packet[capacity]; m_packetsEnd = 0; m_packetsCapacity = capacity; } public void Close() { m_packets = null; } public Packet[] GetPackets(ref int end) { end = this.m_packetsEnd; return m_packets; } public int GetMemoryOverhead() { return (m_packetsCapacity) * Marshal.SizeOf(typeof(Packet)); } // False if not enough space, packet not added. public bool Add(Packet packet) { if (m_packetsEnd == m_packetsCapacity) { behaviac.Debug.LogWarning("buffer overflow...\n"); return false; } m_packets[m_packetsEnd++] = packet; return true; } public void Reset() { m_packetsEnd = 0; } public void Sort() { PacketComparer c = new PacketComparer(); Array.Sort(m_packets, 0, this.m_packetsEnd, c); } private class PacketComparer : IComparer<Packet> { #if USING_BEHAVIAC_SEQUENTIAL public int Compare(Packet pa, Packet pb) { if (pa.seq.Get() < pb.seq.Get()) { return -1; } if (pa.seq.Get() > pb.seq.Get()) { return 1; } return 0; } #else int Compare(Packet pa, Packet pb) { return 0; } #endif } private Packet[] m_packets; private int m_packetsEnd; private int m_packetsCapacity; }; #else class PacketCollection { void Init(uint) {} void Close() {} uint GetMemoryOverhead() { return 0; } }; #endif // #if USING_BEHAVIAC_SEQUENTIAL public class PacketBuffer { private ConnectorInterface _conector; public PacketBuffer(ConnectorInterface c) { _conector = c; m_free = true; } public void AddPacket(Packet packet) { if (packet != null) { // Spin loop until there is a place for new packet. // If this happens to often, it means we are producing packets // quicker than consuming them, increasing max # of packets in buffer // could help. while (m_packetQueue.Count >= SocketConnection.kLocalQueueSize) { //BEHAVIAC_LOGINFO("packet buffer is full... buffer size: %d\n", MAX_PACKETS_IN_BUFFER); System.Threading.Thread.Sleep(1); if (this._conector.WriteSocket == null || !this._conector.WriteSocket.Connected) { break; } } lock (m_packetQueue) { m_packetQueue.Enqueue(packet); } } } #if USING_BEHAVIAC_SEQUENTIAL public bool CollectPackets(PacketCollection coll) { if (m_packetQueue.Count == 0) { return true; } lock (m_packetQueue) { Packet packet = m_packetQueue.Peek(); while (packet == null) { m_packetQueue.Dequeue(); if (m_packetQueue.Count == 0) { break; } packet = m_packetQueue.Peek(); } while (packet != null) { if (coll.Add(packet)) { m_packetQueue.Dequeue(); if (m_packetQueue.Count == 0) { break; } packet = m_packetQueue.Peek(); } else { return false; } } } return true; } #endif private void SendPackets(Socket h) { lock (m_packetQueue) { Packet packet = m_packetQueue.Peek(); while (packet != null) { int bytesWritten = (0); bool success = SocketBase.Write(h, packet.GetData(), ref bytesWritten); // Failed to send data. Most probably sending too much, break and // hope for the best next time if (!success) { Debug.Check(false); behaviac.Debug.LogWarning("A packet is not correctly sent...\n"); break; } m_packetQueue.Dequeue(); // 'Commit' pop if data sent. packet = m_packetQueue.Peek(); } } } public void Clear() { m_packetQueue.Clear(); } public bool m_free; private Queue<Packet> m_packetQueue = new Queue<Packet>(); }; /// <summary> /// Represents a pool of objects with a size limit. /// </summary> /// <typeparam name="T">The type of object in the pool.</typeparam> public class ObjectPool<T> : IDisposable where T : new() { private readonly int size; private readonly object locker; private readonly Queue<T> queue; private int count; /// <summary> /// Initializes a new instance of the ObjectPool class. /// </summary> /// <param name="size">The size of the object pool.</param> public ObjectPool(int size) { if (size <= 0) { const string message = "The size of the pool must be greater than zero."; throw new ArgumentOutOfRangeException("size", size, message); } this.size = size; locker = new object(); queue = new Queue<T>(); } /// <summary> /// Retrieves an item from the pool. /// </summary> /// <returns>The item retrieved from the pool.</returns> public T Get() { lock (locker) { if (queue.Count > 0) { return queue.Dequeue(); } count++; return new T(); } } /// <summary> /// Places an item in the pool. /// </summary> /// <param name="item">The item to place to the pool.</param> public void Put(T item) { lock (locker) { if (count < size) { queue.Enqueue(item); } else { using(item as IDisposable) { count--; } } } } /// <summary> /// Disposes of items in the pool that implement IDisposable. /// </summary> public void Dispose() { lock (locker) { count = 0; while (queue.Count > 0) { using(queue.Dequeue() as IDisposable) { } } } } } public class CustomObjectPool : IEnumerable { private readonly int m_capacity; private class PacketSegment { public int m_count; public Packet[] m_buffer; public PacketSegment m_next; } private PacketSegment m_segments; public CustomObjectPool(int objectCountPerSegment) { m_capacity = objectCountPerSegment; } public System.Collections.IEnumerator GetEnumerator() { PacketSegment n = m_segments; while (n != null) { for (int i = 0; i < n.m_count; ++i) { yield return n.m_buffer[i]; } n = n.m_next; } } public Packet Allocate() { if (m_segments == null || m_segments.m_count >= m_capacity) { AllocSegment(); } Packet p = m_segments.m_buffer[m_segments.m_count++]; return p; } private void AllocSegment() { PacketSegment n = new PacketSegment(); n.m_count = 0; n.m_buffer = new Packet[m_capacity]; for (int i = 0; i < m_capacity; ++i) { n.m_buffer[i] = new Packet(); } if (m_segments != null) { m_segments.m_next = n; } m_segments = n; } public void Clear() { PacketSegment n = m_segments; while (n != null) { n.m_buffer = null; n = n.m_next; } m_segments = null; } public int GetMemoryUsage() { return 0; } }; public abstract class ConnectorInterface { private const int kMaxTextLength = 228; public ConnectorInterface() { Debug.Check(Marshal.SizeOf(typeof(Text)) < SocketConnection.kMaxPacketDataSize); Debug.Check(Marshal.SizeOf(typeof(Packet)) < SocketConnection.kMaxPacketSize); #if !USING_BEHAVIAC_SEQUENTIAL Debug.Check(sizeof(Packet) == sizeof(AllocInfo) + 2); #endif #if USING_BEHAVIAC_SEQUENTIAL //Debug.Check(sizeof(Packet) == sizeof(Text) + 2 + 4); Debug.Check((int)Marshal.OffsetOf(typeof(Packet), "seq") == Marshal.SizeOf(typeof(Packet)) - Marshal.SizeOf(typeof(Atomic32))); // seq must be the last member #endif // Local queue size must be power of two. Debug.Check((SocketConnection.kLocalQueueSize & (SocketConnection.kLocalQueueSize - 1)) == 0); m_port = (0); m_writeSocket = null; m_packetBuffers = null; m_maxTracedThreads = 0; m_isConnected.Set(0); m_isDisconnected.Set(0); m_isConnectedFinished.Set(0); m_isInited.Set(0); m_terminating.Set(0); m_packetPool = null; m_packetCollection = null; m_packetsCount = 0; s_tracerThread = null; m_bHandleMessage = true; } ~ConnectorInterface() { this.Close(); } private void RecordText(string text) { if (this.m_packetPool != null) { //if it is out of memory here, please check 'SetupConnection' Packet pP = this.m_packetPool.Allocate(); if (pP != null) { pP.Init((byte)CommandId.CMDID_TEXT, SocketConnection.GetNextSeq().Next()); pP.SetData(text); } } } private void CreateAndStartThread() { s_tracerThread = new System.Threading.Thread(MemTracer_ThreadFunc); s_tracerThread.Start(); } public bool IsConnected() { return m_isConnected.Get() != 0; } private bool IsDisconnected() { return m_isDisconnected.Get() != 0; } private bool IsConnectedFinished() { return m_isConnectedFinished.Get() != 0; } public bool IsInited() { return m_isInited.Get() != 0; } private void SetConnectPort(ushort port) { this.m_port = port; } private void AddPacket(Packet packet, bool bReserve) { if (this.IsConnected() && this.m_writeSocket != null && this.m_writeSocket.Connected) { int bufferIndex = this.GetBufferIndex(bReserve); if (bufferIndex > 0) { m_packetBuffers[bufferIndex].AddPacket(packet); this.m_packetsCount++; } else { //Debug.Check(false); Debug.LogError("invalid bufferIndex"); } } } private int GetBufferIndex(bool bReserve) { //Debug.Check(t_packetBufferIndex != -1); int bufferIndex = (int)t_packetBufferIndex; //WHEN bReserve is false, it is unsafe to allocate memory as other threads might be allocating //you can avoid the following assert to malloc a block of memory in your thread at the very beginning Debug.Check(bufferIndex > 0 || bReserve); //bufferIndex initially is 0 if (bufferIndex <= 0 && bReserve) { bufferIndex = ReserveThreadPacketBuffer(); } return bufferIndex; } protected abstract void OnConnection(); protected virtual void OnRecieveMessages(string msgs) { } protected void SendAllPackets() { if (this.m_writeSocket != null && this.m_writeSocket.Connected) { for (int i = 0; i < m_maxTracedThreads; ++i) { if (m_packetBuffers[i] != null && !m_packetBuffers[i].m_free) { #if USING_BEHAVIAC_SEQUENTIAL if (!m_packetBuffers[i].CollectPackets(m_packetCollection)) { break; } #else m_packetBuffers[i].SendPackets(m_writeSocket); #endif } } #if USING_BEHAVIAC_SEQUENTIAL // TODO: Deal with Socket.Write failures. // (right now packet is lost). m_packetCollection.Sort(); int endIndex = 0; Packet[] packets = m_packetCollection.GetPackets(ref endIndex); for (int i = 0; i < endIndex; ++i) { Packet p = packets[i]; int bytesWritten = (0); SocketBase.Write(this.m_writeSocket, p.GetData(), ref bytesWritten); if (this.m_writeSocket == null || !this.m_writeSocket.Connected || bytesWritten <= 0) { break; } } m_packetCollection.Reset(); #endif this.m_packetsCount = 0; } } private static string GetStringFromBuffer(byte[] data, int dataIdx, int maxLen, bool isAsc) { System.Text.Encoding ecode; if (isAsc) { ecode = new System.Text.ASCIIEncoding(); } else { ecode = new System.Text.UTF8Encoding(); } string ret = ecode.GetString(data, dataIdx, maxLen); char[] zeroChars = { '\0', '?' }; return ret.TrimEnd(zeroChars); } /** return true if 'msgCheck' is received */ protected bool ReceivePackets(string msgCheck) { if (this.m_writeSocket != null && this.m_writeSocket.Connected) { int kBufferLen = 2048; byte[] buffer = new byte[kBufferLen]; bool found = false; int reads = SocketBase.Read(ref m_writeSocket, buffer, kBufferLen); while (reads > 0 && this.m_writeSocket != null && this.m_writeSocket.Connected) { //BEHAVIAC_LOG(MEMDIC_LOG_INFO, buffer); lock (this) { ms_texts += GetStringFromBuffer(buffer, 0, reads, true); } if (!string.IsNullOrEmpty(msgCheck) && ms_texts.IndexOf(msgCheck) != -1) { found = true; } reads = SocketBase.Read(ref m_writeSocket, buffer, kBufferLen); } if (this.m_bHandleMessage && this.m_writeSocket != null && this.m_writeSocket.Connected) { string msgs = ""; if (this.ReadText(ref msgs)) { this.OnRecieveMessages(msgs); return true; } } return found; } return false; } private void ThreadFunc() { Log("behaviac: Socket Thread Starting\n"); try { this.ReserveThreadPacketBuffer(); int bufferIndex = t_packetBufferIndex; Debug.Check(bufferIndex > 0); bool blockingSocket = true; Socket serverSocket = null; try { serverSocket = SocketBase.Create(blockingSocket); if (serverSocket == null) { Log("behaviac: Couldn't create server socket.\n"); return; } string bufferTemp = string.Format("behaviac: Listening at port {0}...\n", m_port); Log(bufferTemp); // max connections: 1, don't allow multiple clients? if (!SocketBase.Listen(serverSocket, m_port, 1)) { Log("behaviac: Couldn't configure server socket.\n"); SocketBase.Close(ref serverSocket); return; } } catch (Exception ex) { Debug.LogError(ex.Message); } while (m_terminating.Get() == 0) { //wait for connecting while (m_terminating.Get() == 0) { if (SocketBase.TestConnection(serverSocket)) { break; } System.Threading.Thread.Sleep(100); } if (m_terminating.Get() == 0) { Log("behaviac: accepting...\n"); try { m_writeSocket = SocketBase.Accept(serverSocket, SocketConnection.kSocketBufferSize); if (m_writeSocket == null) { Log("behaviac: Couldn't create write socket.\n"); SocketBase.Close(ref serverSocket); return; } } catch (Exception ex) { Debug.LogError(ex.Message); } try { m_isConnected.AtomicInc(); System.Threading.Thread.Sleep(1); OnConnection(); m_isConnectedFinished.AtomicInc(); System.Threading.Thread.Sleep(1); //this.OnConnectionFinished(); Log("behaviac: Connected. accepted\n"); } catch (Exception ex) { Debug.LogError(ex.Message); } try { while (m_terminating.Get() == 0 && this.m_writeSocket != null) { System.Threading.Thread.Sleep(1); this.SendAllPackets(); this.ReceivePackets(""); } if (this.m_writeSocket != null && this.m_writeSocket.Connected) { // One last time, to send any outstanding packets out there. this.SendAllPackets(); } SocketBase.Close(ref this.m_writeSocket); this.Clear(); Log("behaviac: disconnected. \n"); } catch (Exception ex) { Debug.LogError(ex.Message + ex.StackTrace); } } }//while (!m_terminating) SocketBase.Close(ref serverSocket); this.Clear(); } catch (Exception ex) { Debug.LogError(ex.Message); } Log("behaviac: ThreadFunc exited. \n"); } public int GetMemoryOverhead() { int threads = GetNumTrackedThreads(); int bufferSize = Marshal.SizeOf(typeof(PacketBuffer)) * threads; int packetCollectionSize = m_packetCollection != null ? m_packetCollection.GetMemoryOverhead() : 0; int packetPoolSize = m_packetPool != null ? m_packetPool.GetMemoryUsage() : 0; return bufferSize + packetCollectionSize + packetPoolSize; } public int GetNumTrackedThreads() { int numTrackedThreads = (0); if (m_packetBuffers != null) { for (int i = 0; i < m_maxTracedThreads; ++i) { if (m_packetBuffers[i] != null && !m_packetBuffers[i].m_free) { ++numTrackedThreads; } } } return numTrackedThreads; } public int GetPacketsCount() { //not thread safe if (this.IsConnected()) { return m_packetsCount; } return 0; } public void SendText(string text, byte commandId /*= (byte)CommandId.CMDID_TEXT*/) { if (this.IsConnected()) { Packet packet = new Packet(commandId, SocketConnection.GetNextSeq().Next()); packet.SetData(text); this.AddPacket(packet, true); gs_packetsStats.texts++; } //else //{ // RecordText(text); //} } public bool ReadText(ref string text) { if (this.IsConnected()) { lock (this) { text = this.ms_texts; this.ms_texts = string.Empty; return !string.IsNullOrEmpty(text); } } return false; } protected int ReserveThreadPacketBuffer() { int bufferIndex = t_packetBufferIndex; //THREAD_ID_TYPE id = behaviac.GetTID(); //BEHAVIAC_LOGINFO("ReserveThreadPacketBuffer:%d thread %d\n", bufferIndex, id); //bufferIndex initially is -1 if (bufferIndex <= 0) { int retIndex = (-2); lock (this) { // NOTE: This is quite naive attempt to make sure that main thread queue // is the last one (rely on the fact that it's most likely to be the first // one trying to send message). This means EndFrame event should be sent after // memory operations from that frame. // (doesn't matter in SEQUENTIAL mode). for (int i = m_maxTracedThreads - 1; i >= 0; --i) { if (m_packetBuffers[i] == null) { m_packetBuffers[i] = new PacketBuffer(this); } if (m_packetBuffers[i] != null) { if (m_packetBuffers[i].m_free) { m_packetBuffers[i].m_free = false; retIndex = i; break; } } } if (retIndex > 0) { t_packetBufferIndex = retIndex; } else { Log("behaviac: Couldn't reserve packet buffer, too many active threads.\n"); Debug.Check(false); } bufferIndex = retIndex; } //BEHAVIAC_LOGINFO("ReserveThreadPacketBuffer:%d thread %d\n", bufferIndex, id); } return bufferIndex; } protected void Log(string msg) { behaviac.Debug.Log(msg); } protected virtual void Clear() { this.m_isConnected.Set(0); this.m_isDisconnected.Set(0); this.m_isConnectedFinished.Set(0); this.m_terminating.Set(0); if (this.m_packetBuffers != null) { int bufferIndex = this.GetBufferIndex(false); if (bufferIndex > 0) { this.m_packetBuffers[bufferIndex].Clear(); } } if (this.m_packetPool != null) { this.m_packetPool.Clear(); } if (this.m_packetBuffers != null) { this.m_packetCollection.Reset(); } this.m_packetsCount = 0; } protected void SendExistingPackets() { int packetsCount = 0; foreach (Packet p in this.m_packetPool) { int bytesWritten = (0); SocketBase.Write(m_writeSocket, p.GetData(), ref bytesWritten); packetsCount++; } //wait for the finish System.Threading.Thread.Sleep(1000); this.m_packetPool.Clear(); } protected ushort m_port; protected Socket m_writeSocket; protected PacketBuffer[] m_packetBuffers; protected PacketCollection m_packetCollection; protected CustomObjectPool m_packetPool; protected int m_maxTracedThreads; protected Atomic32 m_isInited; protected Atomic32 m_isConnected; protected Atomic32 m_isDisconnected; protected Atomic32 m_isConnectedFinished; protected Atomic32 m_terminating; protected volatile int m_packetsCount; protected struct PacketsStats { public int texts; public int init; }; private System.Threading.Thread s_tracerThread; protected string ms_texts; protected volatile bool m_bHandleMessage; protected PacketsStats gs_packetsStats; [ThreadStatic] protected static int t_packetBufferIndex = -1; public bool Init(int maxTracedThreads, ushort port, bool bBlocking) { this.Clear(); m_port = ushort.MaxValue; m_packetPool = new CustomObjectPool(4096); m_packetCollection = new PacketCollection(); m_packetBuffers = new PacketBuffer[maxTracedThreads]; m_maxTracedThreads = maxTracedThreads; m_packetCollection.Init(SocketConnection.kGlobalQueueSize); if (!SocketBase.InitSockets()) { this.Log("behaviac: Failed to initialize sockets.\n"); return false; } { behaviac.Debug.Log("behaviac: ConnectorInterface.Init Enter\n"); string portMsg = string.Format("behaviac: listing at port {0}\n", port); behaviac.Debug.Log(portMsg); this.ReserveThreadPacketBuffer(); this.SetConnectPort(port); { this.CreateAndStartThread(); } if (bBlocking) { Debug.LogWarning("behaviac: SetupConnection is blocked, please Choose 'Connect' in the Designer to continue"); while (!this.IsConnected() || !this.IsConnectedFinished()) { // Wait for connection System.Threading.Thread.Sleep(100); } System.Threading.Thread.Sleep(1); Debug.Check(this.IsConnected() && this.IsConnectedFinished()); } behaviac.Debug.Log("behaviac: ConnectorInterface.Init Connected\n"); //wait for the OnConnection ends System.Threading.Thread.Sleep(200); behaviac.Debug.Log("behaviac: ConnectorInterface.Init successful\n"); } m_isInited.AtomicInc(); return m_packetBuffers != null; } public void Close() { m_terminating.AtomicInc(); m_isConnectedFinished.AtomicDec(); m_isDisconnected.AtomicInc(); if (s_tracerThread != null) { if (s_tracerThread.IsAlive) { while (IsConnected() && s_tracerThread.IsAlive) { System.Threading.Thread.Sleep(1); } } lock (this) { m_packetBuffers = null; } if (s_tracerThread.IsAlive) { s_tracerThread.Abort(); } s_tracerThread = null; } if (m_packetCollection != null) { m_packetCollection.Close(); m_packetCollection = null; } m_packetPool = null; t_packetBufferIndex = -1; SocketBase.ShutdownSockets(); m_isInited.AtomicDec(); } public Socket WriteSocket { get { return m_writeSocket; } } private void MemTracer_ThreadFunc(object tracer_) { //ConnectorInterface tracer = (ConnectorInterface)tracer_; this.ThreadFunc(); } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using Xunit; namespace System.Drawing.PrimitivesTest { public class RectangleFTests { [Fact] public void DefaultConstructorTest() { Assert.Equal(RectangleF.Empty, new RectangleF()); } [Theory] [InlineData(0, 0, 0, 0)] [InlineData(float.MaxValue, float.MinValue, float.MinValue, float.MaxValue)] [InlineData(float.MaxValue, 0, 0, float.MaxValue)] [InlineData(0, float.MinValue, float.MaxValue, 0)] public void NonDefaultConstructorTest(float x, float y, float width, float height) { RectangleF rect1 = new RectangleF(x, y, width, height); PointF p = new PointF(x, y); SizeF s = new SizeF(width, height); RectangleF rect2 = new RectangleF(p, s); Assert.Equal(rect1, rect2); } [Theory] [InlineData(0, 0, 0, 0)] [InlineData(float.MaxValue, float.MinValue, float.MinValue, float.MaxValue)] [InlineData(float.MaxValue, 0, 0, float.MaxValue)] [InlineData(0, float.MinValue, float.MaxValue, 0)] public void FromLTRBTest(float left, float top, float right, float bottom) { RectangleF expected = new RectangleF(left, top, right - left, bottom - top); RectangleF actual = RectangleF.FromLTRB(left, top, right, bottom); Assert.Equal(expected, actual); } [Theory] [InlineData(0, 0, 0, 0)] [InlineData(float.MaxValue, float.MinValue, float.MinValue, float.MaxValue)] [InlineData(float.MaxValue, 0, 0, float.MaxValue)] [InlineData(0, float.MinValue, float.MaxValue, 0)] public void DimensionsTest(float x, float y, float width, float height) { RectangleF rect = new RectangleF(x, y, width, height); PointF p = new PointF(x, y); SizeF s = new SizeF(width, height); Assert.Equal(p, rect.Location); Assert.Equal(s, rect.Size); Assert.Equal(x, rect.X); Assert.Equal(y, rect.Y); Assert.Equal(width, rect.Width); Assert.Equal(height, rect.Height); Assert.Equal(x, rect.Left); Assert.Equal(y, rect.Top); Assert.Equal(x + width, rect.Right); Assert.Equal(y + height, rect.Bottom); } [Fact] public void IsEmptyTest() { Assert.True(RectangleF.Empty.IsEmpty); Assert.True(new RectangleF().IsEmpty); Assert.True(new RectangleF(1, -2, -10, 10).IsEmpty); Assert.True(new RectangleF(1, -2, 10, -10).IsEmpty); Assert.True(new RectangleF(1, -2, 0, 0).IsEmpty); Assert.False(new RectangleF(0, 0, 10, 10).IsEmpty); } [Theory] [InlineData(0, 0)] [InlineData(float.MaxValue, float.MinValue)] public static void LocationSetTest(float x, float y) { var point = new PointF(x, y); var rect = new RectangleF(10, 10, 10, 10); rect.Location = point; Assert.Equal(point, rect.Location); Assert.Equal(point.X, rect.X); Assert.Equal(point.Y, rect.Y); } [Theory] [InlineData(0, 0)] [InlineData(float.MaxValue, float.MinValue)] public static void SizeSetTest(float x, float y) { var size = new SizeF(x, y); var rect = new RectangleF(10, 10, 10, 10); rect.Size = size; Assert.Equal(size, rect.Size); Assert.Equal(size.Width, rect.Width); Assert.Equal(size.Height, rect.Height); } [Theory] [InlineData(float.MaxValue, float.MinValue, float.MinValue, float.MaxValue)] [InlineData(float.MaxValue, 0, 0, float.MaxValue)] [InlineData(0, float.MinValue, float.MaxValue, 0)] public void EqualityTest(float x, float y, float width, float height) { RectangleF rect1 = new RectangleF(x, y, width, height); RectangleF rect2 = new RectangleF(width, height, x, y); Assert.True(rect1 != rect2); Assert.False(rect1 == rect2); Assert.False(rect1.Equals(rect2)); Assert.False(rect1.Equals((object)rect2)); } [Fact] public static void EqualityTest_NotRectangleF() { var rectangle = new RectangleF(0, 0, 0, 0); Assert.False(rectangle.Equals(null)); Assert.False(rectangle.Equals(0)); // If RectangleF implements IEquatable<RectangleF> (e.g. in .NET Core), then classes that are implicitly // convertible to RectangleF can potentially be equal. // See https://github.com/dotnet/corefx/issues/5255. bool expectsImplicitCastToRectangleF = typeof(IEquatable<RectangleF>).IsAssignableFrom(rectangle.GetType()); Assert.Equal(expectsImplicitCastToRectangleF, rectangle.Equals(new Rectangle(0, 0, 0, 0))); Assert.False(rectangle.Equals((object)new Rectangle(0, 0, 0, 0))); // No implicit cast } [Fact] public static void GetHashCodeTest() { var rect1 = new RectangleF(10, 10, 10, 10); var rect2 = new RectangleF(10, 10, 10, 10); Assert.Equal(rect1.GetHashCode(), rect2.GetHashCode()); Assert.NotEqual(rect1.GetHashCode(), new RectangleF(20, 10, 10, 10).GetHashCode()); Assert.NotEqual(rect1.GetHashCode(), new RectangleF(10, 20, 10, 10).GetHashCode()); Assert.NotEqual(rect1.GetHashCode(), new RectangleF(10, 10, 20, 10).GetHashCode()); Assert.NotEqual(rect1.GetHashCode(), new RectangleF(10, 10, 10, 20).GetHashCode()); } [Theory] [InlineData(float.MaxValue, float.MinValue, float.MinValue, float.MaxValue)] [InlineData(0, float.MinValue, float.MaxValue, 0)] public void ContainsTest(float x, float y, float width, float height) { RectangleF rect = new RectangleF(x, y, width, height); float X = (x + width) / 2; float Y = (y + height) / 2; PointF p = new PointF(X, Y); RectangleF r = new RectangleF(X, Y, width / 2, height / 2); Assert.False(rect.Contains(X, Y)); Assert.False(rect.Contains(p)); Assert.False(rect.Contains(r)); } [Theory] [InlineData(0, 0, 0, 0)] [InlineData(float.MaxValue / 2, float.MinValue / 2, float.MinValue / 2, float.MaxValue / 2)] [InlineData(0, float.MinValue, float.MaxValue, 0)] public void InflateTest(float x, float y, float width, float height) { RectangleF rect = new RectangleF(x, y, width, height); RectangleF inflatedRect = new RectangleF(x - width, y - height, width + 2 * width, height + 2 * height); rect.Inflate(width, height); Assert.Equal(inflatedRect, rect); SizeF s = new SizeF(x, y); inflatedRect = RectangleF.Inflate(rect, x, y); rect.Inflate(s); Assert.Equal(inflatedRect, rect); } [Theory] [InlineData(float.MaxValue, float.MinValue, float.MaxValue / 2, float.MinValue / 2)] [InlineData(0, float.MinValue, float.MaxValue, 0)] public void IntersectTest(float x, float y, float width, float height) { RectangleF rect1 = new RectangleF(x, y, width, height); RectangleF rect2 = new RectangleF(y, x, width, height); RectangleF expectedRect = RectangleF.Intersect(rect1, rect2); rect1.Intersect(rect2); Assert.Equal(expectedRect, rect1); Assert.False(rect1.IntersectsWith(expectedRect)); } [Fact] public static void Intersect_IntersectingRects_Test() { var rect1 = new RectangleF(0, 0, 5, 5); var rect2 = new RectangleF(1, 1, 3, 3); var expected = new RectangleF(1, 1, 3, 3); Assert.Equal(expected, RectangleF.Intersect(rect1, rect2)); } [Theory] [InlineData(0, 0, 0, 0)] [InlineData(float.MaxValue, float.MinValue, float.MinValue, float.MaxValue)] [InlineData(float.MaxValue, 0, 0, float.MaxValue)] [InlineData(0, float.MinValue, float.MaxValue, 0)] public void UnionTest(float x, float y, float width, float height) { RectangleF a = new RectangleF(x, y, width, height); RectangleF b = new RectangleF(width, height, x, y); float x1 = Math.Min(a.X, b.X); float x2 = Math.Max(a.X + a.Width, b.X + b.Width); float y1 = Math.Min(a.Y, b.Y); float y2 = Math.Max(a.Y + a.Height, b.Y + b.Height); RectangleF expectedRectangle = new RectangleF(x1, y1, x2 - x1, y2 - y1); Assert.Equal(expectedRectangle, RectangleF.Union(a, b)); } [Theory] [InlineData(0, 0, 0, 0)] [InlineData(float.MaxValue, float.MinValue, float.MinValue, float.MaxValue)] [InlineData(float.MaxValue, 0, 0, float.MaxValue)] [InlineData(0, float.MinValue, float.MaxValue, 0)] public void OffsetTest(float x, float y, float width, float height) { RectangleF r1 = new RectangleF(x, y, width, height); RectangleF expectedRect = new RectangleF(x + width, y + height, width, height); PointF p = new PointF(width, height); r1.Offset(p); Assert.Equal(expectedRect, r1); expectedRect.Offset(p); r1.Offset(width, height); Assert.Equal(expectedRect, r1); } [Theory] [InlineData(0, 0, 0, 0)] [InlineData(5, -5, 0.2, -1.3)] public void ToStringTest(float x, float y, float width, float height) { var r = new RectangleF(x, y, width, height); Assert.Equal(string.Format(CultureInfo.CurrentCulture, "{{X={0},Y={1},Width={2},Height={3}}}", r.X, r.Y, r.Width, r.Height), r.ToString()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Globalization; namespace System.DirectoryServices.AccountManagement { public class PrincipalSearcher : IDisposable { // // Public constructors // public PrincipalSearcher() { SetDefaultPageSizeForContext(); } public PrincipalSearcher(Principal queryFilter) { if (null == queryFilter) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.InvalidNullArgument, "queryFilter")); _ctx = queryFilter.Context; this.QueryFilter = queryFilter; // use property to enforce "no persisted principals" check SetDefaultPageSizeForContext(); } // // Public properties // public PrincipalContext Context { get { CheckDisposed(); return _ctx; } } public Principal QueryFilter { get { CheckDisposed(); return _qbeFilter; } set { if (null == value) throw new ArgumentNullException(String.Format(CultureInfo.CurrentCulture, SR.InvalidNullArgument, "queryFilter")); CheckDisposed(); Debug.Assert(value.Context != null); // Make sure they're not passing in a persisted Principal object if ((value != null) && (!value.unpersisted)) throw new ArgumentException(SR.PrincipalSearcherPersistedPrincipal); _qbeFilter = value; _ctx = _qbeFilter.Context; } } // // Public methods // // Calls FindAll(false) to retrieve all matching results public PrincipalSearchResult<Principal> FindAll() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalSearcher", "Entering FindAll()"); CheckDisposed(); return FindAll(false); } // Calls FindAll(true) to retrieve at most one result, then retrieves the first (and only) result from the // FindResult<Principal> and returns it. public Principal FindOne() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalSearcher", "Entering FindOne()"); CheckDisposed(); using (PrincipalSearchResult<Principal> fr = FindAll(true)) { FindResultEnumerator<Principal> fre = (FindResultEnumerator<Principal>)fr.GetEnumerator(); // If there's (at least) one result, return it. Else return null. if (fre.MoveNext()) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalSearcher", "FindOne(): found a principal"); return (Principal)fre.Current; } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalSearcher", "FindOne(): found no principal"); return null; } } } // The wormhole to the native searcher underlying this PrincipalSearcher. // This method validates that a PrincipalContext has been set on the searcher and that the QBE // filter, if supplied, has no referential properties set. // // If the underlying StoreCtx does not expose a native searcher (StoreCtx.SupportsSearchNatively is false), // throws an exception. // // Otherwise, calls StoreCtx.PushFilterToNativeSearcher to push the current QBE filter // into underlyingSearcher (automatically constructing a fresh native searcher if underlyingSearcher is null), // and returns underlyingSearcher. public object GetUnderlyingSearcher() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalSearcher", "Entering GetUnderlyingSearcher"); CheckDisposed(); // We have to have a filter if (_qbeFilter == null) throw new InvalidOperationException(SR.PrincipalSearcherMustSetFilter); // Double-check that the Principal isn't persisted. We don't allow them to assign a persisted // Principal as the filter, but they could have persisted it after assigning it to the QueryFilter // property. if (!_qbeFilter.unpersisted) throw new InvalidOperationException(SR.PrincipalSearcherPersistedPrincipal); // Validate the QBE filter: make sure it doesn't have any non-scalar properties set. if (HasReferentialPropertiesSet()) throw new InvalidOperationException(SR.PrincipalSearcherNonReferentialProps); StoreCtx storeCtx = _ctx.QueryCtx; Debug.Assert(storeCtx != null); // The underlying context must actually support search (i.e., no MSAM/reg-SAM) if (storeCtx.SupportsSearchNatively == false) throw new InvalidOperationException(SR.PrincipalSearcherNoUnderlying); // We need to generate the searcher every time because the object could change // outside of our control. _underlyingSearcher = storeCtx.PushFilterToNativeSearcher(this); return _underlyingSearcher; } public Type GetUnderlyingSearcherType() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalSearcher", "Entering GetUnderlyingSearcherType"); CheckDisposed(); // We have to have a filter if (_qbeFilter == null) throw new InvalidOperationException(SR.PrincipalSearcherMustSetFilter); StoreCtx storeCtx = _ctx.QueryCtx; Debug.Assert(storeCtx != null); // The underlying context must actually support search (i.e., no MSAM/reg-SAM) if (storeCtx.SupportsSearchNatively == false) throw new InvalidOperationException(SR.PrincipalSearcherNoUnderlying); return storeCtx.SearcherNativeType(); } public virtual void Dispose() { if (!_disposed) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalSearcher", "Dispose: disposing"); if ((this.UnderlyingSearcher != null) && (this.UnderlyingSearcher is IDisposable)) { GlobalDebug.WriteLineIf( GlobalDebug.Info, "PrincipalSearcher", "Dispose: disposing underlying searcher of type " + this.UnderlyingSearcher.GetType().ToString()); ((IDisposable)this.UnderlyingSearcher).Dispose(); } _disposed = true; GC.SuppressFinalize(this); } } // // Private implementation // private PrincipalContext _ctx; // Are we disposed? private bool _disposed = false; // Directly corresponds to the PrincipalSearcher.QueryFilter property. // Null means "return all principals". private Principal _qbeFilter; // The default page size to use. This value is automatically set // whenever a PrincipalContext is assigned to this object. private int _pageSize = 0; internal int PageSize { get { return _pageSize; } } // The underlying searcher (e.g., DirectorySearcher) corresponding to this PrincipalSearcher. // Set by StoreCtx. PushFilterToNativeSearcher(), based on the qbeFilter. // If not set, either there is no underlying searcher (SAM), or PushFilterToNativeSearcher has not // yet been called. private object _underlyingSearcher = null; internal object UnderlyingSearcher { get { return _underlyingSearcher; } set { _underlyingSearcher = value; } } // The core search method. // This method validates that a PrincipalContext has been set on the searcher and that the QBE // filter, if supplied, has no referential properties set. // // For the ctx.QueryCtx, calls StoreCtx.Query to perform the query and retrieve a // ResultSet representing the results of that query. // Then constructs a FindResult<Principal>, passing it the collection of one or more ResultSets. // // Returns at most one result in the FindResult<Principal> if returnOne == true, no limit on results // returned otherwise. private PrincipalSearchResult<Principal> FindAll(bool returnOne) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalSearcher", "Entering FindAll, returnOne=" + returnOne.ToString()); if (_qbeFilter == null) throw new InvalidOperationException(SR.PrincipalSearcherMustSetFilter); // Double-check that the Principal isn't persisted. We don't allow them to assign a persisted // Principal as the filter, but they could have persisted it after assigning it to the QueryFilter // property. if (!_qbeFilter.unpersisted) throw new InvalidOperationException(SR.PrincipalSearcherPersistedPrincipal); // Validate the QBE filter: make sure it doesn't have any non-scalar properties set. if (HasReferentialPropertiesSet()) throw new InvalidOperationException(SR.PrincipalSearcherNonReferentialProps); GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalSearcher", "FindAll: qbeFilter is non-null and passes"); ResultSet resultSet = _ctx.QueryCtx.Query(this, returnOne ? 1 : -1); PrincipalSearchResult<Principal> fr = new PrincipalSearchResult<Principal>(resultSet); return fr; } private void SetDefaultPageSizeForContext() { _pageSize = 0; if (_qbeFilter != null) { // If our context is AD-backed (has an ADStoreCtx), use pagesize of 256. // Otherwise, turn off paging. GlobalDebug.WriteLineIf( GlobalDebug.Info, "PrincipalSearcher", "SetDefaultPageSizeForContext: type is " + _ctx.QueryCtx.GetType().ToString()); if (_ctx.QueryCtx is ADStoreCtx) { // Found an AD context _pageSize = 256; } } return; } // Checks this.qbeFilter to determine if any referential properties are set private bool HasReferentialPropertiesSet() { // If using a null query filter, nothing to validate, as it can't have any referential // properties set. if (_qbeFilter == null) return false; // Since the QBE filter must be in the "unpersisted" state, any set properties have their changed // flag still set (qbeFilter.GetChangeStatusForProperty() == true). Therefore, checking which properties // have been set == checking which properties have their change flag set to true. Debug.Assert(_qbeFilter.unpersisted == true); // Retrieve the list of referential properties for this type of Principal. // If this type of Principal doesn't have any, the Properties hashtable will return null. Type t = _qbeFilter.GetType(); GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalSearcher", "HasReferentialPropertiesSet: using type " + t.ToString()); ArrayList referentialProperties = (ArrayList)ReferentialProperties.Properties[t]; if (referentialProperties != null) { foreach (string propertyName in referentialProperties) { if (_qbeFilter.GetChangeStatusForProperty(propertyName) == true) { // Property was set. GlobalDebug.WriteLineIf(GlobalDebug.Warn, "PrincipalSearcher", "HasReferentialPropertiesSet: found ref property " + propertyName); return true; } } } return false; } // Checks if the principal searcher has been disposed, and throws an appropriate exception if it has. private void CheckDisposed() { if (_disposed) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "PrincipalSearcher", "CheckDisposed: accessing disposed object"); throw new ObjectDisposedException(this.GetType().ToString()); } } } }
// // Copyright (c) 2017 The nanoFramework project contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // using CorDebugInterop; using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace nanoFramework.Tools.VisualStudio.Extension { public class ManagedCallbacks { public abstract class ManagedCallback { public abstract void Dispatch(ICorDebugManagedCallback callback); } public class ManagedCallbackThread : ManagedCallback { public enum EventType { CreateThread, ExitThread, NameChange, Other, } protected CorDebugThread m_thread; private EventType m_eventType; protected bool m_fSuspendThreadEvents; public ManagedCallbackThread(CorDebugThread thread, EventType eventType) { //breakpoints can happen on virtual threads.. m_thread = thread.GetRealCorDebugThread(); m_eventType = eventType; m_fSuspendThreadEvents = (m_eventType == EventType.CreateThread); } public ManagedCallbackThread(CorDebugThread thread) : this(thread, EventType.Other) { } public CorDebugThread Thread { get { return m_thread.GetRealCorDebugThread(); } } public sealed override void Dispatch( ICorDebugManagedCallback callback ) { bool fSuspendThreadEventsSav = m_thread.SuspendThreadEvents; try { m_thread.SuspendThreadEvents = m_fSuspendThreadEvents; DispatchThreadEvent( callback ); } finally { m_thread.SuspendThreadEvents = fSuspendThreadEventsSav; } } public virtual void DispatchThreadEvent(ICorDebugManagedCallback callback) { switch (m_eventType) { case EventType.CreateThread: callback.CreateThread(m_thread.AppDomain, m_thread); break; case EventType.ExitThread: callback.ExitThread(m_thread.AppDomain, m_thread); break; case EventType.NameChange: callback.NameChange(m_thread.AppDomain, m_thread); break; case EventType.Other: Debug.Assert(false, "Invalid ManagedCallbackThread event"); break; } } } public class ManagedCallbackBreakpoint : ManagedCallbackThread { protected CorDebugBreakpoint m_breakpoint; protected Type m_typeToMarshal; public ManagedCallbackBreakpoint(CorDebugThread thread, CorDebugBreakpoint breakpoint, Type typeToMarshal) : base(thread) { m_breakpoint = breakpoint; m_typeToMarshal = typeToMarshal; } public ManagedCallbackBreakpoint(CorDebugThread thread, CorDebugBreakpoint breakpoint) : this (thread, breakpoint, typeof(ICorDebugBreakpoint)) { } public override void DispatchThreadEvent(ICorDebugManagedCallback callback) { //HACK HACK HACK //This is an ugly hack. cdpe.dll expects the callback to Breakpoint to occur with the same IntPtr //that they received from a CreateBreakpoint method, which is likely a ICorDebugFunctionBreakpoint //(that's all there is implemented now at least) //The default interop code will marshal an ICorDebugBreakpoint, as the API says, which will not be equal //and will cause execution to break at the entryPoint. //Alternative fix is to change the interop assembly, since we don't support any breakpoints besides //ICorDebugFunctionBreakpoints as of yet, but this will do as well IntPtr pUnk = Marshal.GetComInterfaceForObject(m_breakpoint, m_typeToMarshal); callback.Breakpoint(m_thread.AppDomain, m_thread, pUnk); Marshal.Release(pUnk); } } public class ManagedCallbackDebugMessage : ManagedCallbackThread { private string m_switchName; private string m_message; private LoggingLevelEnum m_level; private CorDebugAppDomain m_appDomain; public ManagedCallbackDebugMessage(CorDebugThread thread, CorDebugAppDomain appDomain, string switchName, string message, LoggingLevelEnum level) : base (thread) { m_switchName = switchName; m_message = message; m_level = level; m_appDomain = appDomain; } public override void DispatchThreadEvent(ICorDebugManagedCallback callback) { callback.LogMessage(m_appDomain, m_thread, (int) m_level, m_switchName, m_message); } } public class ManagedCallbackBreakpointSetError : ManagedCallbackBreakpoint { uint m_error; public ManagedCallbackBreakpointSetError(CorDebugThread thread, CorDebugBreakpoint breakpoint, uint error) : base(thread, breakpoint) { m_error = error; } public override void DispatchThreadEvent(ICorDebugManagedCallback callback) { callback.BreakpointSetError(m_thread.AppDomain, m_thread, m_breakpoint, m_error); } } public class ManagedCallbackStepComplete : ManagedCallbackThread { CorDebugStepper m_stepper; CorDebugStepReason m_reason; public ManagedCallbackStepComplete(CorDebugThread thread, CorDebugStepper stepper, CorDebugStepReason reason) : base(thread) { m_stepper = stepper; m_reason = reason; } public override void DispatchThreadEvent(ICorDebugManagedCallback callback) { callback.StepComplete(m_thread.AppDomain, m_thread, m_stepper, m_reason); } } public class ManagedCallbackBreak : ManagedCallbackThread { public ManagedCallbackBreak(CorDebugThread thread) : base(thread) { } public override void DispatchThreadEvent(ICorDebugManagedCallback callback) { callback.Break(m_thread.AppDomain, m_thread); } } public class ManagedCallbackException : ManagedCallbackThread { CorDebugExceptionCallbackType m_type; CorDebugFrame m_frame; uint m_ip; public ManagedCallbackException(CorDebugThread thread, CorDebugFrame frame, uint ip, CorDebugExceptionCallbackType type) : base(thread) { m_type = type; m_frame = frame; m_ip = ip; if(!thread.Engine.Capabilities.ExceptionFilters) { m_fSuspendThreadEvents = (m_type == CorDebugExceptionCallbackType.DEBUG_EXCEPTION_FIRST_CHANCE) || (m_type == CorDebugExceptionCallbackType.DEBUG_EXCEPTION_USER_FIRST_CHANCE); } //Because we are now doing two-pass exception handling, the stack's IP isn't going to be the handler, so //we have to use the IP sent via the breakpointDef and not the stack frame. if (m_frame != null && m_frame.Function != null && m_frame.Function.HasSymbols) { m_ip = m_frame.Function.GetILCLRFromILnanoCLR(m_ip); } } public override void DispatchThreadEvent(ICorDebugManagedCallback callback) { ICorDebugManagedCallback2 callback2 = (ICorDebugManagedCallback2)callback; callback2.Exception( m_thread.AppDomain, m_thread, m_frame, m_ip, m_type, (uint)CorDebugExceptionFlags.DEBUG_EXCEPTION_CAN_BE_INTERCEPTED ); } } public class ManagedCallbackExceptionUnwind : ManagedCallbackThread { CorDebugExceptionUnwindCallbackType m_type; CorDebugFrame m_frame; public ManagedCallbackExceptionUnwind(CorDebugThread thread, CorDebugFrame frame, CorDebugExceptionUnwindCallbackType type) : base(thread) { Debug.Assert(type == CorDebugExceptionUnwindCallbackType.DEBUG_EXCEPTION_INTERCEPTED, "UnwindBegin is not supported"); m_type = type; m_frame = frame; } public override void DispatchThreadEvent(ICorDebugManagedCallback callback) { ((ICorDebugManagedCallback2)callback).ExceptionUnwind(m_thread.AppDomain, m_thread, m_type, 0); } } public class ManagedCallbackEval : ManagedCallbackThread { public new enum EventType { EvalComplete, EvalException } CorDebugEval m_eval; EventType m_eventType; public ManagedCallbackEval(CorDebugThread thread, CorDebugEval eval, EventType eventType) : base(thread) { m_eval = eval; m_eventType = eventType; } public override void DispatchThreadEvent(ICorDebugManagedCallback callback) { switch (m_eventType) { case EventType.EvalComplete: callback.EvalComplete(m_thread.AppDomain, m_thread, m_eval); break; case EventType.EvalException: callback.EvalException(m_thread.AppDomain, m_thread, m_eval); break; } } } public class ManagedCallbackProcess : ManagedCallback { public enum EventType { CreateProcess, ExitProcess, ControlCTrap, Other } protected CorDebugProcess m_process; EventType m_eventType; public ManagedCallbackProcess(CorDebugProcess process, EventType eventType) { m_process = process; m_eventType = eventType; } public override void Dispatch(ICorDebugManagedCallback callback) { switch (m_eventType) { case EventType.CreateProcess: callback.CreateProcess(m_process); break; case EventType.ExitProcess: callback.ExitProcess(m_process); break; case EventType.ControlCTrap: callback.ControlCTrap(m_process); break; case EventType.Other: Debug.Assert(false, "Invalid ManagedCallbackProcess event"); break; } } } public class ManagedCallbackProcessError : ManagedCallbackProcess { int m_errorHR; uint m_errorCode; public ManagedCallbackProcessError(CorDebugProcess process, int errorHR, uint errorCode) : base(process, EventType.Other) { m_errorHR = errorHR; m_errorCode = errorCode; } public override void Dispatch(ICorDebugManagedCallback callback) { callback.DebuggerError(m_process, m_errorHR, m_errorCode); } } public class ManagedCallbackAppDomain : ManagedCallback { public enum EventType { CreateAppDomain, ExitAppDomain, Other, } protected CorDebugAppDomain m_appDomain; EventType m_eventType; public ManagedCallbackAppDomain(CorDebugAppDomain appDomain, EventType eventType) { m_appDomain = appDomain; m_eventType = eventType; } public override void Dispatch(ICorDebugManagedCallback callback) { switch (m_eventType) { case EventType.CreateAppDomain: callback.CreateAppDomain(m_appDomain.Process, m_appDomain); break; case EventType.ExitAppDomain: callback.ExitAppDomain(m_appDomain.Process, m_appDomain); break; case EventType.Other: Debug.Assert(false, "Invalid ManagedCallbackAppDomain event"); break; } } } public class ManagedCallbackAssembly : ManagedCallback { public enum EventType { LoadAssembly, LoadModule, UnloadAssembly, UnloadModule } CorDebugAssembly m_assembly; EventType m_eventType; public ManagedCallbackAssembly(CorDebugAssembly assembly, EventType eventType) { m_assembly = assembly; m_eventType = eventType; } public override void Dispatch(ICorDebugManagedCallback callback) { switch (m_eventType) { case EventType.LoadAssembly: callback.LoadAssembly(m_assembly.AppDomain, m_assembly); break; case EventType.LoadModule: callback.LoadModule(m_assembly.AppDomain, m_assembly); break; case EventType.UnloadAssembly: callback.UnloadAssembly(m_assembly.AppDomain, m_assembly); break; case EventType.UnloadModule: callback.UnloadModule(m_assembly.AppDomain, m_assembly); break; } } } public class ManagedCallbackClass : ManagedCallback { public enum EventType { LoadClass, UnloadClass } CorDebugClass m_class; EventType m_eventType; public ManagedCallbackClass(CorDebugClass c, EventType eventType) { m_class = c; m_eventType = eventType; } public override void Dispatch(ICorDebugManagedCallback callback) { ICorDebugAppDomain appDomain = m_class.Assembly.AppDomain; switch (m_eventType) { case EventType.LoadClass: callback.LoadClass(appDomain, m_class); break; case EventType.UnloadClass: callback.UnloadClass(appDomain, m_class); break; } } } } }
using System; using System.Text; using System.Runtime.Serialization; using Newtonsoft.Json; using HETSAPI.Models; namespace HETSAPI.ViewModels { /// <summary> /// History View Model /// </summary> [DataContract] public sealed class HistoryViewModel : IEquatable<HistoryViewModel> { /// <summary> /// History View Model Constructor /// </summary> public HistoryViewModel() { } /// <summary> /// Initializes a new instance of the <see cref="HistoryViewModel" /> class. /// </summary> /// <param name="id">A system-generated unique identifier for a History (required).</param> /// <param name="historyText">The text of the history entry tracked against the related entity..</param> /// <param name="lastUpdateUserid">Audit information - SM User Id for the User who most recently updated the record..</param> /// <param name="lastUpdateTimestamp">Audit information - Timestamp for record modification.</param> /// <param name="affectedEntityId">The primary key of the affected record.</param> public HistoryViewModel(int id, string historyText = null, string lastUpdateUserid = null, DateTime? lastUpdateTimestamp = null, int? affectedEntityId = null) { Id = id; HistoryText = historyText; LastUpdateUserid = lastUpdateUserid; LastUpdateTimestamp = lastUpdateTimestamp; AffectedEntityId = affectedEntityId; } /// <summary> /// A system-generated unique identifier for a History /// </summary> /// <value>A system-generated unique identifier for a History</value> [DataMember(Name="id")] [MetaData (Description = "A system-generated unique identifier for a History")] public int Id { get; set; } /// <summary> /// The text of the history entry tracked against the related entity. /// </summary> /// <value>The text of the history entry tracked against the related entity.</value> [DataMember(Name="historyText")] [MetaData (Description = "The text of the history entry tracked against the related entity.")] public string HistoryText { get; set; } /// <summary> /// Audit information - SM User Id for the User who most recently updated the record. /// </summary> /// <value>Audit information - SM User Id for the User who most recently updated the record.</value> [DataMember(Name="lastUpdateUserid")] [MetaData (Description = "Audit information - SM User Id for the User who most recently updated the record.")] public string LastUpdateUserid { get; set; } /// <summary> /// Audit information - Timestamp for record modification /// </summary> /// <value>Audit information - Timestamp for record modification</value> [DataMember(Name="lastUpdateTimestamp")] [MetaData (Description = "Audit information - Timestamp for record modification")] public DateTime? LastUpdateTimestamp { get; set; } /// <summary> /// The primary key of the affected record /// </summary> /// <value>The primary key of the affected record</value> [DataMember(Name="affectedEntityId")] [MetaData (Description = "The primary key of the affected record")] public int? AffectedEntityId { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class HistoryViewModel {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" HistoryText: ").Append(HistoryText).Append("\n"); sb.Append(" LastUpdateUserid: ").Append(LastUpdateUserid).Append("\n"); sb.Append(" LastUpdateTimestamp: ").Append(LastUpdateTimestamp).Append("\n"); sb.Append(" AffectedEntityId: ").Append(AffectedEntityId).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (obj is null) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj.GetType() == GetType() && Equals((HistoryViewModel)obj); } /// <summary> /// Returns true if HistoryViewModel instances are equal /// </summary> /// <param name="other">Instance of HistoryViewModel to be compared</param> /// <returns>Boolean</returns> public bool Equals(HistoryViewModel other) { if (other is null) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( Id == other.Id || Id.Equals(other.Id) ) && ( HistoryText == other.HistoryText || HistoryText != null && HistoryText.Equals(other.HistoryText) ) && ( LastUpdateUserid == other.LastUpdateUserid || LastUpdateUserid != null && LastUpdateUserid.Equals(other.LastUpdateUserid) ) && ( LastUpdateTimestamp == other.LastUpdateTimestamp || LastUpdateTimestamp != null && LastUpdateTimestamp.Equals(other.LastUpdateTimestamp) ) && ( AffectedEntityId == other.AffectedEntityId || AffectedEntityId != null && AffectedEntityId.Equals(other.AffectedEntityId) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks hash = hash * 59 + Id.GetHashCode(); if (HistoryText != null) { hash = hash * 59 + HistoryText.GetHashCode(); } if (LastUpdateUserid != null) { hash = hash * 59 + LastUpdateUserid.GetHashCode(); } if (LastUpdateTimestamp != null) { hash = hash * 59 + LastUpdateTimestamp.GetHashCode(); } if (AffectedEntityId != null) { hash = hash * 59 + AffectedEntityId.GetHashCode(); } return hash; } } #region Operators /// <summary> /// Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(HistoryViewModel left, HistoryViewModel right) { return Equals(left, right); } /// <summary> /// Not Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(HistoryViewModel left, HistoryViewModel right) { return !Equals(left, right); } #endregion Operators } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.IO; using System.Management.Automation; using Markdig; using Markdig.Renderers; using Markdig.Syntax; namespace Microsoft.PowerShell.MarkdownRender { /// <summary> /// Enum to name all the properties of PSMarkdownOptionInfo. /// </summary> public enum MarkdownOptionInfoProperty { /// <summary> /// Property name Header1. /// </summary> Header1, /// <summary> /// Property name Header2. /// </summary> Header2, /// <summary> /// Property name Header3. /// </summary> Header3, /// <summary> /// Property name Header4. /// </summary> Header4, /// <summary> /// Property name Header5. /// </summary> Header5, /// <summary> /// Property name Header6. /// </summary> Header6, /// <summary> /// Property name Code. /// </summary> Code, /// <summary> /// Property name Link. /// </summary> Link, /// <summary> /// Property name Image. /// </summary> Image, /// <summary> /// Property name EmphasisBold. /// </summary> EmphasisBold, /// <summary> /// Property name EmphasisItalics. /// </summary> EmphasisItalics } /// <summary> /// Class to represent color preference options for various Markdown elements. /// </summary> public sealed class PSMarkdownOptionInfo { private const char Esc = (char)0x1b; private const string EndSequence = "[0m"; /// <summary> /// Gets or sets current VT100 escape sequence for header 1. /// </summary> public string Header1 { get; set; } /// <summary> /// Gets or sets current VT100 escape sequence for header 2. /// </summary> public string Header2 { get; set; } /// <summary> /// Gets or sets current VT100 escape sequence for header 3. /// </summary> public string Header3 { get; set; } /// <summary> /// Gets or sets current VT100 escape sequence for header 4. /// </summary> public string Header4 { get; set; } /// <summary> /// Gets or sets current VT100 escape sequence for header 5. /// </summary> public string Header5 { get; set; } /// <summary> /// Gets or sets current VT100 escape sequence for header 6. /// </summary> public string Header6 { get; set; } /// <summary> /// Gets or sets current VT100 escape sequence for code inline and code blocks. /// </summary> public string Code { get; set; } /// <summary> /// Gets or sets current VT100 escape sequence for links. /// </summary> public string Link { get; set; } /// <summary> /// Gets or sets current VT100 escape sequence for images. /// </summary> public string Image { get; set; } /// <summary> /// Gets or sets current VT100 escape sequence for bold text. /// </summary> public string EmphasisBold { get; set; } /// <summary> /// Gets or sets current VT100 escape sequence for italics text. /// </summary> public string EmphasisItalics { get; set; } /// <summary> /// Gets or sets a value indicating whether VT100 escape sequences should be added. Default it true. /// </summary> public bool EnableVT100Encoding { get; set; } /// <summary> /// Get the property as an rendered escape sequence. /// This is used by formatting system for displaying. /// </summary> /// <param name="propertyName">Name of the property to get as escape sequence.</param> /// <returns>Specified property name as escape sequence.</returns> public string AsEscapeSequence(MarkdownOptionInfoProperty propertyName) { switch (propertyName) { case MarkdownOptionInfoProperty.Header1: return string.Concat(Esc, Header1, Header1, Esc, EndSequence); case MarkdownOptionInfoProperty.Header2: return string.Concat(Esc, Header2, Header2, Esc, EndSequence); case MarkdownOptionInfoProperty.Header3: return string.Concat(Esc, Header3, Header3, Esc, EndSequence); case MarkdownOptionInfoProperty.Header4: return string.Concat(Esc, Header4, Header4, Esc, EndSequence); case MarkdownOptionInfoProperty.Header5: return string.Concat(Esc, Header5, Header5, Esc, EndSequence); case MarkdownOptionInfoProperty.Header6: return string.Concat(Esc, Header6, Header6, Esc, EndSequence); case MarkdownOptionInfoProperty.Code: return string.Concat(Esc, Code, Code, Esc, EndSequence); case MarkdownOptionInfoProperty.Link: return string.Concat(Esc, Link, Link, Esc, EndSequence); case MarkdownOptionInfoProperty.Image: return string.Concat(Esc, Image, Image, Esc, EndSequence); case MarkdownOptionInfoProperty.EmphasisBold: return string.Concat(Esc, EmphasisBold, EmphasisBold, Esc, EndSequence); case MarkdownOptionInfoProperty.EmphasisItalics: return string.Concat(Esc, EmphasisItalics, EmphasisItalics, Esc, EndSequence); default: break; } return null; } /// <summary> /// Initializes a new instance of the <see cref="PSMarkdownOptionInfo"/> class and sets dark as the default theme. /// </summary> public PSMarkdownOptionInfo() { SetDarkTheme(); EnableVT100Encoding = true; } private const string Header1Dark = "[7m"; private const string Header2Dark = "[4;93m"; private const string Header3Dark = "[4;94m"; private const string Header4Dark = "[4;95m"; private const string Header5Dark = "[4;96m"; private const string Header6Dark = "[4;97m"; private const string CodeDark = "[48;2;155;155;155;38;2;30;30;30m"; private const string CodeMacOS = "[107;95m"; private const string LinkDark = "[4;38;5;117m"; private const string ImageDark = "[33m"; private const string EmphasisBoldDark = "[1m"; private const string EmphasisItalicsDark = "[36m"; private const string Header1Light = "[7m"; private const string Header2Light = "[4;33m"; private const string Header3Light = "[4;34m"; private const string Header4Light = "[4;35m"; private const string Header5Light = "[4;36m"; private const string Header6Light = "[4;30m"; private const string CodeLight = "[48;2;155;155;155;38;2;30;30;30m"; private const string LinkLight = "[4;38;5;117m"; private const string ImageLight = "[33m"; private const string EmphasisBoldLight = "[1m"; private const string EmphasisItalicsLight = "[36m"; /// <summary> /// Set all preference for dark theme. /// </summary> public void SetDarkTheme() { Header1 = Header1Dark; Header2 = Header2Dark; Header3 = Header3Dark; Header4 = Header4Dark; Header5 = Header5Dark; Header6 = Header6Dark; Link = LinkDark; Image = ImageDark; EmphasisBold = EmphasisBoldDark; EmphasisItalics = EmphasisItalicsDark; SetCodeColor(isDarkTheme: true); } /// <summary> /// Set all preference for light theme. /// </summary> public void SetLightTheme() { Header1 = Header1Light; Header2 = Header2Light; Header3 = Header3Light; Header4 = Header4Light; Header5 = Header5Light; Header6 = Header6Light; Link = LinkLight; Image = ImageLight; EmphasisBold = EmphasisBoldLight; EmphasisItalics = EmphasisItalicsLight; SetCodeColor(isDarkTheme: false); } private void SetCodeColor(bool isDarkTheme) { // MacOS terminal app does not support extended colors for VT100, so we special case for it. Code = Platform.IsMacOS ? CodeMacOS : isDarkTheme ? CodeDark : CodeLight; } } /// <summary> /// Class to represent default VT100 escape sequences. /// </summary> public class VT100EscapeSequences { private const char Esc = (char)0x1B; private string endSequence = Esc + "[0m"; // For code blocks, [500@ make sure that the whole line has background color. private const string LongBackgroundCodeBlock = "[500@"; private PSMarkdownOptionInfo options; /// <summary> /// Initializes a new instance of the <see cref="VT100EscapeSequences"/> class. /// </summary> /// <param name="optionInfo">PSMarkdownOptionInfo object to initialize with.</param> public VT100EscapeSequences(PSMarkdownOptionInfo optionInfo) { if (optionInfo == null) { throw new ArgumentNullException("optionInfo"); } options = optionInfo; } /// <summary> /// Class to represent default VT100 escape sequences. /// </summary> /// <param name="headerText">Text of the header to format.</param> /// <returns>Formatted Header 1 string.</returns> public string FormatHeader1(string headerText) { return FormatHeader(headerText, options.Header1); } /// <summary> /// Class to represent default VT100 escape sequences. /// </summary> /// <param name="headerText">Text of the header to format.</param> /// <returns>Formatted Header 2 string.</returns> public string FormatHeader2(string headerText) { return FormatHeader(headerText, options.Header2); } /// <summary> /// Class to represent default VT100 escape sequences. /// </summary> /// <param name="headerText">Text of the header to format.</param> /// <returns>Formatted Header 3 string.</returns> public string FormatHeader3(string headerText) { return FormatHeader(headerText, options.Header3); } /// <summary> /// Class to represent default VT100 escape sequences. /// </summary> /// <param name="headerText">Text of the header to format.</param> /// <returns>Formatted Header 4 string.</returns> public string FormatHeader4(string headerText) { return FormatHeader(headerText, options.Header4); } /// <summary> /// Class to represent default VT100 escape sequences. /// </summary> /// <param name="headerText">Text of the header to format.</param> /// <returns>Formatted Header 5 string.</returns> public string FormatHeader5(string headerText) { return FormatHeader(headerText, options.Header5); } /// <summary> /// Class to represent default VT100 escape sequences. /// </summary> /// <param name="headerText">Text of the header to format.</param> /// <returns>Formatted Header 6 string.</returns> public string FormatHeader6(string headerText) { return FormatHeader(headerText, options.Header6); } /// <summary> /// Class to represent default VT100 escape sequences. /// </summary> /// <param name="codeText">Text of the code block to format.</param> /// <param name="isInline">True if it is a inline code block, false otherwise.</param> /// <returns>Formatted code block string.</returns> public string FormatCode(string codeText, bool isInline) { bool isVT100Enabled = options.EnableVT100Encoding; if (isInline) { if (isVT100Enabled) { return string.Concat(Esc, options.Code, codeText, endSequence); } else { return codeText; } } else { if (isVT100Enabled) { return string.Concat(Esc, options.Code, codeText, Esc, LongBackgroundCodeBlock, endSequence); } else { return codeText; } } } /// <summary> /// Class to represent default VT100 escape sequences. /// </summary> /// <param name="linkText">Text of the link to format.</param> /// <param name="url">URL of the link.</param> /// <param name="hideUrl">True url should be hidden, false otherwise. Default is true.</param> /// <returns>Formatted link string.</returns> public string FormatLink(string linkText, string url, bool hideUrl = true) { bool isVT100Enabled = options.EnableVT100Encoding; if (hideUrl) { if (isVT100Enabled) { return string.Concat(Esc, options.Link, "\"", linkText, "\"", endSequence); } else { return string.Concat("\"", linkText, "\""); } } else { if (isVT100Enabled) { return string.Concat("\"", linkText, "\" (", Esc, options.Link, url, endSequence, ")"); } else { return string.Concat("\"", linkText, "\" (", url, ")"); } } } /// <summary> /// Class to represent default VT100 escape sequences. /// </summary> /// <param name="emphasisText">Text to format as emphasis.</param> /// <param name="isBold">True if it is to be formatted as bold, false to format it as italics.</param> /// <returns>Formatted emphasis string.</returns> public string FormatEmphasis(string emphasisText, bool isBold) { var sequence = isBold ? options.EmphasisBold : options.EmphasisItalics; if (options.EnableVT100Encoding) { return string.Concat(Esc, sequence, emphasisText, endSequence); } else { return emphasisText; } } /// <summary> /// Class to represent default VT100 escape sequences. /// </summary> /// <param name="altText">Text of the image to format.</param> /// <returns>Formatted image string.</returns> public string FormatImage(string altText) { var text = altText; if (string.IsNullOrEmpty(altText)) { text = "Image"; } if (options.EnableVT100Encoding) { return string.Concat(Esc, options.Image, "[", text, "]", endSequence); } else { return string.Concat("[", text, "]"); } } private string FormatHeader(string headerText, string headerEscapeSequence) { if (options.EnableVT100Encoding) { return string.Concat(Esc, headerEscapeSequence, headerText, endSequence); } else { return headerText; } } } }
/* * Copyright (c) 2007-2008, openmetaverse.org * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Drawing; using OpenMetaverse.Assets; namespace OpenMetaverse.Imaging { /// <summary> /// A set of textures that are layered on texture of each other and "baked" /// in to a single texture, for avatar appearances /// </summary> public class Baker { #region Properties /// <summary>Final baked texture</summary> public AssetTexture BakedTexture { get { return bakedTexture; } } /// <summary>Component layers</summary> public List<AppearanceManager.TextureData> Textures { get { return textures; } } /// <summary>Width of the final baked image and scratchpad</summary> public int BakeWidth { get { return bakeWidth; } } /// <summary>Height of the final baked image and scratchpad</summary> public int BakeHeight { get { return bakeHeight; } } /// <summary>Bake type</summary> public BakeType BakeType { get { return bakeType; } } /// <summary>Is this one of the 3 skin bakes</summary> private bool IsSkin { get { return bakeType == BakeType.Head || bakeType == BakeType.LowerBody || bakeType == BakeType.UpperBody; } } #endregion #region Private fields /// <summary>Final baked texture</summary> private AssetTexture bakedTexture; /// <summary>Component layers</summary> private List<AppearanceManager.TextureData> textures = new List<AppearanceManager.TextureData>(); /// <summary>Width of the final baked image and scratchpad</summary> private int bakeWidth; /// <summary>Height of the final baked image and scratchpad</summary> private int bakeHeight; /// <summary>Bake type</summary> private BakeType bakeType; #endregion #region Constructor /// <summary> /// Default constructor /// </summary> /// <param name="bakeType">Bake type</param> public Baker(BakeType bakeType) { this.bakeType = bakeType; if (bakeType == BakeType.Eyes) { bakeWidth = 128; bakeHeight = 128; } else { bakeWidth = 512; bakeHeight = 512; } } #endregion #region Public methods /// <summary> /// Adds layer for baking /// </summary> /// <param name="tdata">TexturaData struct that contains texture and its params</param> public void AddTexture(AppearanceManager.TextureData tdata) { lock (textures) { textures.Add(tdata); } } public void Bake() { bakedTexture = new AssetTexture(new ManagedImage(bakeWidth, bakeHeight, ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha | ManagedImage.ImageChannels.Bump)); // Base color for eye bake is white, color of layer0 for others if (bakeType == BakeType.Eyes) { InitBakedLayerColor(Color4.White); } else if (textures.Count > 0) { InitBakedLayerColor(textures[0].Color); } // Do we have skin texture? bool SkinTexture = textures.Count > 0 && textures[0].Texture != null; if (bakeType == BakeType.Head) { DrawLayer(LoadResourceLayer("head_color.tga"), false); AddAlpha(bakedTexture.Image, LoadResourceLayer("head_alpha.tga")); MultiplyLayerFromAlpha(bakedTexture.Image, LoadResourceLayer("head_skingrain.tga")); } if (!SkinTexture && bakeType == BakeType.UpperBody) { DrawLayer(LoadResourceLayer("upperbody_color.tga"), false); } if (!SkinTexture && bakeType == BakeType.LowerBody) { DrawLayer(LoadResourceLayer("lowerbody_color.tga"), false); } ManagedImage alphaWearableTexture = null; // Layer each texture on top of one other, applying alpha masks as we go for (int i = 0; i < textures.Count; i++) { // Skip if we have no texture on this layer if (textures[i].Texture == null) continue; // Is this Alpha wearable and does it have an alpha channel? if (textures[i].TextureIndex >= AvatarTextureIndex.LowerAlpha && textures[i].TextureIndex <= AvatarTextureIndex.HairAlpha) { if (textures[i].Texture.Image.Alpha != null) { alphaWearableTexture = textures[i].Texture.Image.Clone(); } continue; } // Don't draw skin on head bake first // For head bake skin texture is drawn last, go figure if (bakeType == BakeType.Head && i == 0) continue; ManagedImage texture = textures[i].Texture.Image.Clone(); //File.WriteAllBytes(bakeType + "-texture-layer-" + i + ".tga", texture.ExportTGA()); // Resize texture to the size of baked layer // FIXME: if texture is smaller than the layer, don't stretch it, tile it if (texture.Width != bakeWidth || texture.Height != bakeHeight) { try { texture.ResizeNearestNeighbor(bakeWidth, bakeHeight); } catch (Exception) { continue; } } // Special case for hair layer for the head bake // If we don't have skin texture, we discard hair alpha // and apply hair pattern over the texture if (!SkinTexture && bakeType == BakeType.Head && i == 1) { if (texture.Alpha != null) { for (int j = 0; j < texture.Alpha.Length; j++) texture.Alpha[j] = (byte)255; } MultiplyLayerFromAlpha(texture, LoadResourceLayer("head_hair.tga")); } // Aply tint and alpha masks except for skin that has a texture // on layer 0 which always overrides other skin settings if (!(IsSkin && i == 0)) { ApplyTint(texture, textures[i].Color); // For hair bake, we skip all alpha masks // and use one from the texture, for both // alpha and morph layers if (bakeType == BakeType.Hair) { if (texture.Alpha != null) { bakedTexture.Image.Bump = texture.Alpha; } else { for (int j = 0; j < bakedTexture.Image.Bump.Length; j++) bakedTexture.Image.Bump[j] = byte.MaxValue; } } // Apply parametrized alpha masks else if (textures[i].AlphaMasks != null && textures[i].AlphaMasks.Count > 0) { // Combined mask for the layer, fully transparent to begin with ManagedImage combinedMask = new ManagedImage(bakeWidth, bakeHeight, ManagedImage.ImageChannels.Alpha); int addedMasks = 0; // First add mask in normal blend mode foreach (KeyValuePair<VisualAlphaParam, float> kvp in textures[i].AlphaMasks) { if (!MaskBelongsToBake(kvp.Key.TGAFile)) continue; if (kvp.Key.MultiplyBlend == false && (kvp.Value > 0f || !kvp.Key.SkipIfZero)) { ApplyAlpha(combinedMask, kvp.Key, kvp.Value); //File.WriteAllBytes(bakeType + "-layer-" + i + "-mask-" + addedMasks + ".tga", combinedMask.ExportTGA()); addedMasks++; } } // If there were no mask in normal blend mode make aplha fully opaque if (addedMasks == 0) for (int l = 0; l < combinedMask.Alpha.Length; l++) combinedMask.Alpha[l] = 255; // Add masks in multiply blend mode foreach (KeyValuePair<VisualAlphaParam, float> kvp in textures[i].AlphaMasks) { if (!MaskBelongsToBake(kvp.Key.TGAFile)) continue; if (kvp.Key.MultiplyBlend == true && (kvp.Value > 0f || !kvp.Key.SkipIfZero)) { ApplyAlpha(combinedMask, kvp.Key, kvp.Value); //File.WriteAllBytes(bakeType + "-layer-" + i + "-mask-" + addedMasks + ".tga", combinedMask.ExportTGA()); addedMasks++; } } if (addedMasks > 0) { // Apply combined alpha mask to the cloned texture AddAlpha(texture, combinedMask); // Is this layer used for morph mask? If it is, use its // alpha as the morth for the whole bake if (Textures[i].TextureIndex == AppearanceManager.MorphLayerForBakeType(bakeType)) { bakedTexture.Image.Bump = combinedMask.Alpha; } } //File.WriteAllBytes(bakeType + "-masked-texture-" + i + ".tga", texture.ExportTGA()); } } bool useAlpha = i == 0 && (BakeType == BakeType.Skirt || BakeType == BakeType.Hair); DrawLayer(texture, useAlpha); //File.WriteAllBytes(bakeType + "-layer-" + i + ".tga", texture.ExportTGA()); } // For head, we add skin last if (SkinTexture && bakeType == BakeType.Head) { ManagedImage texture = textures[0].Texture.Image.Clone(); if (texture.Width != bakeWidth || texture.Height != bakeHeight) { try { texture.ResizeNearestNeighbor(bakeWidth, bakeHeight); } catch (Exception) { } } DrawLayer(texture, false); } // Apply any alpha wearable textures to make parts of the avatar disappear if (alphaWearableTexture != null) { AddAlpha(bakedTexture.Image, alphaWearableTexture); } // We are done, encode asset for finalized bake bakedTexture.Encode(); //File.WriteAllBytes(bakeType + ".tga", bakedTexture.Image.ExportTGA()); } private static object ResourceSync = new object(); public static ManagedImage LoadResourceLayer(string fileName) { try { Bitmap bitmap = null; lock (ResourceSync) { using (Stream stream = Helpers.GetResourceStream(fileName, Settings.RESOURCE_DIR)) { bitmap = LoadTGAClass.LoadTGA(stream); } } if (bitmap == null) { Logger.Log(String.Format("Failed loading resource file: {0}", fileName), Helpers.LogLevel.Error); return null; } else { return new ManagedImage(bitmap); } } catch (Exception e) { Logger.Log(String.Format("Failed loading resource file: {0} ({1})", fileName, e.Message), Helpers.LogLevel.Error, e); return null; } } /// <summary> /// Converts avatar texture index (face) to Bake type /// </summary> /// <param name="index">Face number (AvatarTextureIndex)</param> /// <returns>BakeType, layer to which this texture belongs to</returns> public static BakeType BakeTypeFor(AvatarTextureIndex index) { switch (index) { case AvatarTextureIndex.HeadBodypaint: return BakeType.Head; case AvatarTextureIndex.UpperBodypaint: case AvatarTextureIndex.UpperGloves: case AvatarTextureIndex.UpperUndershirt: case AvatarTextureIndex.UpperShirt: case AvatarTextureIndex.UpperJacket: return BakeType.UpperBody; case AvatarTextureIndex.LowerBodypaint: case AvatarTextureIndex.LowerUnderpants: case AvatarTextureIndex.LowerSocks: case AvatarTextureIndex.LowerShoes: case AvatarTextureIndex.LowerPants: case AvatarTextureIndex.LowerJacket: return BakeType.LowerBody; case AvatarTextureIndex.EyesIris: return BakeType.Eyes; case AvatarTextureIndex.Skirt: return BakeType.Skirt; case AvatarTextureIndex.Hair: return BakeType.Hair; default: return BakeType.Unknown; } } #endregion #region Private layer compositing methods private bool MaskBelongsToBake(string mask) { if ((bakeType == BakeType.LowerBody && mask.Contains("upper")) || (bakeType == BakeType.LowerBody && mask.Contains("shirt")) || (bakeType == BakeType.UpperBody && mask.Contains("lower"))) { return false; } else { return true; } } private bool DrawLayer(ManagedImage source, bool addSourceAlpha) { if (source == null) return false; bool sourceHasColor; bool sourceHasAlpha; bool sourceHasBump; int i = 0; sourceHasColor = ((source.Channels & ManagedImage.ImageChannels.Color) != 0 && source.Red != null && source.Green != null && source.Blue != null); sourceHasAlpha = ((source.Channels & ManagedImage.ImageChannels.Alpha) != 0 && source.Alpha != null); sourceHasBump = ((source.Channels & ManagedImage.ImageChannels.Bump) != 0 && source.Bump != null); addSourceAlpha = (addSourceAlpha && sourceHasAlpha); byte alpha = Byte.MaxValue; byte alphaInv = (byte)(Byte.MaxValue - alpha); byte[] bakedRed = bakedTexture.Image.Red; byte[] bakedGreen = bakedTexture.Image.Green; byte[] bakedBlue = bakedTexture.Image.Blue; byte[] bakedAlpha = bakedTexture.Image.Alpha; byte[] bakedBump = bakedTexture.Image.Bump; byte[] sourceRed = source.Red; byte[] sourceGreen = source.Green; byte[] sourceBlue = source.Blue; byte[] sourceAlpha = sourceHasAlpha ? source.Alpha : null; byte[] sourceBump = sourceHasBump ? source.Bump : null; for (int y = 0; y < bakeHeight; y++) { for (int x = 0; x < bakeWidth; x++) { if (sourceHasAlpha) { alpha = sourceAlpha[i]; alphaInv = (byte)(Byte.MaxValue - alpha); } if (sourceHasColor) { bakedRed[i] = (byte)((bakedRed[i] * alphaInv + sourceRed[i] * alpha) >> 8); bakedGreen[i] = (byte)((bakedGreen[i] * alphaInv + sourceGreen[i] * alpha) >> 8); bakedBlue[i] = (byte)((bakedBlue[i] * alphaInv + sourceBlue[i] * alpha) >> 8); } if (addSourceAlpha) { if (sourceAlpha[i] < bakedAlpha[i]) { bakedAlpha[i] = sourceAlpha[i]; } } if (sourceHasBump) bakedBump[i] = sourceBump[i]; ++i; } } return true; } /// <summary> /// Make sure images exist, resize source if needed to match the destination /// </summary> /// <param name="dest">Destination image</param> /// <param name="src">Source image</param> /// <returns>Sanitization was succefull</returns> private bool SanitizeLayers(ManagedImage dest, ManagedImage src) { if (dest == null || src == null) return false; if ((dest.Channels & ManagedImage.ImageChannels.Alpha) == 0) { dest.ConvertChannels(dest.Channels | ManagedImage.ImageChannels.Alpha); } if (dest.Width != src.Width || dest.Height != src.Height) { try { src.ResizeNearestNeighbor(dest.Width, dest.Height); } catch (Exception) { return false; } } return true; } private void ApplyAlpha(ManagedImage dest, VisualAlphaParam param, float val) { ManagedImage src = LoadResourceLayer(param.TGAFile); if (dest == null || src == null || src.Alpha == null) return; if ((dest.Channels & ManagedImage.ImageChannels.Alpha) == 0) { dest.ConvertChannels(ManagedImage.ImageChannels.Alpha | dest.Channels); } if (dest.Width != src.Width || dest.Height != src.Height) { try { src.ResizeNearestNeighbor(dest.Width, dest.Height); } catch (Exception) { return; } } for (int i = 0; i < dest.Alpha.Length; i++) { byte alpha = src.Alpha[i] <= ((1 - val) * 255) ? (byte)0 : (byte)255; if (param.MultiplyBlend) { dest.Alpha[i] = (byte)((dest.Alpha[i] * alpha) >> 8); } else { if (alpha > dest.Alpha[i]) { dest.Alpha[i] = alpha; } } } } private void AddAlpha(ManagedImage dest, ManagedImage src) { if (!SanitizeLayers(dest, src)) return; for (int i = 0; i < dest.Alpha.Length; i++) { if (src.Alpha[i] < dest.Alpha[i]) { dest.Alpha[i] = src.Alpha[i]; } } } private void MultiplyLayerFromAlpha(ManagedImage dest, ManagedImage src) { if (!SanitizeLayers(dest, src)) return; for (int i = 0; i < dest.Red.Length; i++) { dest.Red[i] = (byte)((dest.Red[i] * src.Alpha[i]) >> 8); dest.Green[i] = (byte)((dest.Green[i] * src.Alpha[i]) >> 8); dest.Blue[i] = (byte)((dest.Blue[i] * src.Alpha[i]) >> 8); } } private void ApplyTint(ManagedImage dest, Color4 src) { if (dest == null) return; for (int i = 0; i < dest.Red.Length; i++) { dest.Red[i] = (byte)((dest.Red[i] * Utils.FloatToByte(src.R, 0f, 1f)) >> 8); dest.Green[i] = (byte)((dest.Green[i] * Utils.FloatToByte(src.G, 0f, 1f)) >> 8); dest.Blue[i] = (byte)((dest.Blue[i] * Utils.FloatToByte(src.B, 0f, 1f)) >> 8); } } /// <summary> /// Fills a baked layer as a solid *appearing* color. The colors are /// subtly dithered on a 16x16 grid to prevent the JPEG2000 stage from /// compressing it too far since it seems to cause upload failures if /// the image is a pure solid color /// </summary> /// <param name="color">Color of the base of this layer</param> private void InitBakedLayerColor(Color4 color) { InitBakedLayerColor(color.R, color.G, color.B); } /// <summary> /// Fills a baked layer as a solid *appearing* color. The colors are /// subtly dithered on a 16x16 grid to prevent the JPEG2000 stage from /// compressing it too far since it seems to cause upload failures if /// the image is a pure solid color /// </summary> /// <param name="r">Red value</param> /// <param name="g">Green value</param> /// <param name="b">Blue value</param> private void InitBakedLayerColor(float r, float g, float b) { byte rByte = Utils.FloatToByte(r, 0f, 1f); byte gByte = Utils.FloatToByte(g, 0f, 1f); byte bByte = Utils.FloatToByte(b, 0f, 1f); byte rAlt, gAlt, bAlt; rAlt = rByte; gAlt = gByte; bAlt = bByte; if (rByte < Byte.MaxValue) rAlt++; else rAlt--; if (gByte < Byte.MaxValue) gAlt++; else gAlt--; if (bByte < Byte.MaxValue) bAlt++; else bAlt--; int i = 0; byte[] red = bakedTexture.Image.Red; byte[] green = bakedTexture.Image.Green; byte[] blue = bakedTexture.Image.Blue; byte[] alpha = bakedTexture.Image.Alpha; byte[] bump = bakedTexture.Image.Bump; for (int y = 0; y < bakeHeight; y++) { for (int x = 0; x < bakeWidth; x++) { if (((x ^ y) & 0x10) == 0) { red[i] = rAlt; green[i] = gByte; blue[i] = bByte; alpha[i] = Byte.MaxValue; bump[i] = 0; } else { red[i] = rByte; green[i] = gAlt; blue[i] = bAlt; alpha[i] = Byte.MaxValue; bump[i] = 0; } ++i; } } } #endregion } }
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // 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. // ----------------------------------------------------------------------------- // Original code from SlimDX project. // Greetings to SlimDX Group. Original code published with the following license: // ----------------------------------------------------------------------------- /* * Copyright (c) 2007-2011 SlimDX Group * * 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.Windows.Forms; using SharpDX.Windows; namespace SharpDX.Samples { /// <summary> /// Root clas for a Demo Application /// </summary> public abstract class DemoApp { private readonly DemoTime clock = new DemoTime(); private FormWindowState _currentFormWindowState; private bool _disposed; private Form _form; private float _frameAccumulator; private int _frameCount; private DemoConfiguration _demoConfiguration; /// <summary> /// Performs object finalization. /// </summary> ~DemoApp() { if (!_disposed) { Dispose(false); _disposed = true; } } /// <summary> /// Disposes of object resources. /// </summary> public void Dispose() { if (!_disposed) { Dispose(true); _disposed = true; } GC.SuppressFinalize(this); } /// <summary> /// Disposes of object resources. /// </summary> /// <param name = "disposeManagedResources">If true, managed resources should be /// disposed of in addition to unmanaged resources.</param> protected virtual void Dispose(bool disposeManagedResources) { if (disposeManagedResources) { if (_form != null) _form.Dispose(); } } /// <summary> /// Return the Handle to display to. /// </summary> protected IntPtr DisplayHandle { get { return _form.Handle; } } /// <summary> /// Gets the config. /// </summary> /// <value>The config.</value> public DemoConfiguration Config { get { return _demoConfiguration; } } /// <summary> /// Gets the number of seconds passed since the last frame. /// </summary> public float FrameDelta { get; private set; } /// <summary> /// Gets the number of seconds passed since the last frame. /// </summary> public float FramePerSecond { get; private set; } /// <summary> /// Create Form for this demo. /// </summary> /// <param name="config"></param> /// <returns></returns> protected virtual Form CreateForm(DemoConfiguration config) { return new RenderForm(config.Title) { ClientSize = new System.Drawing.Size(config.Width, config.Height) }; } /// <summary> /// Runs the demo with default presentation /// </summary> public void Run() { Run(new DemoConfiguration()); } /// <summary> /// Runs the demo. /// </summary> public void Run(DemoConfiguration demoConfiguration) { _demoConfiguration = demoConfiguration ?? new DemoConfiguration(); _form = CreateForm(_demoConfiguration); Initialize(_demoConfiguration); bool isFormClosed = false; bool formIsResizing = false; _form.MouseClick += HandleMouseClick; _form.KeyDown += HandleKeyDown; _form.KeyUp += HandleKeyUp; _form.Resize += (o, args) => { if (_form.WindowState != _currentFormWindowState) { HandleResize(o, args); } _currentFormWindowState = _form.WindowState; }; _form.ResizeBegin += (o, args) => { formIsResizing = true; }; _form.ResizeEnd += (o, args) => { formIsResizing = false; HandleResize(o, args); }; _form.Closed += (o, args) => { isFormClosed = true; }; LoadContent(); clock.Start(); BeginRun(); RenderLoop.Run(_form, () => { if (isFormClosed) { return; } OnUpdate(); if (!formIsResizing) Render(); }); UnloadContent(); EndRun(); // Dispose explicity Dispose(); } /// <summary> /// In a derived class, implements logic to initialize the sample. /// </summary> protected abstract void Initialize(DemoConfiguration demoConfiguration); protected virtual void LoadContent() { } protected virtual void UnloadContent() { } /// <summary> /// In a derived class, implements logic to update any relevant sample state. /// </summary> protected virtual void Update(DemoTime time) { } /// <summary> /// In a derived class, implements logic to render the sample. /// </summary> protected virtual void Draw(DemoTime time) { } protected virtual void BeginRun() { } protected virtual void EndRun() { } /// <summary> /// In a derived class, implements logic that should occur before all /// other rendering. /// </summary> protected virtual void BeginDraw() { } /// <summary> /// In a derived class, implements logic that should occur after all /// other rendering. /// </summary> protected virtual void EndDraw() { } /// <summary> /// Quits the sample. /// </summary> public void Exit() { _form.Close(); } /// <summary> /// Updates sample state. /// </summary> private void OnUpdate() { FrameDelta = (float)clock.Update(); Update(clock); } protected System.Drawing.Size RenderingSize { get { return _form.ClientSize; } } /// <summary> /// Renders the sample. /// </summary> private void Render() { _frameAccumulator += FrameDelta; ++_frameCount; if (_frameAccumulator >= 1.0f) { FramePerSecond = _frameCount / _frameAccumulator; _form.Text = _demoConfiguration.Title + " - FPS: " + FramePerSecond; _frameAccumulator = 0.0f; _frameCount = 0; } BeginDraw(); Draw(clock); EndDraw(); } protected virtual void MouseClick(MouseEventArgs e) { } protected virtual void KeyDown(KeyEventArgs e) { if (e.KeyCode == Keys.Escape) Exit(); } protected virtual void KeyUp(KeyEventArgs e) { } /// <summary> /// Handles a mouse click event. /// </summary> /// <param name = "sender">The sender.</param> /// <param name = "e">The <see cref = "System.Windows.Forms.MouseEventArgs" /> instance containing the event data.</param> private void HandleMouseClick(object sender, MouseEventArgs e) { MouseClick(e); } /// <summary> /// Handles a key down event. /// </summary> /// <param name = "sender">The sender.</param> /// <param name = "e">The <see cref = "System.Windows.Forms.KeyEventArgs" /> instance containing the event data.</param> private void HandleKeyDown(object sender, KeyEventArgs e) { KeyDown(e); } /// <summary> /// Handles a key up event. /// </summary> /// <param name = "sender">The sender.</param> /// <param name = "e">The <see cref = "System.Windows.Forms.KeyEventArgs" /> instance containing the event data.</param> private void HandleKeyUp(object sender, KeyEventArgs e) { KeyUp(e); } private void HandleResize(object sender, EventArgs e) { if (_form.WindowState == FormWindowState.Minimized) { return; } // UnloadContent(); //_configuration.WindowWidth = _form.ClientSize.Width; //_configuration.WindowHeight = _form.ClientSize.Height; //if( Context9 != null ) { // userInterfaceRenderer.Dispose(); // Context9.PresentParameters.BackBufferWidth = _configuration.WindowWidth; // Context9.PresentParameters.BackBufferHeight = _configuration.WindowHeight; // Context9.Device.Reset( Context9.PresentParameters ); // userInterfaceRenderer = new UserInterfaceRenderer9( Context9.Device, _form.ClientSize.Width, _form.ClientSize.Height ); //} else if( Context10 != null ) { // userInterfaceRenderer.Dispose(); // Context10.SwapChain.ResizeBuffers( 1, WindowWidth, WindowHeight, Context10.SwapChain.Description.ModeDescription.Format, Context10.SwapChain.Description.Flags ); // userInterfaceRenderer = new UserInterfaceRenderer10( Context10.Device, _form.ClientSize.Width, _form.ClientSize.Height ); //} // LoadContent(); } } }
using UnityEngine; using UnityEngine.Events; using System; using System.Collections.Generic; using UMA.PoseTools; namespace UMA.CharacterSystem { //A serialized version of DNAConverterBehaviour, so that we can include these settings in assetBundles, which cannot include their own scripts... //Uses DynamicUmaDna which can have Dynamic DNA Names based on a DynamicUmaDnaAsset - if there is no asset set DynamicUmaDna falls back to UMADnaHumanoid public class DynamicDNAConverterBehaviour : DynamicDNAConverterBehaviourBase { bool builtHashes = false; //the deafult list of BoneHashes based on UMADnaHumanoid but any UMA Bones can be added here and be modified by a Skeleton Modifier public List<HashListItem> hashList = new List<HashListItem>(); public List<SkeletonModifier> skeletonModifiers = new List<SkeletonModifier>(); public bool overallModifiersEnabled = true; public float overallScale = 1f; //public Vector2 heightModifiers = new Vector2(0.85f, 1.2f); [Tooltip("When Unity calculates the bounds it uses bounds based on the animation included when the mesh was exported. This can mean the bounds are not very 'tight' or go below the characters feet. Checking this will make the bounds tight to the characters head/feet. You can then use the 'BoundsPadding' option below to add extra space.")] public bool tightenBounds = true; [Tooltip("You can pad or tighten your bounds with these controls")] public Vector3 boundsAdjust = Vector3.zero; [Tooltip("The character Radius is used to calculate the fitting of the collider.")] public Vector2 radiusAdjust = new Vector2(0.23f,0); public Vector3 massModifiers = new Vector3(46f, 26f, 26f); public UMABonePose startingPose = null; [Range(0f,1f)] [Tooltip("Adjust the influence the StartingPose has on the mesh. Tip: This can be animated to morph your character!")] public float startingPoseWeight = 1f; private Dictionary<string, List<UnityAction<string, float>>> _dnaCallbackDelegates = new Dictionary<string, List<UnityAction<string, float>>>(); public DynamicDNAConverterBehaviour() { ApplyDnaAction = ApplyDynamicDnaAction; DNAType = typeof(DynamicUMADna); } public override void Prepare() { if (builtHashes) return; for (int i = 0; i < hashList.Count; i++) { hashList[i].hash = UMAUtils.StringToHash(hashList[i].hashName); } builtHashes = true; } /// <summary> /// Returns the set dnaTypeHash or generates one if not set /// </summary> /// <returns></returns> public override int DNATypeHash //we may not need this override since dnaTypeHash might never be 0 { get { if (dnaAsset != null) { return dnaAsset.dnaTypeHash; } else { Debug.LogWarning(this.name + " did not have a DNA Asset assigned. This is required for DynamicDnaConverters."); } return 0; } } public bool AddDnaCallbackDelegate(UnityAction<string, float> callback, string targetDnaName) { bool added = false; if (!_dnaCallbackDelegates.ContainsKey(targetDnaName)) { _dnaCallbackDelegates.Add(targetDnaName, new List<UnityAction<string, float>>()); _dnaCallbackDelegates[targetDnaName].Add(callback); added = true; } else { bool found = false; for(int i = 0; i < _dnaCallbackDelegates[targetDnaName].Count; i++) { if(_dnaCallbackDelegates[targetDnaName][i] == callback) { found = true; break; } } if (!found) { _dnaCallbackDelegates[targetDnaName].Add(callback); added = true; } } return added; } public bool RemoveDnaCallbackDelegate(UnityAction<string, float> callback, string targetDnaName) { bool removed = false; if (!_dnaCallbackDelegates.ContainsKey(targetDnaName)) { removed = true; } else { int removeIndex = -1; for (int i = 0; i < _dnaCallbackDelegates[targetDnaName].Count; i++) { if (_dnaCallbackDelegates[targetDnaName][i] == callback) { removeIndex = i; break; } } if (removeIndex > -1) { _dnaCallbackDelegates[targetDnaName].RemoveAt(removeIndex); if(_dnaCallbackDelegates[targetDnaName].Count == 0) { _dnaCallbackDelegates.Remove(targetDnaName); } removed = true; } } return removed; } public void ApplyDynamicDnaAction(UMAData umaData, UMASkeleton skeleton) { UpdateDynamicUMADnaBones(umaData, skeleton, false); ApplyDnaCallbackDelegates(umaData); } public void UpdateDynamicUMADnaBones(UMAData umaData, UMASkeleton skeleton, bool asReset = false) { UMADnaBase umaDna; //need to use the typehash umaDna = umaData.GetDna(DNATypeHash); if (umaDna == null || asReset == true) { umaDna = null; } //Make the DNAAssets match if they dont already... if(umaDna != null) if (((DynamicUMADnaBase)umaDna).dnaAsset != dnaAsset) { ((DynamicUMADnaBase)umaDna).dnaAsset = dnaAsset; } float overallScaleCalc = 0; //float lowerBackScale = 0; //bool overallScaleFound = false; //bool lowerBackScaleFound = false; for (int i = 0; i < skeletonModifiers.Count; i++) { skeletonModifiers[i].umaDNA = umaDna; var thisHash = (skeletonModifiers[i].hash != 0) ? skeletonModifiers[i].hash : GetHash(skeletonModifiers[i].hashName); //With these ValueX.x is the calculated value and ValueX.y is min and ValueX.z is max var thisValueX = skeletonModifiers[i].ValueX; var thisValueY = skeletonModifiers[i].ValueY; var thisValueZ = skeletonModifiers[i].ValueZ; if (skeletonModifiers[i].hashName == "Position" && skeletonModifiers[i].property == SkeletonModifier.SkeletonPropType.Scale) { //TODO eli added something for overall scale to RaceData- whats that supposed to do? var calcVal = thisValueX.x - skeletonModifiers[i].valuesX.val.value + overallScale; overallScaleCalc = Mathf.Clamp(calcVal, thisValueX.y, thisValueX.z); skeleton.SetScale(skeletonModifiers[i].hash, new Vector3(overallScaleCalc, overallScaleCalc, overallScaleCalc)); //overallScaleFound = true; //Debug.Log("overallScaleCalc was " + overallScaleCalc); } /*else if (skeletonModifiers[i].hashName == "LowerBack" && skeletonModifiers[i].property == SkeletonModifier.SkeletonPropType.Scale) { lowerBackScale = Mathf.Clamp(thisValueX.x, thisValueX.y, thisValueX.z); skeleton.SetScale(skeletonModifiers[i].hash, new Vector3(lowerBackScale, lowerBackScale, lowerBackScale)); lowerBackScaleFound = true; }*/ else if (skeletonModifiers[i].property == SkeletonModifier.SkeletonPropType.Position) { skeleton.SetPositionRelative(thisHash, new Vector3( Mathf.Clamp(thisValueX.x, thisValueX.y, thisValueX.z), Mathf.Clamp(thisValueY.x, thisValueY.y, thisValueY.z), Mathf.Clamp(thisValueZ.x, thisValueZ.y, thisValueZ.z))); } else if (skeletonModifiers[i].property == SkeletonModifier.SkeletonPropType.Rotation) { skeleton.SetRotationRelative(thisHash, Quaternion.Euler(new Vector3( Mathf.Clamp(thisValueX.x, thisValueX.y, thisValueX.z), Mathf.Clamp(thisValueY.x, thisValueY.y, thisValueY.z), Mathf.Clamp(thisValueZ.x, thisValueZ.y, thisValueZ.z))),1f); } else if (skeletonModifiers[i].property == SkeletonModifier.SkeletonPropType.Scale) { skeleton.SetScale(thisHash, new Vector3( Mathf.Clamp(thisValueX.x, thisValueX.y, thisValueX.z), Mathf.Clamp(thisValueY.x, thisValueY.y, thisValueY.z), Mathf.Clamp(thisValueZ.x, thisValueZ.y, thisValueZ.z))); } } if (startingPose != null && asReset == false) { for (int i = 0; i < startingPose.poses.Length; i++) { skeleton.Morph(startingPose.poses[i].hash, startingPose.poses[i].position, startingPose.poses[i].scale, startingPose.poses[i].rotation, startingPoseWeight); } } //overall modifiers //Try to use updated Bounds to set the height. if (overallModifiersEnabled && umaData.GetRenderer(0) != null) { if (umaData.rendererCount < 1) return; if (!umaData.GetRenderer(0).enabled) return; if(umaData.GetRenderer(0).localBounds.size.y == 0) return; var currentSMROffscreenSetting = umaData.GetRenderer(0).updateWhenOffscreen; Bounds newBounds; //for this to properly calculate if the character is in a scaled game object it needs to be moved into the root var umaTransform = umaData.transform; var oldParent = umaTransform.parent; var originalRot = umaTransform.localRotation; var originalPos = umaTransform.localPosition; //we also need to disable any collider that is on it so it doesn't hit anything when its moved var thisCollider = umaData.gameObject.GetComponent<Collider>(); bool thisColliderEnabled = false; if (thisCollider) { thisColliderEnabled = thisCollider.enabled; thisCollider.enabled = false; } //Now move into the root umaTransform.SetParent(null, false); umaTransform.localRotation = Quaternion.identity; umaTransform.localPosition = Vector3.zero; //Do the calculations umaData.GetRenderer(0).updateWhenOffscreen = true; newBounds = new Bounds(umaData.GetRenderer(0).localBounds.center, umaData.GetRenderer(0).localBounds.size); umaData.GetRenderer(0).updateWhenOffscreen = currentSMROffscreenSetting; //move it back umaTransform.SetParent(oldParent, false); umaTransform.localRotation = originalRot; umaTransform.localPosition = originalPos; //set any collider to its original setting if (thisCollider) thisCollider.enabled = thisColliderEnabled; //somehow the bounds end up beneath the floor i.e. newBounds.center.y - newBounds.extents.y is actually a minus number //tighten bounds fixes this if (tightenBounds) { Vector3 newCenter = new Vector3(newBounds.center.x, newBounds.center.y, newBounds.center.z); Vector3 newSize = new Vector3(newBounds.size.x, newBounds.size.y, newBounds.size.z); if (newBounds.center.y - newBounds.extents.y < 0) { var underAmount = newBounds.center.y - newBounds.extents.y; newSize.y = (newBounds.center.y * 2) - underAmount; newCenter.y = newSize.y / 2; } Bounds modifiedBounds = new Bounds(newCenter, newSize); newBounds = modifiedBounds; } //character height can be based on the resulting height umaData.characterHeight = newBounds.size.y * (1 + radiusAdjust.y); //radius could be based on the resulting width umaData.characterRadius = (newBounds.size.x * (radiusAdjust.x/*/2*/) + newBounds.size.z * (radiusAdjust.x /*/ 2*/)) /2; //then base the mass on a compond of those two modified by the mass modifiers values var radiusAsDNA = (umaData.characterRadius * 2) * overallScaleCalc; var radiusYAsDNA = ((1 + radiusAdjust.y) * 0.5f) * overallScaleCalc; umaData.characterMass = (massModifiers.x * overallScaleCalc) + massModifiers.y * radiusYAsDNA + massModifiers.z * radiusAsDNA; //add bounds padding if any was set if (boundsAdjust != Vector3.zero) { newBounds.Expand(boundsAdjust); } //set the padded bounds umaData.GetRenderer(0).localBounds = newBounds; } } public void ApplyDnaCallbackDelegates(UMAData umaData) { if (_dnaCallbackDelegates.Count == 0) return; UMADnaBase umaDna; //need to use the typehash umaDna = umaData.GetDna(DNATypeHash); if (umaDna.Count == 0) return; foreach(KeyValuePair<string, List<UnityAction<string, float>>> kp in _dnaCallbackDelegates) { for(int i = 0; i < kp.Value.Count; i++) { kp.Value[i].Invoke(kp.Key, (umaDna as DynamicUMADna).GetValue(kp.Key, true)); } } } /// <summary> /// Method to temporarily remove any dna from a Skeleton. Useful for getting bone values for pre and post dna (since the skeletons own unmodified values often dont *quite* match for some reason- I think because a recipes 0.5 values end up as 0.5019608 when they come out of binary) /// Or it could be that I need to change the way this outputs values maybe? /// </summary> /// <param name="umaData"></param> public void RemoveDNAChangesFromSkeleton(UMAData umaData) { //sending true makes all the starting values set to zero UpdateDynamicUMADnaBones(umaData, umaData.skeleton, true); } int GetHash(string hashName) { return hashList[hashList.FindIndex(s => s.hashName == hashName)].hash; } #region SPECIAL TYPES // a class for Bone hashes [Serializable] public class HashListItem { public string hashName = ""; public int hash = 0; public HashListItem() { } public HashListItem(string nameToAdd) { hashName = nameToAdd; hash = UMAUtils.StringToHash(nameToAdd); } public HashListItem(string nameToAdd, int hashToAdd) { hashName = nameToAdd; var thisHash = hashToAdd; if(thisHash == 0) thisHash = UMAUtils.StringToHash(nameToAdd); hash = thisHash; } } //The main Skeleton Modifier Class- contains child classes for defining values [Serializable] public class SkeletonModifier { public enum SkeletonPropType { Position, Rotation, Scale } public string hashName; public int hash; public SkeletonPropType property = SkeletonPropType.Position; public spVal valuesX; public spVal valuesY; public spVal valuesZ; [HideInInspector] public UMADnaBase umaDNA; protected Dictionary<SkeletonPropType, Vector3> skelAddDefaults = new Dictionary<SkeletonPropType, Vector3> { {SkeletonPropType.Position, new Vector3(0f,-0.1f, 0.1f) }, {SkeletonPropType.Rotation, new Vector3(0f,-360f, 360f) }, {SkeletonPropType.Scale, new Vector3(1f,0f, 5f) } }; public Vector3 ValueX { get { return valuesX.CalculateValue(umaDNA); } } public Vector3 ValueY { get { return valuesY.CalculateValue(umaDNA); } } public Vector3 ValueZ { get { return valuesZ.CalculateValue(umaDNA); } } public SkeletonModifier() { } public SkeletonModifier(string _hashName, int _hash, SkeletonPropType _propType) { hashName = _hashName; hash = _hash; property = _propType; valuesX = new spVal(skelAddDefaults[_propType]); valuesY = new spVal(skelAddDefaults[_propType]); valuesZ = new spVal(skelAddDefaults[_propType]); } public SkeletonModifier(SkeletonModifier importedModifier) { hashName = importedModifier.hashName; hash = importedModifier.hash; property = importedModifier.property; valuesX = importedModifier.valuesX; valuesY = importedModifier.valuesY; valuesZ = importedModifier.valuesZ; umaDNA = importedModifier.umaDNA; } //Skeleton Modifier Special Types [Serializable] public class spVal { public spValValue val; public float min = 1; public float max = 1; public spVal() { } public spVal(Vector3 startingVals) { val = new spValValue(); val.value = startingVals.x; min = startingVals.y; max = startingVals.z; } public Vector3 CalculateValue(UMADnaBase umaDNA) { var thisVal = new Vector3(); //val thisVal.x = val.CalculateValue(umaDNA); //valmin thisVal.y = min; //max thisVal.z = max; return thisVal; } //spVal Special Types [Serializable] public class spValValue { public float value = 0f; public List<spValModifier> modifiers = new List<spValModifier>(); public float CalculateValue(UMADnaBase umaDNA) { float thisVal = value; float modifierVal = 0; float tempModifierVal = 0; string dnaCombineMethod = ""; bool inModifierPair = false; if (modifiers.Count > 0) { for (int i = 0; i < modifiers.Count; i++) { if (modifiers[i].DNATypeName != "None" && (modifiers[i].modifier == spValModifier.spValModifierType.AddDNA || modifiers[i].modifier == spValModifier.spValModifierType.DivideDNA || modifiers[i].modifier == spValModifier.spValModifierType.MultiplyDNA || modifiers[i].modifier == spValModifier.spValModifierType.SubtractDNA)) { tempModifierVal = GetUmaDNAValue(modifiers[i].DNATypeName, umaDNA); tempModifierVal -= 0.5f; inModifierPair = true; if (modifiers[i].modifier == spValModifier.spValModifierType.AddDNA) { dnaCombineMethod = "Add"; } else if (modifiers[i].modifier == spValModifier.spValModifierType.DivideDNA) { dnaCombineMethod = "Divide"; } else if (modifiers[i].modifier == spValModifier.spValModifierType.MultiplyDNA) { dnaCombineMethod = "Multiply"; } else if (modifiers[i].modifier == spValModifier.spValModifierType.SubtractDNA) { dnaCombineMethod = "Subtract"; } } else { if (modifiers[i].modifier == spValModifier.spValModifierType.Add) { modifierVal += (tempModifierVal + modifiers[i].modifierValue); tempModifierVal = 0; inModifierPair = false; } else if (modifiers[i].modifier == spValModifier.spValModifierType.Divide) { modifierVal += (tempModifierVal / modifiers[i].modifierValue); tempModifierVal = 0; inModifierPair = false; } else if (modifiers[i].modifier == spValModifier.spValModifierType.Multiply) { modifierVal += (tempModifierVal * modifiers[i].modifierValue); tempModifierVal = 0; inModifierPair = false; } else if (modifiers[i].modifier == spValModifier.spValModifierType.Subtract) { modifierVal += (tempModifierVal - modifiers[i].modifierValue); tempModifierVal = 0; inModifierPair = false; } } if (modifierVal != 0 && inModifierPair == false) { if (dnaCombineMethod == "Add") { thisVal += modifierVal; } if (dnaCombineMethod == "Subtract") { thisVal -= modifierVal; } if (dnaCombineMethod == "Multiply") { thisVal *= modifierVal; } if (dnaCombineMethod == "Divide") { thisVal /= modifierVal; } modifierVal = 0; dnaCombineMethod = ""; } } //in the case of left/Right(Up)LegAdjust the umadna is subtracted from the result without being multiplied by anything //this accounts for the scenario where umaDna is left trailing with no correcponding add/subtract/multiply/divide multiplier if (tempModifierVal != 0 && inModifierPair != false) { if (dnaCombineMethod == "Add") { thisVal += tempModifierVal; } if (dnaCombineMethod == "Subtract") { thisVal -= tempModifierVal; } if (dnaCombineMethod == "Multiply") { thisVal *= tempModifierVal; } if (dnaCombineMethod == "Divide") { thisVal /= tempModifierVal; } dnaCombineMethod = ""; modifierVal = 0; tempModifierVal = 0; inModifierPair = false; } } return thisVal; } public float GetUmaDNAValue(string DNATypeName, UMADnaBase umaDnaIn) { if (umaDnaIn == null) return 0.5f; DynamicUMADnaBase umaDna = (DynamicUMADnaBase)umaDnaIn; float val = 0.5f; if (DNATypeName == "None" || umaDna == null) { return val; } val = umaDna.GetValue(DNATypeName,true);//implimented a 'failSilently' option here because recipes may have dna in that the dna asset no longer has return val; } //spValValue Special Types [Serializable] public class spValModifier { public enum spValModifierType { Add, Subtract, Multiply, Divide, AddDNA, SubtractDNA, MultiplyDNA, DivideDNA } public spValModifierType modifier = spValModifierType.Add; public string DNATypeName = ""; public float modifierValue = 0f; } } } } #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 BenchmarkDotNet.Attributes; using BenchmarkDotNet.Configs; using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Toolchains.CsProj; using BenchmarkDotNet.Toolchains.DotNetCli; using System.Buffers.Text; using System.IO; using System.Text.Formatting; namespace System.Text.JsonLab.Benchmarks { //[MemoryDiagnoser] //[DisassemblyDiagnoser(printPrologAndEpilog: true, recursiveDepth: 3)] [Config(typeof(ConfigWithCustomEnvVars))] public class JsonWriterPerf { private class ConfigWithCustomEnvVars : ManualConfig { private const string JitNoInline = "COMPlus_TieredCompilation"; public ConfigWithCustomEnvVars() { Add(Job.Core .With(new[] { new EnvironmentVariable(JitNoInline, "0") }) .WithWarmupCount(3) .WithTargetCount(5) .With(CsProjCoreToolchain.From(NetCoreAppSettings.NetCoreApp30))); } } private static readonly byte[] Message = Encoding.UTF8.GetBytes("message"); private static readonly byte[] HelloWorld = Encoding.UTF8.GetBytes("Hello, World!"); private static readonly byte[] ExtraArray = Encoding.UTF8.GetBytes("ExtraArray"); private static readonly byte[] First = Encoding.UTF8.GetBytes("first"); private static readonly byte[] John = Encoding.UTF8.GetBytes("John"); private static readonly byte[] FirNst = Encoding.UTF8.GetBytes("fir\nst"); private static readonly byte[] JohNn = Encoding.UTF8.GetBytes("Joh\nn"); private const int ExtraArraySize = 100; private const int BufferSize = 1024 + (ExtraArraySize * 64); private ArrayFormatterWrapper _arrayFormatterWrapper; private ArrayFormatter _arrayFormatter; private MemoryStream _memoryStream; private StreamWriter _streamWriter; private int[] _data; private byte[] _output; private long[] _longs; private int[] dataArray; private DateTime MyDate; [Params(false)] public bool Formatted; [Params(true)] public bool SkipValidation; [GlobalSetup] public void Setup() { _data = new int[ExtraArraySize]; Random rand = new Random(42); for (int i = 0; i < ExtraArraySize; i++) { _data[i] = rand.Next(-10000, 10000); } var buffer = new byte[BufferSize]; _memoryStream = new MemoryStream(buffer); _streamWriter = new StreamWriter(_memoryStream, new UTF8Encoding(false), BufferSize, true); _arrayFormatterWrapper = new ArrayFormatterWrapper(10000, SymbolTable.InvariantUtf8); _arrayFormatter = new ArrayFormatter(BufferSize, SymbolTable.InvariantUtf8); // To pass an initialBuffer to Utf8Json: // _output = new byte[BufferSize]; _output = null; var random = new Random(42); const int numberOfItems = 10; _longs = new long[numberOfItems]; _longs[0] = 0; _longs[1] = long.MaxValue; _longs[2] = long.MinValue; _longs[3] = 12345678901; _longs[4] = -12345678901; for (int i = 5; i < numberOfItems; i++) { long value = random.Next(int.MinValue, int.MaxValue); value += value < 0 ? int.MinValue : int.MaxValue; _longs[i] = value; } dataArray = new int[100]; for (int i = 0; i < 100; i++) dataArray[i] = 12345; MyDate = DateTime.Now; } //[Benchmark] public void WriterSystemTextJsonValues() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); json.WriteStartArray(Encoding.UTF8.GetBytes("numbers"), suppressEscaping: true); for (int i = 0; i < 100; i++) json.WriteNumberValue(12345); json.WriteEndArray(); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void WriterSystemTextJsonArrayValues() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); json.WriteNumberArray(Encoding.UTF8.GetBytes("numbers"), dataArray, suppressEscaping: true); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void WritePropertyValueSuppressEscaping() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); for (int i = 0; i < 100; i++) json.WriteString("first", "John", suppressEscaping: true); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void WritePropertyValueEscapeUnnecessarily() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); for (int i = 0; i < 100; i++) json.WriteString("first", "John", suppressEscaping: false); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void WritePropertyValueEscapingRequiredLarger() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); for (int i = 0; i < 100; i++) json.WriteString("fir\nstaaaa\naaaa", "Joh\nnaaaa\naaaa"); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void WritePropertyValueEscapingRequired() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); for (int i = 0; i < 100; i++) json.WriteString("fir\nst", "Joh\nn"); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void NewtonsoftSuppressEscaping() { using (var json = new Newtonsoft.Json.JsonTextWriter(GetWriter())) { json.Formatting = Formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None; json.WriteStartObject(); for (int i = 0; i < 100; i++) { json.WritePropertyName("first", escape: false); json.WriteValue("John"); } json.WriteEndObject(); } } //[Benchmark] public void NewtonsoftEscapeUnnecessarily() { using (var json = new Newtonsoft.Json.JsonTextWriter(GetWriter())) { json.Formatting = Formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None; json.WriteStartObject(); for (int i = 0; i < 100; i++) { json.WritePropertyName("first", escape: true); json.WriteValue("John"); } json.WriteEndObject(); } } //[Benchmark] public void NewtonsoftEscapingRequired() { using (var json = new Newtonsoft.Json.JsonTextWriter(GetWriter())) { json.Formatting = Formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None; json.WriteStartObject(); for (int i = 0; i < 100; i++) { json.WritePropertyName("fir\nst"); json.WriteValue("Joh\nn"); } json.WriteEndObject(); } } //[Benchmark] public void WriterSystemTextJsonBasicNoDefault() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); for (int i = 0; i < 100; i++) json.WriteString("first", "John"); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void Utf8JsonWriteString() { global::Utf8Json.JsonWriter json = new global::Utf8Json.JsonWriter(); json.WriteBeginObject(); for (int i = 0; i < 100; i++) { json.WritePropertyName("fir\nst"); json.WriteString("Joh\nn"); } json.WriteEndObject(); } //[Benchmark] public void Utf8JsonWriteStringRaw() { global::Utf8Json.JsonWriter json = new global::Utf8Json.JsonWriter(); byte[] first = global::Utf8Json.JsonWriter.GetEncodedPropertyName("fir\nst"); byte[] john = global::Utf8Json.JsonWriter.GetEncodedPropertyName("Joh\nn"); json.WriteBeginObject(); for (int i = 0; i < 100; i++) { json.WriteRaw(first); json.WriteNameSeparator(); json.WriteRaw(john); } json.WriteEndObject(); } //[Benchmark] public void WriteDateTimeUnescaped() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); for (int i = 0; i < 100; i++) json.WriteString(First, MyDate, suppressEscaping: true); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void WriteDateTimeUnescapedOverhead() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); for (int i = 0; i < 100; i++) json.WriteString(First, MyDate, suppressEscaping: false); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void WriteNullUnescapedUtf16() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); for (int i = 0; i < 100; i++) json.WriteNull("first", suppressEscaping: true); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void WriteBoolUnescapedUtf16() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); for (int i = 0; i < 100; i++) json.WriteBoolean("first", value: true, suppressEscaping: true); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void NewtonsoftBoolUnescaped() { using (var json = new Newtonsoft.Json.JsonTextWriter(GetWriter())) { json.Formatting = Formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None; json.WriteStartObject(); for (int i = 0; i < 100; i++) { json.WritePropertyName("first", escape: false); json.WriteValue(true); } json.WriteEndObject(); } } //[Benchmark] public void WriteNumberUnescapedUtf16() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); for (int i = 0; i < 100; i++) json.WriteNumber("first", value: 123456, suppressEscaping: true); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void NewtonsoftNumberUnescaped() { using (var json = new Newtonsoft.Json.JsonTextWriter(GetWriter())) { json.Formatting = Formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None; json.WriteStartObject(); for (int i = 0; i < 100; i++) { json.WritePropertyName("first", escape: false); json.WriteValue(123456); } json.WriteEndObject(); } } //[Benchmark] public void WriteNullUnescapedOverheadUtf16() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); for (int i = 0; i < 100; i++) json.WriteNull("first", suppressEscaping: false); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void NewtonsoftNullUnescaped() { using (var json = new Newtonsoft.Json.JsonTextWriter(GetWriter())) { json.Formatting = Formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None; json.WriteStartObject(); for (int i = 0; i < 100; i++) { json.WritePropertyName("first", escape: false); json.WriteValue((object)null); } json.WriteEndObject(); } } //[Benchmark] public void NewtonsoftNullUnescapedOverhead() { using (var json = new Newtonsoft.Json.JsonTextWriter(GetWriter())) { json.Formatting = Formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None; json.WriteStartObject(); for (int i = 0; i < 100; i++) { json.WritePropertyName("first", escape: true); json.WriteValue((object)null); } json.WriteEndObject(); } } //[Benchmark] public void WriteDateTimeUnescapedUtf16() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); for (int i = 0; i < 100; i++) json.WriteString("first", MyDate, suppressEscaping: true); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void WriteDateTimeUnescapedOverheadUtf16() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); for (int i = 0; i < 100; i++) json.WriteString("first", MyDate, suppressEscaping: false); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void NewtonsoftDateTimeUnescaped() { using (var json = new Newtonsoft.Json.JsonTextWriter(GetWriter())) { json.Formatting = Formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None; json.WriteStartObject(); for (int i = 0; i < 100; i++) { json.WritePropertyName("first", escape: false); json.WriteValue(MyDate); } json.WriteEndObject(); } } //[Benchmark] public void NewtonsoftDateTimeUnescapedOverhead() { using (var json = new Newtonsoft.Json.JsonTextWriter(GetWriter())) { json.Formatting = Formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None; json.WriteStartObject(); for (int i = 0; i < 100; i++) { json.WritePropertyName("first", escape: true); json.WriteValue(MyDate); } json.WriteEndObject(); } } //[Benchmark] public void WriterSystemTextJsonBasicUtf8Unescaped() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); for (int i = 0; i < 100; i++) json.WriteString(First, John, suppressEscaping: true); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void WriterSystemTextJsonBasicUtf8UnescapedSkip() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); for (int i = 0; i < 100; i++) json.WriteStringSkipEscape(First, John); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void WriterSystemTextJsonBasicUtf8UnescapedOverhead() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); for (int i = 0; i < 100; i++) json.WriteString(First, John, suppressEscaping: false); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void WriterSystemTextJsonBasicUtf8() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); for (int i = 0; i < 100; i++) json.WriteString(FirNst, JohNn); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void WriterSystemTextJsonBasicUtf8NoDefault() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); for (int i = 0; i < 100; i++) json.WriteString(First, John); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void WriterNewtonsoftBasic() { WriterNewtonsoftBasic(Formatted, GetWriter(), _data.AsSpan(0, 10)); } [Benchmark] public void SystemTextJson() { _arrayFormatterWrapper.Clear(); WriterSystemJsonBasic(Formatted, SkipValidation, _arrayFormatterWrapper, _data.AsSpan(0, 10)); } //[Benchmark] public void WriterUtf8JsonBasic() { WriterUtf8JsonBasic(_data.AsSpan(0, 10)); } //[Benchmark] public void WriterSystemTextJsonHelloWorld() { _arrayFormatterWrapper.Clear(); WriterSystemTextJsonHelloWorldUtf8(Formatted, _arrayFormatterWrapper); } //[Benchmark] public void WriteArray() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); json.WriteNumberArray(Message, _longs, suppressEscaping: true); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void WriteArrayLoop() { _arrayFormatterWrapper.Clear(); var state = new JsonWriterState(options: new JsonWriterOptions { Indented = Formatted, SkipValidation = SkipValidation }); var json = new Utf8JsonWriter2(_arrayFormatterWrapper, state); json.WriteStartObject(); json.WriteStartArray(Message, suppressEscaping: true); for (int i = 0; i < _longs.Length; i++) json.WriteNumberValue(_longs[i]); json.WriteEndArray(); json.WriteEndObject(); json.Flush(); } //[Benchmark] public void WriteArrayUtf8Json() { global::Utf8Json.JsonWriter json = new global::Utf8Json.JsonWriter(_output); json.WriteBeginObject(); json.WritePropertyName("message"); json.WriteBeginArray(); for (int i = 0; i < _longs.Length; i++) json.WriteInt64(_longs[i]); json.WriteEndArray(); json.WriteEndObject(); } //[Benchmark] public void WriteArrayNewtonsoft() { using (var json = new Newtonsoft.Json.JsonTextWriter(GetWriter())) { json.Formatting = Formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None; json.WriteStartObject(); json.WritePropertyName("message"); json.WriteStartArray(); for (var i = 0; i < _longs.Length; i++) { json.WriteValue(_longs[i]); } json.WriteEnd(); json.WriteEnd(); } } //[Benchmark] public void WriterNewtonsoftHelloWorld() { WriterNewtonsoftHelloWorld(Formatted, GetWriter()); } //[Benchmark] public void WriterUtf8JsonHelloWorld() { WriterUtf8JsonHelloWorldHelper(_output); } //[Benchmark] [Arguments(1)] [Arguments(2)] [Arguments(5)] [Arguments(10)] [Arguments(100)] [Arguments(1000)] [Arguments(10000)] [Arguments(100000)] [Arguments(1000000)] [Arguments(10000000)] public void WriterSystemTextJsonArrayOnly(int size) { _arrayFormatterWrapper.Clear(); WriterSystemTextJsonArrayOnlyUtf8(Formatted, _arrayFormatterWrapper, _data.AsSpan(0, size)); } //[Benchmark] [Arguments(1)] [Arguments(2)] [Arguments(5)] [Arguments(10)] [Arguments(100)] [Arguments(1000)] [Arguments(10000)] [Arguments(100000)] [Arguments(1000000)] [Arguments(10000000)] public void WriterUtf8JsonArrayOnly(int size) { WriterUtf8JsonArrayOnly(_data.AsSpan(0, size), _output); } private TextWriter GetWriter() { _memoryStream.Seek(0, SeekOrigin.Begin); return _streamWriter; } private static void WriterNewtonsoftBasic(bool formatted, TextWriter writer, ReadOnlySpan<int> data) { using (var json = new Newtonsoft.Json.JsonTextWriter(writer)) { json.Formatting = formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None; json.WriteStartObject(); json.WritePropertyName("age"); json.WriteValue(42); json.WritePropertyName("first"); json.WriteValue("John"); json.WritePropertyName("last"); json.WriteValue("Smith"); json.WritePropertyName("phoneNumbers"); json.WriteStartArray(); json.WriteValue("425-000-1212"); json.WriteValue("425-000-1213"); json.WriteEnd(); json.WritePropertyName("address"); json.WriteStartObject(); json.WritePropertyName("street"); json.WriteValue("1 Microsoft Way"); json.WritePropertyName("city"); json.WriteValue("Redmond"); json.WritePropertyName("zip"); json.WriteValue(98052); json.WriteEnd(); json.WritePropertyName("ExtraArray"); json.WriteStartArray(); for (var i = 0; i < data.Length; i++) { json.WriteValue(data[i]); } json.WriteEnd(); json.WriteEnd(); } } private static void WriterSystemJsonBasic(bool formatted, bool skipValidation, ArrayFormatterWrapper output, ReadOnlySpan<int> data) { var state = new JsonWriterState(options: new JsonWriterOptions { Indented = formatted, SkipValidation = skipValidation }); var json = new Utf8JsonWriter2(output, state); json.WriteStartObject(); json.WriteNumber("age", 42); json.WriteString("first", "John"); json.WriteString("last", "Smith"); json.WriteStartArray("phoneNumbers"); json.WriteStringValue("425-000-1212"); json.WriteStringValue("425-000-1213"); json.WriteEndArray(); json.WriteStartObject("address"); json.WriteString("street", "1 Microsoft Way"); json.WriteString("city", "Redmond"); json.WriteNumber("zip", 98052); json.WriteEndObject(); json.WriteStartArray("ExtraArray"); for (var i = 0; i < data.Length; i++) { json.WriteNumberValue(data[i]); } json.WriteEndArray(); json.WriteEndObject(); json.Flush(); } private static void WriterUtf8JsonBasic(ReadOnlySpan<int> data) { global::Utf8Json.JsonWriter json = new global::Utf8Json.JsonWriter(); json.WriteBeginObject(); json.WritePropertyName("age"); json.WriteInt32(42); json.WriteValueSeparator(); json.WritePropertyName("first"); json.WriteString("John"); json.WriteValueSeparator(); json.WritePropertyName("last"); json.WriteString("Smith"); json.WriteValueSeparator(); json.WritePropertyName("phoneNumbers"); json.WriteBeginArray(); json.WriteString("425-000-1212"); json.WriteValueSeparator(); json.WriteString("425-000-1213"); json.WriteEndArray(); json.WriteValueSeparator(); json.WritePropertyName("address"); json.WriteBeginObject(); json.WritePropertyName("street"); json.WriteString("1 Microsoft Way"); json.WriteValueSeparator(); json.WritePropertyName("city"); json.WriteString("Redmond"); json.WriteValueSeparator(); json.WritePropertyName("zip"); json.WriteInt32(98052); json.WriteEndObject(); json.WriteValueSeparator(); json.WritePropertyName("ExtraArray"); json.WriteBeginArray(); for (var i = 0; i < data.Length - 1; i++) { json.WriteInt32(data[i]); json.WriteValueSeparator(); } if (data.Length > 0) json.WriteInt32(data[data.Length - 1]); json.WriteEndArray(); json.WriteEndObject(); } private static void WriterSystemTextJsonHelloWorldUtf8(bool formatted, ArrayFormatterWrapper output) { var json = new Utf8JsonWriter<ArrayFormatterWrapper>(output, formatted); json.WriteObjectStart(); json.WriteAttributeUtf8(Message, HelloWorld); json.WriteObjectEnd(); json.Flush(); } private static void WriterNewtonsoftHelloWorld(bool formatted, TextWriter writer) { using (var json = new Newtonsoft.Json.JsonTextWriter(writer)) { json.Formatting = formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None; json.WriteStartObject(); json.WritePropertyName("message"); json.WriteValue("Hello, World!"); json.WriteEnd(); } } private static void WriterUtf8JsonHelloWorldHelper(byte[] output) { global::Utf8Json.JsonWriter json = new global::Utf8Json.JsonWriter(output); json.WriteBeginObject(); json.WritePropertyName("message"); json.WriteString("Hello, World!"); json.WriteEndObject(); } private static void WriterSystemTextJsonArrayOnlyUtf8(bool formatted, ArrayFormatterWrapper output, ReadOnlySpan<int> data) { var json = new Utf8JsonWriter<ArrayFormatterWrapper>(output, formatted); json.WriteArrayUtf8(ExtraArray, data); json.Flush(); } private static void WriterUtf8JsonArrayOnly(ReadOnlySpan<int> data, byte[] output) { global::Utf8Json.JsonWriter json = new global::Utf8Json.JsonWriter(output); json.WriteBeginArray(); json.WritePropertyName("ExtraArray"); for (var i = 0; i < data.Length - 1; i++) { json.WriteInt32(data[i]); json.WriteValueSeparator(); } if (data.Length > 0) json.WriteInt32(data[data.Length - 1]); json.WriteEndArray(); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// AssetVersionResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Serverless.V1.Service.Asset { public class AssetVersionResource : Resource { public sealed class VisibilityEnum : StringEnum { private VisibilityEnum(string value) : base(value) {} public VisibilityEnum() {} public static implicit operator VisibilityEnum(string value) { return new VisibilityEnum(value); } public static readonly VisibilityEnum Public = new VisibilityEnum("public"); public static readonly VisibilityEnum Private = new VisibilityEnum("private"); public static readonly VisibilityEnum Protected = new VisibilityEnum("protected"); } private static Request BuildReadRequest(ReadAssetVersionOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Serverless, "/v1/Services/" + options.PathServiceSid + "/Assets/" + options.PathAssetSid + "/Versions", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of all Asset Versions. /// </summary> /// <param name="options"> Read AssetVersion parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AssetVersion </returns> public static ResourceSet<AssetVersionResource> Read(ReadAssetVersionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<AssetVersionResource>.FromJson("asset_versions", response.Content); return new ResourceSet<AssetVersionResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of all Asset Versions. /// </summary> /// <param name="options"> Read AssetVersion parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AssetVersion </returns> public static async System.Threading.Tasks.Task<ResourceSet<AssetVersionResource>> ReadAsync(ReadAssetVersionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<AssetVersionResource>.FromJson("asset_versions", response.Content); return new ResourceSet<AssetVersionResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of all Asset Versions. /// </summary> /// <param name="pathServiceSid"> The SID of the Service to read the Asset Version resource from </param> /// <param name="pathAssetSid"> The SID of the Asset resource that is the parent of the Asset Version resources to read /// </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AssetVersion </returns> public static ResourceSet<AssetVersionResource> Read(string pathServiceSid, string pathAssetSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadAssetVersionOptions(pathServiceSid, pathAssetSid){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of all Asset Versions. /// </summary> /// <param name="pathServiceSid"> The SID of the Service to read the Asset Version resource from </param> /// <param name="pathAssetSid"> The SID of the Asset resource that is the parent of the Asset Version resources to read /// </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AssetVersion </returns> public static async System.Threading.Tasks.Task<ResourceSet<AssetVersionResource>> ReadAsync(string pathServiceSid, string pathAssetSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadAssetVersionOptions(pathServiceSid, pathAssetSid){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<AssetVersionResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<AssetVersionResource>.FromJson("asset_versions", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<AssetVersionResource> NextPage(Page<AssetVersionResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Serverless) ); var response = client.Request(request); return Page<AssetVersionResource>.FromJson("asset_versions", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<AssetVersionResource> PreviousPage(Page<AssetVersionResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Serverless) ); var response = client.Request(request); return Page<AssetVersionResource>.FromJson("asset_versions", response.Content); } private static Request BuildFetchRequest(FetchAssetVersionOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Serverless, "/v1/Services/" + options.PathServiceSid + "/Assets/" + options.PathAssetSid + "/Versions/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a specific Asset Version. /// </summary> /// <param name="options"> Fetch AssetVersion parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AssetVersion </returns> public static AssetVersionResource Fetch(FetchAssetVersionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Retrieve a specific Asset Version. /// </summary> /// <param name="options"> Fetch AssetVersion parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AssetVersion </returns> public static async System.Threading.Tasks.Task<AssetVersionResource> FetchAsync(FetchAssetVersionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Retrieve a specific Asset Version. /// </summary> /// <param name="pathServiceSid"> The SID of the Service to fetch the Asset Version resource from </param> /// <param name="pathAssetSid"> The SID of the Asset resource that is the parent of the Asset Version resource to fetch /// </param> /// <param name="pathSid"> The SID that identifies the Asset Version resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AssetVersion </returns> public static AssetVersionResource Fetch(string pathServiceSid, string pathAssetSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchAssetVersionOptions(pathServiceSid, pathAssetSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// Retrieve a specific Asset Version. /// </summary> /// <param name="pathServiceSid"> The SID of the Service to fetch the Asset Version resource from </param> /// <param name="pathAssetSid"> The SID of the Asset resource that is the parent of the Asset Version resource to fetch /// </param> /// <param name="pathSid"> The SID that identifies the Asset Version resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AssetVersion </returns> public static async System.Threading.Tasks.Task<AssetVersionResource> FetchAsync(string pathServiceSid, string pathAssetSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchAssetVersionOptions(pathServiceSid, pathAssetSid, pathSid); return await FetchAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a AssetVersionResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> AssetVersionResource object represented by the provided JSON </returns> public static AssetVersionResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<AssetVersionResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the Asset Version resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the Account that created the Asset Version resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The SID of the Service that the Asset Version resource is associated with /// </summary> [JsonProperty("service_sid")] public string ServiceSid { get; private set; } /// <summary> /// The SID of the Asset resource that is the parent of the Asset Version /// </summary> [JsonProperty("asset_sid")] public string AssetSid { get; private set; } /// <summary> /// The URL-friendly string by which the Asset Version can be referenced /// </summary> [JsonProperty("path")] public string Path { get; private set; } /// <summary> /// The access control that determines how the Asset Version can be accessed /// </summary> [JsonProperty("visibility")] [JsonConverter(typeof(StringEnumConverter))] public AssetVersionResource.VisibilityEnum Visibility { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the Asset Version resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The absolute URL of the Asset Version resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private AssetVersionResource() { } } }
using System; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using AllReady.Features.Login; using AllReady.Features.Manage; using AllReady.Models; using AllReady.Security; using AllReady.ViewModels.Manage; using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Routing; namespace AllReady.Controllers { [Authorize] public class ManageController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly IMediator _mediator; public ManageController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IMediator mediator) { _userManager = userManager; _signInManager = signInManager; _mediator = mediator; } // GET: /Manage/Index [HttpGet] public async Task<IActionResult> Index(ManageMessageId? message = null) { ViewData[STATUS_MESSAGE] = message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set." : message == ManageMessageId.Error ? ERROR_OCCURRED : message == ManageMessageId.AddPhoneSuccess ? "Your mobile phone number was added." : message == ManageMessageId.RemovePhoneSuccess ? "Your mobile phone number was removed." : ""; var user = await GetCurrentUser(); return View(await user.ToViewModel(_userManager, _signInManager)); } // POST: /Manage/Index [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Index(IndexViewModel model) { var shouldRefreshSignin = false; var user = await GetCurrentUser(); if (!ModelState.IsValid) { var viewModelWithInputs = await user.ToViewModel(_userManager, _signInManager); viewModelWithInputs.FirstName= model.FirstName; viewModelWithInputs.LastName = model.LastName; viewModelWithInputs.TimeZoneId = model.TimeZoneId; viewModelWithInputs.AssociatedSkills = model.AssociatedSkills; return View(viewModelWithInputs); } if (!string.IsNullOrEmpty(model.FirstName)) { user.FirstName= model.FirstName; shouldRefreshSignin = true; } if (!string.IsNullOrEmpty(model.LastName)) { user.LastName= model.LastName; shouldRefreshSignin = true; } if (user.TimeZoneId != model.TimeZoneId) { user.TimeZoneId = model.TimeZoneId; await _userManager.RemoveClaimsAsync(user, User.Claims.Where(c => c.Type == Security.ClaimTypes.TimeZoneId)); await _userManager.AddClaimAsync(user, new Claim(Security.ClaimTypes.TimeZoneId, user.TimeZoneId)); shouldRefreshSignin = true; } user.AssociatedSkills.RemoveAll(usk => model.AssociatedSkills == null || !model.AssociatedSkills.Any(msk => msk.SkillId == usk.SkillId)); if (model.AssociatedSkills != null) { user.AssociatedSkills.AddRange(model.AssociatedSkills.Where(msk => !user.AssociatedSkills.Any(usk => usk.SkillId == msk.SkillId))); } user.AssociatedSkills?.ForEach(usk => usk.UserId = user.Id); await _mediator.SendAsync(new UpdateUser { User = user }); if (shouldRefreshSignin) { await _signInManager.RefreshSignInAsync(user); } await UpdateUserProfileCompleteness(user); return RedirectToAction(nameof(Index)); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ResendEmailConfirmation() { var user = await _userManager.GetUserAsync(User); var token = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Action(new UrlActionContext { Action = nameof(AccountController.ConfirmEmail), Controller = "Account", Values = new { userId = user.Id, token }, Protocol = HttpContext.Request.Scheme }); await _mediator.SendAsync(new SendConfirmAccountEmail { Email = user.Email, CallbackUrl = callbackUrl }); return RedirectToAction(nameof(EmailConfirmationSent)); } [HttpGet] public IActionResult EmailConfirmationSent() { return View(); } // GET: /Account/RemoveLogin [HttpGet] public async Task<IActionResult> RemoveLogin() { var user = await GetCurrentUser(); var linkedAccounts = await _userManager.GetLoginsAsync(user); ViewData[SHOW_REMOVE_BUTTON] = await _userManager.HasPasswordAsync(user) || linkedAccounts.Count > 1; return View(linkedAccounts); } // POST: /Manage/RemoveLogin [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemoveLogin(string loginProvider, string providerKey) { ManageMessageId? message = ManageMessageId.Error; var user = await GetCurrentUser(); if (user != null) { var result = await _userManager.RemoveLoginAsync(user, loginProvider, providerKey); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); message = ManageMessageId.RemoveLoginSuccess; } } return RedirectToAction(nameof(ManageLogins), new { Message = message }); } // GET: /Account/AddPhoneNumber public IActionResult AddPhoneNumber() { return View(); } // POST: /Account/AddPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } // Generate the token and send it await GenerateChangePhoneNumberTokenAndSendAccountSecurityTokenSms(await GetCurrentUser(), model.PhoneNumber); return RedirectToAction(nameof(VerifyPhoneNumber), new { model.PhoneNumber }); } // POST: /Account/ResendPhoneNumberConfirmation [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ResendPhoneNumberConfirmation(string phoneNumber) { await GenerateChangePhoneNumberTokenAndSendAccountSecurityTokenSms(await GetCurrentUser(), phoneNumber); return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = phoneNumber }); } // POST: /Manage/EnableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> EnableTwoFactorAuthentication() { var user = await GetCurrentUser(); if (user != null) { await _userManager.SetTwoFactorEnabledAsync(user, true); await _signInManager.SignInAsync(user, isPersistent: false); } return RedirectToAction(nameof(Index)); } // POST: /Manage/DisableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> DisableTwoFactorAuthentication() { var user = await GetCurrentUser(); if (user != null) { await _userManager.SetTwoFactorEnabledAsync(user, false); await _signInManager.SignInAsync(user, isPersistent: false); } return RedirectToAction(nameof(Index)); } // GET: /Account/VerifyPhoneNumber [HttpGet] public IActionResult VerifyPhoneNumber(string phoneNumber) { // Send an SMS to verify the mobile phone number return phoneNumber == null ? View(ERROR_VIEW) : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber }); } // POST: /Account/VerifyPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUser(); if (user != null) { var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code); if (result.Succeeded) { await UpdateUserProfileCompleteness(user); await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess }); } } // If we got this far, something failed, redisplay the form ModelState.AddModelError(string.Empty, "Failed to verify mobile phone number"); return View(model); } // GET: /Account/RemovePhoneNumber [HttpGet] public async Task<IActionResult> RemovePhoneNumber() { var user = await GetCurrentUser(); if (user != null) { var result = await _userManager.SetPhoneNumberAsync(user, null); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); await UpdateUserProfileCompleteness(user); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess }); } } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } // GET: /Manage/ChangePassword [HttpGet] public IActionResult ChangePassword() { return View(); } // POST: /Account/Manage [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUser(); if (user != null) { var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess }); } AddErrorsToModelState(result); return View(model); } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } // GET: /Manage/ChangeEmail [HttpGet] public IActionResult ChangeEmail() { return View(); } // POST: /Account/ChangeEmail [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ChangeEmail(ChangeEmailViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUser(); if (user != null) { if(!await _userManager.CheckPasswordAsync(user, model.Password)) { ModelState.AddModelError(nameof(model.Password), "The password supplied is not correct"); return View(model); } var existingUser = await _userManager.FindByEmailAsync(model.NewEmail.Normalize()); if(existingUser != null) { // The username/email is already registered ModelState.AddModelError(nameof(model.NewEmail), "The email supplied is already registered"); return View(model); } user.PendingNewEmail = model.NewEmail; await _userManager.UpdateAsync(user); await BuildCallbackUrlAndSendNewEmailAddressConfirmationEmail(user, model.NewEmail); return RedirectToAction(nameof(EmailConfirmationSent)); } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } // GET: /Manage/ConfirmNewEmail [HttpGet] public async Task<IActionResult> ConfirmNewEmail(string token) { if (token == null) { return View(ERROR_VIEW); } var user = await GetCurrentUser(); if (user == null) { return View(ERROR_VIEW); } var result = await _userManager.ChangeEmailAsync(user, user.PendingNewEmail, token); if(result.Succeeded) { await _userManager.SetUserNameAsync(user, user.PendingNewEmail); user.PendingNewEmail = null; await _userManager.UpdateAsync(user); } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangeEmailSuccess }); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ResendChangeEmailConfirmation() { var user = await GetCurrentUser(); if(string.IsNullOrEmpty(user.PendingNewEmail)) { return View(ERROR_VIEW); } await BuildCallbackUrlAndSendNewEmailAddressConfirmationEmail(user, user.PendingNewEmail); return RedirectToAction(nameof(EmailConfirmationSent)); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> CancelChangeEmail() { var user = await GetCurrentUser(); user.PendingNewEmail = null; await _userManager.UpdateAsync(user); return RedirectToAction(nameof(Index)); } // GET: /Manage/SetPassword [HttpGet] public IActionResult SetPassword() { return View(); } // POST: /Manage/SetPassword [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> SetPassword(SetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUser(); if (user != null) { var result = await _userManager.AddPasswordAsync(user, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess }); } AddErrorsToModelState(result); return View(model); } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } //GET: /Account/Manage [HttpGet] public async Task<IActionResult> ManageLogins(ManageMessageId? message = null) { ViewData[STATUS_MESSAGE] = message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed." : message == ManageMessageId.AddLoginSuccess ? "The external login was added." : message == ManageMessageId.Error ? ERROR_OCCURRED : ""; var user = await GetCurrentUser(); if (user == null) { return View(ERROR_VIEW); } var userLogins = await _userManager.GetLoginsAsync(user); var schemes = await _signInManager.GetExternalAuthenticationSchemesAsync(); var otherLogins = schemes.Where(auth => userLogins.All(ul => auth.Name != ul.LoginProvider)).ToList(); ViewData[SHOW_REMOVE_BUTTON] = user.PasswordHash != null || userLogins.Count > 1; return View(new ManageLoginsViewModel { CurrentLogins = userLogins, OtherLogins = otherLogins }); } // POST: /Manage/LinkLogin [HttpPost] [ValidateAntiForgeryToken] public IActionResult LinkLogin(string provider) { // Request a redirect to the external login provider to link a login for the current user var redirectUrl = Url.Action(new UrlActionContext { Action = nameof(LinkLoginCallback), Controller = MANAGE_CONTROLLER }); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User)); return new ChallengeResult(provider, properties); } // GET: /Manage/LinkLoginCallback [HttpGet] public async Task<ActionResult> LinkLoginCallback() { var user = await GetCurrentUser(); if (user == null) { return View(ERROR_VIEW); } var info = await _signInManager.GetExternalLoginInfoAsync(_userManager.GetUserId(User)); if (info == null) { return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error }); } var result = await _userManager.AddLoginAsync(user, info); var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error; return RedirectToAction(nameof(ManageLogins), new { Message = message }); } private async Task BuildCallbackUrlAndSendNewEmailAddressConfirmationEmail(ApplicationUser applicationUser, string userEmail) { var token = await _userManager.GenerateChangeEmailTokenAsync(applicationUser, userEmail); var callbackUrl = Url.Action(new UrlActionContext { Action = nameof(ConfirmNewEmail), Controller = MANAGE_CONTROLLER, Values = new { token = token }, Protocol = HttpContext.Request.Scheme }); await _mediator.SendAsync(new SendNewEmailAddressConfirmationEmail { Email = userEmail, CallbackUrl = callbackUrl }); } private async Task GenerateChangePhoneNumberTokenAndSendAccountSecurityTokenSms(ApplicationUser applicationUser, string phoneNumber) { var token = await _userManager.GenerateChangePhoneNumberTokenAsync(applicationUser, phoneNumber); await _mediator.SendAsync(new SendAccountSecurityTokenSms { PhoneNumber = phoneNumber, Token = token }); } private async Task UpdateUserProfileCompleteness(ApplicationUser user) { if (user.IsProfileComplete()) { await _mediator.SendAsync(new RemoveUserProfileIncompleteClaimCommand { UserId = user.Id }); await _signInManager.RefreshSignInAsync(user); } } private void AddErrorsToModelState(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } public enum ManageMessageId { AddPhoneSuccess, AddLoginSuccess, ChangePasswordSuccess, ChangeEmailSuccess, SetTwoFactorSuccess, SetPasswordSuccess, RemoveLoginSuccess, RemovePhoneSuccess, Error } private async Task<ApplicationUser> GetCurrentUser() { return await _mediator.SendAsync(new UserByUserIdQuery { UserId = _userManager.GetUserId(User) }); } //ViewData Constants private const string SHOW_REMOVE_BUTTON = "ShowRemoveButton"; private const string STATUS_MESSAGE = "StatusMessage"; //Message Constants private const string ERROR_OCCURRED = "An error has occurred."; //Controller Names private const string MANAGE_CONTROLLER = "Manage"; //View Names private const string ERROR_VIEW = "Error"; } }
// Lucene version compatibility level 4.8.1 using YAF.Lucene.Net.Analysis.TokenAttributes; using YAF.Lucene.Net.Analysis.Util; using YAF.Lucene.Net.Support; using YAF.Lucene.Net.Util; using System; using System.Text; namespace YAF.Lucene.Net.Analysis.Miscellaneous { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Configuration options for the <see cref="WordDelimiterFilter"/>. /// <para/> /// LUCENENET specific - these options were passed as int constant flags in Lucene. /// </summary> [System.Flags] public enum WordDelimiterFlags { /// <summary> /// Causes parts of words to be generated: /// <para/> /// "PowerShot" => "Power" "Shot" /// </summary> GENERATE_WORD_PARTS = 1, /// <summary> /// Causes number subwords to be generated: /// <para/> /// "500-42" => "500" "42" /// </summary> GENERATE_NUMBER_PARTS = 2, /// <summary> /// Causes maximum runs of word parts to be catenated: /// <para/> /// "wi-fi" => "wifi" /// </summary> CATENATE_WORDS = 4, /// <summary> /// Causes maximum runs of word parts to be catenated: /// <para/> /// "wi-fi" => "wifi" /// </summary> CATENATE_NUMBERS = 8, /// <summary> /// Causes all subword parts to be catenated: /// <para/> /// "wi-fi-4000" => "wifi4000" /// </summary> CATENATE_ALL = 16, /// <summary> /// Causes original words are preserved and added to the subword list (Defaults to false) /// <para/> /// "500-42" => "500" "42" "500-42" /// </summary> PRESERVE_ORIGINAL = 32, /// <summary> /// If not set, causes case changes to be ignored (subwords will only be generated /// given SUBWORD_DELIM tokens) /// </summary> SPLIT_ON_CASE_CHANGE = 64, /// <summary> /// If not set, causes numeric changes to be ignored (subwords will only be generated /// given SUBWORD_DELIM tokens). /// </summary> SPLIT_ON_NUMERICS = 128, /// <summary> /// Causes trailing "'s" to be removed for each subword /// <para/> /// "O'Neil's" => "O", "Neil" /// </summary> STEM_ENGLISH_POSSESSIVE = 256 } /// <summary> /// Splits words into subwords and performs optional transformations on subword /// groups. Words are split into subwords with the following rules: /// <list type="bullet"> /// <item><description>split on intra-word delimiters (by default, all non alpha-numeric /// characters): <c>"Wi-Fi"</c> &#8594; <c>"Wi", "Fi"</c></description></item> /// <item><description>split on case transitions: <c>"PowerShot"</c> &#8594; /// <c>"Power", "Shot"</c></description></item> /// <item><description>split on letter-number transitions: <c>"SD500"</c> &#8594; /// <c>"SD", "500"</c></description></item> /// <item><description>leading and trailing intra-word delimiters on each subword are ignored: /// <c>"//hello---there, 'dude'"</c> &#8594; /// <c>"hello", "there", "dude"</c></description></item> /// <item><description>trailing "'s" are removed for each subword: <c>"O'Neil's"</c> /// &#8594; <c>"O", "Neil"</c> /// <ul> /// <item><description>Note: this step isn't performed in a separate filter because of possible /// subword combinations.</description></item> /// </ul> /// </description></item> /// </list> /// <para/> /// The <b>combinations</b> parameter affects how subwords are combined: /// <list type="bullet"> /// <item><description>combinations="0" causes no subword combinations: <code>"PowerShot"</code> /// &#8594; <c>0:"Power", 1:"Shot"</c> (0 and 1 are the token positions)</description></item> /// <item><description>combinations="1" means that in addition to the subwords, maximum runs of /// non-numeric subwords are catenated and produced at the same position of the /// last subword in the run: /// <ul> /// <item><description><c>"PowerShot"</c> &#8594; /// <c>0:"Power", 1:"Shot" 1:"PowerShot"</c></description></item> /// <item><description><c>"A's+B's&amp;C's"</c> -gt; <c>0:"A", 1:"B", 2:"C", 2:"ABC"</c> /// </description></item> /// <item><description><c>"Super-Duper-XL500-42-AutoCoder!"</c> &#8594; /// <c>0:"Super", 1:"Duper", 2:"XL", 2:"SuperDuperXL", 3:"500" 4:"42", 5:"Auto", 6:"Coder", 6:"AutoCoder"</c> /// </description></item> /// </ul> /// </description></item> /// </list> /// <para/> /// One use for <see cref="WordDelimiterFilter"/> is to help match words with different /// subword delimiters. For example, if the source text contained "wi-fi" one may /// want "wifi" "WiFi" "wi-fi" "wi+fi" queries to all match. One way of doing so /// is to specify combinations="1" in the analyzer used for indexing, and /// combinations="0" (the default) in the analyzer used for querying. Given that /// the current <see cref="Standard.StandardTokenizer"/> immediately removes many intra-word /// delimiters, it is recommended that this filter be used after a tokenizer that /// does not do this (such as <see cref="Core.WhitespaceTokenizer"/>). /// </summary> public sealed class WordDelimiterFilter : TokenFilter { // LUCENENET: Added as a replacement for null in Java internal const int NOT_SET = 0x00; public const int LOWER = 0x01; public const int UPPER = 0x02; public const int DIGIT = 0x04; public const int SUBWORD_DELIM = 0x08; // combinations: for testing, not for setting bits public const int ALPHA = 0x03; public const int ALPHANUM = 0x07; // LUCENENET specific - made flags into their own [Flags] enum named WordDelimiterFlags and de-nested from this type /// <summary> /// If not null is the set of tokens to protect from being delimited /// /// </summary> private readonly CharArraySet protWords; private readonly WordDelimiterFlags flags; private readonly ICharTermAttribute termAttribute; private readonly IOffsetAttribute offsetAttribute; private readonly IPositionIncrementAttribute posIncAttribute; private readonly ITypeAttribute typeAttribute; // used for iterating word delimiter breaks private readonly WordDelimiterIterator iterator; // used for concatenating runs of similar typed subwords (word,number) private readonly WordDelimiterConcatenation concat; // number of subwords last output by concat. private int lastConcatCount = 0; // used for catenate all private readonly WordDelimiterConcatenation concatAll; // used for accumulating position increment gaps private int accumPosInc = 0; private char[] savedBuffer = new char[1024]; private int savedStartOffset; private int savedEndOffset; private string savedType; private bool hasSavedState = false; // if length by start + end offsets doesn't match the term text then assume // this is a synonym and don't adjust the offsets. private bool hasIllegalOffsets = false; // for a run of the same subword type within a word, have we output anything? private bool hasOutputToken = false; // when preserve original is on, have we output any token following it? // this token must have posInc=0! private bool hasOutputFollowingOriginal = false; /// <summary> /// Creates a new WordDelimiterFilter /// </summary> /// <param name="matchVersion"> lucene compatibility version </param> /// <param name="in"> TokenStream to be filtered </param> /// <param name="charTypeTable"> table containing character types </param> /// <param name="configurationFlags"> Flags configuring the filter </param> /// <param name="protWords"> If not null is the set of tokens to protect from being delimited </param> public WordDelimiterFilter(LuceneVersion matchVersion, TokenStream @in, byte[] charTypeTable, WordDelimiterFlags configurationFlags, CharArraySet protWords) : base(@in) { this.termAttribute = AddAttribute<ICharTermAttribute>(); this.offsetAttribute = AddAttribute<IOffsetAttribute>(); this.posIncAttribute = AddAttribute<IPositionIncrementAttribute>(); this.typeAttribute = AddAttribute<ITypeAttribute>(); concat = new WordDelimiterConcatenation(this); concatAll = new WordDelimiterConcatenation(this); sorter = new OffsetSorter(this); if (!matchVersion.OnOrAfter(LuceneVersion.LUCENE_48)) { throw new ArgumentException("This class only works with Lucene 4.8+. To emulate the old (broken) behavior of WordDelimiterFilter, use Lucene47WordDelimiterFilter"); } this.flags = configurationFlags; this.protWords = protWords; this.iterator = new WordDelimiterIterator(charTypeTable, Has(WordDelimiterFlags.SPLIT_ON_CASE_CHANGE), Has(WordDelimiterFlags.SPLIT_ON_NUMERICS), Has(WordDelimiterFlags.STEM_ENGLISH_POSSESSIVE)); } /// <summary> /// Creates a new WordDelimiterFilter using <see cref="WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE"/> /// as its charTypeTable /// </summary> /// <param name="matchVersion"> lucene compatibility version </param> /// <param name="in"> <see cref="TokenStream"/> to be filtered </param> /// <param name="configurationFlags"> Flags configuring the filter </param> /// <param name="protWords"> If not null is the set of tokens to protect from being delimited </param> public WordDelimiterFilter(LuceneVersion matchVersion, TokenStream @in, WordDelimiterFlags configurationFlags, CharArraySet protWords) : this(matchVersion, @in, WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE, configurationFlags, protWords) { } public override bool IncrementToken() { while (true) { if (!hasSavedState) { // process a new input word if (!m_input.IncrementToken()) { return false; } int termLength = termAttribute.Length; char[] termBuffer = termAttribute.Buffer; accumPosInc += posIncAttribute.PositionIncrement; iterator.SetText(termBuffer, termLength); iterator.Next(); // word of no delimiters, or protected word: just return it if ((iterator.current == 0 && iterator.end == termLength) || (protWords != null && protWords.Contains(termBuffer, 0, termLength))) { posIncAttribute.PositionIncrement = accumPosInc; accumPosInc = 0; first = false; return true; } // word of simply delimiters if (iterator.end == WordDelimiterIterator.DONE && !Has(WordDelimiterFlags.PRESERVE_ORIGINAL)) { // if the posInc is 1, simply ignore it in the accumulation // TODO: proper hole adjustment (FilteringTokenFilter-like) instead of this previous logic! if (posIncAttribute.PositionIncrement == 1 && !first) { accumPosInc--; } continue; } SaveState(); hasOutputToken = false; hasOutputFollowingOriginal = !Has(WordDelimiterFlags.PRESERVE_ORIGINAL); lastConcatCount = 0; if (Has(WordDelimiterFlags.PRESERVE_ORIGINAL)) { posIncAttribute.PositionIncrement = accumPosInc; accumPosInc = 0; first = false; return true; } } // at the end of the string, output any concatenations if (iterator.end == WordDelimiterIterator.DONE) { if (!concat.IsEmpty) { if (FlushConcatenation(concat)) { Buffer(); continue; } } if (!concatAll.IsEmpty) { // only if we haven't output this same combo above! if (concatAll.subwordCount > lastConcatCount) { concatAll.WriteAndClear(); Buffer(); continue; } concatAll.Clear(); } if (bufferedPos < bufferedLen) { if (bufferedPos == 0) { sorter.Sort(0, bufferedLen); } ClearAttributes(); RestoreState(buffered[bufferedPos++]); if (first && posIncAttribute.PositionIncrement == 0) { // can easily happen with strange combinations (e.g. not outputting numbers, but concat-all) posIncAttribute.PositionIncrement = 1; } first = false; return true; } // no saved concatenations, on to the next input word bufferedPos = bufferedLen = 0; hasSavedState = false; continue; } // word surrounded by delimiters: always output if (iterator.IsSingleWord()) { GeneratePart(true); iterator.Next(); first = false; return true; } int wordType = iterator.Type; // do we already have queued up incompatible concatenations? if (!concat.IsEmpty && (concat.type & wordType) == 0) { if (FlushConcatenation(concat)) { hasOutputToken = false; Buffer(); continue; } hasOutputToken = false; } // add subwords depending upon options if (ShouldConcatenate(wordType)) { if (concat.IsEmpty) { concat.type = wordType; } Concatenate(concat); } // add all subwords (catenateAll) if (Has(WordDelimiterFlags.CATENATE_ALL)) { Concatenate(concatAll); } // if we should output the word or number part if (ShouldGenerateParts(wordType)) { GeneratePart(false); Buffer(); } iterator.Next(); } } public override void Reset() { base.Reset(); hasSavedState = false; concat.Clear(); concatAll.Clear(); accumPosInc = bufferedPos = bufferedLen = 0; first = true; } // ================================================= Helper Methods ================================================ private AttributeSource.State[] buffered = new AttributeSource.State[8]; private int[] startOff = new int[8]; private int[] posInc = new int[8]; private int bufferedLen = 0; private int bufferedPos = 0; private bool first; internal class OffsetSorter : InPlaceMergeSorter // LUCENENET NOTE: Changed from private to internal because exposed by internal member { private readonly WordDelimiterFilter outerInstance; public OffsetSorter(WordDelimiterFilter outerInstance) { this.outerInstance = outerInstance; } protected override int Compare(int i, int j) { int cmp = outerInstance.startOff[i].CompareTo(outerInstance.startOff[j]); if (cmp == 0) { cmp = outerInstance.posInc[j].CompareTo(outerInstance.posInc[i]); } return cmp; } protected override void Swap(int i, int j) { AttributeSource.State tmp = outerInstance.buffered[i]; outerInstance.buffered[i] = outerInstance.buffered[j]; outerInstance.buffered[j] = tmp; int tmp2 = outerInstance.startOff[i]; outerInstance.startOff[i] = outerInstance.startOff[j]; outerInstance.startOff[j] = tmp2; tmp2 = outerInstance.posInc[i]; outerInstance.posInc[i] = outerInstance.posInc[j]; outerInstance.posInc[j] = tmp2; } } private readonly OffsetSorter sorter; private void Buffer() { if (bufferedLen == buffered.Length) { int newSize = ArrayUtil.Oversize(bufferedLen + 1, 8); buffered = Arrays.CopyOf(buffered, newSize); startOff = Arrays.CopyOf(startOff, newSize); posInc = Arrays.CopyOf(posInc, newSize); } startOff[bufferedLen] = offsetAttribute.StartOffset; posInc[bufferedLen] = posIncAttribute.PositionIncrement; buffered[bufferedLen] = CaptureState(); bufferedLen++; } /// <summary> /// Saves the existing attribute states /// </summary> private void SaveState() { // otherwise, we have delimiters, save state savedStartOffset = offsetAttribute.StartOffset; savedEndOffset = offsetAttribute.EndOffset; // if length by start + end offsets doesn't match the term text then assume this is a synonym and don't adjust the offsets. hasIllegalOffsets = (savedEndOffset - savedStartOffset != termAttribute.Length); savedType = typeAttribute.Type; if (savedBuffer.Length < termAttribute.Length) { savedBuffer = new char[ArrayUtil.Oversize(termAttribute.Length, RamUsageEstimator.NUM_BYTES_CHAR)]; } Array.Copy(termAttribute.Buffer, 0, savedBuffer, 0, termAttribute.Length); iterator.text = savedBuffer; hasSavedState = true; } /// <summary> /// Flushes the given <see cref="WordDelimiterConcatenation"/> by either writing its concat and then clearing, or just clearing. /// </summary> /// <param name="concatenation"> <see cref="WordDelimiterConcatenation"/> that will be flushed </param> /// <returns> <c>true</c> if the concatenation was written before it was cleared, <c>false</c> otherwise </returns> private bool FlushConcatenation(WordDelimiterConcatenation concatenation) { lastConcatCount = concatenation.subwordCount; if (concatenation.subwordCount != 1 || !ShouldGenerateParts(concatenation.type)) { concatenation.WriteAndClear(); return true; } concatenation.Clear(); return false; } /// <summary> /// Determines whether to concatenate a word or number if the current word is the given type /// </summary> /// <param name="wordType"> Type of the current word used to determine if it should be concatenated </param> /// <returns> <c>true</c> if concatenation should occur, <c>false</c> otherwise </returns> private bool ShouldConcatenate(int wordType) { return (Has(WordDelimiterFlags.CATENATE_WORDS) && IsAlpha(wordType)) || (Has(WordDelimiterFlags.CATENATE_NUMBERS) && IsDigit(wordType)); } /// <summary> /// Determines whether a word/number part should be generated for a word of the given type /// </summary> /// <param name="wordType"> Type of the word used to determine if a word/number part should be generated </param> /// <returns> <c>true</c> if a word/number part should be generated, <c>false</c> otherwise </returns> private bool ShouldGenerateParts(int wordType) { return (Has(WordDelimiterFlags.GENERATE_WORD_PARTS) && IsAlpha(wordType)) || (Has(WordDelimiterFlags.GENERATE_NUMBER_PARTS) && IsDigit(wordType)); } /// <summary> /// Concatenates the saved buffer to the given <see cref="WordDelimiterConcatenation"/> /// </summary> /// <param name="concatenation"> <see cref="WordDelimiterConcatenation"/> to concatenate the buffer to </param> private void Concatenate(WordDelimiterConcatenation concatenation) { if (concatenation.IsEmpty) { concatenation.startOffset = savedStartOffset + iterator.current; } concatenation.Append(savedBuffer, iterator.current, iterator.end - iterator.current); concatenation.endOffset = savedStartOffset + iterator.end; } /// <summary> /// Generates a word/number part, updating the appropriate attributes /// </summary> /// <param name="isSingleWord"> <c>true</c> if the generation is occurring from a single word, <c>false</c> otherwise </param> private void GeneratePart(bool isSingleWord) { ClearAttributes(); termAttribute.CopyBuffer(savedBuffer, iterator.current, iterator.end - iterator.current); int startOffset = savedStartOffset + iterator.current; int endOffset = savedStartOffset + iterator.end; if (hasIllegalOffsets) { // historically this filter did this regardless for 'isSingleWord', // but we must do a sanity check: if (isSingleWord && startOffset <= savedEndOffset) { offsetAttribute.SetOffset(startOffset, savedEndOffset); } else { offsetAttribute.SetOffset(savedStartOffset, savedEndOffset); } } else { offsetAttribute.SetOffset(startOffset, endOffset); } posIncAttribute.PositionIncrement = Position(false); typeAttribute.Type = savedType; } /// <summary> /// Get the position increment gap for a subword or concatenation /// </summary> /// <param name="inject"> true if this token wants to be injected </param> /// <returns> position increment gap </returns> private int Position(bool inject) { int posInc = accumPosInc; if (hasOutputToken) { accumPosInc = 0; return inject ? 0 : Math.Max(1, posInc); } hasOutputToken = true; if (!hasOutputFollowingOriginal) { // the first token following the original is 0 regardless hasOutputFollowingOriginal = true; return 0; } // clear the accumulated position increment accumPosInc = 0; return Math.Max(1, posInc); } /// <summary> /// Checks if the given word type includes <see cref="ALPHA"/> /// </summary> /// <param name="type"> Word type to check </param> /// <returns> <c>true</c> if the type contains <see cref="ALPHA"/>, <c>false</c> otherwise </returns> internal static bool IsAlpha(int type) { return (type & ALPHA) != 0; } /// <summary> /// Checks if the given word type includes <see cref="DIGIT"/> /// </summary> /// <param name="type"> Word type to check </param> /// <returns> <c>true</c> if the type contains <see cref="DIGIT"/>, <c>false</c> otherwise </returns> internal static bool IsDigit(int type) { return (type & DIGIT) != 0; } /// <summary> /// Checks if the given word type includes <see cref="SUBWORD_DELIM"/> /// </summary> /// <param name="type"> Word type to check </param> /// <returns> <c>true</c> if the type contains <see cref="SUBWORD_DELIM"/>, <c>false</c> otherwise </returns> internal static bool IsSubwordDelim(int type) { return (type & SUBWORD_DELIM) != 0; } /// <summary> /// Checks if the given word type includes <see cref="UPPER"/> /// </summary> /// <param name="type"> Word type to check </param> /// <returns> <c>true</c> if the type contains <see cref="UPPER"/>, <c>false</c> otherwise </returns> internal static bool IsUpper(int type) { return (type & UPPER) != 0; } /// <summary> /// Determines whether the given flag is set /// </summary> /// <param name="flag"> Flag to see if set </param> /// <returns> <c>true</c> if flag is set </returns> private bool Has(WordDelimiterFlags flag) { return (flags & flag) != 0; } // ================================================= Inner Classes ================================================= /// <summary> /// A WDF concatenated 'run' /// </summary> internal sealed class WordDelimiterConcatenation { private readonly WordDelimiterFilter outerInstance; public WordDelimiterConcatenation(WordDelimiterFilter outerInstance) { this.outerInstance = outerInstance; } private readonly StringBuilder buffer = new StringBuilder(); internal int startOffset; internal int endOffset; internal int type; internal int subwordCount; /// <summary> /// Appends the given text of the given length, to the concetenation at the given offset /// </summary> /// <param name="text"> Text to append </param> /// <param name="offset"> Offset in the concetenation to add the text </param> /// <param name="length"> Length of the text to append </param> internal void Append(char[] text, int offset, int length) { buffer.Append(text, offset, length); subwordCount++; } /// <summary> /// Writes the concatenation to the attributes /// </summary> internal void Write() { outerInstance.ClearAttributes(); if (outerInstance.termAttribute.Length < buffer.Length) { outerInstance.termAttribute.ResizeBuffer(buffer.Length); } char[] termbuffer = outerInstance.termAttribute.Buffer; buffer.CopyTo(0, termbuffer, 0, buffer.Length); outerInstance.termAttribute.Length = buffer.Length; if (outerInstance.hasIllegalOffsets) { outerInstance.offsetAttribute.SetOffset(outerInstance.savedStartOffset, outerInstance.savedEndOffset); } else { outerInstance.offsetAttribute.SetOffset(startOffset, endOffset); } outerInstance.posIncAttribute.PositionIncrement = outerInstance.Position(true); outerInstance.typeAttribute.Type = outerInstance.savedType; outerInstance.accumPosInc = 0; } /// <summary> /// Determines if the concatenation is empty /// </summary> /// <returns> <c>true</c> if the concatenation is empty, <c>false</c> otherwise </returns> internal bool IsEmpty => buffer.Length == 0; /// <summary> /// Clears the concatenation and resets its state /// </summary> internal void Clear() { buffer.Length = 0; startOffset = endOffset = type = subwordCount = 0; } /// <summary> /// Convenience method for the common scenario of having to write the concetenation and then clearing its state /// </summary> internal void WriteAndClear() { Write(); Clear(); } } // questions: // negative numbers? -42 indexed as just 42? // dollar sign? $42 // percent sign? 33% // downsides: if source text is "powershot" then a query of "PowerShot" won't match! } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class ExtensionsTests { [Fact] public static void ReadExtensions() { using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate)) { X509ExtensionCollection exts = c.Extensions; int count = exts.Count; Assert.Equal(6, count); X509Extension[] extensions = new X509Extension[count]; exts.CopyTo(extensions, 0); extensions = extensions.OrderBy(e => e.Oid.Value).ToArray(); // There are an awful lot of magic-looking values in this large test. // These values are embedded within the certificate, and the test is // just verifying the object interpretation. In the event the test data // (TestData.MsCertificate) is replaced, this whole body will need to be // redone. { // Authority Information Access X509Extension aia = extensions[0]; Assert.Equal("1.3.6.1.5.5.7.1.1", aia.Oid.Value); Assert.False(aia.Critical); byte[] expectedDer = ( "304c304a06082b06010505073002863e687474703a2f2f7777772e6d" + "6963726f736f66742e636f6d2f706b692f63657274732f4d6963436f" + "645369675043415f30382d33312d323031302e637274").HexToByteArray(); Assert.Equal(expectedDer, aia.RawData); } { // Subject Key Identifier X509Extension skid = extensions[1]; Assert.Equal("2.5.29.14", skid.Oid.Value); Assert.False(skid.Critical); byte[] expected = "04145971a65a334dda980780ff841ebe87f9723241f2".HexToByteArray(); Assert.Equal(expected, skid.RawData); Assert.True(skid is X509SubjectKeyIdentifierExtension); X509SubjectKeyIdentifierExtension rich = (X509SubjectKeyIdentifierExtension)skid; Assert.Equal("5971A65A334DDA980780FF841EBE87F9723241F2", rich.SubjectKeyIdentifier); } { // Subject Alternative Names X509Extension sans = extensions[2]; Assert.Equal("2.5.29.17", sans.Oid.Value); Assert.False(sans.Critical); byte[] expected = ( "3048a4463044310d300b060355040b13044d4f505231333031060355" + "0405132a33313539352b34666166306237312d616433372d34616133" + "2d613637312d373662633035323334346164").HexToByteArray(); Assert.Equal(expected, sans.RawData); } { // CRL Distribution Points X509Extension cdps = extensions[3]; Assert.Equal("2.5.29.31", cdps.Oid.Value); Assert.False(cdps.Critical); byte[] expected = ( "304d304ba049a0478645687474703a2f2f63726c2e6d6963726f736f" + "66742e636f6d2f706b692f63726c2f70726f64756374732f4d696343" + "6f645369675043415f30382d33312d323031302e63726c").HexToByteArray(); Assert.Equal(expected, cdps.RawData); } { // Authority Key Identifier X509Extension akid = extensions[4]; Assert.Equal("2.5.29.35", akid.Oid.Value); Assert.False(akid.Critical); byte[] expected = "30168014cb11e8cad2b4165801c9372e331616b94c9a0a1f".HexToByteArray(); Assert.Equal(expected, akid.RawData); } { // Extended Key Usage (X.509/2000 says Extended, Win32/NetFX say Enhanced) X509Extension eku = extensions[5]; Assert.Equal("2.5.29.37", eku.Oid.Value); Assert.False(eku.Critical); byte[] expected = "300a06082b06010505070303".HexToByteArray(); Assert.Equal(expected, eku.RawData); Assert.True(eku is X509EnhancedKeyUsageExtension); X509EnhancedKeyUsageExtension rich = (X509EnhancedKeyUsageExtension)eku; OidCollection usages = rich.EnhancedKeyUsages; Assert.Equal(1, usages.Count); Oid oid = usages[0]; // Code Signing Assert.Equal("1.3.6.1.5.5.7.3.3", oid.Value); } } } [Fact] public static void KeyUsageExtensionDefaultCtor() { X509KeyUsageExtension e = new X509KeyUsageExtension(); string oidValue = e.Oid.Value; Assert.Equal("2.5.29.15", oidValue); byte[] r = e.RawData; Assert.Null(r); X509KeyUsageFlags keyUsages = e.KeyUsages; Assert.Equal(X509KeyUsageFlags.None, keyUsages); } [Fact] public static void KeyUsageExtension_CrlSign() { TestKeyUsageExtension(X509KeyUsageFlags.CrlSign, false, "03020102".HexToByteArray()); } [Fact] public static void KeyUsageExtension_DataEncipherment() { TestKeyUsageExtension(X509KeyUsageFlags.DataEncipherment, false, "03020410".HexToByteArray()); } [Fact] public static void KeyUsageExtension_DecipherOnly() { TestKeyUsageExtension(X509KeyUsageFlags.DecipherOnly, false, "0303070080".HexToByteArray()); } [Fact] public static void KeyUsageExtension_DigitalSignature() { TestKeyUsageExtension(X509KeyUsageFlags.DigitalSignature, false, "03020780".HexToByteArray()); } [Fact] public static void KeyUsageExtension_EncipherOnly() { TestKeyUsageExtension(X509KeyUsageFlags.EncipherOnly, false, "03020001".HexToByteArray()); } [Fact] public static void KeyUsageExtension_KeyAgreement() { TestKeyUsageExtension(X509KeyUsageFlags.KeyAgreement, false, "03020308".HexToByteArray()); } [Fact] public static void KeyUsageExtension_KeyCertSign() { TestKeyUsageExtension(X509KeyUsageFlags.KeyCertSign, false, "03020204".HexToByteArray()); } [Fact] public static void KeyUsageExtension_KeyEncipherment() { TestKeyUsageExtension(X509KeyUsageFlags.KeyEncipherment, false, "03020520".HexToByteArray()); } [Fact] public static void KeyUsageExtension_None() { TestKeyUsageExtension(X509KeyUsageFlags.None, false, "030100".HexToByteArray()); } [Fact] public static void KeyUsageExtension_NonRepudiation() { TestKeyUsageExtension(X509KeyUsageFlags.NonRepudiation, false, "03020640".HexToByteArray()); } [Fact] public static void BasicConstraintsExtensionDefault() { X509BasicConstraintsExtension e = new X509BasicConstraintsExtension(); string oidValue = e.Oid.Value; Assert.Equal("2.5.29.19", oidValue); byte[] rawData = e.RawData; Assert.Null(rawData); Assert.False(e.CertificateAuthority); Assert.False(e.HasPathLengthConstraint); Assert.Equal(0, e.PathLengthConstraint); } [Theory] [MemberData(nameof(BasicConstraintsData))] public static void BasicConstraintsExtensionEncode( bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint, bool critical, string expectedDerString) { X509BasicConstraintsExtension ext = new X509BasicConstraintsExtension( certificateAuthority, hasPathLengthConstraint, pathLengthConstraint, critical); byte[] expectedDer = expectedDerString.HexToByteArray(); Assert.Equal(expectedDer, ext.RawData); } [Theory] [MemberData(nameof(BasicConstraintsData))] public static void BasicConstraintsExtensionDecode( bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint, bool critical, string rawDataString) { byte[] rawData = rawDataString.HexToByteArray(); int expectedPathLengthConstraint = hasPathLengthConstraint ? pathLengthConstraint : 0; X509BasicConstraintsExtension ext = new X509BasicConstraintsExtension(new AsnEncodedData(rawData), critical); Assert.Equal(certificateAuthority, ext.CertificateAuthority); Assert.Equal(hasPathLengthConstraint, ext.HasPathLengthConstraint); Assert.Equal(expectedPathLengthConstraint, ext.PathLengthConstraint); } public static object[][] BasicConstraintsData = new object[][] { new object[] { false, false, 0, false, "3000" }, new object[] { false, false, 121, false, "3000" }, new object[] { true, false, 0, false, "30030101ff" }, new object[] { false, true, 0, false, "3003020100" }, new object[] { false, true, 7654321, false, "3005020374cbb1" }, new object[] { true, true, 559, false, "30070101ff0202022f" }, }; [Fact] public static void EnhancedKeyUsageExtensionDefault() { X509EnhancedKeyUsageExtension e = new X509EnhancedKeyUsageExtension(); string oidValue = e.Oid.Value; Assert.Equal("2.5.29.37", oidValue); byte[] rawData = e.RawData; Assert.Null(rawData); OidCollection usages = e.EnhancedKeyUsages; Assert.Equal(0, usages.Count); } [Fact] public static void EnhancedKeyUsageExtension_Empty() { OidCollection usages = new OidCollection(); TestEnhancedKeyUsageExtension(usages, false, "3000".HexToByteArray()); } [Fact] public static void EnhancedKeyUsageExtension_2Oids() { Oid oid1 = Oid.FromOidValue("1.3.6.1.5.5.7.3.1", OidGroup.EnhancedKeyUsage); Oid oid2 = Oid.FromOidValue("1.3.6.1.4.1.311.10.3.1", OidGroup.EnhancedKeyUsage); OidCollection usages = new OidCollection(); usages.Add(oid1); usages.Add(oid2); TestEnhancedKeyUsageExtension(usages, false, "301606082b06010505070301060a2b0601040182370a0301".HexToByteArray()); } [Theory] [InlineData("1")] [InlineData("3.0")] [InlineData("Invalid Value")] public static void EnhancedKeyUsageExtension_InvalidOid(string invalidOidValue) { OidCollection oids = new OidCollection { new Oid(invalidOidValue) }; Assert.ThrowsAny<CryptographicException>(() => new X509EnhancedKeyUsageExtension(oids, false)); } [Fact] public static void SubjectKeyIdentifierExtensionDefault() { X509SubjectKeyIdentifierExtension e = new X509SubjectKeyIdentifierExtension(); string oidValue = e.Oid.Value; Assert.Equal("2.5.29.14", oidValue); byte[] rawData = e.RawData; Assert.Null(rawData); string skid = e.SubjectKeyIdentifier; Assert.Null(skid); } [Fact] public static void SubjectKeyIdentifierExtension_Bytes() { byte[] sk = { 1, 2, 3, 4 }; X509SubjectKeyIdentifierExtension e = new X509SubjectKeyIdentifierExtension(sk, false); byte[] rawData = e.RawData; Assert.Equal("040401020304".HexToByteArray(), rawData); e = new X509SubjectKeyIdentifierExtension(new AsnEncodedData(rawData), false); string skid = e.SubjectKeyIdentifier; Assert.Equal("01020304", skid); } [Fact] public static void SubjectKeyIdentifierExtension_String() { string sk = "01ABcd"; X509SubjectKeyIdentifierExtension e = new X509SubjectKeyIdentifierExtension(sk, false); byte[] rawData = e.RawData; Assert.Equal("040301abcd".HexToByteArray(), rawData); e = new X509SubjectKeyIdentifierExtension(new AsnEncodedData(rawData), false); string skid = e.SubjectKeyIdentifier; Assert.Equal("01ABCD", skid); } [Fact] public static void SubjectKeyIdentifierExtension_PublicKey() { PublicKey pk; using (var cert = new X509Certificate2(TestData.MsCertificate)) { pk = cert.PublicKey; } X509SubjectKeyIdentifierExtension e = new X509SubjectKeyIdentifierExtension(pk, false); byte[] rawData = e.RawData; Assert.Equal("04145971a65a334dda980780ff841ebe87f9723241f2".HexToByteArray(), rawData); e = new X509SubjectKeyIdentifierExtension(new AsnEncodedData(rawData), false); string skid = e.SubjectKeyIdentifier; Assert.Equal("5971A65A334DDA980780FF841EBE87F9723241F2", skid); } [Fact] public static void SubjectKeyIdentifierExtension_PublicKeySha1() { TestSubjectKeyIdentifierExtension( TestData.MsCertificate, X509SubjectKeyIdentifierHashAlgorithm.Sha1, false, "04145971a65a334dda980780ff841ebe87f9723241f2".HexToByteArray(), "5971A65A334DDA980780FF841EBE87F9723241F2"); } [Fact] public static void SubjectKeyIdentifierExtension_PublicKeyShortSha1() { TestSubjectKeyIdentifierExtension( TestData.MsCertificate, X509SubjectKeyIdentifierHashAlgorithm.ShortSha1, false, "04084ebe87f9723241f2".HexToByteArray(), "4EBE87F9723241F2"); } [Fact] public static void SubjectKeyIdentifierExtension_PublicKeyCapiSha1() { TestSubjectKeyIdentifierExtension( TestData.MsCertificate, X509SubjectKeyIdentifierHashAlgorithm.CapiSha1, false, "0414a260a870be1145ed71e2bb5aa19463a4fe9dcc41".HexToByteArray(), "A260A870BE1145ED71E2BB5AA19463A4FE9DCC41"); } [Fact] public static void ReadInvalidExtension_KeyUsage() { X509KeyUsageExtension keyUsageExtension = new X509KeyUsageExtension(new AsnEncodedData(Array.Empty<byte>()), false); Assert.ThrowsAny<CryptographicException>(() => keyUsageExtension.KeyUsages); } private static void TestKeyUsageExtension(X509KeyUsageFlags flags, bool critical, byte[] expectedDer) { X509KeyUsageExtension ext = new X509KeyUsageExtension(flags, critical); byte[] rawData = ext.RawData; Assert.Equal(expectedDer, rawData); // Assert that format doesn't crash string s = ext.Format(false); // Rebuild it from the RawData. ext = new X509KeyUsageExtension(new AsnEncodedData(rawData), critical); Assert.Equal(flags, ext.KeyUsages); } private static void TestEnhancedKeyUsageExtension( OidCollection usages, bool critical, byte[] expectedDer) { X509EnhancedKeyUsageExtension ext = new X509EnhancedKeyUsageExtension(usages, critical); byte[] rawData = ext.RawData; Assert.Equal(expectedDer, rawData); ext = new X509EnhancedKeyUsageExtension(new AsnEncodedData(rawData), critical); OidCollection actualUsages = ext.EnhancedKeyUsages; Assert.Equal(usages.Count, actualUsages.Count); for (int i = 0; i < usages.Count; i++) { Assert.Equal(usages[i].Value, actualUsages[i].Value); } } private static void TestSubjectKeyIdentifierExtension( byte[] certBytes, X509SubjectKeyIdentifierHashAlgorithm algorithm, bool critical, byte[] expectedDer, string expectedIdentifier) { PublicKey pk; using (var cert = new X509Certificate2(certBytes)) { pk = cert.PublicKey; } X509SubjectKeyIdentifierExtension ext = new X509SubjectKeyIdentifierExtension(pk, algorithm, critical); byte[] rawData = ext.RawData; Assert.Equal(expectedDer, rawData); ext = new X509SubjectKeyIdentifierExtension(new AsnEncodedData(rawData), critical); Assert.Equal(expectedIdentifier, ext.SubjectKeyIdentifier); } } }
// 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; internal class test { public static int Main() { int x; int y; bool pass = true; x = -10; y = 4; x = x + y; if (x != -6) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx = x + y failed. x: {0}, \texpected: -6\n", x); pass = false; } x = -10; y = 4; x = x - y; if (x != -14) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx = x - y failed. x: {0}, \texpected: -14\n", x); pass = false; } x = -10; y = 4; x = x * y; if (x != -40) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx = x * y failed. x: {0}, \texpected: -40\n", x); pass = false; } x = -10; y = 4; x = x / y; if (x != -2) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx = x / y failed. x: {0}, \texpected: -2\n", x); pass = false; } x = -10; y = 4; x = x % y; if (x != -2) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx = x % y failed. x: {0}, \texpected: -2\n", x); pass = false; } x = -10; y = 4; x = x << y; if (x != -160) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx = x << y failed. x: {0}, \texpected: -160\n", x); pass = false; } x = -10; y = 4; x = x >> y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx = x >> y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x = x & y; if (x != 4) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx = x & y failed. x: {0}, \texpected: 4\n", x); pass = false; } x = -10; y = 4; x = x ^ y; if (x != -14) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx = x ^ y failed. x: {0}, \texpected: -14\n", x); pass = false; } x = -10; y = 4; x = x | y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx = x | y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x += x + y; if (x != -16) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx += x + y failed. x: {0}, \texpected: -16\n", x); pass = false; } x = -10; y = 4; x += x - y; if (x != -24) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx += x - y failed. x: {0}, \texpected: -24\n", x); pass = false; } x = -10; y = 4; x += x * y; if (x != -50) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx += x * y failed. x: {0}, \texpected: -50\n", x); pass = false; } x = -10; y = 4; x += x / y; if (x != -12) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx += x / y failed. x: {0}, \texpected: -12\n", x); pass = false; } x = -10; y = 4; x += x % y; if (x != -12) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx += x % y failed. x: {0}, \texpected: -12\n", x); pass = false; } x = -10; y = 4; x += x << y; if (x != -170) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx += x << y failed. x: {0}, \texpected: -170\n", x); pass = false; } x = -10; y = 4; x += x >> y; if (x != -11) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx += x >> y failed. x: {0}, \texpected: -11\n", x); pass = false; } x = -10; y = 4; x += x & y; if (x != -6) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx += x & y failed. x: {0}, \texpected: -6\n", x); pass = false; } x = -10; y = 4; x += x ^ y; if (x != -24) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx += x ^ y failed. x: {0}, \texpected: -24\n", x); pass = false; } x = -10; y = 4; x += x | y; if (x != -20) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx += x | y failed. x: {0}, \texpected: -20\n", x); pass = false; } x = -10; y = 4; x -= x + y; if (x != -4) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx -= x + y failed. x: {0}, \texpected: -4\n", x); pass = false; } x = -10; y = 4; x -= x - y; if (x != 4) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx -= x - y failed. x: {0}, \texpected: 4\n", x); pass = false; } x = -10; y = 4; x -= x * y; if (x != 30) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx -= x * y failed. x: {0}, \texpected: 30\n", x); pass = false; } x = -10; y = 4; x -= x / y; if (x != -8) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx -= x / y failed. x: {0}, \texpected: -8\n", x); pass = false; } x = -10; y = 4; x -= x % y; if (x != -8) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx -= x % y failed. x: {0}, \texpected: -8\n", x); pass = false; } x = -10; y = 4; x -= x << y; if (x != 150) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx -= x << y failed. x: {0}, \texpected: 150\n", x); pass = false; } x = -10; y = 4; x -= x >> y; if (x != -9) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx -= x >> y failed. x: {0}, \texpected: -9\n", x); pass = false; } x = -10; y = 4; x -= x & y; if (x != -14) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx -= x & y failed. x: {0}, \texpected: -14\n", x); pass = false; } x = -10; y = 4; x -= x ^ y; if (x != 4) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx -= x ^ y failed. x: {0}, \texpected: 4\n", x); pass = false; } x = -10; y = 4; x -= x | y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx -= x | y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x *= x + y; if (x != 60) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx *= x + y failed. x: {0}, \texpected: 60\n", x); pass = false; } x = -10; y = 4; x *= x - y; if (x != 140) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx *= x - y failed. x: {0}, \texpected: 140\n", x); pass = false; } x = -10; y = 4; x *= x * y; if (x != 400) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx *= x * y failed. x: {0}, \texpected: 400\n", x); pass = false; } x = -10; y = 4; x *= x / y; if (x != 20) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx *= x / y failed. x: {0}, \texpected: 20\n", x); pass = false; } x = -10; y = 4; x *= x % y; if (x != 20) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx *= x % y failed. x: {0}, \texpected: 20\n", x); pass = false; } x = -10; y = 4; x *= x << y; if (x != 1600) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx *= x << y failed. x: {0}, \texpected: 1600\n", x); pass = false; } x = -10; y = 4; x *= x >> y; if (x != 10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx *= x >> y failed. x: {0}, \texpected: 10\n", x); pass = false; } x = -10; y = 4; x *= x & y; if (x != -40) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx *= x & y failed. x: {0}, \texpected: -40\n", x); pass = false; } x = -10; y = 4; x *= x ^ y; if (x != 140) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx *= x ^ y failed. x: {0}, \texpected: 140\n", x); pass = false; } x = -10; y = 4; x *= x | y; if (x != 100) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx *= x | y failed. x: {0}, \texpected: 100\n", x); pass = false; } x = -10; y = 4; x /= x + y; if (x != 1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx /= x + y failed. x: {0}, \texpected: 1\n", x); pass = false; } x = -10; y = 4; x /= x - y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx /= x - y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x /= x * y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx /= x * y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x /= x / y; if (x != 5) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx /= x / y failed. x: {0}, \texpected: 5\n", x); pass = false; } x = -10; y = 4; x /= x % y; if (x != 5) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx /= x % y failed. x: {0}, \texpected: 5\n", x); pass = false; } x = -10; y = 4; x /= x << y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx /= x << y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x /= x >> y; if (x != 10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx /= x >> y failed. x: {0}, \texpected: 10\n", x); pass = false; } x = -10; y = 4; x /= x & y; if (x != -2) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx /= x & y failed. x: {0}, \texpected: -2\n", x); pass = false; } x = -10; y = 4; x /= x ^ y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx /= x ^ y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x /= x | y; if (x != 1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx /= x | y failed. x: {0}, \texpected: 1\n", x); pass = false; } x = -10; y = 4; x %= x + y; if (x != -4) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx %= x + y failed. x: {0}, \texpected: -4\n", x); pass = false; } x = -10; y = 4; x %= x - y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx %= x - y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x %= x * y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx %= x * y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x %= x / y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx %= x / y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x %= x % y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx %= x % y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x %= x << y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx %= x << y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x %= x >> y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx %= x >> y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x %= x & y; if (x != -2) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx %= x & y failed. x: {0}, \texpected: -2\n", x); pass = false; } x = -10; y = 4; x %= x ^ y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx %= x ^ y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x %= x | y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx %= x | y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x <<= x + y; if (x != -671088640) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx <<= x + y failed. x: {0}, \texpected: -671088640\n", x); pass = false; } x = -10; y = 4; x <<= x - y; if (x != -2621440) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx <<= x - y failed. x: {0}, \texpected: -2621440\n", x); pass = false; } x = -10; y = 4; x <<= x * y; if (x != -167772160) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx <<= x * y failed. x: {0}, \texpected: -167772160\n", x); pass = false; } x = -10; y = 4; x <<= x / y; if (x != -2147483648) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx <<= x / y failed. x: {0}, \texpected: -2147483648\n", x); pass = false; } x = -10; y = 4; x <<= x % y; if (x != -2147483648) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx <<= x % y failed. x: {0}, \texpected: -2147483648\n", x); pass = false; } x = -10; y = 4; x <<= x << y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx <<= x << y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x <<= x >> y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx <<= x >> y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x <<= x & y; if (x != -160) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx <<= x & y failed. x: {0}, \texpected: -160\n", x); pass = false; } x = -10; y = 4; x <<= x ^ y; if (x != -2621440) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx <<= x ^ y failed. x: {0}, \texpected: -2621440\n", x); pass = false; } x = -10; y = 4; x <<= x | y; if (x != -41943040) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx <<= x | y failed. x: {0}, \texpected: -41943040\n", x); pass = false; } x = -10; y = 4; x >>= x + y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx >>= x + y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x >>= x - y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx >>= x - y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x >>= x * y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx >>= x * y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x >>= x / y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx >>= x / y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x >>= x % y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx >>= x % y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x >>= x << y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx >>= x << y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x >>= x >> y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx >>= x >> y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x >>= x & y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx >>= x & y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x >>= x ^ y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx >>= x ^ y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x >>= x | y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx >>= x | y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x &= x + y; if (x != -14) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx &= x + y failed. x: {0}, \texpected: -14\n", x); pass = false; } x = -10; y = 4; x &= x - y; if (x != -14) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx &= x - y failed. x: {0}, \texpected: -14\n", x); pass = false; } x = -10; y = 4; x &= x * y; if (x != -48) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx &= x * y failed. x: {0}, \texpected: -48\n", x); pass = false; } x = -10; y = 4; x &= x / y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx &= x / y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x &= x % y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx &= x % y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x &= x << y; if (x != -160) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx &= x << y failed. x: {0}, \texpected: -160\n", x); pass = false; } x = -10; y = 4; x &= x >> y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx &= x >> y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x &= x & y; if (x != 4) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx &= x & y failed. x: {0}, \texpected: 4\n", x); pass = false; } x = -10; y = 4; x &= x ^ y; if (x != -14) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx &= x ^ y failed. x: {0}, \texpected: -14\n", x); pass = false; } x = -10; y = 4; x &= x | y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx &= x | y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x ^= x + y; if (x != 12) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx ^= x + y failed. x: {0}, \texpected: 12\n", x); pass = false; } x = -10; y = 4; x ^= x - y; if (x != 4) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx ^= x - y failed. x: {0}, \texpected: 4\n", x); pass = false; } x = -10; y = 4; x ^= x * y; if (x != 46) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx ^= x * y failed. x: {0}, \texpected: 46\n", x); pass = false; } x = -10; y = 4; x ^= x / y; if (x != 8) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx ^= x / y failed. x: {0}, \texpected: 8\n", x); pass = false; } x = -10; y = 4; x ^= x % y; if (x != 8) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx ^= x % y failed. x: {0}, \texpected: 8\n", x); pass = false; } x = -10; y = 4; x ^= x << y; if (x != 150) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx ^= x << y failed. x: {0}, \texpected: 150\n", x); pass = false; } x = -10; y = 4; x ^= x >> y; if (x != 9) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx ^= x >> y failed. x: {0}, \texpected: 9\n", x); pass = false; } x = -10; y = 4; x ^= x & y; if (x != -14) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx ^= x & y failed. x: {0}, \texpected: -14\n", x); pass = false; } x = -10; y = 4; x ^= x ^ y; if (x != 4) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx ^= x ^ y failed. x: {0}, \texpected: 4\n", x); pass = false; } x = -10; y = 4; x ^= x | y; if (x != 0) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx ^= x | y failed. x: {0}, \texpected: 0\n", x); pass = false; } x = -10; y = 4; x |= x + y; if (x != -2) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx |= x + y failed. x: {0}, \texpected: -2\n", x); pass = false; } x = -10; y = 4; x |= x - y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx |= x - y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x |= x * y; if (x != -2) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx |= x * y failed. x: {0}, \texpected: -2\n", x); pass = false; } x = -10; y = 4; x |= x / y; if (x != -2) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx |= x / y failed. x: {0}, \texpected: -2\n", x); pass = false; } x = -10; y = 4; x |= x % y; if (x != -2) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx |= x % y failed. x: {0}, \texpected: -2\n", x); pass = false; } x = -10; y = 4; x |= x << y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx |= x << y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x |= x >> y; if (x != -1) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx |= x >> y failed. x: {0}, \texpected: -1\n", x); pass = false; } x = -10; y = 4; x |= x & y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx |= x & y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x |= x ^ y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx |= x ^ y failed. x: {0}, \texpected: -10\n", x); pass = false; } x = -10; y = 4; x |= x | y; if (x != -10) { Console.WriteLine("Initial parameters: x is -10 and y is 4."); Console.WriteLine("\tx |= x | y failed. x: {0}, \texpected: -10\n", x); pass = false; } if (pass) { Console.WriteLine("PASSED."); return 100; } else return 1; } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Reflection; using Newtonsoft.Json.Utilities; using System.Collections; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Serialization { /// <summary> /// Contract details for a <see cref="System.Type"/> used by the <see cref="JsonSerializer"/>. /// </summary> public class JsonArrayContract : JsonContainerContract { /// <summary> /// Gets the <see cref="System.Type"/> of the collection items. /// </summary> /// <value>The <see cref="System.Type"/> of the collection items.</value> public Type CollectionItemType { get; private set; } /// <summary> /// Gets a value indicating whether the collection type is a multidimensional array. /// </summary> /// <value><c>true</c> if the collection type is a multidimensional array; otherwise, <c>false</c>.</value> public bool IsMultidimensionalArray { get; private set; } private readonly Type _genericCollectionDefinitionType; private Type _genericWrapperType; private ObjectConstructor<object> _genericWrapperCreator; private Func<object> _genericTemporaryCollectionCreator; internal bool IsArray { get; private set; } internal bool ShouldCreateWrapper { get; private set; } internal bool CanDeserialize { get; private set; } private readonly ConstructorInfo _parametrizedConstructor; private ObjectConstructor<object> _parametrizedCreator; internal ObjectConstructor<object> ParametrizedCreator { get { if (_parametrizedCreator == null) _parametrizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParametrizedConstructor(_parametrizedConstructor); return _parametrizedCreator; } } internal bool HasParametrizedCreator { get { return _parametrizedCreator != null || _parametrizedConstructor != null; } } /// <summary> /// Initializes a new instance of the <see cref="JsonArrayContract"/> class. /// </summary> /// <param name="underlyingType">The underlying type for the contract.</param> public JsonArrayContract(Type underlyingType) : base(underlyingType) { ContractType = JsonContractType.Array; IsArray = CreatedType.IsArray; bool canDeserialize; Type tempCollectionType; if (IsArray) { CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType); IsReadOnlyOrFixedSize = true; _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); canDeserialize = true; IsMultidimensionalArray = (IsArray && UnderlyingType.GetArrayRank() > 1); } else if (typeof(IList).IsAssignableFrom(underlyingType)) { if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType)) CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; else CollectionItemType = ReflectionUtils.GetCollectionItemType(underlyingType); if (underlyingType == typeof(IList)) CreatedType = typeof(List<object>); if (CollectionItemType != null) _parametrizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyCollection<>)); canDeserialize = true; } else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType)) { CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ICollection<>)) || ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IList<>))) CreatedType = typeof(List<>).MakeGenericType(CollectionItemType); #if !(NET20 || NET35 || PORTABLE40) if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ISet<>))) CreatedType = typeof(HashSet<>).MakeGenericType(CollectionItemType); #endif _parametrizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); canDeserialize = true; ShouldCreateWrapper = true; } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>), out tempCollectionType)) { CollectionItemType = tempCollectionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>)) || ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyList<>))) CreatedType = typeof(ReadOnlyCollection<>).MakeGenericType(CollectionItemType); _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); _parametrizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(CreatedType, CollectionItemType); IsReadOnlyOrFixedSize = true; canDeserialize = HasParametrizedCreator; } #endif else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IEnumerable<>), out tempCollectionType)) { CollectionItemType = tempCollectionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IEnumerable<>))) CreatedType = typeof(List<>).MakeGenericType(CollectionItemType); _parametrizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); #if !(NET35 || NET20) if (!HasParametrizedCreator && underlyingType.Name == FSharpUtils.FSharpListTypeName) { FSharpUtils.EnsureInitialized(underlyingType.Assembly()); _parametrizedCreator = FSharpUtils.CreateSeq(CollectionItemType); } #endif if (underlyingType.IsGenericType() && underlyingType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { _genericCollectionDefinitionType = tempCollectionType; IsReadOnlyOrFixedSize = false; ShouldCreateWrapper = false; canDeserialize = true; } else { _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); IsReadOnlyOrFixedSize = true; ShouldCreateWrapper = true; canDeserialize = HasParametrizedCreator; } } else { // types that implement IEnumerable and nothing else canDeserialize = false; ShouldCreateWrapper = true; } CanDeserialize = canDeserialize; #if (NET20 || NET35) if (CollectionItemType != null && ReflectionUtils.IsNullableType(CollectionItemType)) { // bug in .NET 2.0 & 3.5 that List<Nullable<T>> throws an error when adding null via IList.Add(object) // wrapper will handle calling Add(T) instead if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(List<>), out tempCollectionType) || (IsArray && !IsMultidimensionalArray)) { ShouldCreateWrapper = true; } } #endif #if !(NET20 || NET35 || NET40 || PORTABLE40) Type immutableCreatedType; ObjectConstructor<object> immutableParameterizedCreator; if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract(underlyingType, CollectionItemType, out immutableCreatedType, out immutableParameterizedCreator)) { CreatedType = immutableCreatedType; _parametrizedCreator = immutableParameterizedCreator; IsReadOnlyOrFixedSize = true; CanDeserialize = true; } #endif } internal IWrappedCollection CreateWrapper(object list) { if (_genericWrapperCreator == null) { _genericWrapperType = typeof(CollectionWrapper<>).MakeGenericType(CollectionItemType); Type constructorArgument; if (ReflectionUtils.InheritsGenericDefinition(_genericCollectionDefinitionType, typeof(List<>)) || _genericCollectionDefinitionType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) constructorArgument = typeof(ICollection<>).MakeGenericType(CollectionItemType); else constructorArgument = _genericCollectionDefinitionType; ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument }); _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParametrizedConstructor(genericWrapperConstructor); } return (IWrappedCollection)_genericWrapperCreator(list); } internal IList CreateTemporaryCollection() { if (_genericTemporaryCollectionCreator == null) { // multidimensional array will also have array instances in it Type collectionItemType = (IsMultidimensionalArray) ? typeof(object) : CollectionItemType; Type temporaryListType = typeof(List<>).MakeGenericType(collectionItemType); _genericTemporaryCollectionCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(temporaryListType); } return (IList)_genericTemporaryCollectionCreator(); } } }
// FileSystemInfoTest.cs - NUnit Test Cases for System.IO.FileSystemInfo class // // Ville Palo (vi64pa@koti.soon.fi) // // (C) 2003 Ville Palo // using NUnit.Framework; using System; using System.IO; using System.Globalization; using System.Threading; namespace MonoTests.System.IO { [TestFixture] public class FileSystemInfoTest : Assertion { string TempFolder = Path.Combine (Path.GetTempPath (), "MonoTests.System.IO.Tests"); static readonly char DSC = Path.DirectorySeparatorChar; [SetUp] protected void SetUp() { if (Directory.Exists (TempFolder)) Directory.Delete (TempFolder, true); Directory.CreateDirectory (TempFolder); Thread.CurrentThread.CurrentCulture = new CultureInfo ("EN-us"); } [TearDown] protected void TearDown() { if (Directory.Exists (TempFolder)) Directory.Delete (TempFolder, true); } bool Windows { get { return Path.DirectorySeparatorChar == '\\'; } } bool Unix { get { return Path.DirectorySeparatorChar == '/'; } } bool Mac { get { return Path.DirectorySeparatorChar == ':'; } } private void DeleteFile (string path) { if (File.Exists (path)) File.Delete (path); } private void DeleteDir (string path) { if (Directory.Exists (path)) Directory.Delete (path, true); } [Test] public void CreationTimeFile () { string path = TempFolder + DSC + "FSIT.CreationTime.Test"; DeleteFile (path); if (Unix) { // Unix doesn't support CreationTimes return; } try { File.Create (path).Close (); FileSystemInfo info = new FileInfo (path); info.CreationTime = new DateTime (1999, 12, 31, 11, 59, 59); DateTime time = info.CreationTime; AssertEquals ("test#01", 1999, time.Year); AssertEquals ("test#02", 12, time.Month); AssertEquals ("test#03", 31, time.Day); AssertEquals ("test#04", 11, time.Hour); AssertEquals ("test#05", 59, time.Minute); AssertEquals ("test#06", 59, time.Second); time = TimeZone.CurrentTimeZone.ToLocalTime (info.CreationTimeUtc); AssertEquals ("test#07", 1999, time.Year); AssertEquals ("test#08", 12, time.Month); AssertEquals ("test#09", 31, time.Day); AssertEquals ("test#10", 11, time.Hour); AssertEquals ("test#11", 59, time.Minute); AssertEquals ("test#12", 59, time.Second); info.CreationTimeUtc = new DateTime (1999, 12, 31, 11, 59, 59); time = TimeZone.CurrentTimeZone.ToUniversalTime (info.CreationTime); AssertEquals ("test#13", 1999, time.Year); AssertEquals ("test#14", 12, time.Month); AssertEquals ("test#15", 31, time.Day); AssertEquals ("test#16", 11, time.Hour); AssertEquals ("test#17", 59, time.Minute); AssertEquals ("test#18", 59, time.Second); time = info.CreationTimeUtc; AssertEquals ("test#19", 1999, time.Year); AssertEquals ("test#20", 12, time.Month); AssertEquals ("test#21", 31, time.Day); AssertEquals ("test#22", 11, time.Hour); AssertEquals ("test#23", 59, time.Minute); AssertEquals ("test#24", 59, time.Second); } finally { DeleteFile (path); } } [Test] public void CreationTimeDirectory () { string path = TempFolder + DSC + "FSIT.CreationTimeDirectory.Test"; DeleteDir (path); if (Unix) { // Unix doesn't support CreationTimes return; } try { FileSystemInfo info = Directory.CreateDirectory (path); info.CreationTime = new DateTime (1999, 12, 31, 11, 59, 59); DateTime time = info.CreationTime; AssertEquals ("test#01", 1999, time.Year); AssertEquals ("test#02", 12, time.Month); AssertEquals ("test#03", 31, time.Day); time = TimeZone.CurrentTimeZone.ToLocalTime (info.CreationTimeUtc); AssertEquals ("test#07", 1999, time.Year); AssertEquals ("test#08", 12, time.Month); AssertEquals ("test#09", 31, time.Day); AssertEquals ("test#10", 11, time.Hour); info.CreationTimeUtc = new DateTime (1999, 12, 31, 11, 59, 59); time = TimeZone.CurrentTimeZone.ToUniversalTime (info.CreationTime); AssertEquals ("test#13", 1999, time.Year); AssertEquals ("test#14", 12, time.Month); AssertEquals ("test#15", 31, time.Day); time = TimeZone.CurrentTimeZone.ToLocalTime (info.CreationTimeUtc); AssertEquals ("test#19", 1999, time.Year); AssertEquals ("test#20", 12, time.Month); AssertEquals ("test#21", 31, time.Day); } finally { DeleteDir (path); } } [Test] public void CreationTimeNoFileOrDirectory () { string path = TempFolder + DSC + "FSIT.CreationTimeNoFile.Test"; DeleteFile (path); DeleteDir (path); try { FileSystemInfo info = new FileInfo (path); DateTime time = TimeZone.CurrentTimeZone.ToUniversalTime(info.CreationTime); AssertEquals ("test#01", 1601, time.Year); AssertEquals ("test#02", 1, time.Month); AssertEquals ("test#03", 1, time.Day); AssertEquals ("test#04", 0, time.Hour); AssertEquals ("test#05", 0, time.Minute); AssertEquals ("test#06", 0, time.Second); AssertEquals ("test#07", 0, time.Millisecond); info = new DirectoryInfo (path); time = TimeZone.CurrentTimeZone.ToUniversalTime(info.CreationTime); AssertEquals ("test#08", 1601, time.Year); AssertEquals ("test#09", 1, time.Month); AssertEquals ("test#10", 1, time.Day); AssertEquals ("test#11", 0, time.Hour); AssertEquals ("test#12", 0, time.Minute); AssertEquals ("test#13", 0, time.Second); AssertEquals ("test#14", 0, time.Millisecond); } finally { DeleteFile (path); DeleteDir (path); } } [Test] public void Extenssion () { string path = TempFolder + DSC + "FSIT.Extenssion.Test"; DeleteFile (path); try { FileSystemInfo info = new FileInfo (path); AssertEquals ("test#01", ".Test", info.Extension); } finally { DeleteFile (path); } } [Test] public void DefaultLastAccessTime () { string path = TempFolder + DSC + "FSIT.DefaultLastAccessTime.Test"; DeleteFile (path); try { FileSystemInfo info = new FileInfo (path); DateTime time = TimeZone.CurrentTimeZone.ToUniversalTime(info.LastAccessTime); AssertEquals ("test#01", 1601, time.Year); AssertEquals ("test#02", 1, time.Month); AssertEquals ("test#03", 1, time.Day); AssertEquals ("test#04", 0, time.Hour); AssertEquals ("test#05", 0, time.Minute); AssertEquals ("test#06", 0, time.Second); AssertEquals ("test#07", 0, time.Millisecond); } finally { DeleteFile (path); } } [Test] public void LastAccessTime () { string path = TempFolder + DSC + "FSIT.LastAccessTime.Test"; DeleteFile (path); try { File.Create (path).Close (); FileSystemInfo info = new FileInfo (path); DateTime time; info = new FileInfo (path); info.LastAccessTime = new DateTime (2000, 1, 1, 1, 1, 1); time = info.LastAccessTime; AssertEquals ("test#01", 2000, time.Year); AssertEquals ("test#02", 1, time.Month); AssertEquals ("test#03", 1, time.Day); AssertEquals ("test#04", 1, time.Hour); time = TimeZone.CurrentTimeZone.ToLocalTime (info.LastAccessTimeUtc); AssertEquals ("test#05", 2000, time.Year); AssertEquals ("test#06", 1, time.Month); AssertEquals ("test#07", 1, time.Day); AssertEquals ("test#08", 1, time.Hour); info.LastAccessTimeUtc = new DateTime (2000, 1, 1, 1, 1, 1); time = TimeZone.CurrentTimeZone.ToUniversalTime (info.LastAccessTime); AssertEquals ("test#09", 2000, time.Year); AssertEquals ("test#10", 1, time.Month); AssertEquals ("test#11", 1, time.Day); AssertEquals ("test#12", 1, time.Hour); time = info.LastAccessTimeUtc; AssertEquals ("test#13", 2000, time.Year); AssertEquals ("test#14", 1, time.Month); AssertEquals ("test#15", 1, time.Day); AssertEquals ("test#16", 1, time.Hour); } finally { DeleteFile (path); } } [Test] public void DefaultLastWriteTime () { string path = TempFolder + DSC + "FSIT.DefaultLastWriteTime.Test"; DeleteDir (path); try { FileSystemInfo info = new DirectoryInfo (path); DateTime time = TimeZone.CurrentTimeZone.ToUniversalTime(info.LastWriteTime); AssertEquals ("test#01", 1601, time.Year); AssertEquals ("test#02", 1, time.Month); AssertEquals ("test#03", 1, time.Day); AssertEquals ("test#04", 0, time.Hour); AssertEquals ("test#05", 0, time.Minute); AssertEquals ("test#06", 0, time.Second); AssertEquals ("test#07", 0, time.Millisecond); } finally { DeleteDir (path); } } [Test] public void LastWriteTime () { string path = TempFolder + DSC + "FSIT.LastWriteTime.Test"; DeleteDir (path); try { FileSystemInfo info = Directory.CreateDirectory (path); info.LastWriteTime = new DateTime (2000, 1, 1, 1, 1, 1); DateTime time = info.LastWriteTime; AssertEquals ("test#01", 2000, time.Year); AssertEquals ("test#02", 1, time.Month); AssertEquals ("test#03", 1, time.Day); AssertEquals ("test#04", 1, time.Hour); time = info.LastWriteTimeUtc.ToLocalTime (); AssertEquals ("test#05", 2000, time.Year); AssertEquals ("test#06", 1, time.Month); AssertEquals ("test#07", 1, time.Day); AssertEquals ("test#08", 1, time.Hour); info.LastWriteTimeUtc = new DateTime (2000, 1, 1, 1, 1, 1); time = info.LastWriteTimeUtc; AssertEquals ("test#09", 2000, time.Year); AssertEquals ("test#10", 1, time.Month); AssertEquals ("test#11", 1, time.Day); AssertEquals ("test#12", 1, time.Hour); time = info.LastWriteTime.ToUniversalTime (); AssertEquals ("test#13", 2000, time.Year); AssertEquals ("test#14", 1, time.Month); AssertEquals ("test#15", 1, time.Day); AssertEquals ("test#16", 1, time.Hour); } finally { DeleteDir (path); } } } }
//------------------------------------------------------------------------------ // <copyright file="Stylesheet.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml.Xsl.XsltOld { using Res = System.Xml.Utils.Res; using System; using System.Diagnostics; using System.Xml; using System.Xml.XPath; using System.Collections; internal class Stylesheet { private ArrayList imports = new ArrayList(); private Hashtable modeManagers; private Hashtable templateNameTable = new Hashtable(); private Hashtable attributeSetTable; private int templateCount; //private ArrayList preserveSpace; private Hashtable queryKeyTable; private ArrayList whitespaceList; private bool whitespace; private Hashtable scriptObjectTypes = new Hashtable(); private TemplateManager templates; private class WhitespaceElement { private int key; private double priority; private bool preserveSpace; internal double Priority { get { return this.priority; } } internal int Key { get { return this.key; } } internal bool PreserveSpace { get { return this.preserveSpace; } } internal WhitespaceElement(int Key, double priority, bool PreserveSpace) { this.key = Key; this.priority = priority; this.preserveSpace = PreserveSpace; } internal void ReplaceValue(bool PreserveSpace) { this.preserveSpace = PreserveSpace; } } internal bool Whitespace { get { return this.whitespace ; } } internal ArrayList Imports { get { return this.imports ; } } internal Hashtable AttributeSetTable { get { return this.attributeSetTable; } } internal void AddSpace(Compiler compiler, String query, double Priority, bool PreserveSpace) { WhitespaceElement elem; if (this.queryKeyTable != null) { if (this.queryKeyTable.Contains(query)) { elem = (WhitespaceElement) this.queryKeyTable[query]; elem.ReplaceValue(PreserveSpace); return; } } else{ this.queryKeyTable = new Hashtable(); this.whitespaceList = new ArrayList(); } int key = compiler.AddQuery(query); elem = new WhitespaceElement(key, Priority, PreserveSpace); this.queryKeyTable[query] = elem; this.whitespaceList.Add(elem); } internal void SortWhiteSpace(){ if (this.queryKeyTable != null){ for (int i= 0; i < this.whitespaceList.Count ; i++ ) { for(int j = this.whitespaceList.Count - 1; j > i; j--) { WhitespaceElement elem1, elem2; elem1 = (WhitespaceElement) this.whitespaceList[j - 1]; elem2 = (WhitespaceElement) this.whitespaceList[j]; if (elem2.Priority < elem1.Priority) { this.whitespaceList[j - 1] = elem2; this.whitespaceList[j] = elem1; } } } this.whitespace = true; } if (this.imports != null) { for (int importIndex = this.imports.Count - 1; importIndex >= 0; importIndex --) { Stylesheet stylesheet = (Stylesheet) this.imports[importIndex]; if (stylesheet.Whitespace) { stylesheet.SortWhiteSpace(); this.whitespace = true; } } } } internal bool PreserveWhiteSpace(Processor proc, XPathNavigator node){ // last one should win. I.E. We starting from the end. I.E. Lowest priority should go first if (this.whitespaceList != null) { for (int i = this.whitespaceList.Count - 1; 0 <= i; i --) { WhitespaceElement elem = (WhitespaceElement) this.whitespaceList[i]; if (proc.Matches(node, elem.Key)) { return elem.PreserveSpace; } } } if (this.imports != null) { for (int importIndex = this.imports.Count - 1; importIndex >= 0; importIndex --) { Stylesheet stylesheet = (Stylesheet) this.imports[importIndex]; if (! stylesheet.PreserveWhiteSpace(proc, node)) return false; } } return true; } internal void AddAttributeSet(AttributeSetAction attributeSet) { Debug.Assert(attributeSet.Name != null); if (this.attributeSetTable == null) { this.attributeSetTable = new Hashtable(); } Debug.Assert(this.attributeSetTable != null); if (this.attributeSetTable.ContainsKey(attributeSet.Name) == false) { this.attributeSetTable[attributeSet.Name] = attributeSet; } else { // merge the attribute-sets ((AttributeSetAction)this.attributeSetTable[attributeSet.Name]).Merge(attributeSet); } } internal void AddTemplate(TemplateAction template) { XmlQualifiedName mode = template.Mode; // // Ensure template has a unique name // Debug.Assert(this.templateNameTable != null); if (template.Name != null) { if (this.templateNameTable.ContainsKey(template.Name) == false) { this.templateNameTable[template.Name] = template; } else { throw XsltException.Create(Res.Xslt_DupTemplateName, template.Name.ToString()); } } if (template.MatchKey != Compiler.InvalidQueryKey) { if (this.modeManagers == null) { this.modeManagers = new Hashtable(); } Debug.Assert(this.modeManagers != null); if (mode == null) { mode = XmlQualifiedName.Empty; } TemplateManager manager = (TemplateManager) this.modeManagers[mode]; if (manager == null) { manager = new TemplateManager(this, mode); this.modeManagers[mode] = manager; if (mode.IsEmpty) { Debug.Assert(this.templates == null); this.templates = manager; } } Debug.Assert(manager != null); template.TemplateId = ++ this.templateCount; manager.AddTemplate(template); } } internal void ProcessTemplates() { if (this.modeManagers != null) { IDictionaryEnumerator enumerator = this.modeManagers.GetEnumerator(); while (enumerator.MoveNext()) { Debug.Assert(enumerator.Value is TemplateManager); TemplateManager manager = (TemplateManager) enumerator.Value; manager.ProcessTemplates(); } } if (this.imports != null) { for (int importIndex = this.imports.Count - 1; importIndex >= 0; importIndex --) { Debug.Assert(this.imports[importIndex] is Stylesheet); Stylesheet stylesheet = (Stylesheet) this.imports[importIndex]; Debug.Assert(stylesheet != null); // // Process templates in imported stylesheet // stylesheet.ProcessTemplates(); } } } internal void ReplaceNamespaceAlias(Compiler compiler){ if (this.modeManagers != null) { IDictionaryEnumerator enumerator = this.modeManagers.GetEnumerator(); while (enumerator.MoveNext()) { TemplateManager manager = (TemplateManager) enumerator.Value; if (manager.templates != null) { for(int i=0 ; i< manager.templates.Count; i++) { TemplateAction template = (TemplateAction) manager.templates[i]; template.ReplaceNamespaceAlias(compiler); } } } } if (this.templateNameTable != null) { IDictionaryEnumerator enumerator = this.templateNameTable.GetEnumerator(); while (enumerator.MoveNext()) { TemplateAction template = (TemplateAction) enumerator.Value; template.ReplaceNamespaceAlias(compiler); } } if (this.imports != null) { for (int importIndex = this.imports.Count - 1; importIndex >= 0; importIndex --) { Stylesheet stylesheet = (Stylesheet) this.imports[importIndex]; stylesheet.ReplaceNamespaceAlias(compiler); } } } internal TemplateAction FindTemplate(Processor processor, XPathNavigator navigator, XmlQualifiedName mode) { Debug.Assert(processor != null && navigator != null); Debug.Assert(mode != null); TemplateAction action = null; // // Try to find template within this stylesheet first // if (this.modeManagers != null) { TemplateManager manager = (TemplateManager) this.modeManagers[mode]; if (manager != null) { Debug.Assert(manager.Mode.Equals(mode)); action = manager.FindTemplate(processor, navigator); } } // // If unsuccessful, search in imported documents from backwards // if (action == null) { action = FindTemplateImports(processor, navigator, mode); } return action; } internal TemplateAction FindTemplateImports(Processor processor, XPathNavigator navigator, XmlQualifiedName mode) { TemplateAction action = null; // // Do we have imported stylesheets? // if (this.imports != null) { for (int importIndex = this.imports.Count - 1; importIndex >= 0; importIndex --) { Debug.Assert(this.imports[importIndex] is Stylesheet); Stylesheet stylesheet = (Stylesheet) this.imports[importIndex]; Debug.Assert(stylesheet != null); // // Search in imported stylesheet // action = stylesheet.FindTemplate(processor, navigator, mode); if (action != null) { return action; } } } return action; } internal TemplateAction FindTemplate(Processor processor, XPathNavigator navigator) { Debug.Assert(processor != null && navigator != null); Debug.Assert(this.templates == null && this.modeManagers == null || this.templates == this.modeManagers[XmlQualifiedName.Empty]); TemplateAction action = null; // // Try to find template within this stylesheet first // if (this.templates != null) { action = this.templates.FindTemplate(processor, navigator); } // // If unsuccessful, search in imported documents from backwards // if (action == null) { action = FindTemplateImports(processor, navigator); } return action; } internal TemplateAction FindTemplate(XmlQualifiedName name) { //Debug.Assert(this.templateNameTable == null); TemplateAction action = null; // // Try to find template within this stylesheet first // if (this.templateNameTable != null) { action = (TemplateAction)this.templateNameTable[name]; } // // If unsuccessful, search in imported documents from backwards // if (action == null && this.imports != null) { for (int importIndex = this.imports.Count - 1; importIndex >= 0; importIndex --) { Debug.Assert(this.imports[importIndex] is Stylesheet); Stylesheet stylesheet = (Stylesheet) this.imports[importIndex]; Debug.Assert(stylesheet != null); // // Search in imported stylesheet // action = stylesheet.FindTemplate(name); if (action != null) { return action; } } } return action; } internal TemplateAction FindTemplateImports(Processor processor, XPathNavigator navigator) { TemplateAction action = null; // // Do we have imported stylesheets? // if (this.imports != null) { for (int importIndex = this.imports.Count - 1; importIndex >= 0; importIndex --) { Debug.Assert(this.imports[importIndex] is Stylesheet); Stylesheet stylesheet = (Stylesheet) this.imports[importIndex]; Debug.Assert(stylesheet != null); // // Search in imported stylesheet // action = stylesheet.FindTemplate(processor, navigator); if (action != null) { return action; } } } return action; } internal Hashtable ScriptObjectTypes { get { return this.scriptObjectTypes; } } } }
// 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! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>CustomerFeed</c> resource.</summary> public sealed partial class CustomerFeedName : gax::IResourceName, sys::IEquatable<CustomerFeedName> { /// <summary>The possible contents of <see cref="CustomerFeedName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>customers/{customer_id}/customerFeeds/{feed_id}</c>.</summary> CustomerFeed = 1, } private static gax::PathTemplate s_customerFeed = new gax::PathTemplate("customers/{customer_id}/customerFeeds/{feed_id}"); /// <summary>Creates a <see cref="CustomerFeedName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="CustomerFeedName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static CustomerFeedName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CustomerFeedName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CustomerFeedName"/> with the pattern <c>customers/{customer_id}/customerFeeds/{feed_id}</c> /// . /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="CustomerFeedName"/> constructed from the provided ids.</returns> public static CustomerFeedName FromCustomerFeed(string customerId, string feedId) => new CustomerFeedName(ResourceNameType.CustomerFeed, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomerFeedName"/> with pattern /// <c>customers/{customer_id}/customerFeeds/{feed_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomerFeedName"/> with pattern /// <c>customers/{customer_id}/customerFeeds/{feed_id}</c>. /// </returns> public static string Format(string customerId, string feedId) => FormatCustomerFeed(customerId, feedId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomerFeedName"/> with pattern /// <c>customers/{customer_id}/customerFeeds/{feed_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomerFeedName"/> with pattern /// <c>customers/{customer_id}/customerFeeds/{feed_id}</c>. /// </returns> public static string FormatCustomerFeed(string customerId, string feedId) => s_customerFeed.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId))); /// <summary>Parses the given resource name string into a new <see cref="CustomerFeedName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/customerFeeds/{feed_id}</c></description></item> /// </list> /// </remarks> /// <param name="customerFeedName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CustomerFeedName"/> if successful.</returns> public static CustomerFeedName Parse(string customerFeedName) => Parse(customerFeedName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CustomerFeedName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/customerFeeds/{feed_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customerFeedName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="CustomerFeedName"/> if successful.</returns> public static CustomerFeedName Parse(string customerFeedName, bool allowUnparsed) => TryParse(customerFeedName, allowUnparsed, out CustomerFeedName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CustomerFeedName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/customerFeeds/{feed_id}</c></description></item> /// </list> /// </remarks> /// <param name="customerFeedName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CustomerFeedName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string customerFeedName, out CustomerFeedName result) => TryParse(customerFeedName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CustomerFeedName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/customerFeeds/{feed_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customerFeedName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="CustomerFeedName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string customerFeedName, bool allowUnparsed, out CustomerFeedName result) { gax::GaxPreconditions.CheckNotNull(customerFeedName, nameof(customerFeedName)); gax::TemplatedResourceName resourceName; if (s_customerFeed.TryParseName(customerFeedName, out resourceName)) { result = FromCustomerFeed(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(customerFeedName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private CustomerFeedName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string feedId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; FeedId = feedId; } /// <summary> /// Constructs a new instance of a <see cref="CustomerFeedName"/> class from the component parts of pattern /// <c>customers/{customer_id}/customerFeeds/{feed_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> public CustomerFeedName(string customerId, string feedId) : this(ResourceNameType.CustomerFeed, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>Feed</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FeedId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerFeed: return s_customerFeed.Expand(CustomerId, FeedId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as CustomerFeedName); /// <inheritdoc/> public bool Equals(CustomerFeedName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CustomerFeedName a, CustomerFeedName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CustomerFeedName a, CustomerFeedName b) => !(a == b); } public partial class CustomerFeed { /// <summary> /// <see cref="CustomerFeedName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal CustomerFeedName ResourceNameAsCustomerFeedName { get => string.IsNullOrEmpty(ResourceName) ? null : CustomerFeedName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary><see cref="FeedName"/>-typed view over the <see cref="Feed"/> resource name property.</summary> internal FeedName FeedAsFeedName { get => string.IsNullOrEmpty(Feed) ? null : FeedName.Parse(Feed, allowUnparsed: true); set => Feed = value?.ToString() ?? ""; } } }
using System; using System.Collections.Specialized; using System.Linq; using Moq; using Avalonia.Controls.Presenters; using Avalonia.Controls.Templates; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.UnitTests; using Avalonia.VisualTree; using Xunit; using Avalonia.Markup.Data; using Avalonia.Data; using System.Collections.Generic; namespace Avalonia.Controls.UnitTests { public class ContentControlTests { [Fact] public void Template_Should_Be_Instantiated() { var target = new ContentControl(); target.Content = "Foo"; target.Template = GetTemplate(); target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); var child = ((IVisual)target).VisualChildren.Single(); Assert.IsType<Border>(child); child = child.VisualChildren.Single(); Assert.IsType<ContentPresenter>(child); child = child.VisualChildren.Single(); Assert.IsType<TextBlock>(child); } [Fact] public void Templated_Children_Should_Be_Styled() { var root = new TestRoot(); var target = new ContentControl(); var styler = new Mock<IStyler>(); AvaloniaLocator.CurrentMutable.Bind<IStyler>().ToConstant(styler.Object); target.Content = "Foo"; target.Template = GetTemplate(); root.Child = target; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); styler.Verify(x => x.ApplyStyles(It.IsAny<ContentControl>()), Times.Once()); styler.Verify(x => x.ApplyStyles(It.IsAny<Border>()), Times.Once()); styler.Verify(x => x.ApplyStyles(It.IsAny<ContentPresenter>()), Times.Once()); styler.Verify(x => x.ApplyStyles(It.IsAny<TextBlock>()), Times.Once()); } [Fact] public void ContentPresenter_Should_Have_TemplatedParent_Set() { var target = new ContentControl(); var child = new Border(); target.Template = GetTemplate(); target.Content = child; target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); var contentPresenter = child.GetVisualParent<ContentPresenter>(); Assert.Equal(target, contentPresenter.TemplatedParent); } [Fact] public void Content_Should_Have_TemplatedParent_Set_To_Null() { var target = new ContentControl(); var child = new Border(); target.Template = GetTemplate(); target.Content = child; target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); Assert.Null(child.TemplatedParent); } [Fact] public void Control_Content_Should_Be_Logical_Child_Before_ApplyTemplate() { var target = new ContentControl { Template = GetTemplate(), }; var child = new Control(); target.Content = child; Assert.Equal(child.Parent, target); Assert.Equal(child.GetLogicalParent(), target); Assert.Equal(new[] { child }, target.GetLogicalChildren()); } [Fact] public void Control_Content_Should_Be_Logical_Child_After_ApplyTemplate() { var target = new ContentControl { Template = GetTemplate(), }; var child = new Control(); target.Content = child; target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); Assert.Equal(child.Parent, target); Assert.Equal(child.GetLogicalParent(), target); Assert.Equal(new[] { child }, target.GetLogicalChildren()); } [Fact] public void Should_Use_ContentTemplate_To_Create_Control() { var target = new ContentControl { Template = GetTemplate(), ContentTemplate = new FuncDataTemplate<string>((_, __) => new Canvas()), }; target.Content = "Foo"; target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); var child = target.Presenter.Child; Assert.IsType<Canvas>(child); } [Fact] public void DataTemplate_Created_Control_Should_Be_Logical_Child_After_ApplyTemplate() { var target = new ContentControl { Template = GetTemplate(), }; target.Content = "Foo"; target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); var child = target.Presenter.Child; Assert.NotNull(child); Assert.Equal(target, child.Parent); Assert.Equal(target, child.GetLogicalParent()); Assert.Equal(new[] { child }, target.GetLogicalChildren()); } [Fact] public void Clearing_Content_Should_Clear_Logical_Child() { var target = new ContentControl(); var child = new Control(); target.Content = child; Assert.Equal(new[] { child }, target.GetLogicalChildren()); target.Content = null; Assert.Null(child.Parent); Assert.Null(child.GetLogicalParent()); Assert.Empty(target.GetLogicalChildren()); } [Fact] public void Setting_Content_Should_Fire_LogicalChildren_CollectionChanged() { var target = new ContentControl(); var child = new Control(); var called = false; ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = e.Action == NotifyCollectionChangedAction.Add; target.Template = GetTemplate(); target.Content = child; target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); Assert.True(called); } [Fact] public void Clearing_Content_Should_Fire_LogicalChildren_CollectionChanged() { var target = new ContentControl(); var child = new Control(); var called = false; target.Template = GetTemplate(); target.Content = child; target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = true; target.Content = null; ((ContentPresenter)target.Presenter).UpdateChild(); Assert.True(called); } [Fact] public void Changing_Content_Should_Fire_LogicalChildren_CollectionChanged() { var target = new ContentControl(); var child1 = new Control(); var child2 = new Control(); var called = false; target.Template = GetTemplate(); target.Content = child1; target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = true; target.Content = child2; target.Presenter.ApplyTemplate(); Assert.True(called); } [Fact] public void Changing_Content_Should_Update_Presenter() { var target = new ContentControl(); target.Template = GetTemplate(); target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); target.Content = "Foo"; ((ContentPresenter)target.Presenter).UpdateChild(); Assert.Equal("Foo", ((TextBlock)target.Presenter.Child).Text); target.Content = "Bar"; ((ContentPresenter)target.Presenter).UpdateChild(); Assert.Equal("Bar", ((TextBlock)target.Presenter.Child).Text); } [Fact] public void DataContext_Should_Be_Set_For_DataTemplate_Created_Content() { var target = new ContentControl(); target.Template = GetTemplate(); target.Content = "Foo"; target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); Assert.Equal("Foo", target.Presenter.Child.DataContext); } [Fact] public void DataContext_Should_Not_Be_Set_For_Control_Content() { var target = new ContentControl(); target.Template = GetTemplate(); target.Content = new TextBlock(); target.ApplyTemplate(); ((ContentPresenter)target.Presenter).UpdateChild(); Assert.Null(target.Presenter.Child.DataContext); } [Fact] public void Binding_ContentTemplate_After_Content_Does_Not_Leave_Orpaned_TextBlock() { // Test for #1271. var children = new List<IControl>(); var presenter = new ContentPresenter(); // The content and then the content template property need to be bound with delayed bindings // as they are in Avalonia.Markup.Xaml. DelayedBinding.Add(presenter, ContentPresenter.ContentProperty, new Binding("Content") { Priority = BindingPriority.TemplatedParent, RelativeSource = new RelativeSource(RelativeSourceMode.TemplatedParent), }); DelayedBinding.Add(presenter, ContentPresenter.ContentTemplateProperty, new Binding("ContentTemplate") { Priority = BindingPriority.TemplatedParent, RelativeSource = new RelativeSource(RelativeSourceMode.TemplatedParent), }); presenter.GetObservable(ContentPresenter.ChildProperty).Subscribe(children.Add); var target = new ContentControl { Template = new FuncControlTemplate<ContentControl>((_, __) => presenter), ContentTemplate = new FuncDataTemplate<string>((_, __) => new Canvas()), Content = "foo", }; // The control must be rooted. var root = new TestRoot { Child = target, }; target.ApplyTemplate(); // When the template is applied, the Content property is bound before the ContentTemplate // property, causing a TextBlock to be created by the default template before ContentTemplate // is bound. Assert.Collection( children, x => Assert.Null(x), x => Assert.IsType<TextBlock>(x), x => Assert.IsType<Canvas>(x)); var textBlock = (TextBlock)children[1]; // The leak in #1271 was caused by the TextBlock's logical parent not being cleared when // it is replaced by the Canvas. Assert.Null(textBlock.GetLogicalParent()); } [Fact] public void Should_Set_Child_LogicalParent_After_Removing_And_Adding_Back_To_Logical_Tree() { using (UnitTestApplication.Start(TestServices.RealStyler)) { var target = new ContentControl(); var root = new TestRoot { Styles = { new Style(x => x.OfType<ContentControl>()) { Setters = { new Setter(ContentControl.TemplateProperty, GetTemplate()), } } }, Child = target }; target.Content = "Foo"; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); Assert.Equal(target, target.Presenter.Child.LogicalParent); root.Child = null; Assert.Null(target.Template); target.Content = null; root.Child = target; target.Content = "Bar"; Assert.Equal(target, target.Presenter.Child.LogicalParent); } } private FuncControlTemplate GetTemplate() { return new FuncControlTemplate<ContentControl>((parent, scope) => { return new Border { Background = new Media.SolidColorBrush(0xffffffff), Child = new ContentPresenter { Name = "PART_ContentPresenter", [~ContentPresenter.ContentProperty] = parent[~ContentControl.ContentProperty], [~ContentPresenter.ContentTemplateProperty] = parent[~ContentControl.ContentTemplateProperty], }.RegisterInNameScope(scope) }; }); } } }
// <copyright file="WebElement.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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 System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Drawing; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using OpenQA.Selenium.Interactions.Internal; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium { public class WebElement : IWebElement, IFindsElement, IWrapsDriver, ILocatable, ITakesScreenshot, IWebDriverObjectReference { /// <summary> /// The property name that represents a web element in the wire protocol. /// </summary> public const string ElementReferencePropertyName = "element-6066-11e4-a52e-4f735466cecf"; private WebDriver driver; private string elementId; /// <summary> /// Initializes a new instance of the <see cref="WebElement"/> class. /// </summary> /// <param name="parentDriver">The <see cref="WebDriver"/> instance that is driving this element.</param> /// <param name="id">The ID value provided to identify the element.</param> public WebElement(WebDriver parentDriver, string id) { this.driver = parentDriver; this.elementId = id; } /// <summary> /// Gets the <see cref="IWebDriver"/> driving this element. /// </summary> public IWebDriver WrappedDriver { get { return this.driver; } } /// <summary> /// Gets the tag name of this element. /// </summary> /// <remarks> /// The <see cref="TagName"/> property returns the tag name of the /// element, not the value of the name attribute. For example, it will return /// "input" for an element specified by the HTML markup &lt;input name="foo" /&gt;. /// </remarks> /// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception> public virtual string TagName { get { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("id", this.elementId); Response commandResponse = this.Execute(DriverCommand.GetElementTagName, parameters); return commandResponse.Value.ToString(); } } /// <summary> /// Gets the innerText of this element, without any leading or trailing whitespace, /// and with other whitespace collapsed. /// </summary> /// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception> public virtual string Text { get { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("id", this.elementId); Response commandResponse = this.Execute(DriverCommand.GetElementText, parameters); return commandResponse.Value.ToString(); } } /// <summary> /// Gets a value indicating whether or not this element is enabled. /// </summary> /// <remarks>The <see cref="Enabled"/> property will generally /// return <see langword="true"/> for everything except explicitly disabled input elements.</remarks> /// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception> public virtual bool Enabled { get { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("id", this.elementId); Response commandResponse = this.Execute(DriverCommand.IsElementEnabled, parameters); return (bool)commandResponse.Value; } } /// <summary> /// Gets a value indicating whether or not this element is selected. /// </summary> /// <remarks>This operation only applies to input elements such as checkboxes, /// options in a select element and radio buttons.</remarks> /// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception> public virtual bool Selected { get { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("id", this.elementId); Response commandResponse = this.Execute(DriverCommand.IsElementSelected, parameters); return (bool)commandResponse.Value; } } /// <summary> /// Gets a <see cref="Point"/> object containing the coordinates of the upper-left corner /// of this element relative to the upper-left corner of the page. /// </summary> /// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception> public virtual Point Location { get { string getLocationCommand = DriverCommand.GetElementRect; Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("id", this.Id); Response commandResponse = this.Execute(getLocationCommand, parameters); Dictionary<string, object> rawPoint = (Dictionary<string, object>)commandResponse.Value; int x = Convert.ToInt32(rawPoint["x"], CultureInfo.InvariantCulture); int y = Convert.ToInt32(rawPoint["y"], CultureInfo.InvariantCulture); return new Point(x, y); } } /// <summary> /// Gets a <see cref="Size"/> object containing the height and width of this element. /// </summary> /// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception> public virtual Size Size { get { string getSizeCommand = DriverCommand.GetElementRect; Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("id", this.Id); Response commandResponse = this.Execute(getSizeCommand, parameters); Dictionary<string, object> rawSize = (Dictionary<string, object>)commandResponse.Value; int width = Convert.ToInt32(rawSize["width"], CultureInfo.InvariantCulture); int height = Convert.ToInt32(rawSize["height"], CultureInfo.InvariantCulture); return new Size(width, height); } } /// <summary> /// Gets a value indicating whether or not this element is displayed. /// </summary> /// <remarks>The <see cref="Displayed"/> property avoids the problem /// of having to parse an element's "style" attribute to determine /// visibility of an element.</remarks> /// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception> public virtual bool Displayed { get { Response commandResponse = null; Dictionary<string, object> parameters = new Dictionary<string, object>(); string atom = GetAtom("is-displayed.js"); parameters.Add("script", atom); parameters.Add("args", new object[] { this.ToElementReference().ToDictionary() }); commandResponse = this.Execute(DriverCommand.ExecuteScript, parameters); return (bool)commandResponse.Value; } } /// <summary> /// Gets the point where the element would be when scrolled into view. /// </summary> public virtual Point LocationOnScreenOnceScrolledIntoView { get { Dictionary<string, object> rawLocation; object scriptResponse = this.driver.ExecuteScript("var rect = arguments[0].getBoundingClientRect(); return {'x': rect.left, 'y': rect.top};", this); rawLocation = scriptResponse as Dictionary<string, object>; int x = Convert.ToInt32(rawLocation["x"], CultureInfo.InvariantCulture); int y = Convert.ToInt32(rawLocation["y"], CultureInfo.InvariantCulture); return new Point(x, y); } } /// <summary> /// Gets the computed accessible label of this element. /// </summary> public virtual string ComputedAccessibleLabel { get { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("id", this.Id); Response commandResponse = this.Execute(DriverCommand.GetComputedAccessibleLabel, parameters); return commandResponse.Value.ToString(); } } /// <summary> /// Gets the computed ARIA role for this element. /// </summary> public virtual string ComputedAccessibleRole { get { // TODO: Returning this as a string is incorrect. The W3C WebDriver Specification // needs to be updated to more throughly document the structure of what is returned // by this command. Once that is done, a type-safe class will be created, and will // be returned by this property. Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("id", this.Id); Response commandResponse = this.Execute(DriverCommand.GetComputedAccessibleRole, parameters); return commandResponse.Value.ToString(); } } /// <summary> /// Gets the coordinates identifying the location of this element using /// various frames of reference. /// </summary> public virtual ICoordinates Coordinates { get { return new ElementCoordinates(this); } } /// <summary> /// Gets the internal ID of the element. /// </summary> string IWebDriverObjectReference.ObjectReferenceId { get { return this.elementId; } } /// <summary> /// Gets the ID of the element /// </summary> /// <remarks>This property is internal to the WebDriver instance, and is /// not intended to be used in your code. The element's ID has no meaning /// outside of internal WebDriver usage, so it would be improper to scope /// it as public. However, both subclasses of <see cref="RemoteWebElement"/> /// and the parent driver hosting the element have a need to access the /// internal element ID. Therefore, we have two properties returning the /// same value, one scoped as internal, the other as protected.</remarks> protected string Id { get { return this.elementId; } } /// <summary> /// Clears the content of this element. /// </summary> /// <remarks>If this element is a text entry element, the <see cref="Clear"/> /// method will clear the value. It has no effect on other elements. Text entry elements /// are defined as elements with INPUT or TEXTAREA tags.</remarks> /// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception> public virtual void Clear() { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("id", this.elementId); this.Execute(DriverCommand.ClearElement, parameters); } /// <summary> /// Clicks this element. /// </summary> /// <remarks> /// Click this element. If the click causes a new page to load, the <see cref="Click"/> /// method will attempt to block until the page has loaded. After calling the /// <see cref="Click"/> method, you should discard all references to this /// element unless you know that the element and the page will still be present. /// Otherwise, any further operations performed on this element will have an undefined /// behavior. /// </remarks> /// <exception cref="InvalidElementStateException">Thrown when the target element is not enabled.</exception> /// <exception cref="ElementNotVisibleException">Thrown when the target element is not visible.</exception> /// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception> public virtual void Click() { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("id", this.elementId); this.Execute(DriverCommand.ClickElement, parameters); } /// <summary> /// Finds the first <see cref="IWebElement"/> using the given method. /// </summary> /// <param name="by">The locating mechanism to use.</param> /// <returns>The first matching <see cref="IWebElement"/> on the current context.</returns> /// <exception cref="NoSuchElementException">If no element matches the criteria.</exception> public virtual IWebElement FindElement(By by) { if (by == null) { throw new ArgumentNullException(nameof(@by), "by cannot be null"); } return by.FindElement(this); } /// <summary> /// Finds a child element matching the given mechanism and value. /// </summary> /// <param name="mechanism">The mechanism by which to find the element.</param> /// <param name="value">The value to use to search for the element.</param> /// <returns>The first <see cref="IWebElement"/> matching the given criteria.</returns> public virtual IWebElement FindElement(string mechanism, string value) { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("id", this.elementId); parameters.Add("using", mechanism); parameters.Add("value", value); Response commandResponse = this.Execute(DriverCommand.FindChildElement, parameters); return this.driver.GetElementFromResponse(commandResponse); } /// <summary> /// Finds all <see cref="IWebElement">IWebElements</see> within the current context /// using the given mechanism. /// </summary> /// <param name="by">The locating mechanism to use.</param> /// <returns>A <see cref="ReadOnlyCollection{T}"/> of all <see cref="IWebElement">WebElements</see> /// matching the current criteria, or an empty list if nothing matches.</returns> public virtual ReadOnlyCollection<IWebElement> FindElements(By by) { if (by == null) { throw new ArgumentNullException(nameof(@by), "by cannot be null"); } return by.FindElements(this); } /// <summary> /// Finds all child elements matching the given mechanism and value. /// </summary> /// <param name="mechanism">The mechanism by which to find the elements.</param> /// <param name="value">The value to use to search for the elements.</param> /// <returns>A collection of all of the <see cref="IWebElement">IWebElements</see> matching the given criteria.</returns> public virtual ReadOnlyCollection<IWebElement> FindElements(string mechanism, string value) { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("id", this.elementId); parameters.Add("using", mechanism); parameters.Add("value", value); Response commandResponse = this.Execute(DriverCommand.FindChildElements, parameters); return this.driver.GetElementsFromResponse(commandResponse); } /// <summary> /// Gets the value of the specified attribute or property for this element. /// </summary> /// <param name="attributeName">The name of the attribute or property.</param> /// <returns>The attribute's or property's current value. Returns a <see langword="null"/> /// if the value is not set.</returns> /// <remarks>The <see cref="GetAttribute"/> method will return the current value /// of the attribute or property, even if the value has been modified after the page /// has been loaded. Note that the value of the following attributes will be returned /// even if there is no explicit attribute on the element: /// <list type="table"> /// <listheader> /// <term>Attribute name</term> /// <term>Value returned if not explicitly specified</term> /// <term>Valid element types</term> /// </listheader> /// <item> /// <description>checked</description> /// <description>checked</description> /// <description>Check Box</description> /// </item> /// <item> /// <description>selected</description> /// <description>selected</description> /// <description>Options in Select elements</description> /// </item> /// <item> /// <description>disabled</description> /// <description>disabled</description> /// <description>Input and other UI elements</description> /// </item> /// </list> /// The method looks both in declared attributes in the HTML markup of the page, and /// in the properties of the element as found when accessing the element's properties /// via JavaScript. /// </remarks> /// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception> public virtual string GetAttribute(string attributeName) { Response commandResponse = null; string attributeValue = string.Empty; Dictionary<string, object> parameters = new Dictionary<string, object>(); string atom = GetAtom("get-attribute.js"); parameters.Add("script", atom); parameters.Add("args", new object[] { this.ToElementReference().ToDictionary(), attributeName }); commandResponse = this.Execute(DriverCommand.ExecuteScript, parameters); if (commandResponse.Value == null) { attributeValue = null; } else { attributeValue = commandResponse.Value.ToString(); // Normalize string values of boolean results as lowercase. if (commandResponse.Value is bool) { attributeValue = attributeValue.ToLowerInvariant(); } } return attributeValue; } /// <summary> /// Gets the value of a declared HTML attribute of this element. /// </summary> /// <param name="attributeName">The name of the HTML attribute to get the value of.</param> /// <returns>The HTML attribute's current value. Returns a <see langword="null"/> if the /// value is not set or the declared attribute does not exist.</returns> /// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception> /// <remarks> /// As opposed to the <see cref="GetAttribute(string)"/> method, this method /// only returns attributes declared in the element's HTML markup. To access the value /// of an IDL property of the element, either use the <see cref="GetAttribute(string)"/> /// method or the <see cref="GetDomProperty(string)"/> method. /// </remarks> public virtual string GetDomAttribute(string attributeName) { string attributeValue = string.Empty; Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("id", this.Id); parameters.Add("name", attributeName); Response commandResponse = this.Execute(DriverCommand.GetElementAttribute, parameters); if (commandResponse.Value == null) { attributeValue = null; } else { attributeValue = commandResponse.Value.ToString(); } return attributeValue; } /// <summary> /// Gets the value of a JavaScript property of this element. /// </summary> /// <param name="propertyName">The name of the JavaScript property to get the value of.</param> /// <returns>The JavaScript property's current value. Returns a <see langword="null"/> if the /// value is not set or the property does not exist.</returns> /// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception> [Obsolete("Use the GetDomProperty method instead.")] public virtual string GetProperty(string propertyName) { return this.GetDomProperty(propertyName); } /// <summary> /// Gets the value of a JavaScript property of this element. /// </summary> /// <param name="propertyName">The name of the JavaScript property to get the value of.</param> /// <returns>The JavaScript property's current value. Returns a <see langword="null"/> if the /// value is not set or the property does not exist.</returns> /// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception> public virtual string GetDomProperty(string propertyName) { string propertyValue = string.Empty; Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("id", this.Id); parameters.Add("name", propertyName); Response commandResponse = this.Execute(DriverCommand.GetElementProperty, parameters); if (commandResponse.Value == null) { propertyValue = null; } else { propertyValue = commandResponse.Value.ToString(); } return propertyValue; } /// <summary> /// Gets the representation of an element's shadow root for accessing the shadow DOM of a web component. /// </summary> /// <returns>A shadow root representation.</returns> /// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception> /// <exception cref="NoSuchShadowRootException">Thrown when this element does not have a shadow root.</exception> public virtual ISearchContext GetShadowRoot() { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("id", this.Id); Response commandResponse = this.Execute(DriverCommand.GetElementShadowRoot, parameters); Dictionary<string, object> shadowRootDictionary = commandResponse.Value as Dictionary<string, object>; if (shadowRootDictionary == null) { throw new WebDriverException("Get shadow root command succeeded, but response value does not represent a shadow root."); } if (!shadowRootDictionary.ContainsKey(ShadowRoot.ShadowRootReferencePropertyName)) { throw new WebDriverException("Get shadow root command succeeded, but response value does not have a shadow root key value."); } string shadowRootId = shadowRootDictionary[ShadowRoot.ShadowRootReferencePropertyName].ToString(); return new ShadowRoot(this.driver, shadowRootId); } /// <summary> /// Gets the value of a CSS property of this element. /// </summary> /// <param name="propertyName">The name of the CSS property to get the value of.</param> /// <returns>The value of the specified CSS property.</returns> /// <remarks>The value returned by the <see cref="GetCssValue"/> /// method is likely to be unpredictable in a cross-browser environment. /// Color values should be returned as hex strings. For example, a /// "background-color" property set as "green" in the HTML source, will /// return "#008000" for its value.</remarks> /// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception> public virtual string GetCssValue(string propertyName) { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("id", this.Id); parameters.Add("name", propertyName); Response commandResponse = this.Execute(DriverCommand.GetElementValueOfCssProperty, parameters); return commandResponse.Value.ToString(); } /// <summary> /// Gets a <see cref="Screenshot"/> object representing the image of this element on the screen. /// </summary> /// <returns>A <see cref="Screenshot"/> object containing the image.</returns> public virtual Screenshot GetScreenshot() { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("id", this.elementId); // Get the screenshot as base64. Response screenshotResponse = this.Execute(DriverCommand.ElementScreenshot, parameters); string base64 = screenshotResponse.Value.ToString(); // ... and convert it. return new Screenshot(base64); } /// <summary> /// Simulates typing text into the element. /// </summary> /// <param name="text">The text to type into the element.</param> /// <remarks>The text to be typed may include special characters like arrow keys, /// backspaces, function keys, and so on. Valid special keys are defined in /// <see cref="Keys"/>.</remarks> /// <seealso cref="Keys"/> /// <exception cref="InvalidElementStateException">Thrown when the target element is not enabled.</exception> /// <exception cref="ElementNotVisibleException">Thrown when the target element is not visible.</exception> /// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception> public virtual void SendKeys(string text) { if (text == null) { throw new ArgumentNullException(nameof(text), "text cannot be null"); } var fileNames = text.Split('\n'); if (fileNames.All(this.driver.FileDetector.IsFile)) { var uploadResults = new List<string>(); foreach (var fileName in fileNames) { uploadResults.Add(this.UploadFile(fileName)); } text = string.Join("\n", uploadResults); } // N.B. The Java remote server expects a CharSequence as the value input to // SendKeys. In JSON, these are serialized as an array of strings, with a // single character to each element of the array. Thus, we must use ToCharArray() // to get the same effect. // TODO: Remove either "keysToSend" or "value" property, whichever is not the // appropriate one for spec compliance. Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("id", this.elementId); parameters.Add("text", text); parameters.Add("value", text.ToCharArray()); this.Execute(DriverCommand.SendKeysToElement, parameters); } /// <summary> /// Submits this element to the web server. /// </summary> /// <remarks>If this current element is a form, or an element within a form, /// then this will be submitted to the web server. If this causes the current /// page to change, then this method will attempt to block until the new page /// is loaded.</remarks> /// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception> public virtual void Submit() { string elementType = this.GetAttribute("type"); if (elementType != null && elementType == "submit") { this.Click(); } else { IWebElement form = this.FindElement(By.XPath("./ancestor-or-self::form")); this.driver.ExecuteScript( "var e = arguments[0].ownerDocument.createEvent('Event');" + "e.initEvent('submit', true, true);" + "if (arguments[0].dispatchEvent(e)) { arguments[0].submit(); }", form); } } /// <summary> /// Returns a string that represents the current <see cref="WebElement"/>. /// </summary> /// <returns>A string that represents the current <see cref="WebElement"/>.</returns> public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "Element (id = {0})", this.elementId); } /// <summary> /// Method to get the hash code of the element /// </summary> /// <returns>Integer of the hash code for the element</returns> public override int GetHashCode() { return this.elementId.GetHashCode(); } /// <summary> /// Compares if two elements are equal /// </summary> /// <param name="obj">Object to compare against</param> /// <returns>A boolean if it is equal or not</returns> public override bool Equals(object obj) { IWebElement other = obj as IWebElement; if (other == null) { return false; } IWrapsElement objAsWrapsElement = obj as IWrapsElement; if (objAsWrapsElement != null) { other = objAsWrapsElement.WrappedElement; } WebElement otherAsElement = other as WebElement; if (otherAsElement == null) { return false; } if (this.elementId == otherAsElement.Id) { // For drivers that implement ID equality, we can check for equal IDs // here, and expect them to be equal. There is a potential danger here // where two different elements are assigned the same ID. return true; } return false; } Dictionary<string, object> IWebDriverObjectReference.ToDictionary() { Dictionary<string, object> elementDictionary = new Dictionary<string, object>(); elementDictionary.Add(ElementReferencePropertyName, this.elementId); return elementDictionary; } /// <summary> /// Executes a command on this element using the specified parameters. /// </summary> /// <param name="commandToExecute">The <see cref="DriverCommand"/> to execute against this element.</param> /// <param name="parameters">A <see cref="Dictionary{K, V}"/> containing names and values of the parameters for the command.</param> /// <returns>The <see cref="Response"/> object containing the result of the command execution.</returns> protected virtual Response Execute(string commandToExecute, Dictionary<string, object> parameters) { return this.driver.InternalExecute(commandToExecute, parameters); } private static string GetAtom(string atomResourceName) { string atom = string.Empty; using (Stream atomStream = ResourceUtilities.GetResourceStream(atomResourceName, atomResourceName)) { using (StreamReader atomReader = new StreamReader(atomStream)) { atom = atomReader.ReadToEnd(); } } string wrappedAtom = string.Format(CultureInfo.InvariantCulture, "return ({0}).apply(null, arguments);", atom); return wrappedAtom; } private string UploadFile(string localFile) { string base64zip = string.Empty; try { using (MemoryStream fileUploadMemoryStream = new MemoryStream()) { using (ZipArchive zipArchive = new ZipArchive(fileUploadMemoryStream, ZipArchiveMode.Create)) { string fileName = Path.GetFileName(localFile); zipArchive.CreateEntryFromFile(localFile, fileName); } base64zip = Convert.ToBase64String(fileUploadMemoryStream.ToArray()); } Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("file", base64zip); Response response = this.Execute(DriverCommand.UploadFile, parameters); return response.Value.ToString(); } catch (IOException e) { throw new WebDriverException("Cannot upload " + localFile, e); } } private IWebDriverObjectReference ToElementReference() { return this as IWebDriverObjectReference; } } }
using System; using System.Diagnostics; namespace Amib.Threading.Internal { internal enum STPPerformanceCounterType { // Fields ActiveThreads = 0, InUseThreads = 1, OverheadThreads = 2, OverheadThreadsPercent = 3, OverheadThreadsPercentBase = 4, WorkItems = 5, WorkItemsInQueue = 6, WorkItemsProcessed = 7, WorkItemsQueuedPerSecond = 8, WorkItemsProcessedPerSecond = 9, AvgWorkItemWaitTime = 10, AvgWorkItemWaitTimeBase = 11, AvgWorkItemProcessTime = 12, AvgWorkItemProcessTimeBase = 13, WorkItemsGroups = 14, LastCounter = 14, } /// <summary> /// Summary description for STPPerformanceCounter. /// </summary> internal class STPPerformanceCounter { // Fields private PerformanceCounterType _pcType; protected string _counterHelp; protected string _counterName; // Methods public STPPerformanceCounter( string counterName, string counterHelp, PerformanceCounterType pcType) { this._counterName = counterName; this._counterHelp = counterHelp; this._pcType = pcType; } public void AddCounterToCollection(CounterCreationDataCollection counterData) { CounterCreationData counterCreationData = new CounterCreationData( _counterName, _counterHelp, _pcType); counterData.Add(counterCreationData); } // Properties public string Name { get { return _counterName; } } } internal class STPPerformanceCounters { // Fields internal STPPerformanceCounter[] _stpPerformanceCounters; private static STPPerformanceCounters _instance; internal const string _stpCategoryHelp = "SmartThreadPool performance counters"; internal const string _stpCategoryName = "SmartThreadPool"; // Methods static STPPerformanceCounters() { _instance = new STPPerformanceCounters(); } private STPPerformanceCounters() { STPPerformanceCounter[] stpPerformanceCounters = new STPPerformanceCounter[] { new STPPerformanceCounter("Active threads", "The current number of available in the thread pool.", PerformanceCounterType.NumberOfItems32), new STPPerformanceCounter("In use threads", "The current number of threads that execute a work item.", PerformanceCounterType.NumberOfItems32), new STPPerformanceCounter("Overhead threads", "The current number of threads that are active, but are not in use.", PerformanceCounterType.NumberOfItems32), new STPPerformanceCounter("% overhead threads", "The current number of threads that are active, but are not in use in percents.", PerformanceCounterType.RawFraction), new STPPerformanceCounter("% overhead threads base", "The current number of threads that are active, but are not in use in percents.", PerformanceCounterType.RawBase), new STPPerformanceCounter("Work Items", "The number of work items in the Smart Thread Pool. Both queued and processed.", PerformanceCounterType.NumberOfItems32), new STPPerformanceCounter("Work Items in queue", "The current number of work items in the queue", PerformanceCounterType.NumberOfItems32), new STPPerformanceCounter("Work Items processed", "The number of work items already processed", PerformanceCounterType.NumberOfItems32), new STPPerformanceCounter("Work Items queued/sec", "The number of work items queued per second", PerformanceCounterType.RateOfCountsPerSecond32), new STPPerformanceCounter("Work Items processed/sec", "The number of work items processed per second", PerformanceCounterType.RateOfCountsPerSecond32), new STPPerformanceCounter("Avg. Work Item wait time/sec", "The average time a work item supends in the queue waiting for its turn to execute.", PerformanceCounterType.AverageCount64), new STPPerformanceCounter("Avg. Work Item wait time base", "The average time a work item supends in the queue waiting for its turn to execute.", PerformanceCounterType.AverageBase), new STPPerformanceCounter("Avg. Work Item process time/sec", "The average time it takes to process a work item.", PerformanceCounterType.AverageCount64), new STPPerformanceCounter("Avg. Work Item process time base", "The average time it takes to process a work item.", PerformanceCounterType.AverageBase), new STPPerformanceCounter("Work Items Groups", "The current number of work item groups associated with the Smart Thread Pool.", PerformanceCounterType.NumberOfItems32), }; _stpPerformanceCounters = stpPerformanceCounters; SetupCategory(); } private void SetupCategory() { if (!PerformanceCounterCategory.Exists(_stpCategoryName)) { CounterCreationDataCollection counters = new CounterCreationDataCollection(); for (int i = 0; i < _stpPerformanceCounters.Length; i++) { _stpPerformanceCounters[i].AddCounterToCollection(counters); } // *********** Remark for .NET 2.0 *********** // If you are here, it means you got the warning that this overload // of the method is deprecated in .NET 2.0. To use the correct // method overload, uncomment the third argument of // the method. #pragma warning disable 0618 PerformanceCounterCategory.Create( _stpCategoryName, _stpCategoryHelp, //PerformanceCounterCategoryType.MultiInstance, counters); #pragma warning restore 0618 } } // Properties public static STPPerformanceCounters Instance { get { return _instance; } } } internal class STPInstancePerformanceCounter : IDisposable { // Fields private PerformanceCounter _pcs; // Methods protected STPInstancePerformanceCounter() { } public STPInstancePerformanceCounter( string instance, STPPerformanceCounterType spcType) { STPPerformanceCounters counters = STPPerformanceCounters.Instance; _pcs = new PerformanceCounter( STPPerformanceCounters._stpCategoryName, counters._stpPerformanceCounters[(int) spcType].Name, instance, false); _pcs.RawValue = _pcs.RawValue; } ~STPInstancePerformanceCounter() { Close(); } public void Close() { if (_pcs != null) { _pcs.RemoveInstance(); _pcs.Close(); _pcs = null; } } public void Dispose() { Close(); GC.SuppressFinalize(this); } public virtual void Increment() { _pcs.Increment(); } public virtual void IncrementBy(long val) { _pcs.IncrementBy(val); } public virtual void Set(long val) { _pcs.RawValue = val; } } internal class STPInstanceNullPerformanceCounter : STPInstancePerformanceCounter { // Methods public STPInstanceNullPerformanceCounter() {} public override void Increment() {} public override void IncrementBy(long value) {} public override void Set(long val) {} } internal interface ISTPInstancePerformanceCounters : IDisposable { void Close(); void SampleThreads(long activeThreads, long inUseThreads); void SampleWorkItems(long workItemsQueued, long workItemsProcessed); void SampleWorkItemsWaitTime(TimeSpan workItemWaitTime); void SampleWorkItemsProcessTime(TimeSpan workItemProcessTime); } internal class STPInstancePerformanceCounters : ISTPInstancePerformanceCounters, IDisposable { // Fields private STPInstancePerformanceCounter[] _pcs; private static STPInstancePerformanceCounter _stpInstanceNullPerformanceCounter; // Methods static STPInstancePerformanceCounters() { _stpInstanceNullPerformanceCounter = new STPInstanceNullPerformanceCounter(); } public STPInstancePerformanceCounters(string instance) { _pcs = new STPInstancePerformanceCounter[(int)STPPerformanceCounterType.LastCounter]; // STPPerformanceCounters counters = STPPerformanceCounters.Instance; for (int i = 0; i < _pcs.Length; i++) { if (instance != null) { _pcs[i] = new STPInstancePerformanceCounter( instance, (STPPerformanceCounterType) i); } else { _pcs[i] = _stpInstanceNullPerformanceCounter; } } } public void Close() { if (null != _pcs) { for (int i = 0; i < _pcs.Length; i++) { if (null != _pcs[i]) { _pcs[i].Close(); } } _pcs = null; } } ~STPInstancePerformanceCounters() { Close(); } public void Dispose() { Close(); GC.SuppressFinalize(this); } private STPInstancePerformanceCounter GetCounter(STPPerformanceCounterType spcType) { return _pcs[(int) spcType]; } public void SampleThreads(long activeThreads, long inUseThreads) { GetCounter(STPPerformanceCounterType.ActiveThreads).Set(activeThreads); GetCounter(STPPerformanceCounterType.InUseThreads).Set(inUseThreads); GetCounter(STPPerformanceCounterType.OverheadThreads).Set(activeThreads-inUseThreads); GetCounter(STPPerformanceCounterType.OverheadThreadsPercentBase).Set(activeThreads-inUseThreads); GetCounter(STPPerformanceCounterType.OverheadThreadsPercent).Set(inUseThreads); } public void SampleWorkItems(long workItemsQueued, long workItemsProcessed) { GetCounter(STPPerformanceCounterType.WorkItems).Set(workItemsQueued+workItemsProcessed); GetCounter(STPPerformanceCounterType.WorkItemsInQueue).Set(workItemsQueued); GetCounter(STPPerformanceCounterType.WorkItemsProcessed).Set(workItemsProcessed); GetCounter(STPPerformanceCounterType.WorkItemsQueuedPerSecond).Set(workItemsQueued); GetCounter(STPPerformanceCounterType.WorkItemsProcessedPerSecond).Set(workItemsProcessed); } public void SampleWorkItemsWaitTime(TimeSpan workItemWaitTime) { GetCounter(STPPerformanceCounterType.AvgWorkItemWaitTime).IncrementBy((long)workItemWaitTime.TotalMilliseconds); GetCounter(STPPerformanceCounterType.AvgWorkItemWaitTimeBase).Increment(); } public void SampleWorkItemsProcessTime(TimeSpan workItemProcessTime) { GetCounter(STPPerformanceCounterType.AvgWorkItemProcessTime).IncrementBy((long)workItemProcessTime.TotalMilliseconds); GetCounter(STPPerformanceCounterType.AvgWorkItemProcessTimeBase).Increment(); } } internal class NullSTPInstancePerformanceCounters : ISTPInstancePerformanceCounters, IDisposable { static NullSTPInstancePerformanceCounters() { } private static NullSTPInstancePerformanceCounters _instance = new NullSTPInstancePerformanceCounters(null); public static NullSTPInstancePerformanceCounters Instance { get { return _instance; } } public NullSTPInstancePerformanceCounters(string instance) {} public void Close() {} public void Dispose() {} public void SampleThreads(long activeThreads, long inUseThreads) {} public void SampleWorkItems(long workItemsQueued, long workItemsProcessed) {} public void SampleWorkItemsWaitTime(TimeSpan workItemWaitTime) {} public void SampleWorkItemsProcessTime(TimeSpan workItemProcessTime) {} } }
/******************************************************************** * * PropertyBag.cs * -------------- * Derived from PropertyBag.cs by Tony Allowatt * CodeProject: http://www.codeproject.com/cs/miscctrl/bending_property.asp * Last Update: 04/05/2005 * ********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing.Design; using System.Reflection; using CslaGenerator.Attributes; using CslaGenerator.Metadata; namespace CslaGenerator.Util.PropertyBags { /// <summary> /// Represents a collection of custom properties that can be selected into a /// PropertyGrid to provide functionality beyond that of the simple reflection /// normally used to query an object's properties. /// </summary> public class ConvertValuePropertyBag : ICustomTypeDescriptor { #region PropertySpecCollection class definition /// <summary> /// Encapsulates a collection of PropertySpec objects. /// </summary> [Serializable] public class PropertySpecCollection : IList { private readonly ArrayList _innerArray; /// <summary> /// Initializes a new instance of the PropertySpecCollection class. /// </summary> public PropertySpecCollection() { _innerArray = new ArrayList(); } /// <summary> /// Gets or sets the element at the specified index. /// In C#, this property is the indexer for the PropertySpecCollection class. /// </summary> /// <param name="index">The zero-based index of the element to get or set.</param> /// <value> /// The element at the specified index. /// </value> public PropertySpec this[int index] { get { return (PropertySpec) _innerArray[index]; } set { _innerArray[index] = value; } } #region IList Members /// <summary> /// Gets the number of elements in the PropertySpecCollection. /// </summary> /// <value> /// The number of elements contained in the PropertySpecCollection. /// </value> public int Count { get { return _innerArray.Count; } } /// <summary> /// Gets a value indicating whether the PropertySpecCollection has a fixed size. /// </summary> /// <value> /// true if the PropertySpecCollection has a fixed size; otherwise, false. /// </value> public bool IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the PropertySpecCollection is read-only. /// </summary> public bool IsReadOnly { get { return false; } } /// <summary> /// Gets a value indicating whether access to the collection is synchronized (thread-safe). /// </summary> /// <value> /// true if access to the PropertySpecCollection is synchronized (thread-safe); otherwise, false. /// </value> public bool IsSynchronized { get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the collection. /// </summary> /// <value> /// An object that can be used to synchronize access to the collection. /// </value> object ICollection.SyncRoot { get { return null; } } /// <summary> /// Removes all elements from the PropertySpecCollection. /// </summary> public void Clear() { _innerArray.Clear(); } /// <summary> /// Returns an enumerator that can iterate through the PropertySpecCollection. /// </summary> /// <returns>An IEnumerator for the entire PropertySpecCollection.</returns> public IEnumerator GetEnumerator() { return _innerArray.GetEnumerator(); } /// <summary> /// Removes the object at the specified index of the PropertySpecCollection. /// </summary> /// <param name="index">The zero-based index of the element to remove.</param> public void RemoveAt(int index) { _innerArray.RemoveAt(index); } #endregion /// <summary> /// Adds a PropertySpec to the end of the PropertySpecCollection. /// </summary> /// <param name="value">The PropertySpec to be added to the end of the PropertySpecCollection.</param> /// <returns>The PropertySpecCollection index at which the value has been added.</returns> public int Add(PropertySpec value) { int index = _innerArray.Add(value); return index; } /// <summary> /// Adds the elements of an array of PropertySpec objects to the end of the PropertySpecCollection. /// </summary> /// <param name="array">The PropertySpec array whose elements should be added to the end of the /// PropertySpecCollection.</param> public void AddRange(PropertySpec[] array) { _innerArray.AddRange(array); } /// <summary> /// Determines whether a PropertySpec is in the PropertySpecCollection. /// </summary> /// <param name="item">The PropertySpec to locate in the PropertySpecCollection. The element to locate /// can be a null reference (Nothing in Visual Basic).</param> /// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns> public bool Contains(PropertySpec item) { return _innerArray.Contains(item); } /// <summary> /// Determines whether a PropertySpec with the specified name is in the PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns> public bool Contains(string name) { foreach (PropertySpec spec in _innerArray) if (spec.Name == name) return true; return false; } /// <summary> /// Copies the entire PropertySpecCollection to a compatible one-dimensional Array, starting at the /// beginning of the target array. /// </summary> /// <param name="array">The one-dimensional Array that is the destination of the elements copied /// from PropertySpecCollection. The Array must have zero-based indexing.</param> public void CopyTo(PropertySpec[] array) { _innerArray.CopyTo(array); } /// <summary> /// Copies the PropertySpecCollection or a portion of it to a one-dimensional array. /// </summary> /// <param name="array">The one-dimensional Array that is the destination of the elements copied /// from the collection.</param> /// <param name="index">The zero-based index in array at which copying begins.</param> public void CopyTo(PropertySpec[] array, int index) { _innerArray.CopyTo(array, index); } /// <summary> /// Searches for the specified PropertySpec and returns the zero-based index of the first /// occurrence within the entire PropertySpecCollection. /// </summary> /// <param name="value">The PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection, /// if found; otherwise, -1.</returns> public int IndexOf(PropertySpec value) { return _innerArray.IndexOf(value); } /// <summary> /// Searches for the PropertySpec with the specified name and returns the zero-based index of /// the first occurrence within the entire PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection, /// if found; otherwise, -1.</returns> public int IndexOf(string name) { int i = 0; foreach (PropertySpec spec in _innerArray) { //if (spec.Name == name) if (spec.TargetProperty == name) return i; i++; } return -1; } /// <summary> /// Inserts a PropertySpec object into the PropertySpecCollection at the specified index. /// </summary> /// <param name="index">The zero-based index at which value should be inserted.</param> /// <param name="value">The PropertySpec to insert.</param> public void Insert(int index, PropertySpec value) { _innerArray.Insert(index, value); } /// <summary> /// Removes the first occurrence of a specific object from the PropertySpecCollection. /// </summary> /// <param name="obj">The PropertySpec to remove from the PropertySpecCollection.</param> public void Remove(PropertySpec obj) { _innerArray.Remove(obj); } /// <summary> /// Removes the property with the specified name from the PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to remove from the PropertySpecCollection.</param> public void Remove(string name) { int index = IndexOf(name); RemoveAt(index); } /// <summary> /// Copies the elements of the PropertySpecCollection to a new PropertySpec array. /// </summary> /// <returns>A PropertySpec array containing copies of the elements of the PropertySpecCollection.</returns> public PropertySpec[] ToArray() { return (PropertySpec[]) _innerArray.ToArray(typeof (PropertySpec)); } #region Explicit interface implementations for ICollection and IList /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void ICollection.CopyTo(Array array, int index) { CopyTo((PropertySpec[]) array, index); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> int IList.Add(object value) { return Add((PropertySpec) value); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> bool IList.Contains(object obj) { return Contains((PropertySpec) obj); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> object IList.this[int index] { get { return this[index]; } set { this[index] = (PropertySpec) value; } } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> int IList.IndexOf(object obj) { return IndexOf((PropertySpec) obj); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void IList.Insert(int index, object value) { Insert(index, (PropertySpec) value); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void IList.Remove(object value) { Remove((PropertySpec) value); } #endregion } #endregion #region PropertySpecDescriptor class definition private class PropertySpecDescriptor : PropertyDescriptor { private readonly ConvertValuePropertyBag _bag; private readonly PropertySpec _item; public PropertySpecDescriptor(PropertySpec item, ConvertValuePropertyBag bag, string name, Attribute[] attrs) : base(name, attrs) { _bag = bag; _item = item; } public override Type ComponentType { get { return _item.GetType(); } } public override bool IsReadOnly { get { return (Attributes.Matches(ReadOnlyAttribute.Yes)); } } public override Type PropertyType { get { return Type.GetType(_item.TypeName); } } public override bool CanResetValue(object component) { if (_item.DefaultValue == null) return false; return !GetValue(component).Equals(_item.DefaultValue); } public override object GetValue(object component) { // Have the property bag raise an event to get the current value // of the property. var e = new PropertySpecEventArgs(_item, null); _bag.OnGetValue(e); return e.Value; } public override void ResetValue(object component) { SetValue(component, _item.DefaultValue); } public override void SetValue(object component, object value) { // Have the property bag raise an event to set the current value // of the property. var e = new PropertySpecEventArgs(_item, value); _bag.OnSetValue(e); } public override bool ShouldSerializeValue(object component) { object val = GetValue(component); if (_item.DefaultValue == null && val == null) return false; return !val.Equals(_item.DefaultValue); } } #endregion #region Properties and Events private readonly PropertySpecCollection _properties; private string _defaultProperty; private ConvertValueProperty[] _selectedObject; /// <summary> /// Initializes a new instance of the ConvertValuePropertyBag class. /// </summary> public ConvertValuePropertyBag() { _defaultProperty = null; _properties = new PropertySpecCollection(); } public ConvertValuePropertyBag(ConvertValueProperty obj) : this(new[] {obj}) { } public ConvertValuePropertyBag(ConvertValueProperty[] obj) { _defaultProperty = "BaseName"; _properties = new PropertySpecCollection(); _selectedObject = obj; InitPropertyBag(); } /// <summary> /// Gets or sets the name of the default property in the collection. /// </summary> public string DefaultProperty { get { return _defaultProperty; } set { _defaultProperty = value; } } /// <summary> /// Gets or sets the name of the default property in the collection. /// </summary> public ConvertValueProperty[] SelectedObject { get { return _selectedObject; } set { _selectedObject = value; InitPropertyBag(); } } /// <summary> /// Gets the collection of properties contained within this ConvertValuePropertyBag. /// </summary> public PropertySpecCollection Properties { get { return _properties; } } /// <summary> /// Occurs when a PropertyGrid requests the value of a property. /// </summary> public event PropertySpecEventHandler GetValue; /// <summary> /// Occurs when the user changes the value of a property in a PropertyGrid. /// </summary> public event PropertySpecEventHandler SetValue; /// <summary> /// Raises the GetValue event. /// </summary> /// <param name="e">A PropertySpecEventArgs that contains the event data.</param> protected virtual void OnGetValue(PropertySpecEventArgs e) { if (e.Value != null) GetValue(this, e); e.Value = GetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Property.DefaultValue); } /// <summary> /// Raises the SetValue event. /// </summary> /// <param name="e">A PropertySpecEventArgs that contains the event data.</param> protected virtual void OnSetValue(PropertySpecEventArgs e) { if (SetValue != null) SetValue(this, e); SetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Value); } #endregion #region Initialize Propertybag private void InitPropertyBag() { PropertyInfo pi; Type t = typeof (ConvertValueProperty); // _selectedObject.GetType(); PropertyInfo[] props = t.GetProperties(); // Display information for all properties. for (int i = 0; i < props.Length; i++) { pi = props[i]; object[] myAttributes = pi.GetCustomAttributes(true); string category = ""; string description = ""; bool isreadonly = false; bool isbrowsable = true; object defaultvalue = null; string userfriendlyname = ""; string typeconverter = ""; string designertypename = ""; string helptopic = ""; bool bindable = true; string editor = ""; for (int n = 0; n < myAttributes.Length; n++) { var a = (Attribute) myAttributes[n]; switch (a.GetType().ToString()) { case "System.ComponentModel.CategoryAttribute": category = ((CategoryAttribute) a).Category; break; case "System.ComponentModel.DescriptionAttribute": description = ((DescriptionAttribute) a).Description; break; case "System.ComponentModel.ReadOnlyAttribute": isreadonly = ((ReadOnlyAttribute) a).IsReadOnly; break; case "System.ComponentModel.BrowsableAttribute": isbrowsable = ((BrowsableAttribute) a).Browsable; break; case "System.ComponentModel.DefaultValueAttribute": defaultvalue = ((DefaultValueAttribute) a).Value; break; case "CslaGenerator.Attributes.UserFriendlyNameAttribute": userfriendlyname = ((UserFriendlyNameAttribute) a).UserFriendlyName; break; case "CslaGenerator.Attributes.HelpTopicAttribute": helptopic = ((HelpTopicAttribute) a).HelpTopic; break; case "System.ComponentModel.TypeConverterAttribute": typeconverter = ((TypeConverterAttribute) a).ConverterTypeName; break; case "System.ComponentModel.DesignerAttribute": designertypename = ((DesignerAttribute) a).DesignerTypeName; break; case "System.ComponentModel.BindableAttribute": bindable = ((BindableAttribute) a).Bindable; break; case "System.ComponentModel.EditorAttribute": editor = ((EditorAttribute) a).EditorTypeName; break; } } userfriendlyname = userfriendlyname.Length > 0 ? userfriendlyname : pi.Name; var types = new List<string>(); foreach (var obj in _selectedObject) { if (!types.Contains(obj.Name)) types.Add(obj.Name); } // here get rid of ComponentName and Parent bool isValidProperty = (pi.Name != "Properties" && pi.Name != "ComponentName" && pi.Name != "Parent"); if (isValidProperty && IsBrowsable(types.ToArray(), pi.Name)) { // CR added missing parameters //this.Properties.Add(new PropertySpec(userfriendlyname,pi.PropertyType.AssemblyQualifiedName,category,description,defaultvalue, editor, typeconverter, _selectedObject, pi.Name,helptopic)); Properties.Add(new PropertySpec(userfriendlyname, pi.PropertyType.AssemblyQualifiedName, category, description, defaultvalue, editor, typeconverter, _selectedObject, pi.Name, helptopic, isreadonly, isbrowsable, designertypename, bindable)); } } } #endregion private readonly Dictionary<string, PropertyInfo> propertyInfoCache = new Dictionary<string, PropertyInfo>(); private PropertyInfo GetPropertyInfoCache(string propertyName) { if (!propertyInfoCache.ContainsKey(propertyName)) { propertyInfoCache.Add(propertyName, typeof (ConvertValueProperty).GetProperty(propertyName)); } return propertyInfoCache[propertyName]; } private bool IsEnumerable(PropertyInfo prop) { if (prop.PropertyType == typeof (string)) return false; Type[] interfaces = prop.PropertyType.GetInterfaces(); foreach (Type typ in interfaces) if (typ.Name.Contains("IEnumerable")) return true; return false; } #region IsBrowsable map objecttype:propertyname -> true | false private bool IsBrowsable(string[] objectType, string propertyName) { try { if ((GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == Authorization.None || GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == Authorization.ObjectLevel) && (propertyName == "AllowReadRoles" || propertyName == "AllowWriteRoles" || propertyName == "DenyReadRoles" || propertyName == "DenyWriteRoles")) return false; if (_selectedObject.Length > 1 && IsEnumerable(GetPropertyInfoCache(propertyName))) return false; return true; } catch //(Exception e) { Debug.WriteLine(objectType + ":" + propertyName); return true; } } #endregion #region Reflection functions private object GetField(Type t, string name, object target) { object obj = null; Type tx; FieldInfo[] fields; //fields = target.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); fields = target.GetType().GetFields(BindingFlags.Public); tx = target.GetType(); obj = tx.InvokeMember(name, BindingFlags.Default | BindingFlags.GetField, null, target, new object[] {}); return obj; } private object SetField(Type t, string name, object value, object target) { object obj; obj = t.InvokeMember(name, BindingFlags.Default | BindingFlags.SetField, null, target, new[] {value}); return obj; } private bool SetProperty(object obj, string propertyName, object val) { try { // get a reference to the PropertyInfo, exit if no property with that // name PropertyInfo pi = typeof (ConvertValueProperty).GetProperty(propertyName); if (pi == null) return false; // convert the value to the expected type val = Convert.ChangeType(val, pi.PropertyType); // attempt the assignment foreach (ConvertValueProperty bo in (ConvertValueProperty[]) obj) pi.SetValue(bo, val, null); return true; } catch { return false; } } private object GetProperty(object obj, string propertyName, object defaultValue) { try { PropertyInfo pi = GetPropertyInfoCache(propertyName); if (!(pi == null)) { var objs = (ConvertValueProperty[]) obj; var valueList = new ArrayList(); foreach (ConvertValueProperty bo in objs) { object value = pi.GetValue(bo, null); if (!valueList.Contains(value)) { valueList.Add(value); } } switch (valueList.Count) { case 1: return valueList[0]; default: return string.Empty; } } } catch (Exception ex) { Console.WriteLine(ex.Message); } // if property doesn't exist or throws return defaultValue; } #endregion #region ICustomTypeDescriptor explicit interface definitions // Most of the functions required by the ICustomTypeDescriptor are // merely pssed on to the default TypeDescriptor for this type, // which will do something appropriate. The exceptions are noted // below. AttributeCollection ICustomTypeDescriptor.GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } string ICustomTypeDescriptor.GetClassName() { return TypeDescriptor.GetClassName(this, true); } string ICustomTypeDescriptor.GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } TypeConverter ICustomTypeDescriptor.GetConverter() { return TypeDescriptor.GetConverter(this, true); } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { // This function searches the property list for the property // with the same name as the DefaultProperty specified, and // returns a property descriptor for it. If no property is // found that matches DefaultProperty, a null reference is // returned instead. PropertySpec propertySpec = null; if (_defaultProperty != null) { int index = _properties.IndexOf(_defaultProperty); propertySpec = _properties[index]; } if (propertySpec != null) return new PropertySpecDescriptor(propertySpec, this, propertySpec.Name, null); return null; } object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return TypeDescriptor.GetEvents(this, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return ((ICustomTypeDescriptor) this).GetProperties(new Attribute[0]); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { // Rather than passing this function on to the default TypeDescriptor, // which would return the actual properties of ConvertValuePropertyBag, I construct // a list here that contains property descriptors for the elements of the // Properties list in the bag. var props = new ArrayList(); foreach (PropertySpec property in _properties) { var attrs = new ArrayList(); // If a category, description, editor, or type converter are specified // in the PropertySpec, create attributes to define that relationship. if (property.Category != null) attrs.Add(new CategoryAttribute(property.Category)); if (property.Description != null) attrs.Add(new DescriptionAttribute(property.Description)); if (property.EditorTypeName != null) attrs.Add(new EditorAttribute(property.EditorTypeName, typeof (UITypeEditor))); if (property.ConverterTypeName != null) attrs.Add(new TypeConverterAttribute(property.ConverterTypeName)); // Additionally, append the custom attributes associated with the // PropertySpec, if any. if (property.Attributes != null) attrs.AddRange(property.Attributes); if (property.DefaultValue != null) attrs.Add(new DefaultValueAttribute(property.DefaultValue)); attrs.Add(new BrowsableAttribute(property.Browsable)); attrs.Add(new ReadOnlyAttribute(property.ReadOnly)); attrs.Add(new BindableAttribute(property.Bindable)); var attrArray = (Attribute[]) attrs.ToArray(typeof (Attribute)); // Create a new property descriptor for the property item, and add // it to the list. var pd = new PropertySpecDescriptor(property, this, property.Name, attrArray); props.Add(pd); } // Convert the list of PropertyDescriptors to a collection that the // ICustomTypeDescriptor can use, and return it. var propArray = (PropertyDescriptor[]) props.ToArray( typeof (PropertyDescriptor)); return new PropertyDescriptorCollection(propArray); } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return this; } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using Chat.Areas.HelpPage.Models; namespace Chat.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright 2021 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.UI.Controls; using Foundation; using System; using System.Collections.Generic; using System.Threading.Tasks; using UIKit; namespace ArcGISRuntime.Samples.FeatureLayerRenderingModeMap { [Register("FeatureLayerRenderingModeMap")] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Feature layer rendering mode (map)", category: "Layers", description: "Render features statically or dynamically by setting the feature layer rendering mode.", instructions: "Tap the button to trigger the same zoom animation on both static and dynamic maps.", tags: new[] { "dynamic", "feature layer", "features", "rendering", "static" })] public class FeatureLayerRenderingModeMap : UIViewController { // Hold references to UI controls. private MapView _staticMapView; private MapView _dynamicMapView; private UIStackView _stackView; private UIBarButtonItem _zoomButton; // Hold references to the two views. private Viewpoint _zoomOutPoint; private Viewpoint _zoomInPoint; public FeatureLayerRenderingModeMap() { Title = "Feature layer rendering mode (Map)"; } private async void Initialize() { // Viewpoint locations for map view to zoom in and out to. _zoomOutPoint = new Viewpoint(new MapPoint(-118.37, 34.46, SpatialReferences.Wgs84), 650000, 0); _zoomInPoint = new Viewpoint(new MapPoint(-118.45, 34.395, SpatialReferences.Wgs84), 50000, 90); // Configure the maps. _dynamicMapView.Map = new Map(); _staticMapView.Map = new Map(); // Create service feature table using a point, polyline, and polygon service. ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable(new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0")); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable(new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8")); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable(new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9")); // Create feature layers from service feature tables. List<FeatureLayer> featureLayers = new List<FeatureLayer> { new FeatureLayer(polygonServiceFeatureTable), new FeatureLayer(polylineServiceFeatureTable), new FeatureLayer(pointServiceFeatureTable) }; // Add each layer to the map as a static layer and a dynamic layer. foreach (FeatureLayer layer in featureLayers) { // Add the static layer to the top map view. layer.RenderingMode = FeatureRenderingMode.Static; _staticMapView.Map.OperationalLayers.Add(layer); // Add the dynamic layer to the bottom map view. if (layer.FeatureTable is ServiceFeatureTable table) { FeatureLayer dynamicLayer = new FeatureLayer(new ServiceFeatureTable(table.Source)); dynamicLayer.RenderingMode = FeatureRenderingMode.Dynamic; _dynamicMapView.Map.OperationalLayers.Add(dynamicLayer); } } try { // Set the view point of both MapViews. await _staticMapView.SetViewpointAsync(_zoomOutPoint); await _dynamicMapView.SetViewpointAsync(_zoomOutPoint); } catch (Exception e) { Console.WriteLine(e); } } private async void OnZoomClick(object sender, EventArgs e) { try { // Initiate task to zoom both map views in. Task t1 = _staticMapView.SetViewpointAsync(_zoomInPoint, TimeSpan.FromSeconds(5)); Task t2 = _dynamicMapView.SetViewpointAsync(_zoomInPoint, TimeSpan.FromSeconds(5)); await Task.WhenAll(t1, t2); // Delay start of next set of zoom tasks. await Task.Delay(2000); // Initiate task to zoom both map views out. Task t3 = _staticMapView.SetViewpointAsync(_zoomOutPoint, TimeSpan.FromSeconds(5)); Task t4 = _dynamicMapView.SetViewpointAsync(_zoomOutPoint, TimeSpan.FromSeconds(5)); await Task.WhenAll(t3, t4); } catch (Exception ex) { new UIAlertView("Error", ex.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show(); } } public override void ViewDidLoad() { base.ViewDidLoad(); Initialize(); } public override void LoadView() { // Create the views. View = new UIView { BackgroundColor = ApplicationTheme.BackgroundColor }; _staticMapView = new MapView(); _staticMapView.TranslatesAutoresizingMaskIntoConstraints = false; _dynamicMapView = new MapView(); _dynamicMapView.TranslatesAutoresizingMaskIntoConstraints = false; _stackView = new UIStackView(new UIView[] { _staticMapView, _dynamicMapView }); _stackView.TranslatesAutoresizingMaskIntoConstraints = false; _stackView.Distribution = UIStackViewDistribution.FillEqually; _stackView.Axis = View.TraitCollection.VerticalSizeClass == UIUserInterfaceSizeClass.Compact ? UILayoutConstraintAxis.Horizontal : UILayoutConstraintAxis.Vertical; _zoomButton = new UIBarButtonItem(); _zoomButton.Title = "Zoom"; UIToolbar toolbar = new UIToolbar(); toolbar.TranslatesAutoresizingMaskIntoConstraints = false; toolbar.Items = new[] { new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace), _zoomButton, new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace) }; UILabel staticLabel = new UILabel { Text = "Static", BackgroundColor = UIColor.FromWhiteAlpha(0f, .6f), TextColor = UIColor.White, TextAlignment = UITextAlignment.Center, TranslatesAutoresizingMaskIntoConstraints = false }; UILabel dynamicLabel = new UILabel() { Text = "Dynamic", BackgroundColor = UIColor.FromWhiteAlpha(0f, .6f), TextColor = UIColor.White, TextAlignment = UITextAlignment.Center, TranslatesAutoresizingMaskIntoConstraints = false }; // Add the views. View.AddSubviews(_stackView, toolbar, staticLabel, dynamicLabel); // Lay out the views. NSLayoutConstraint.ActivateConstraints(new[] { _stackView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor), _stackView.BottomAnchor.ConstraintEqualTo(toolbar.TopAnchor), _stackView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), _stackView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor), toolbar.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), toolbar.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor), toolbar.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor), staticLabel.TopAnchor.ConstraintEqualTo(_staticMapView.TopAnchor), staticLabel.HeightAnchor.ConstraintEqualTo(40), staticLabel.LeadingAnchor.ConstraintEqualTo(_staticMapView.LeadingAnchor), staticLabel.TrailingAnchor.ConstraintEqualTo(_staticMapView.TrailingAnchor), dynamicLabel.TopAnchor.ConstraintEqualTo(_dynamicMapView.TopAnchor), dynamicLabel.HeightAnchor.ConstraintEqualTo(40), dynamicLabel.LeadingAnchor.ConstraintEqualTo(_dynamicMapView.LeadingAnchor), dynamicLabel.TrailingAnchor.ConstraintEqualTo(_dynamicMapView.TrailingAnchor) }); } public override void TraitCollectionDidChange(UITraitCollection previousTraitCollection) { base.TraitCollectionDidChange(previousTraitCollection); if (View.TraitCollection.VerticalSizeClass == UIUserInterfaceSizeClass.Compact) { _stackView.Axis = UILayoutConstraintAxis.Horizontal; } else { _stackView.Axis = UILayoutConstraintAxis.Vertical; } } public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); // Subscribe to events. _zoomButton.Clicked += OnZoomClick; } public override void ViewDidDisappear(bool animated) { base.ViewDidDisappear(animated); // Unsubscribe from events, per best practice. _zoomButton.Clicked -= OnZoomClick; } } }
// 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; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.DotNet.Cli.CommandLine { internal class CommandLineApplication { private enum ParseOptionResult { Succeeded, ShowHelp, ShowVersion, UnexpectedArgs, } // Indicates whether the parser should throw an exception when it runs into an unexpected argument. // If this field is set to false, the parser will stop parsing when it sees an unexpected argument, and all // remaining arguments, including the first unexpected argument, will be stored in RemainingArguments property. private readonly bool _throwOnUnexpectedArg; public CommandLineApplication(bool throwOnUnexpectedArg = true) { _throwOnUnexpectedArg = throwOnUnexpectedArg; Options = new List<CommandOption>(); Arguments = new List<CommandArgument>(); Commands = new List<CommandLineApplication>(); RemainingArguments = new List<string>(); Invoke = () => 0; } public CommandLineApplication Parent { get; set; } public string Name { get; set; } public string FullName { get; set; } public string Syntax { get; set; } public string Description { get; set; } public List<CommandOption> Options { get; private set; } public CommandOption OptionHelp { get; private set; } public CommandOption OptionVersion { get; private set; } public List<CommandArgument> Arguments { get; private set; } public List<string> RemainingArguments { get; private set; } public bool IsShowingInformation { get; protected set; } // Is showing help or version? public Func<int> Invoke { get; set; } public Func<string> LongVersionGetter { get; set; } public Func<string> ShortVersionGetter { get; set; } public List<CommandLineApplication> Commands { get; private set; } public bool HandleResponseFiles { get; set; } public bool AllowArgumentSeparator { get; set; } public bool HandleRemainingArguments { get; set; } public string ArgumentSeparatorHelpText { get; set; } public CommandLineApplication AddCommand(string name, bool throwOnUnexpectedArg = true) { return AddCommand(name, _ => { }, throwOnUnexpectedArg); } public CommandLineApplication AddCommand(string name, Action<CommandLineApplication> configuration, bool throwOnUnexpectedArg = true) { var command = new CommandLineApplication(throwOnUnexpectedArg) { Name = name }; return AddCommand(command, configuration, throwOnUnexpectedArg); } public CommandLineApplication AddCommand(CommandLineApplication command, bool throwOnUnexpectedArg = true) { return AddCommand(command, _ => { }, throwOnUnexpectedArg); } public CommandLineApplication AddCommand( CommandLineApplication command, Action<CommandLineApplication> configuration, bool throwOnUnexpectedArg = true) { if (command == null || configuration == null) { throw new NullReferenceException(); } command.Parent = this; Commands.Add(command); configuration(command); return command; } public CommandOption Option(string template, string description, CommandOptionType optionType) { return Option(template, description, optionType, _ => { }); } public CommandOption Option(string template, string description, CommandOptionType optionType, Action<CommandOption> configuration) { var option = new CommandOption(template, optionType) { Description = description }; Options.Add(option); configuration(option); return option; } public CommandArgument Argument(string name, string description, bool multipleValues = false) { return Argument(name, description, _ => { }, multipleValues); } public CommandArgument Argument(string name, string description, Action<CommandArgument> configuration, bool multipleValues = false) { var lastArg = Arguments.LastOrDefault(); if (lastArg != null && lastArg.MultipleValues) { var message = string.Format(LocalizableStrings.LastArgumentMultiValueError, lastArg.Name); throw new InvalidOperationException(message); } var argument = new CommandArgument { Name = name, Description = description, MultipleValues = multipleValues }; Arguments.Add(argument); configuration(argument); return argument; } public void OnExecute(Func<int> invoke) { Invoke = invoke; } public void OnExecute(Func<Task<int>> invoke) { Invoke = () => invoke().Result; } public int Execute(params string[] args) { CommandLineApplication command = this; IEnumerator<CommandArgument> arguments = null; if (HandleResponseFiles) { args = ExpandResponseFiles(args).ToArray(); } for (var index = 0; index < args.Length; index++) { var arg = args[index]; bool isLongOption = arg.StartsWith("--"); if (arg == "-?" || arg == "/?") { command.ShowHelp(); return 0; } else if (isLongOption || arg.StartsWith("-")) { CommandOption option; var result = ParseOption(isLongOption, command, args, ref index, out option); if (result == ParseOptionResult.ShowHelp) { command.ShowHelp(); return 0; } else if (result == ParseOptionResult.ShowVersion) { command.ShowVersion(); return 0; } else if (result == ParseOptionResult.UnexpectedArgs) { break; } } else { var subcommand = ParseSubCommand(arg, command); if (subcommand != null) { command = subcommand; } else { if (arguments == null) { arguments = new CommandArgumentEnumerator(command.Arguments.GetEnumerator()); } if (arguments.MoveNext()) { arguments.Current.Values.Add(arg); } else { HandleUnexpectedArg(command, args, index, argTypeName: "command or argument"); break; } } } } if (Commands.Count > 0 && command == this) { throw new CommandParsingException( command, "Required command missing", isRequireSubCommandMissing: true); } return command.Invoke(); } private ParseOptionResult ParseOption( bool isLongOption, CommandLineApplication command, string[] args, ref int index, out CommandOption option) { option = null; ParseOptionResult result = ParseOptionResult.Succeeded; var arg = args[index]; int optionPrefixLength = isLongOption ? 2 : 1; string[] optionComponents = arg.Substring(optionPrefixLength).Split(new[] { ':', '=' }, 2); string optionName = optionComponents[0]; if (isLongOption) { option = command.Options.SingleOrDefault( opt => string.Equals(opt.LongName, optionName, StringComparison.Ordinal)); } else { option = command.Options.SingleOrDefault( opt => string.Equals(opt.ShortName, optionName, StringComparison.Ordinal)); if (option == null) { option = command.Options.SingleOrDefault( opt => string.Equals(opt.SymbolName, optionName, StringComparison.Ordinal)); } } if (option == null) { if (isLongOption && string.IsNullOrEmpty(optionName) && !command._throwOnUnexpectedArg && AllowArgumentSeparator) { // a stand-alone "--" is the argument separator, so skip it and // handle the rest of the args as unexpected args index++; } HandleUnexpectedArg(command, args, index, argTypeName: "option"); result = ParseOptionResult.UnexpectedArgs; } else if (command.OptionHelp == option) { result = ParseOptionResult.ShowHelp; } else if (command.OptionVersion == option) { result = ParseOptionResult.ShowVersion; } else { if (optionComponents.Length == 2) { if (!option.TryParse(optionComponents[1])) { command.ShowHint(); throw new CommandParsingException(command, String.Format(LocalizableStrings.UnexpectedValueForOptionError, optionComponents[1], optionName)); } } else { if (option.OptionType == CommandOptionType.NoValue || option.OptionType == CommandOptionType.BoolValue) { // No value is needed for this option option.TryParse(null); } else { index++; arg = args[index]; if (!option.TryParse(arg)) { command.ShowHint(); throw new CommandParsingException( command, String.Format(LocalizableStrings.UnexpectedValueForOptionError, arg, optionName)); } } } } return result; } private CommandLineApplication ParseSubCommand(string arg, CommandLineApplication command) { foreach (var subcommand in command.Commands) { if (string.Equals(subcommand.Name, arg, StringComparison.OrdinalIgnoreCase)) { return subcommand; } } return null; } // Helper method that adds a help option public CommandOption HelpOption(string template) { // Help option is special because we stop parsing once we see it // So we store it separately for further use OptionHelp = Option(template, LocalizableStrings.ShowHelpInfo, CommandOptionType.NoValue); return OptionHelp; } public CommandOption VersionOption(string template, string shortFormVersion, string longFormVersion = null) { if (longFormVersion == null) { return VersionOption(template, () => shortFormVersion); } else { return VersionOption(template, () => shortFormVersion, () => longFormVersion); } } // Helper method that adds a version option public CommandOption VersionOption(string template, Func<string> shortFormVersionGetter, Func<string> longFormVersionGetter = null) { // Version option is special because we stop parsing once we see it // So we store it separately for further use OptionVersion = Option(template, LocalizableStrings.ShowVersionInfo, CommandOptionType.NoValue); ShortVersionGetter = shortFormVersionGetter; LongVersionGetter = longFormVersionGetter ?? shortFormVersionGetter; return OptionVersion; } // Show short hint that reminds users to use help option public void ShowHint() { if (OptionHelp != null) { Console.WriteLine(string.Format(LocalizableStrings.ShowHintInfo, OptionHelp.LongName)); } } // Show full help public void ShowHelp(string commandName = null) { var headerBuilder = new StringBuilder(LocalizableStrings.UsageHeader); var usagePrefixLength = headerBuilder.Length; for (var cmd = this; cmd != null; cmd = cmd.Parent) { cmd.IsShowingInformation = true; if (cmd != this && cmd.Arguments.Any()) { var args = string.Join(" ", cmd.Arguments.Select(arg => arg.Name)); headerBuilder.Insert(usagePrefixLength, string.Format(LocalizableStrings.UsageItemWithArgs, cmd.Name, args)); } else { headerBuilder.Insert(usagePrefixLength, string.Format(LocalizableStrings.UsageItemWithoutArgs, cmd.Name)); } } CommandLineApplication target; if (commandName == null || string.Equals(Name, commandName, StringComparison.OrdinalIgnoreCase)) { target = this; } else { target = Commands.SingleOrDefault(cmd => string.Equals(cmd.Name, commandName, StringComparison.OrdinalIgnoreCase)); if (target != null) { headerBuilder.AppendFormat(LocalizableStrings.CommandItem, commandName); } else { // The command name is invalid so don't try to show help for something that doesn't exist target = this; } } var optionsBuilder = new StringBuilder(); var commandsBuilder = new StringBuilder(); var argumentsBuilder = new StringBuilder(); var argumentSeparatorBuilder = new StringBuilder(); int maxArgLen = 0; for (var cmd = target; cmd != null; cmd = cmd.Parent) { if (cmd.Arguments.Any()) { if (cmd == target) { headerBuilder.Append(LocalizableStrings.UsageArgumentsToken); } if (argumentsBuilder.Length == 0) { argumentsBuilder.AppendLine(); argumentsBuilder.AppendLine(LocalizableStrings.UsageArgumentsHeader); } maxArgLen = Math.Max(maxArgLen, MaxArgumentLength(cmd.Arguments)); } } for (var cmd = target; cmd != null; cmd = cmd.Parent) { if (cmd.Arguments.Any()) { var outputFormat = LocalizableStrings.UsageArgumentItem; foreach (var arg in cmd.Arguments) { argumentsBuilder.AppendFormat( outputFormat, arg.Name.PadRight(maxArgLen + 2), arg.Description); argumentsBuilder.AppendLine(); } } } if (target.Options.Any()) { headerBuilder.Append(LocalizableStrings.UsageOptionsToken); optionsBuilder.AppendLine(); optionsBuilder.AppendLine(LocalizableStrings.UsageOptionsHeader); var maxOptLen = MaxOptionTemplateLength(target.Options); var outputFormat = string.Format(LocalizableStrings.UsageOptionsItem, maxOptLen + 2); foreach (var opt in target.Options) { optionsBuilder.AppendFormat(outputFormat, opt.Template, opt.Description); optionsBuilder.AppendLine(); } } if (target.Commands.Any()) { headerBuilder.Append(LocalizableStrings.UsageCommandToken); commandsBuilder.AppendLine(); commandsBuilder.AppendLine(LocalizableStrings.UsageCommandsHeader); var maxCmdLen = MaxCommandLength(target.Commands); var outputFormat = string.Format(LocalizableStrings.UsageCommandsItem, maxCmdLen + 2); foreach (var cmd in target.Commands.OrderBy(c => c.Name)) { commandsBuilder.AppendFormat(outputFormat, cmd.Name, cmd.Description); commandsBuilder.AppendLine(); } if (OptionHelp != null) { commandsBuilder.AppendLine(); commandsBuilder.AppendFormat(LocalizableStrings.UsageCommandsDetailHelp, Name); commandsBuilder.AppendLine(); } } if (target.AllowArgumentSeparator || target.HandleRemainingArguments) { if (target.AllowArgumentSeparator) { headerBuilder.Append(LocalizableStrings.UsageCommandAdditionalArgs); } else { headerBuilder.Append(LocalizableStrings.UsageCommandArgs); } if (!string.IsNullOrEmpty(target.ArgumentSeparatorHelpText)) { argumentSeparatorBuilder.AppendLine(); argumentSeparatorBuilder.AppendLine(LocalizableStrings.UsageCommandsAdditionalArgsHeader); argumentSeparatorBuilder.AppendLine(String.Format(LocalizableStrings.UsageCommandsAdditionalArgsItem, target.ArgumentSeparatorHelpText)); argumentSeparatorBuilder.AppendLine(); } } headerBuilder.AppendLine(); var nameAndVersion = new StringBuilder(); nameAndVersion.AppendLine(GetFullNameAndVersion()); nameAndVersion.AppendLine(); Console.Write("{0}{1}{2}{3}{4}{5}", nameAndVersion, headerBuilder, argumentsBuilder, optionsBuilder, commandsBuilder, argumentSeparatorBuilder); } public void ShowVersion() { for (var cmd = this; cmd != null; cmd = cmd.Parent) { cmd.IsShowingInformation = true; } Console.WriteLine(FullName); Console.WriteLine(LongVersionGetter()); } public string GetFullNameAndVersion() { return ShortVersionGetter == null ? FullName : string.Format(LocalizableStrings.ShortVersionTemplate, FullName, ShortVersionGetter()); } public void ShowRootCommandFullNameAndVersion() { var rootCmd = this; while (rootCmd.Parent != null) { rootCmd = rootCmd.Parent; } Console.WriteLine(rootCmd.GetFullNameAndVersion()); Console.WriteLine(); } private int MaxOptionTemplateLength(IEnumerable<CommandOption> options) { var maxLen = 0; foreach (var opt in options) { maxLen = opt.Template.Length > maxLen ? opt.Template.Length : maxLen; } return maxLen; } private int MaxCommandLength(IEnumerable<CommandLineApplication> commands) { var maxLen = 0; foreach (var cmd in commands) { maxLen = cmd.Name.Length > maxLen ? cmd.Name.Length : maxLen; } return maxLen; } private int MaxArgumentLength(IEnumerable<CommandArgument> arguments) { var maxLen = 0; foreach (var arg in arguments) { maxLen = arg.Name.Length > maxLen ? arg.Name.Length : maxLen; } return maxLen; } private void HandleUnexpectedArg(CommandLineApplication command, string[] args, int index, string argTypeName) { if (command._throwOnUnexpectedArg) { command.ShowHint(); throw new CommandParsingException(command, String.Format(LocalizableStrings.UnexpectedArgumentError, argTypeName, args[index])); } else { // All remaining arguments are stored for further use command.RemainingArguments.AddRange(new ArraySegment<string>(args, index, args.Length - index)); } } private IEnumerable<string> ExpandResponseFiles(IEnumerable<string> args) { foreach (var arg in args) { if (!arg.StartsWith("@", StringComparison.Ordinal)) { yield return arg; } else { var fileName = arg.Substring(1); var responseFileArguments = ParseResponseFile(fileName); // ParseResponseFile can suppress expanding this response file by // returning null. In that case, we'll treat the response // file token as a regular argument. if (responseFileArguments == null) { yield return arg; } else { foreach (var responseFileArgument in responseFileArguments) yield return responseFileArgument.Trim(); } } } } private IEnumerable<string> ParseResponseFile(string fileName) { if (!HandleResponseFiles) return null; if (!File.Exists(fileName)) { throw new InvalidOperationException(String.Format(LocalizableStrings.ResponseFileNotFoundError, fileName)); } return File.ReadLines(fileName); } private class CommandArgumentEnumerator : IEnumerator<CommandArgument> { private readonly IEnumerator<CommandArgument> _enumerator; public CommandArgumentEnumerator(IEnumerator<CommandArgument> enumerator) { _enumerator = enumerator; } public CommandArgument Current { get { return _enumerator.Current; } } object IEnumerator.Current { get { return Current; } } public void Dispose() { _enumerator.Dispose(); } public bool MoveNext() { if (Current == null || !Current.MultipleValues) { return _enumerator.MoveNext(); } // If current argument allows multiple values, we don't move forward and // all later values will be added to current CommandArgument.Values return true; } public void Reset() { _enumerator.Reset(); } } } }
using System; namespace Aardvark.Base { /// <summary> /// Wrappers for the best (fastest) available implementation of the respective tensor operation. /// </summary> public static partial class TensorExtensions { #region Conversions (Matrix, Volume) to PixImage<T> public static PixImage<T> ToPixImage<T>(this Matrix<T> matrix) { return matrix.AsVolume().ToPixImage(); } public static PixImage<T> ToPixImage<T>(this Volume<T> volume) { return new PixImage<T>(volume.ToImage()); } public static PixImage<T> ToPixImage<T>(this Volume<T> volume, Col.Format format) { var ch = format.ChannelCount(); if (ch > volume.Size.Z) throw new ArgumentException("volume has not enough channels for requested format"); if (ch < volume.Size.Z) volume = volume.SubVolume(V3l.Zero, new V3l(volume.SX, volume.SY, ch)); return new PixImage<T>(format, volume.ToImage()); } public static PixImage<T> ToPixImage<T>(this Matrix<C3b> matrix) { var pixImage = new PixImage<T>(Col.FormatDefaultOf(typeof(T), 3), (V2i)matrix.Size); pixImage.GetMatrix<C3b>().Set(matrix); return pixImage; } public static PixImage<T> ToPixImage<T>(this Matrix<C3us> matrix) { var pixImage = new PixImage<T>(Col.FormatDefaultOf(typeof(T), 3), (V2i)matrix.Size); pixImage.GetMatrix<C3us>().Set(matrix); return pixImage; } public static PixImage<T> ToPixImage<T>(this Matrix<C3f> matrix) { var pixImage = new PixImage<T>(Col.FormatDefaultOf(typeof(T), 3), (V2i)matrix.Size); pixImage.GetMatrix<C3f>().Set(matrix); return pixImage; } public static PixImage<T> ToPixImage<T>(this Matrix<C4b> matrix) { var pixImage = new PixImage<T>(Col.FormatDefaultOf(typeof(T), 4), (V2i)matrix.Size); pixImage.GetMatrix<C4b>().Set(matrix); return pixImage; } public static PixImage<T> ToPixImage<T>(this Matrix<C4us> matrix) { var pixImage = new PixImage<T>(Col.FormatDefaultOf(typeof(T), 4), (V2i)matrix.Size); pixImage.GetMatrix<C4us>().Set(matrix); return pixImage; } public static PixImage<T> ToPixImage<T>(this Matrix<C4f> matrix) { var pixImage = new PixImage<T>(Col.FormatDefaultOf(typeof(T), 4), (V2i)matrix.Size); pixImage.GetMatrix<C4f>().Set(matrix); return pixImage; } public static PixImage<T> ToPixImage<T, TMatrixData>(this Matrix<TMatrixData, C3b> matrix) { var pixImage = new PixImage<T>(Col.FormatDefaultOf(typeof(T), 3), (V2i)matrix.Size); pixImage.GetMatrix<C3b>().Set(matrix); return pixImage; } public static PixImage<T> ToPixImage<T, TMatrixData>(this Matrix<TMatrixData, C3us> matrix) { var pixImage = new PixImage<T>(Col.FormatDefaultOf(typeof(T), 3), (V2i)matrix.Size); pixImage.GetMatrix<C3us>().Set(matrix); return pixImage; } public static PixImage<T> ToPixImage<T, TMatrixData>(this Matrix<TMatrixData, C3f> matrix) { var pixImage = new PixImage<T>(Col.FormatDefaultOf(typeof(T), 3), (V2i)matrix.Size); pixImage.GetMatrix<C3f>().Set(matrix); return pixImage; } public static PixImage<T> ToPixImage<T, TMatrixData>(this Matrix<TMatrixData, C4b> matrix) { var pixImage = new PixImage<T>(Col.FormatDefaultOf(typeof(T), 4), (V2i)matrix.Size); pixImage.GetMatrix<C4b>().Set(matrix); return pixImage; } public static PixImage<T> ToPixImage<T, TMatrixData>(this Matrix<TMatrixData, C4us> matrix) { var pixImage = new PixImage<T>(Col.FormatDefaultOf(typeof(T), 4), (V2i)matrix.Size); pixImage.GetMatrix<C4us>().Set(matrix); return pixImage; } public static PixImage<T> ToPixImage<T, TMatrixData>(this Matrix<TMatrixData, C4f> matrix) { var pixImage = new PixImage<T>(Col.FormatDefaultOf(typeof(T), 4), (V2i)matrix.Size); pixImage.GetMatrix<C4f>().Set(matrix); return pixImage; } public static PixImage<T> ToPixImage<T>(this IMatrix<C3b> matrix) { if (matrix is Matrix<byte, C3b>) return ((Matrix<byte, C3b>)matrix).ToPixImage<T, byte>(); ; var pixImage = new PixImage<T>(Col.FormatDefaultOf(typeof(T), 3), (V2i)matrix.Dim); pixImage.GetMatrix<C3b>().Set(matrix); return pixImage; } public static PixImage<T> ToPixImage<T>(this IMatrix<C3us> matrix) { if (matrix is Matrix<ushort, C3us>) return ((Matrix<ushort, C3us>)matrix).ToPixImage<T, ushort>(); ; var pixImage = new PixImage<T>(Col.FormatDefaultOf(typeof(T), 3), (V2i)matrix.Dim); pixImage.GetMatrix<C3us>().Set(matrix); return pixImage; } public static PixImage<T> ToPixImage<T>(this IMatrix<C3f> matrix) { if (matrix is Matrix<float, C3f>) return ((Matrix<float, C3f>)matrix).ToPixImage<T, float>(); ; var pixImage = new PixImage<T>(Col.FormatDefaultOf(typeof(T), 3), (V2i)matrix.Dim); pixImage.GetMatrix<C3f>().Set(matrix); return pixImage; } public static PixImage<T> ToPixImage<T>(this IMatrix<C4b> matrix) { if (matrix is Matrix<byte, C4b>) return ((Matrix<byte, C4b>)matrix).ToPixImage<T, byte>(); ; var pixImage = new PixImage<T>(Col.FormatDefaultOf(typeof(T), 4), (V2i)matrix.Dim); pixImage.GetMatrix<C4b>().Set(matrix); return pixImage; } public static PixImage<T> ToPixImage<T>(this IMatrix<C4us> matrix) { if (matrix is Matrix<ushort, C4us>) return ((Matrix<ushort, C4us>)matrix).ToPixImage<T, ushort>(); ; var pixImage = new PixImage<T>(Col.FormatDefaultOf(typeof(T), 4), (V2i)matrix.Dim); pixImage.GetMatrix<C4us>().Set(matrix); return pixImage; } public static PixImage<T> ToPixImage<T>(this IMatrix<C4f> matrix) { if (matrix is Matrix<float, C4f>) return ((Matrix<float, C4f>)matrix).ToPixImage<T, float>(); ; var pixImage = new PixImage<T>(Col.FormatDefaultOf(typeof(T), 4), (V2i)matrix.Dim); pixImage.GetMatrix<C4f>().Set(matrix); return pixImage; } #endregion #region Conversions Volume to Volume (byte, ushort, uint, float, double) [CSharp (internal)] // All the following conversions are internal only, since we do not // know about the channel order at this level. Only PixImages know // about channel order. internal static Volume<ushort> ToUShortColor(this Volume<byte> volume) { return volume.MapToImageWindow(Col.UShortFromByte); } internal static Volume<uint> ToUIntColor(this Volume<byte> volume) { return volume.MapToImageWindow(Col.UIntFromByte); } internal static Volume<float> ToFloatColor(this Volume<byte> volume) { return volume.MapToImageWindow(Col.FloatFromByte); } internal static Volume<double> ToDoubleColor(this Volume<byte> volume) { return volume.MapToImageWindow(Col.DoubleFromByte); } internal static Volume<byte> ToByteColor(this Volume<ushort> volume) { return volume.MapToImageWindow(Col.ByteFromUShort); } internal static Volume<uint> ToUIntColor(this Volume<ushort> volume) { return volume.MapToImageWindow(Col.UIntFromUShort); } internal static Volume<float> ToFloatColor(this Volume<ushort> volume) { return volume.MapToImageWindow(Col.FloatFromUShort); } internal static Volume<double> ToDoubleColor(this Volume<ushort> volume) { return volume.MapToImageWindow(Col.DoubleFromUShort); } internal static Volume<byte> ToByteColor(this Volume<uint> volume) { return volume.MapToImageWindow(Col.ByteFromUInt); } internal static Volume<ushort> ToUShortColor(this Volume<uint> volume) { return volume.MapToImageWindow(Col.UShortFromUInt); } internal static Volume<float> ToFloatColor(this Volume<uint> volume) { return volume.MapToImageWindow(Col.FloatFromUInt); } internal static Volume<double> ToDoubleColor(this Volume<uint> volume) { return volume.MapToImageWindow(Col.DoubleFromUInt); } internal static Volume<byte> ToByteColor(this Volume<float> volume) { return volume.MapToImageWindow(Col.ByteFromFloat); } internal static Volume<ushort> ToUShortColor(this Volume<float> volume) { return volume.MapToImageWindow(Col.UShortFromFloat); } internal static Volume<uint> ToUIntColor(this Volume<float> volume) { return volume.MapToImageWindow(Col.UIntFromFloat); } internal static Volume<double> ToDoubleColor(this Volume<float> volume) { return volume.MapToImageWindow(Col.DoubleFromFloat); } internal static Volume<byte> ToByteColor(this Volume<double> volume) { return volume.MapToImageWindow(Col.ByteFromDouble); } internal static Volume<ushort> ToUShortColor(this Volume<double> volume) { return volume.MapToImageWindow(Col.UShortFromDouble); } internal static Volume<uint> ToUIntColor(this Volume<double> volume) { return volume.MapToImageWindow(Col.UIntFromDouble); } internal static Volume<float> ToFloatColor(this Volume<double> volume) { return volume.MapToImageWindow(Col.FloatFromDouble); } #endregion #region Conversions Tensor4 to Tensor4 (byte, ushort, uint, float, double) [CSharp (internal)] // All the following conversions are internal only, since we do not // know about the channel order at this level. Only PixVolumes know // about channel order. internal static Tensor4<ushort> ToUShortColor(this Tensor4<byte> tensor4) { return tensor4.MapToImageWindow(Col.UShortFromByte); } internal static Tensor4<uint> ToUIntColor(this Tensor4<byte> tensor4) { return tensor4.MapToImageWindow(Col.UIntFromByte); } internal static Tensor4<float> ToFloatColor(this Tensor4<byte> tensor4) { return tensor4.MapToImageWindow(Col.FloatFromByte); } internal static Tensor4<double> ToDoubleColor(this Tensor4<byte> tensor4) { return tensor4.MapToImageWindow(Col.DoubleFromByte); } internal static Tensor4<byte> ToByteColor(this Tensor4<ushort> tensor4) { return tensor4.MapToImageWindow(Col.ByteFromUShort); } internal static Tensor4<uint> ToUIntColor(this Tensor4<ushort> tensor4) { return tensor4.MapToImageWindow(Col.UIntFromUShort); } internal static Tensor4<float> ToFloatColor(this Tensor4<ushort> tensor4) { return tensor4.MapToImageWindow(Col.FloatFromUShort); } internal static Tensor4<double> ToDoubleColor(this Tensor4<ushort> tensor4) { return tensor4.MapToImageWindow(Col.DoubleFromUShort); } internal static Tensor4<byte> ToByteColor(this Tensor4<uint> tensor4) { return tensor4.MapToImageWindow(Col.ByteFromUInt); } internal static Tensor4<ushort> ToUShortColor(this Tensor4<uint> tensor4) { return tensor4.MapToImageWindow(Col.UShortFromUInt); } internal static Tensor4<float> ToFloatColor(this Tensor4<uint> tensor4) { return tensor4.MapToImageWindow(Col.FloatFromUInt); } internal static Tensor4<double> ToDoubleColor(this Tensor4<uint> tensor4) { return tensor4.MapToImageWindow(Col.DoubleFromUInt); } internal static Tensor4<byte> ToByteColor(this Tensor4<float> tensor4) { return tensor4.MapToImageWindow(Col.ByteFromFloat); } internal static Tensor4<ushort> ToUShortColor(this Tensor4<float> tensor4) { return tensor4.MapToImageWindow(Col.UShortFromFloat); } internal static Tensor4<uint> ToUIntColor(this Tensor4<float> tensor4) { return tensor4.MapToImageWindow(Col.UIntFromFloat); } internal static Tensor4<double> ToDoubleColor(this Tensor4<float> tensor4) { return tensor4.MapToImageWindow(Col.DoubleFromFloat); } internal static Tensor4<byte> ToByteColor(this Tensor4<double> tensor4) { return tensor4.MapToImageWindow(Col.ByteFromDouble); } internal static Tensor4<ushort> ToUShortColor(this Tensor4<double> tensor4) { return tensor4.MapToImageWindow(Col.UShortFromDouble); } internal static Tensor4<uint> ToUIntColor(this Tensor4<double> tensor4) { return tensor4.MapToImageWindow(Col.UIntFromDouble); } internal static Tensor4<float> ToFloatColor(this Tensor4<double> tensor4) { return tensor4.MapToImageWindow(Col.FloatFromDouble); } #endregion #region Get/Set Matrix Rows/Cols public static Vector<T> GetRow<T>(this Matrix<T> m, int i) { return m.SubXVector(i); } public static Vector<T> GetCol<T>(this Matrix<T> m, int i) { return m.SubYVector(i); } public static void SetRow<T>(this Matrix<T> m, int i, ref Vector<T> data) { m.SubXVector(i).Set(data); } public static void SetCol<T>(this Matrix<T> m, int i, ref Vector<T> data) { m.SubYVector(i).Set(data); } #endregion #region Transformed (Matrix, Volume) [CSharp] public static Matrix<T> Transformed<T>( this Matrix<T> matrix, ImageTrafo rotation) { long sx = matrix.Size.X, sy = matrix.Size.Y; long dx = matrix.Delta.X, dy = matrix.Delta.Y; switch (rotation) { case ImageTrafo.Identity: return matrix; case ImageTrafo.Rot90: return matrix.SubMatrix(sx - 1, 0, sy, sx, dy, -dx); case ImageTrafo.Rot180: return matrix.SubMatrix(sx - 1, sy - 1, sx, sy, -dx, -dy); case ImageTrafo.Rot270: return matrix.SubMatrix(0, sy - 1, sy, sx, -dy, dx); case ImageTrafo.MirrorX: return matrix.SubMatrix(sx - 1, 0, sx, sy, -dx, dy); case ImageTrafo.Transpose: return matrix.SubMatrix(0, 0, sy, sx, dy, dx); case ImageTrafo.MirrorY: return matrix.SubMatrix(0, sy - 1, sx, sy, dx, -dy); case ImageTrafo.Transverse: return matrix.SubMatrix(sx - 1, sy - 1, sy, sx, -dy, -dx); } throw new ArgumentException(); } public static Volume<T> Transformed<T>( this Volume<T> volume, ImageTrafo rotation) { long sx = volume.Size.X, sy = volume.Size.Y, sz = volume.Size.Z; long dx = volume.Delta.X, dy = volume.Delta.Y, dz = volume.Delta.Z; switch (rotation) { case ImageTrafo.Identity: return volume; case ImageTrafo.Rot90: return volume.SubVolume(sx - 1, 0, 0, sy, sx, sz, dy, -dx, dz); case ImageTrafo.Rot180: return volume.SubVolume(sx - 1, sy - 1, 0, sx, sy, sz, -dx, -dy, dz); case ImageTrafo.Rot270: return volume.SubVolume(0, sy - 1, 0, sy, sx, sz, -dy, dx, dz); case ImageTrafo.MirrorX: return volume.SubVolume(sx - 1, 0, 0, sx, sy, sz, -dx, dy, dz); case ImageTrafo.Transpose: return volume.SubVolume(0, 0, 0, sy, sx, sz, dy, dx, dz); case ImageTrafo.MirrorY: return volume.SubVolume(0, sy - 1, 0, sx, sy, sz, dx, -dy, dz); case ImageTrafo.Transverse: return volume.SubVolume(sx - 1, sy - 1, 0, sy, sx, sz, -dy, -dx, dz); } throw new ArgumentException(); } #endregion } }
// ==++== // // // Copyright (c) 2006 Microsoft Corporation. All rights reserved. // // The use and distribution terms for this software are contained in the file // named license.txt, which can be found in the root of this distribution. // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // You must not remove this notice, or any other, from this software. // // // ==--== namespace Microsoft.JScript { using Microsoft.JScript.Vsa; using System; using System.Collections; using System.Reflection; using System.Reflection.Emit; using System.Runtime.InteropServices.Expando; internal sealed class Member : Binding{ private bool fast; private bool isImplicitWrapper; private LateBinding lateBinding; private Context memberNameContext; internal AST rootObject; private IReflect rootObjectInferredType; //Keeps track of the type inference that was used to do a binding. A binding is invalid if this changes. private LocalBuilder refLoc; private LocalBuilder temp; internal Member(Context context, AST rootObject, AST memberName) : base(context, memberName.context.GetCode()){ this.fast = this.Engine.doFast; this.isImplicitWrapper = false; this.isNonVirtual = rootObject is ThisLiteral && ((ThisLiteral)rootObject).isSuper; this.lateBinding = null; this.memberNameContext = memberName.context; this.rootObject = rootObject; this.rootObjectInferredType = null; this.refLoc = null; this.temp = null; } private void BindName(JSField inferenceTarget){ MemberInfo[] members = null; this.rootObject = this.rootObject.PartiallyEvaluate(); IReflect obType = this.rootObjectInferredType = this.rootObject.InferType(inferenceTarget); if (this.rootObject is ConstantWrapper){ Object ob = Convert.ToObject2(this.rootObject.Evaluate(), this.Engine); if (ob == null){ this.rootObject.context.HandleError(JSError.ObjectExpected); return; } ClassScope csc = ob as ClassScope; Type t = ob as Type; if (csc != null || t != null){ //object is a type. Look for static members on the type only. If none are found, look for instance members on type Type. if (csc != null) this.members = members = csc.GetMember(this.name, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Static|BindingFlags.DeclaredOnly); else this.members = members = t.GetMember(this.name, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Static|BindingFlags.DeclaredOnly); if (members.Length > 0) return; //found a binding //Look for instance members on type Type this.members = members = Typeob.Type.GetMember(this.name, BindingFlags.Public|BindingFlags.Instance); return; } Namespace ns = ob as Namespace; if (ns != null){ String fullname = ns.Name+"."+this.name; csc = this.Engine.GetClass(fullname); if (csc != null){ FieldAttributes attrs = FieldAttributes.Literal; if ((csc.owner.attributes&TypeAttributes.Public) == 0) attrs |= FieldAttributes.Private; this.members = new MemberInfo[]{new JSGlobalField(null, this.name, csc, attrs)}; return; }else{ t = this.Engine.GetType(fullname); if (t != null){ this.members = new MemberInfo[]{t}; return; } } }else if (ob is MathObject || ob is ScriptFunction && !(ob is FunctionObject)) //It is a built in constructor function obType = (IReflect)ob; } obType = this.ProvideWrapperForPrototypeProperties(obType); //Give up and go late bound if not enough is known about the object at compile time. if (obType == Typeob.Object && !this.isNonVirtual){ //The latter provides for super in classes that extend System.Object this.members = new MemberInfo[0]; return; } Type ty = obType as Type; //Interfaces are weird, call a helper if (ty != null && ty.IsInterface){ this.members = JSBinder.GetInterfaceMembers(this.name, ty); return; } ClassScope cs = obType as ClassScope; if (cs != null && cs.owner.isInterface){ this.members = cs.owner.GetInterfaceMember(this.name); return; } //Now run up the inheritance chain until a member is found while (obType != null){ cs = obType as ClassScope; if (cs != null){ //The FlattenHierachy flag here tells ClassScope to add in any overloads found on base classes members = this.members = obType.GetMember(this.name, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance|BindingFlags.DeclaredOnly|BindingFlags.FlattenHierarchy); if (members.Length > 0) return; obType = cs.GetSuperType(); continue; } ty = obType as Type; if (ty == null){ //Dealing with the global scope via the this literal or with a built in object in fast mode this.members = obType.GetMember(this.name, BindingFlags.Public|BindingFlags.Instance); return; } members = this.members = ty.GetMember(this.name, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance|BindingFlags.DeclaredOnly); if (members.Length > 0){ MemberInfo mem = LateBinding.SelectMember(members); if (mem == null){ //Found a method or methods. Need to add any overloads found in base classes. //Do another lookup, this time with the DeclaredOnly flag cleared and asking only for methods members = this.members = ty.GetMember(this.name, MemberTypes.Method, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance); if (members.Length == 0) //Dealing with an indexed property, ask again this.members = ty.GetMember(this.name, MemberTypes.Property, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance); } return; } obType = ty.BaseType; } } internal override Object Evaluate(){ Object value = base.Evaluate(); if (value is Missing) value = null; return value; } internal override LateBinding EvaluateAsLateBinding(){ LateBinding lb = this.lateBinding; if (lb == null){ if (this.member != null && !this.rootObjectInferredType.Equals(this.rootObject.InferType(null))) this.InvalidateBinding(); this.lateBinding = lb = new LateBinding(this.name, null, VsaEngine.executeForJSEE); lb.last_member = this.member; } Object val = this.rootObject.Evaluate(); try{ lb.obj = val = Convert.ToObject(val, this.Engine); if (this.defaultMember == null && this.member != null) lb.last_object = val; }catch(JScriptException e){ if (e.context == null){ e.context = this.rootObject.context; } throw e; } return lb; } internal Object EvaluateAsType(){ WrappedNamespace ns = this.rootObject.EvaluateAsWrappedNamespace(false); Object result = ns.GetMemberValue(this.name); if (result != null && !(result is Missing)) return result; Object ob = null; Member root = this.rootObject as Member; if (root == null){ Lookup lookup = this.rootObject as Lookup; if (lookup == null) return null; ob = lookup.PartiallyEvaluate(); ConstantWrapper cw = ob as ConstantWrapper; if (cw != null) ob = cw.value; else{ JSGlobalField f = lookup.member as JSGlobalField; if (f != null && f.IsLiteral) ob = f.value; else return null; } }else ob = root.EvaluateAsType(); ClassScope csc = ob as ClassScope; if (csc != null){ MemberInfo[] members = csc.GetMember(this.name, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Static|BindingFlags.Instance); if (members.Length == 0) return null; JSMemberField field = members[0] as JSMemberField; if (field == null || !field.IsLiteral || !(field.value is ClassScope) || !field.IsPublic && !field.IsAccessibleFrom(this.Engine.ScriptObjectStackTop())) return null; return field.value; } Type t = ob as Type; if (t != null) return t.GetNestedType(this.name); return null; } internal override WrappedNamespace EvaluateAsWrappedNamespace(bool giveErrorIfNameInUse){ WrappedNamespace root = this.rootObject.EvaluateAsWrappedNamespace(giveErrorIfNameInUse); String name = this.name; root.AddFieldOrUseExistingField(name, Namespace.GetNamespace(root.ToString()+"."+name, this.Engine), FieldAttributes.Literal); return new WrappedNamespace(root.ToString()+"."+name, this.Engine); } protected override Object GetObject(){ return Convert.ToObject(this.rootObject.Evaluate(), this.Engine); } protected override void HandleNoSuchMemberError(){ IReflect obType = this.rootObject.InferType(null); Object obVal = null; if (this.rootObject is ConstantWrapper) obVal = this.rootObject.Evaluate(); if ((obType == Typeob.Object && !this.isNonVirtual) || (obType is JSObject && !((JSObject)obType).noExpando) || (obType is GlobalScope && !((GlobalScope)obType).isKnownAtCompileTime)) return; if (obType is Type){ Type t = (Type)obType; if (Typeob.ScriptFunction.IsAssignableFrom(t) || t == Typeob.MathObject){ //dealing with an assigment to a member of a builtin constructor function. Debug.Assert(this.fast); this.memberNameContext.HandleError(JSError.OLENoPropOrMethod); return; } if (Typeob.IExpando.IsAssignableFrom(t)) return; if (!this.fast) if (t == Typeob.Boolean || t == Typeob.String || Convert.IsPrimitiveNumericType(t)) return; // Check to see if we couldn't get the member because it is non-static. if (obVal is ClassScope){ MemberInfo[] members = ((ClassScope)obVal).GetMember(this.name, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance); if (members.Length > 0){ this.memberNameContext.HandleError(JSError.NonStaticWithTypeName); return; } } } if (obVal is FunctionObject){ this.rootObject = new ConstantWrapper(((FunctionObject)obVal).name, this.rootObject.context); this.memberNameContext.HandleError(JSError.OLENoPropOrMethod); return; } // Check to see if we couldn't get the member because it is static. if (obType is ClassScope){ MemberInfo[] members = ((ClassScope)obType).GetMember(this.name, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Static); if (members.Length > 0){ this.memberNameContext.HandleError(JSError.StaticRequiresTypeName); return; } } if (obVal is Type) this.memberNameContext.HandleError(JSError.NoSuchStaticMember, Convert.ToTypeName((Type)obVal)); else if (obVal is ClassScope) this.memberNameContext.HandleError(JSError.NoSuchStaticMember, Convert.ToTypeName((ClassScope)obVal)); else if (obVal is Namespace) this.memberNameContext.HandleError(JSError.NoSuchType, ((Namespace)obVal).Name+"."+this.name); else{ if (obType == FunctionPrototype.ob && this.rootObject is Binding && ((Binding)this.rootObject).member is JSVariableField && ((JSVariableField)((Binding)this.rootObject).member).value is FunctionObject) return; this.memberNameContext.HandleError(JSError.NoSuchMember, Convert.ToTypeName(obType)); } } internal override IReflect InferType(JSField inference_target){ if (this.members == null){ this.BindName(inference_target); }else{ if (!this.rootObjectInferredType.Equals(this.rootObject.InferType(inference_target))) this.InvalidateBinding(); } return base.InferType(null); } internal override IReflect InferTypeOfCall(JSField inference_target, bool isConstructor){ if (!this.rootObjectInferredType.Equals(this.rootObject.InferType(inference_target))) this.InvalidateBinding(); return base.InferTypeOfCall(null, isConstructor); } internal override AST PartiallyEvaluate(){ this.BindName(null); if (this.members == null || this.members.Length == 0){ //if this rootObject is a constant and its value is a namespace, turn this node also into a namespace constant if (this.rootObject is ConstantWrapper){ Object val = this.rootObject.Evaluate(); if (val is Namespace){ return new ConstantWrapper(Namespace.GetNamespace(((Namespace)val).Name+"."+this.name, this.Engine), this.context); } } this.HandleNoSuchMemberError(); return this; } this.ResolveRHValue(); if (this.member is FieldInfo && ((FieldInfo)this.member).IsLiteral){ Object val = this.member is JSVariableField ? ((JSVariableField)this.member).value : TypeReferences.GetConstantValue((FieldInfo)this.member); if (val is AST){ AST pval = ((AST)val).PartiallyEvaluate(); if (pval is ConstantWrapper) return pval; val = null; } if (!(val is FunctionObject) && (!(val is ClassScope) || ((ClassScope)val).owner.IsStatic)) return new ConstantWrapper(val, this.context); }else if (this.member is Type) return new ConstantWrapper(this.member, this.context); return this; } internal override AST PartiallyEvaluateAsCallable(){ this.BindName(null); //Resolving the call is delayed until the arguments have been partially evaluated return this; } internal override AST PartiallyEvaluateAsReference(){ this.BindName(null); if (this.members == null || this.members.Length == 0){ if (this.isImplicitWrapper && !Convert.IsArray(this.rootObjectInferredType)) this.context.HandleError(JSError.UselessAssignment); else this.HandleNoSuchMemberError(); return this; } this.ResolveLHValue(); if (this.isImplicitWrapper) if (this.member == null || (!(this.member is JSField) && Typeob.JSObject.IsAssignableFrom(this.member.DeclaringType))) this.context.HandleError(JSError.UselessAssignment); return this; } private IReflect ProvideWrapperForPrototypeProperties(IReflect obType){ //Provide for early binding to prototype methods in fast mode, by fudging the type if (obType == Typeob.String){ obType = Globals.globalObject.originalString.Construct(); ((JSObject)obType).noExpando = this.fast; this.isImplicitWrapper = true; }else if ((obType is Type && Typeob.Array.IsAssignableFrom((Type)obType)) || obType is TypedArray){ obType = Globals.globalObject.originalArray.ConstructWrapper(); ((JSObject)obType).noExpando = this.fast; this.isImplicitWrapper = true; }else if (obType == Typeob.Boolean){ obType = Globals.globalObject.originalBoolean.Construct(); ((JSObject)obType).noExpando = this.fast; this.isImplicitWrapper = true; }else if (Convert.IsPrimitiveNumericType(obType)){ Type baseType = (Type)obType; obType = Globals.globalObject.originalNumber.Construct(); ((JSObject)obType).noExpando = this.fast; ((NumberObject)obType).baseType = baseType; this.isImplicitWrapper = true; }else if (obType is Type) obType = Convert.ToIReflect((Type)obType, this.Engine); return obType; } internal override Object ResolveCustomAttribute(ASTList args, IReflect[] argIRs, AST target){ this.name = this.name + "Attribute"; this.BindName(null); if (this.members == null || this.members.Length == 0){ this.name = this.name.Substring(0, this.name.Length-9); this.BindName(null); } return base.ResolveCustomAttribute(args, argIRs, target); } //code in parser relies on the member string (x.y.z...) being returned from here public override String ToString(){ return this.rootObject.ToString() + "." + this.name; } internal override void TranslateToILInitializer(ILGenerator il){ this.rootObject.TranslateToILInitializer(il); if (!this.rootObjectInferredType.Equals(this.rootObject.InferType(null))) this.InvalidateBinding(); if (this.defaultMember != null) return; if (this.member != null) switch(this.member.MemberType){ case MemberTypes.Constructor: case MemberTypes.Method: case MemberTypes.NestedType: case MemberTypes.Property: case MemberTypes.TypeInfo: return; case MemberTypes.Field: if (this.member is JSExpandoField){ this.member = null; break; } return; } this.refLoc = il.DeclareLocal(Typeob.LateBinding); il.Emit(OpCodes.Ldstr, this.name); il.Emit(OpCodes.Newobj, CompilerGlobals.lateBindingConstructor); il.Emit(OpCodes.Stloc, this.refLoc); } protected override void TranslateToILObject(ILGenerator il, Type obType, bool noValue){ if (noValue && obType.IsValueType && obType != Typeob.Enum){ if (this.temp == null) this.rootObject.TranslateToILReference(il, obType); else{ Type tempType = Convert.ToType(this.rootObject.InferType(null)); if (tempType == obType) il.Emit(OpCodes.Ldloca, this.temp); else{ il.Emit(OpCodes.Ldloc, this.temp); Convert.Emit(this, il, tempType, obType); Convert.EmitLdloca(il, obType); } } }else{ if (this.temp == null || this.rootObject is ThisLiteral) this.rootObject.TranslateToIL(il, obType); else{ il.Emit(OpCodes.Ldloc, this.temp); Type tempType = Convert.ToType(this.rootObject.InferType(null)); Convert.Emit(this, il, tempType, obType); } } } protected override void TranslateToILWithDupOfThisOb(ILGenerator il){ IReflect ir = this.rootObject.InferType(null); Type tempType = Convert.ToType(ir); this.rootObject.TranslateToIL(il, tempType); if (ir == Typeob.Object || ir == Typeob.String || ir is TypedArray || (ir == tempType && Typeob.Array.IsAssignableFrom(tempType))){ tempType = Typeob.Object; this.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.toObjectMethod); } il.Emit(OpCodes.Dup); this.temp = il.DeclareLocal(tempType); il.Emit(OpCodes.Stloc, temp); Convert.Emit(this, il, tempType, Typeob.Object); this.TranslateToIL(il, Typeob.Object); } internal void TranslateToLateBinding(ILGenerator il, bool speculativeEarlyBindingsExist){ if (speculativeEarlyBindingsExist){ LocalBuilder temp = il.DeclareLocal(Typeob.Object); il.Emit(OpCodes.Stloc, temp); il.Emit(OpCodes.Ldloc, this.refLoc); il.Emit(OpCodes.Dup); il.Emit(OpCodes.Ldloc, temp); }else{ il.Emit(OpCodes.Ldloc, this.refLoc); il.Emit(OpCodes.Dup); this.TranslateToILObject(il, Typeob.Object, false); } IReflect ir = this.rootObject.InferType(null); if (ir == Typeob.Object || ir == Typeob.String || ir is TypedArray || (ir is Type && ((Type)ir).IsPrimitive) || (ir is Type && Typeob.Array.IsAssignableFrom((Type)ir))){ this.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.toObjectMethod); } il.Emit(OpCodes.Stfld, CompilerGlobals.objectField); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Reflection; using System.Xml; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Serialization.External; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Region.Framework.Scenes.Serialization { /// <summary> /// Serialize and deserialize scene objects. /// </summary> /// This should really be in OpenSim.Framework.Serialization but this would mean circular dependency problems /// right now - hopefully this isn't forever. public class SceneObjectSerializer { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static IUserManagement m_UserManagement; /// <summary> /// Deserialize a scene object from the original xml format /// </summary> /// <param name="xmlData"></param> /// <returns>The scene object deserialized. Null on failure.</returns> public static SceneObjectGroup FromOriginalXmlFormat(string xmlData) { String fixedData = ExternalRepresentationUtils.SanitizeXml(xmlData); using (XmlTextReader wrappedReader = new XmlTextReader(fixedData, XmlNodeType.Element, null)) { using (XmlReader reader = XmlReader.Create(wrappedReader, new XmlReaderSettings() { IgnoreWhitespace = true, ConformanceLevel = ConformanceLevel.Fragment})) { try { return FromOriginalXmlFormat(reader); } catch (Exception e) { m_log.Error("[SERIALIZER]: Deserialization of xml failed ", e); Util.LogFailedXML("[SERIALIZER]:", fixedData); return null; } } } } /// <summary> /// Deserialize a scene object from the original xml format /// </summary> /// <param name="xmlData"></param> /// <returns>The scene object deserialized. Null on failure.</returns> public static SceneObjectGroup FromOriginalXmlFormat(XmlReader reader) { //m_log.DebugFormat("[SOG]: Starting deserialization of SOG"); //int time = System.Environment.TickCount; int linkNum; reader.ReadToFollowing("RootPart"); reader.ReadToFollowing("SceneObjectPart"); SceneObjectGroup sceneObject = new SceneObjectGroup(SceneObjectPart.FromXml(reader)); reader.ReadToFollowing("OtherParts"); if (reader.ReadToDescendant("Part")) { do { if (reader.ReadToDescendant("SceneObjectPart")) { SceneObjectPart part = SceneObjectPart.FromXml(reader); linkNum = part.LinkNum; sceneObject.AddPart(part); part.LinkNum = linkNum; part.TrimPermissions(); } } while (reader.ReadToNextSibling("Part")); reader.ReadEndElement(); } if (reader.Name == "KeyframeMotion" && reader.NodeType == XmlNodeType.Element) { string innerkeytxt = reader.ReadElementContentAsString(); sceneObject.RootPart.KeyframeMotion = KeyframeMotion.FromData(sceneObject, Convert.FromBase64String(innerkeytxt)); } else sceneObject.RootPart.KeyframeMotion = null; // Script state may, or may not, exist. Not having any, is NOT // ever a problem. sceneObject.LoadScriptState(reader); sceneObject.InvalidateDeepEffectivePerms(); return sceneObject; } /// <summary> /// Serialize a scene object to the original xml format /// </summary> /// <param name="sceneObject"></param> /// <returns></returns> public static string ToOriginalXmlFormat(SceneObjectGroup sceneObject) { return ToOriginalXmlFormat(sceneObject, true); } /// <summary> /// Serialize a scene object to the original xml format /// </summary> /// <param name="sceneObject"></param> /// <param name="doScriptStates">Control whether script states are also serialized.</para> /// <returns></returns> public static string ToOriginalXmlFormat(SceneObjectGroup sceneObject, bool doScriptStates) { using (StringWriter sw = new StringWriter()) { using (XmlTextWriter writer = new XmlTextWriter(sw)) { ToOriginalXmlFormat(sceneObject, writer, doScriptStates); } return sw.ToString(); } } /// <summary> /// Serialize a scene object to the original xml format /// </summary> /// <param name="sceneObject"></param> /// <returns></returns> public static void ToOriginalXmlFormat(SceneObjectGroup sceneObject, XmlTextWriter writer, bool doScriptStates) { ToOriginalXmlFormat(sceneObject, writer, doScriptStates, false); } public static string ToOriginalXmlFormat(SceneObjectGroup sceneObject, string scriptedState) { using (StringWriter sw = new StringWriter()) { using (XmlTextWriter writer = new XmlTextWriter(sw)) { writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty); ToOriginalXmlFormat(sceneObject, writer, false, true); writer.WriteRaw(scriptedState); writer.WriteEndElement(); } return sw.ToString(); } } /// <summary> /// Serialize a scene object to the original xml format /// </summary> /// <param name="sceneObject"></param> /// <param name="writer"></param> /// <param name="noRootElement">If false, don't write the enclosing SceneObjectGroup element</param> /// <returns></returns> public static void ToOriginalXmlFormat( SceneObjectGroup sceneObject, XmlTextWriter writer, bool doScriptStates, bool noRootElement) { // m_log.DebugFormat("[SERIALIZER]: Starting serialization of {0}", sceneObject.Name); // int time = System.Environment.TickCount; if (!noRootElement) writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty); writer.WriteStartElement(String.Empty, "RootPart", String.Empty); ToXmlFormat(sceneObject.RootPart, writer); writer.WriteEndElement(); writer.WriteStartElement(String.Empty, "OtherParts", String.Empty); SceneObjectPart[] parts = sceneObject.Parts; for (int i = 0; i < parts.Length; i++) { SceneObjectPart part = parts[i]; if (part.UUID != sceneObject.RootPart.UUID) { writer.WriteStartElement(String.Empty, "Part", String.Empty); ToXmlFormat(part, writer); writer.WriteEndElement(); } } writer.WriteEndElement(); // OtherParts if (sceneObject.RootPart.KeyframeMotion != null) { Byte[] data = sceneObject.RootPart.KeyframeMotion.Serialize(); writer.WriteStartElement(String.Empty, "KeyframeMotion", String.Empty); writer.WriteBase64(data, 0, data.Length); writer.WriteEndElement(); } if (doScriptStates) sceneObject.SaveScriptedState(writer); if (!noRootElement) writer.WriteEndElement(); // SceneObjectGroup // m_log.DebugFormat("[SERIALIZER]: Finished serialization of SOG {0}, {1}ms", sceneObject.Name, System.Environment.TickCount - time); } protected static void ToXmlFormat(SceneObjectPart part, XmlTextWriter writer) { SOPToXml2(writer, part, new Dictionary<string, object>()); } public static SceneObjectGroup FromXml2Format(string xmlData) { //m_log.DebugFormat("[SOG]: Starting deserialization of SOG"); //int time = System.Environment.TickCount; try { XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlData); XmlNodeList parts = doc.GetElementsByTagName("SceneObjectPart"); if (parts.Count == 0) { m_log.Error("[SERIALIZER]: Deserialization of xml failed: No SceneObjectPart nodes"); Util.LogFailedXML("[SERIALIZER]:", xmlData); return null; } SceneObjectGroup sceneObject; using(StringReader sr = new StringReader(parts[0].OuterXml)) { using(XmlTextReader reader = new XmlTextReader(sr)) sceneObject = new SceneObjectGroup(SceneObjectPart.FromXml(reader)); } // Then deal with the rest SceneObjectPart part; for (int i = 1; i < parts.Count; i++) { using(StringReader sr = new StringReader(parts[i].OuterXml)) { using(XmlTextReader reader = new XmlTextReader(sr)) { part = SceneObjectPart.FromXml(reader); } } int originalLinkNum = part.LinkNum; sceneObject.AddPart(part); // SceneObjectGroup.AddPart() tries to be smart and automatically set the LinkNum. // We override that here if (originalLinkNum != 0) part.LinkNum = originalLinkNum; } XmlNodeList keymotion = doc.GetElementsByTagName("KeyframeMotion"); if (keymotion.Count > 0) sceneObject.RootPart.KeyframeMotion = KeyframeMotion.FromData(sceneObject, Convert.FromBase64String(keymotion[0].InnerText)); else sceneObject.RootPart.KeyframeMotion = null; // Script state may, or may not, exist. Not having any, is NOT // ever a problem. sceneObject.LoadScriptState(doc); // sceneObject.AggregatePerms(); return sceneObject; } catch (Exception e) { m_log.Error("[SERIALIZER]: Deserialization of xml failed ", e); Util.LogFailedXML("[SERIALIZER]:", xmlData); return null; } } /// <summary> /// Serialize a scene object to the 'xml2' format. /// </summary> /// <param name="sceneObject"></param> /// <returns></returns> public static string ToXml2Format(SceneObjectGroup sceneObject) { using (StringWriter sw = new StringWriter()) { using (XmlTextWriter writer = new XmlTextWriter(sw)) { SOGToXml2(writer, sceneObject, new Dictionary<string,object>()); } return sw.ToString(); } } /// <summary> /// Modifies a SceneObjectGroup. /// </summary> /// <param name="sog">The object</param> /// <returns>Whether the object was actually modified</returns> public delegate bool SceneObjectModifier(SceneObjectGroup sog); /// <summary> /// Modifies an object by deserializing it; applying 'modifier' to each SceneObjectGroup; and reserializing. /// </summary> /// <param name="assetId">The object's UUID</param> /// <param name="data">Serialized data</param> /// <param name="modifier">The function to run on each SceneObjectGroup</param> /// <returns>The new serialized object's data, or null if an error occurred</returns> public static byte[] ModifySerializedObject(UUID assetId, byte[] data, SceneObjectModifier modifier) { List<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>(); CoalescedSceneObjects coa = null; string xmlData = ExternalRepresentationUtils.SanitizeXml(Utils.BytesToString(data)); if (CoalescedSceneObjectsSerializer.TryFromXml(xmlData, out coa)) { // m_log.DebugFormat("[SERIALIZER]: Loaded coalescence {0} has {1} objects", assetId, coa.Count); if (coa.Objects.Count == 0) { m_log.WarnFormat("[SERIALIZER]: Aborting load of coalesced object from asset {0} as it has zero loaded components", assetId); return null; } sceneObjects.AddRange(coa.Objects); } else { SceneObjectGroup deserializedObject = FromOriginalXmlFormat(xmlData); if (deserializedObject != null) { sceneObjects.Add(deserializedObject); } else { m_log.WarnFormat("[SERIALIZER]: Aborting load of object from asset {0} as deserialization failed", assetId); return null; } } bool modified = false; foreach (SceneObjectGroup sog in sceneObjects) { if (modifier(sog)) modified = true; } if (modified) { if (coa != null) data = Utils.StringToBytes(CoalescedSceneObjectsSerializer.ToXml(coa)); else data = Utils.StringToBytes(ToOriginalXmlFormat(sceneObjects[0])); } return data; } #region manual serialization private static Dictionary<string, Action<SceneObjectPart, XmlReader>> m_SOPXmlProcessors = new Dictionary<string, Action<SceneObjectPart, XmlReader>>(); private static Dictionary<string, Action<TaskInventoryItem, XmlReader>> m_TaskInventoryXmlProcessors = new Dictionary<string, Action<TaskInventoryItem, XmlReader>>(); private static Dictionary<string, Action<PrimitiveBaseShape, XmlReader>> m_ShapeXmlProcessors = new Dictionary<string, Action<PrimitiveBaseShape, XmlReader>>(); static SceneObjectSerializer() { #region SOPXmlProcessors initialization m_SOPXmlProcessors.Add("AllowedDrop", ProcessAllowedDrop); m_SOPXmlProcessors.Add("CreatorID", ProcessCreatorID); m_SOPXmlProcessors.Add("CreatorData", ProcessCreatorData); m_SOPXmlProcessors.Add("FolderID", ProcessFolderID); m_SOPXmlProcessors.Add("InventorySerial", ProcessInventorySerial); m_SOPXmlProcessors.Add("TaskInventory", ProcessTaskInventory); m_SOPXmlProcessors.Add("UUID", ProcessUUID); m_SOPXmlProcessors.Add("LocalId", ProcessLocalId); m_SOPXmlProcessors.Add("Name", ProcessName); m_SOPXmlProcessors.Add("Material", ProcessMaterial); m_SOPXmlProcessors.Add("PassTouches", ProcessPassTouches); m_SOPXmlProcessors.Add("PassCollisions", ProcessPassCollisions); m_SOPXmlProcessors.Add("RegionHandle", ProcessRegionHandle); m_SOPXmlProcessors.Add("ScriptAccessPin", ProcessScriptAccessPin); m_SOPXmlProcessors.Add("GroupPosition", ProcessGroupPosition); m_SOPXmlProcessors.Add("OffsetPosition", ProcessOffsetPosition); m_SOPXmlProcessors.Add("RotationOffset", ProcessRotationOffset); m_SOPXmlProcessors.Add("Velocity", ProcessVelocity); m_SOPXmlProcessors.Add("AngularVelocity", ProcessAngularVelocity); m_SOPXmlProcessors.Add("Acceleration", ProcessAcceleration); m_SOPXmlProcessors.Add("Description", ProcessDescription); m_SOPXmlProcessors.Add("Color", ProcessColor); m_SOPXmlProcessors.Add("Text", ProcessText); m_SOPXmlProcessors.Add("SitName", ProcessSitName); m_SOPXmlProcessors.Add("TouchName", ProcessTouchName); m_SOPXmlProcessors.Add("LinkNum", ProcessLinkNum); m_SOPXmlProcessors.Add("ClickAction", ProcessClickAction); m_SOPXmlProcessors.Add("Shape", ProcessShape); m_SOPXmlProcessors.Add("Scale", ProcessScale); m_SOPXmlProcessors.Add("SitTargetOrientation", ProcessSitTargetOrientation); m_SOPXmlProcessors.Add("SitTargetPosition", ProcessSitTargetPosition); m_SOPXmlProcessors.Add("SitTargetPositionLL", ProcessSitTargetPositionLL); m_SOPXmlProcessors.Add("SitTargetOrientationLL", ProcessSitTargetOrientationLL); m_SOPXmlProcessors.Add("ParentID", ProcessParentID); m_SOPXmlProcessors.Add("CreationDate", ProcessCreationDate); m_SOPXmlProcessors.Add("Category", ProcessCategory); m_SOPXmlProcessors.Add("SalePrice", ProcessSalePrice); m_SOPXmlProcessors.Add("ObjectSaleType", ProcessObjectSaleType); m_SOPXmlProcessors.Add("OwnershipCost", ProcessOwnershipCost); m_SOPXmlProcessors.Add("GroupID", ProcessGroupID); m_SOPXmlProcessors.Add("OwnerID", ProcessOwnerID); m_SOPXmlProcessors.Add("LastOwnerID", ProcessLastOwnerID); m_SOPXmlProcessors.Add("RezzerID", ProcessRezzerID); m_SOPXmlProcessors.Add("BaseMask", ProcessBaseMask); m_SOPXmlProcessors.Add("OwnerMask", ProcessOwnerMask); m_SOPXmlProcessors.Add("GroupMask", ProcessGroupMask); m_SOPXmlProcessors.Add("EveryoneMask", ProcessEveryoneMask); m_SOPXmlProcessors.Add("NextOwnerMask", ProcessNextOwnerMask); m_SOPXmlProcessors.Add("Flags", ProcessFlags); m_SOPXmlProcessors.Add("CollisionSound", ProcessCollisionSound); m_SOPXmlProcessors.Add("CollisionSoundVolume", ProcessCollisionSoundVolume); m_SOPXmlProcessors.Add("MediaUrl", ProcessMediaUrl); m_SOPXmlProcessors.Add("AttachedPos", ProcessAttachedPos); m_SOPXmlProcessors.Add("DynAttrs", ProcessDynAttrs); m_SOPXmlProcessors.Add("TextureAnimation", ProcessTextureAnimation); m_SOPXmlProcessors.Add("ParticleSystem", ProcessParticleSystem); m_SOPXmlProcessors.Add("PayPrice0", ProcessPayPrice0); m_SOPXmlProcessors.Add("PayPrice1", ProcessPayPrice1); m_SOPXmlProcessors.Add("PayPrice2", ProcessPayPrice2); m_SOPXmlProcessors.Add("PayPrice3", ProcessPayPrice3); m_SOPXmlProcessors.Add("PayPrice4", ProcessPayPrice4); m_SOPXmlProcessors.Add("Buoyancy", ProcessBuoyancy); m_SOPXmlProcessors.Add("Force", ProcessForce); m_SOPXmlProcessors.Add("Torque", ProcessTorque); m_SOPXmlProcessors.Add("VolumeDetectActive", ProcessVolumeDetectActive); m_SOPXmlProcessors.Add("Vehicle", ProcessVehicle); m_SOPXmlProcessors.Add("PhysicsInertia", ProcessPhysicsInertia); m_SOPXmlProcessors.Add("RotationAxisLocks", ProcessRotationAxisLocks); m_SOPXmlProcessors.Add("PhysicsShapeType", ProcessPhysicsShapeType); m_SOPXmlProcessors.Add("Density", ProcessDensity); m_SOPXmlProcessors.Add("Friction", ProcessFriction); m_SOPXmlProcessors.Add("Bounce", ProcessBounce); m_SOPXmlProcessors.Add("GravityModifier", ProcessGravityModifier); m_SOPXmlProcessors.Add("CameraEyeOffset", ProcessCameraEyeOffset); m_SOPXmlProcessors.Add("CameraAtOffset", ProcessCameraAtOffset); m_SOPXmlProcessors.Add("SoundID", ProcessSoundID); m_SOPXmlProcessors.Add("SoundGain", ProcessSoundGain); m_SOPXmlProcessors.Add("SoundFlags", ProcessSoundFlags); m_SOPXmlProcessors.Add("SoundRadius", ProcessSoundRadius); m_SOPXmlProcessors.Add("SoundQueueing", ProcessSoundQueueing); #endregion #region TaskInventoryXmlProcessors initialization m_TaskInventoryXmlProcessors.Add("AssetID", ProcessTIAssetID); m_TaskInventoryXmlProcessors.Add("BasePermissions", ProcessTIBasePermissions); m_TaskInventoryXmlProcessors.Add("CreationDate", ProcessTICreationDate); m_TaskInventoryXmlProcessors.Add("CreatorID", ProcessTICreatorID); m_TaskInventoryXmlProcessors.Add("CreatorData", ProcessTICreatorData); m_TaskInventoryXmlProcessors.Add("Description", ProcessTIDescription); m_TaskInventoryXmlProcessors.Add("EveryonePermissions", ProcessTIEveryonePermissions); m_TaskInventoryXmlProcessors.Add("Flags", ProcessTIFlags); m_TaskInventoryXmlProcessors.Add("GroupID", ProcessTIGroupID); m_TaskInventoryXmlProcessors.Add("GroupPermissions", ProcessTIGroupPermissions); m_TaskInventoryXmlProcessors.Add("InvType", ProcessTIInvType); m_TaskInventoryXmlProcessors.Add("ItemID", ProcessTIItemID); m_TaskInventoryXmlProcessors.Add("OldItemID", ProcessTIOldItemID); m_TaskInventoryXmlProcessors.Add("LastOwnerID", ProcessTILastOwnerID); m_TaskInventoryXmlProcessors.Add("Name", ProcessTIName); m_TaskInventoryXmlProcessors.Add("NextPermissions", ProcessTINextPermissions); m_TaskInventoryXmlProcessors.Add("OwnerID", ProcessTIOwnerID); m_TaskInventoryXmlProcessors.Add("CurrentPermissions", ProcessTICurrentPermissions); m_TaskInventoryXmlProcessors.Add("ParentID", ProcessTIParentID); m_TaskInventoryXmlProcessors.Add("ParentPartID", ProcessTIParentPartID); m_TaskInventoryXmlProcessors.Add("PermsGranter", ProcessTIPermsGranter); m_TaskInventoryXmlProcessors.Add("PermsMask", ProcessTIPermsMask); m_TaskInventoryXmlProcessors.Add("Type", ProcessTIType); m_TaskInventoryXmlProcessors.Add("OwnerChanged", ProcessTIOwnerChanged); #endregion #region ShapeXmlProcessors initialization m_ShapeXmlProcessors.Add("ProfileCurve", ProcessShpProfileCurve); m_ShapeXmlProcessors.Add("TextureEntry", ProcessShpTextureEntry); m_ShapeXmlProcessors.Add("ExtraParams", ProcessShpExtraParams); m_ShapeXmlProcessors.Add("PathBegin", ProcessShpPathBegin); m_ShapeXmlProcessors.Add("PathCurve", ProcessShpPathCurve); m_ShapeXmlProcessors.Add("PathEnd", ProcessShpPathEnd); m_ShapeXmlProcessors.Add("PathRadiusOffset", ProcessShpPathRadiusOffset); m_ShapeXmlProcessors.Add("PathRevolutions", ProcessShpPathRevolutions); m_ShapeXmlProcessors.Add("PathScaleX", ProcessShpPathScaleX); m_ShapeXmlProcessors.Add("PathScaleY", ProcessShpPathScaleY); m_ShapeXmlProcessors.Add("PathShearX", ProcessShpPathShearX); m_ShapeXmlProcessors.Add("PathShearY", ProcessShpPathShearY); m_ShapeXmlProcessors.Add("PathSkew", ProcessShpPathSkew); m_ShapeXmlProcessors.Add("PathTaperX", ProcessShpPathTaperX); m_ShapeXmlProcessors.Add("PathTaperY", ProcessShpPathTaperY); m_ShapeXmlProcessors.Add("PathTwist", ProcessShpPathTwist); m_ShapeXmlProcessors.Add("PathTwistBegin", ProcessShpPathTwistBegin); m_ShapeXmlProcessors.Add("PCode", ProcessShpPCode); m_ShapeXmlProcessors.Add("ProfileBegin", ProcessShpProfileBegin); m_ShapeXmlProcessors.Add("ProfileEnd", ProcessShpProfileEnd); m_ShapeXmlProcessors.Add("ProfileHollow", ProcessShpProfileHollow); m_ShapeXmlProcessors.Add("Scale", ProcessShpScale); m_ShapeXmlProcessors.Add("LastAttachPoint", ProcessShpLastAttach); m_ShapeXmlProcessors.Add("State", ProcessShpState); m_ShapeXmlProcessors.Add("ProfileShape", ProcessShpProfileShape); m_ShapeXmlProcessors.Add("HollowShape", ProcessShpHollowShape); m_ShapeXmlProcessors.Add("SculptTexture", ProcessShpSculptTexture); m_ShapeXmlProcessors.Add("SculptType", ProcessShpSculptType); // Ignore "SculptData"; this element is deprecated m_ShapeXmlProcessors.Add("FlexiSoftness", ProcessShpFlexiSoftness); m_ShapeXmlProcessors.Add("FlexiTension", ProcessShpFlexiTension); m_ShapeXmlProcessors.Add("FlexiDrag", ProcessShpFlexiDrag); m_ShapeXmlProcessors.Add("FlexiGravity", ProcessShpFlexiGravity); m_ShapeXmlProcessors.Add("FlexiWind", ProcessShpFlexiWind); m_ShapeXmlProcessors.Add("FlexiForceX", ProcessShpFlexiForceX); m_ShapeXmlProcessors.Add("FlexiForceY", ProcessShpFlexiForceY); m_ShapeXmlProcessors.Add("FlexiForceZ", ProcessShpFlexiForceZ); m_ShapeXmlProcessors.Add("LightColorR", ProcessShpLightColorR); m_ShapeXmlProcessors.Add("LightColorG", ProcessShpLightColorG); m_ShapeXmlProcessors.Add("LightColorB", ProcessShpLightColorB); m_ShapeXmlProcessors.Add("LightColorA", ProcessShpLightColorA); m_ShapeXmlProcessors.Add("LightRadius", ProcessShpLightRadius); m_ShapeXmlProcessors.Add("LightCutoff", ProcessShpLightCutoff); m_ShapeXmlProcessors.Add("LightFalloff", ProcessShpLightFalloff); m_ShapeXmlProcessors.Add("LightIntensity", ProcessShpLightIntensity); m_ShapeXmlProcessors.Add("FlexiEntry", ProcessShpFlexiEntry); m_ShapeXmlProcessors.Add("LightEntry", ProcessShpLightEntry); m_ShapeXmlProcessors.Add("SculptEntry", ProcessShpSculptEntry); m_ShapeXmlProcessors.Add("Media", ProcessShpMedia); #endregion } #region SOPXmlProcessors private static void ProcessAllowedDrop(SceneObjectPart obj, XmlReader reader) { obj.AllowedDrop = Util.ReadBoolean(reader); } private static void ProcessCreatorID(SceneObjectPart obj, XmlReader reader) { obj.CreatorID = Util.ReadUUID(reader, "CreatorID"); } private static void ProcessCreatorData(SceneObjectPart obj, XmlReader reader) { obj.CreatorData = reader.ReadElementContentAsString("CreatorData", String.Empty); } private static void ProcessFolderID(SceneObjectPart obj, XmlReader reader) { obj.FolderID = Util.ReadUUID(reader, "FolderID"); } private static void ProcessInventorySerial(SceneObjectPart obj, XmlReader reader) { obj.InventorySerial = (uint)reader.ReadElementContentAsInt("InventorySerial", String.Empty); } private static void ProcessTaskInventory(SceneObjectPart obj, XmlReader reader) { obj.TaskInventory = ReadTaskInventory(reader, "TaskInventory"); } private static void ProcessUUID(SceneObjectPart obj, XmlReader reader) { obj.UUID = Util.ReadUUID(reader, "UUID"); } private static void ProcessLocalId(SceneObjectPart obj, XmlReader reader) { obj.LocalId = (uint)reader.ReadElementContentAsLong("LocalId", String.Empty); } private static void ProcessName(SceneObjectPart obj, XmlReader reader) { obj.Name = reader.ReadElementString("Name"); } private static void ProcessMaterial(SceneObjectPart obj, XmlReader reader) { obj.Material = (byte)reader.ReadElementContentAsInt("Material", String.Empty); } private static void ProcessPassTouches(SceneObjectPart obj, XmlReader reader) { obj.PassTouches = Util.ReadBoolean(reader); } private static void ProcessPassCollisions(SceneObjectPart obj, XmlReader reader) { obj.PassCollisions = Util.ReadBoolean(reader); } private static void ProcessRegionHandle(SceneObjectPart obj, XmlReader reader) { obj.RegionHandle = (ulong)reader.ReadElementContentAsLong("RegionHandle", String.Empty); } private static void ProcessScriptAccessPin(SceneObjectPart obj, XmlReader reader) { obj.ScriptAccessPin = reader.ReadElementContentAsInt("ScriptAccessPin", String.Empty); } private static void ProcessGroupPosition(SceneObjectPart obj, XmlReader reader) { obj.GroupPosition = Util.ReadVector(reader, "GroupPosition"); } private static void ProcessOffsetPosition(SceneObjectPart obj, XmlReader reader) { obj.OffsetPosition = Util.ReadVector(reader, "OffsetPosition"); ; } private static void ProcessRotationOffset(SceneObjectPart obj, XmlReader reader) { obj.RotationOffset = Util.ReadQuaternion(reader, "RotationOffset"); } private static void ProcessVelocity(SceneObjectPart obj, XmlReader reader) { obj.Velocity = Util.ReadVector(reader, "Velocity"); } private static void ProcessAngularVelocity(SceneObjectPart obj, XmlReader reader) { obj.AngularVelocity = Util.ReadVector(reader, "AngularVelocity"); } private static void ProcessAcceleration(SceneObjectPart obj, XmlReader reader) { obj.Acceleration = Util.ReadVector(reader, "Acceleration"); } private static void ProcessDescription(SceneObjectPart obj, XmlReader reader) { obj.Description = reader.ReadElementString("Description"); } private static void ProcessColor(SceneObjectPart obj, XmlReader reader) { reader.ReadStartElement("Color"); if (reader.Name == "R") { float r = reader.ReadElementContentAsFloat("R", String.Empty); float g = reader.ReadElementContentAsFloat("G", String.Empty); float b = reader.ReadElementContentAsFloat("B", String.Empty); float a = reader.ReadElementContentAsFloat("A", String.Empty); obj.Color = Color.FromArgb((int)a, (int)r, (int)g, (int)b); reader.ReadEndElement(); } } private static void ProcessText(SceneObjectPart obj, XmlReader reader) { obj.Text = reader.ReadElementString("Text", String.Empty); } private static void ProcessSitName(SceneObjectPart obj, XmlReader reader) { obj.SitName = reader.ReadElementString("SitName", String.Empty); } private static void ProcessTouchName(SceneObjectPart obj, XmlReader reader) { obj.TouchName = reader.ReadElementString("TouchName", String.Empty); } private static void ProcessLinkNum(SceneObjectPart obj, XmlReader reader) { obj.LinkNum = reader.ReadElementContentAsInt("LinkNum", String.Empty); } private static void ProcessClickAction(SceneObjectPart obj, XmlReader reader) { obj.ClickAction = (byte)reader.ReadElementContentAsInt("ClickAction", String.Empty); } private static void ProcessRotationAxisLocks(SceneObjectPart obj, XmlReader reader) { obj.RotationAxisLocks = (byte)reader.ReadElementContentAsInt("RotationAxisLocks", String.Empty); } private static void ProcessPhysicsShapeType(SceneObjectPart obj, XmlReader reader) { obj.PhysicsShapeType = (byte)reader.ReadElementContentAsInt("PhysicsShapeType", String.Empty); } private static void ProcessDensity(SceneObjectPart obj, XmlReader reader) { obj.Density = reader.ReadElementContentAsFloat("Density", String.Empty); } private static void ProcessFriction(SceneObjectPart obj, XmlReader reader) { obj.Friction = reader.ReadElementContentAsFloat("Friction", String.Empty); } private static void ProcessBounce(SceneObjectPart obj, XmlReader reader) { obj.Restitution = reader.ReadElementContentAsFloat("Bounce", String.Empty); } private static void ProcessGravityModifier(SceneObjectPart obj, XmlReader reader) { obj.GravityModifier = reader.ReadElementContentAsFloat("GravityModifier", String.Empty); } private static void ProcessCameraEyeOffset(SceneObjectPart obj, XmlReader reader) { obj.SetCameraEyeOffset(Util.ReadVector(reader, "CameraEyeOffset")); } private static void ProcessCameraAtOffset(SceneObjectPart obj, XmlReader reader) { obj.SetCameraAtOffset(Util.ReadVector(reader, "CameraAtOffset")); } private static void ProcessSoundID(SceneObjectPart obj, XmlReader reader) { obj.Sound = Util.ReadUUID(reader, "SoundID"); } private static void ProcessSoundGain(SceneObjectPart obj, XmlReader reader) { obj.SoundGain = reader.ReadElementContentAsDouble("SoundGain", String.Empty); } private static void ProcessSoundFlags(SceneObjectPart obj, XmlReader reader) { obj.SoundFlags = (byte)reader.ReadElementContentAsInt("SoundFlags", String.Empty); } private static void ProcessSoundRadius(SceneObjectPart obj, XmlReader reader) { obj.SoundRadius = reader.ReadElementContentAsDouble("SoundRadius", String.Empty); } private static void ProcessSoundQueueing(SceneObjectPart obj, XmlReader reader) { obj.SoundQueueing = Util.ReadBoolean(reader); } private static void ProcessVehicle(SceneObjectPart obj, XmlReader reader) { SOPVehicle vehicle = SOPVehicle.FromXml2(reader); if (vehicle == null) { obj.VehicleParams = null; m_log.DebugFormat( "[SceneObjectSerializer]: Parsing Vehicle for object part {0} {1} encountered errors. Please see earlier log entries.", obj.Name, obj.UUID); } else { obj.VehicleParams = vehicle; } } private static void ProcessPhysicsInertia(SceneObjectPart obj, XmlReader reader) { PhysicsInertiaData pdata = PhysicsInertiaData.FromXml2(reader); if (pdata == null) { obj.PhysicsInertia = null; m_log.DebugFormat( "[SceneObjectSerializer]: Parsing PhysicsInertiaData for object part {0} {1} encountered errors. Please see earlier log entries.", obj.Name, obj.UUID); } else { obj.PhysicsInertia = pdata; } } private static void ProcessShape(SceneObjectPart obj, XmlReader reader) { List<string> errorNodeNames; obj.Shape = ReadShape(reader, "Shape", out errorNodeNames, obj); if (errorNodeNames != null) { m_log.DebugFormat( "[SceneObjectSerializer]: Parsing PrimitiveBaseShape for object part {0} {1} encountered errors in properties {2}.", obj.Name, obj.UUID, string.Join(", ", errorNodeNames.ToArray())); } } private static void ProcessScale(SceneObjectPart obj, XmlReader reader) { obj.Scale = Util.ReadVector(reader, "Scale"); } private static void ProcessSitTargetOrientation(SceneObjectPart obj, XmlReader reader) { obj.SitTargetOrientation = Util.ReadQuaternion(reader, "SitTargetOrientation"); } private static void ProcessSitTargetPosition(SceneObjectPart obj, XmlReader reader) { obj.SitTargetPosition = Util.ReadVector(reader, "SitTargetPosition"); } private static void ProcessSitTargetPositionLL(SceneObjectPart obj, XmlReader reader) { obj.SitTargetPositionLL = Util.ReadVector(reader, "SitTargetPositionLL"); } private static void ProcessSitTargetOrientationLL(SceneObjectPart obj, XmlReader reader) { obj.SitTargetOrientationLL = Util.ReadQuaternion(reader, "SitTargetOrientationLL"); } private static void ProcessParentID(SceneObjectPart obj, XmlReader reader) { string str = reader.ReadElementContentAsString("ParentID", String.Empty); obj.ParentID = Convert.ToUInt32(str); } private static void ProcessCreationDate(SceneObjectPart obj, XmlReader reader) { obj.CreationDate = reader.ReadElementContentAsInt("CreationDate", String.Empty); } private static void ProcessCategory(SceneObjectPart obj, XmlReader reader) { obj.Category = (uint)reader.ReadElementContentAsInt("Category", String.Empty); } private static void ProcessSalePrice(SceneObjectPart obj, XmlReader reader) { obj.SalePrice = reader.ReadElementContentAsInt("SalePrice", String.Empty); } private static void ProcessObjectSaleType(SceneObjectPart obj, XmlReader reader) { obj.ObjectSaleType = (byte)reader.ReadElementContentAsInt("ObjectSaleType", String.Empty); } private static void ProcessOwnershipCost(SceneObjectPart obj, XmlReader reader) { obj.OwnershipCost = reader.ReadElementContentAsInt("OwnershipCost", String.Empty); } private static void ProcessGroupID(SceneObjectPart obj, XmlReader reader) { obj.GroupID = Util.ReadUUID(reader, "GroupID"); } private static void ProcessOwnerID(SceneObjectPart obj, XmlReader reader) { obj.OwnerID = Util.ReadUUID(reader, "OwnerID"); } private static void ProcessLastOwnerID(SceneObjectPart obj, XmlReader reader) { obj.LastOwnerID = Util.ReadUUID(reader, "LastOwnerID"); } private static void ProcessRezzerID(SceneObjectPart obj, XmlReader reader) { obj.RezzerID = Util.ReadUUID(reader, "RezzerID"); } private static void ProcessBaseMask(SceneObjectPart obj, XmlReader reader) { obj.BaseMask = (uint)reader.ReadElementContentAsInt("BaseMask", String.Empty); } private static void ProcessOwnerMask(SceneObjectPart obj, XmlReader reader) { obj.OwnerMask = (uint)reader.ReadElementContentAsInt("OwnerMask", String.Empty); } private static void ProcessGroupMask(SceneObjectPart obj, XmlReader reader) { obj.GroupMask = (uint)reader.ReadElementContentAsInt("GroupMask", String.Empty); } private static void ProcessEveryoneMask(SceneObjectPart obj, XmlReader reader) { obj.EveryoneMask = (uint)reader.ReadElementContentAsInt("EveryoneMask", String.Empty); } private static void ProcessNextOwnerMask(SceneObjectPart obj, XmlReader reader) { obj.NextOwnerMask = (uint)reader.ReadElementContentAsInt("NextOwnerMask", String.Empty); } private static void ProcessFlags(SceneObjectPart obj, XmlReader reader) { obj.Flags = Util.ReadEnum<PrimFlags>(reader, "Flags"); } private static void ProcessCollisionSound(SceneObjectPart obj, XmlReader reader) { obj.CollisionSound = Util.ReadUUID(reader, "CollisionSound"); } private static void ProcessCollisionSoundVolume(SceneObjectPart obj, XmlReader reader) { obj.CollisionSoundVolume = reader.ReadElementContentAsFloat("CollisionSoundVolume", String.Empty); } private static void ProcessMediaUrl(SceneObjectPart obj, XmlReader reader) { obj.MediaUrl = reader.ReadElementContentAsString("MediaUrl", String.Empty); } private static void ProcessAttachedPos(SceneObjectPart obj, XmlReader reader) { obj.AttachedPos = Util.ReadVector(reader, "AttachedPos"); } private static void ProcessDynAttrs(SceneObjectPart obj, XmlReader reader) { obj.DynAttrs.ReadXml(reader); } private static void ProcessTextureAnimation(SceneObjectPart obj, XmlReader reader) { obj.TextureAnimation = Convert.FromBase64String(reader.ReadElementContentAsString("TextureAnimation", String.Empty)); } private static void ProcessParticleSystem(SceneObjectPart obj, XmlReader reader) { obj.ParticleSystem = Convert.FromBase64String(reader.ReadElementContentAsString("ParticleSystem", String.Empty)); } private static void ProcessPayPrice0(SceneObjectPart obj, XmlReader reader) { obj.PayPrice[0] = (int)reader.ReadElementContentAsInt("PayPrice0", String.Empty); } private static void ProcessPayPrice1(SceneObjectPart obj, XmlReader reader) { obj.PayPrice[1] = (int)reader.ReadElementContentAsInt("PayPrice1", String.Empty); } private static void ProcessPayPrice2(SceneObjectPart obj, XmlReader reader) { obj.PayPrice[2] = (int)reader.ReadElementContentAsInt("PayPrice2", String.Empty); } private static void ProcessPayPrice3(SceneObjectPart obj, XmlReader reader) { obj.PayPrice[3] = (int)reader.ReadElementContentAsInt("PayPrice3", String.Empty); } private static void ProcessPayPrice4(SceneObjectPart obj, XmlReader reader) { obj.PayPrice[4] = (int)reader.ReadElementContentAsInt("PayPrice4", String.Empty); } private static void ProcessBuoyancy(SceneObjectPart obj, XmlReader reader) { obj.Buoyancy = (float)reader.ReadElementContentAsFloat("Buoyancy", String.Empty); } private static void ProcessForce(SceneObjectPart obj, XmlReader reader) { obj.Force = Util.ReadVector(reader, "Force"); } private static void ProcessTorque(SceneObjectPart obj, XmlReader reader) { obj.Torque = Util.ReadVector(reader, "Torque"); } private static void ProcessVolumeDetectActive(SceneObjectPart obj, XmlReader reader) { obj.VolumeDetectActive = Util.ReadBoolean(reader); } #endregion #region TaskInventoryXmlProcessors private static void ProcessTIAssetID(TaskInventoryItem item, XmlReader reader) { item.AssetID = Util.ReadUUID(reader, "AssetID"); } private static void ProcessTIBasePermissions(TaskInventoryItem item, XmlReader reader) { item.BasePermissions = (uint)reader.ReadElementContentAsInt("BasePermissions", String.Empty); } private static void ProcessTICreationDate(TaskInventoryItem item, XmlReader reader) { item.CreationDate = (uint)reader.ReadElementContentAsInt("CreationDate", String.Empty); } private static void ProcessTICreatorID(TaskInventoryItem item, XmlReader reader) { item.CreatorID = Util.ReadUUID(reader, "CreatorID"); } private static void ProcessTICreatorData(TaskInventoryItem item, XmlReader reader) { item.CreatorData = reader.ReadElementContentAsString("CreatorData", String.Empty); } private static void ProcessTIDescription(TaskInventoryItem item, XmlReader reader) { item.Description = reader.ReadElementContentAsString("Description", String.Empty); } private static void ProcessTIEveryonePermissions(TaskInventoryItem item, XmlReader reader) { item.EveryonePermissions = (uint)reader.ReadElementContentAsInt("EveryonePermissions", String.Empty); } private static void ProcessTIFlags(TaskInventoryItem item, XmlReader reader) { item.Flags = (uint)reader.ReadElementContentAsInt("Flags", String.Empty); } private static void ProcessTIGroupID(TaskInventoryItem item, XmlReader reader) { item.GroupID = Util.ReadUUID(reader, "GroupID"); } private static void ProcessTIGroupPermissions(TaskInventoryItem item, XmlReader reader) { item.GroupPermissions = (uint)reader.ReadElementContentAsInt("GroupPermissions", String.Empty); } private static void ProcessTIInvType(TaskInventoryItem item, XmlReader reader) { item.InvType = reader.ReadElementContentAsInt("InvType", String.Empty); } private static void ProcessTIItemID(TaskInventoryItem item, XmlReader reader) { item.ItemID = Util.ReadUUID(reader, "ItemID"); } private static void ProcessTIOldItemID(TaskInventoryItem item, XmlReader reader) { item.OldItemID = Util.ReadUUID(reader, "OldItemID"); } private static void ProcessTILastOwnerID(TaskInventoryItem item, XmlReader reader) { item.LastOwnerID = Util.ReadUUID(reader, "LastOwnerID"); } private static void ProcessTIName(TaskInventoryItem item, XmlReader reader) { item.Name = reader.ReadElementContentAsString("Name", String.Empty); } private static void ProcessTINextPermissions(TaskInventoryItem item, XmlReader reader) { item.NextPermissions = (uint)reader.ReadElementContentAsInt("NextPermissions", String.Empty); } private static void ProcessTIOwnerID(TaskInventoryItem item, XmlReader reader) { item.OwnerID = Util.ReadUUID(reader, "OwnerID"); } private static void ProcessTICurrentPermissions(TaskInventoryItem item, XmlReader reader) { item.CurrentPermissions = (uint)reader.ReadElementContentAsInt("CurrentPermissions", String.Empty); } private static void ProcessTIParentID(TaskInventoryItem item, XmlReader reader) { item.ParentID = Util.ReadUUID(reader, "ParentID"); } private static void ProcessTIParentPartID(TaskInventoryItem item, XmlReader reader) { item.ParentPartID = Util.ReadUUID(reader, "ParentPartID"); } private static void ProcessTIPermsGranter(TaskInventoryItem item, XmlReader reader) { item.PermsGranter = Util.ReadUUID(reader, "PermsGranter"); } private static void ProcessTIPermsMask(TaskInventoryItem item, XmlReader reader) { item.PermsMask = reader.ReadElementContentAsInt("PermsMask", String.Empty); } private static void ProcessTIType(TaskInventoryItem item, XmlReader reader) { item.Type = reader.ReadElementContentAsInt("Type", String.Empty); } private static void ProcessTIOwnerChanged(TaskInventoryItem item, XmlReader reader) { item.OwnerChanged = Util.ReadBoolean(reader); } #endregion #region ShapeXmlProcessors private static void ProcessShpProfileCurve(PrimitiveBaseShape shp, XmlReader reader) { shp.ProfileCurve = (byte)reader.ReadElementContentAsInt("ProfileCurve", String.Empty); } private static void ProcessShpTextureEntry(PrimitiveBaseShape shp, XmlReader reader) { byte[] teData = Convert.FromBase64String(reader.ReadElementString("TextureEntry")); shp.Textures = new Primitive.TextureEntry(teData, 0, teData.Length); } private static void ProcessShpExtraParams(PrimitiveBaseShape shp, XmlReader reader) { shp.ExtraParams = Convert.FromBase64String(reader.ReadElementString("ExtraParams")); } private static void ProcessShpPathBegin(PrimitiveBaseShape shp, XmlReader reader) { shp.PathBegin = (ushort)reader.ReadElementContentAsInt("PathBegin", String.Empty); } private static void ProcessShpPathCurve(PrimitiveBaseShape shp, XmlReader reader) { shp.PathCurve = (byte)reader.ReadElementContentAsInt("PathCurve", String.Empty); } private static void ProcessShpPathEnd(PrimitiveBaseShape shp, XmlReader reader) { shp.PathEnd = (ushort)reader.ReadElementContentAsInt("PathEnd", String.Empty); } private static void ProcessShpPathRadiusOffset(PrimitiveBaseShape shp, XmlReader reader) { shp.PathRadiusOffset = (sbyte)reader.ReadElementContentAsInt("PathRadiusOffset", String.Empty); } private static void ProcessShpPathRevolutions(PrimitiveBaseShape shp, XmlReader reader) { shp.PathRevolutions = (byte)reader.ReadElementContentAsInt("PathRevolutions", String.Empty); } private static void ProcessShpPathScaleX(PrimitiveBaseShape shp, XmlReader reader) { shp.PathScaleX = (byte)reader.ReadElementContentAsInt("PathScaleX", String.Empty); } private static void ProcessShpPathScaleY(PrimitiveBaseShape shp, XmlReader reader) { shp.PathScaleY = (byte)reader.ReadElementContentAsInt("PathScaleY", String.Empty); } private static void ProcessShpPathShearX(PrimitiveBaseShape shp, XmlReader reader) { shp.PathShearX = (byte)reader.ReadElementContentAsInt("PathShearX", String.Empty); } private static void ProcessShpPathShearY(PrimitiveBaseShape shp, XmlReader reader) { shp.PathShearY = (byte)reader.ReadElementContentAsInt("PathShearY", String.Empty); } private static void ProcessShpPathSkew(PrimitiveBaseShape shp, XmlReader reader) { shp.PathSkew = (sbyte)reader.ReadElementContentAsInt("PathSkew", String.Empty); } private static void ProcessShpPathTaperX(PrimitiveBaseShape shp, XmlReader reader) { shp.PathTaperX = (sbyte)reader.ReadElementContentAsInt("PathTaperX", String.Empty); } private static void ProcessShpPathTaperY(PrimitiveBaseShape shp, XmlReader reader) { shp.PathTaperY = (sbyte)reader.ReadElementContentAsInt("PathTaperY", String.Empty); } private static void ProcessShpPathTwist(PrimitiveBaseShape shp, XmlReader reader) { shp.PathTwist = (sbyte)reader.ReadElementContentAsInt("PathTwist", String.Empty); } private static void ProcessShpPathTwistBegin(PrimitiveBaseShape shp, XmlReader reader) { shp.PathTwistBegin = (sbyte)reader.ReadElementContentAsInt("PathTwistBegin", String.Empty); } private static void ProcessShpPCode(PrimitiveBaseShape shp, XmlReader reader) { shp.PCode = (byte)reader.ReadElementContentAsInt("PCode", String.Empty); } private static void ProcessShpProfileBegin(PrimitiveBaseShape shp, XmlReader reader) { shp.ProfileBegin = (ushort)reader.ReadElementContentAsInt("ProfileBegin", String.Empty); } private static void ProcessShpProfileEnd(PrimitiveBaseShape shp, XmlReader reader) { shp.ProfileEnd = (ushort)reader.ReadElementContentAsInt("ProfileEnd", String.Empty); } private static void ProcessShpProfileHollow(PrimitiveBaseShape shp, XmlReader reader) { shp.ProfileHollow = (ushort)reader.ReadElementContentAsInt("ProfileHollow", String.Empty); } private static void ProcessShpScale(PrimitiveBaseShape shp, XmlReader reader) { shp.Scale = Util.ReadVector(reader, "Scale"); } private static void ProcessShpState(PrimitiveBaseShape shp, XmlReader reader) { shp.State = (byte)reader.ReadElementContentAsInt("State", String.Empty); } private static void ProcessShpLastAttach(PrimitiveBaseShape shp, XmlReader reader) { shp.LastAttachPoint = (byte)reader.ReadElementContentAsInt("LastAttachPoint", String.Empty); } private static void ProcessShpProfileShape(PrimitiveBaseShape shp, XmlReader reader) { shp.ProfileShape = Util.ReadEnum<ProfileShape>(reader, "ProfileShape"); } private static void ProcessShpHollowShape(PrimitiveBaseShape shp, XmlReader reader) { shp.HollowShape = Util.ReadEnum<HollowShape>(reader, "HollowShape"); } private static void ProcessShpSculptTexture(PrimitiveBaseShape shp, XmlReader reader) { shp.SculptTexture = Util.ReadUUID(reader, "SculptTexture"); } private static void ProcessShpSculptType(PrimitiveBaseShape shp, XmlReader reader) { shp.SculptType = (byte)reader.ReadElementContentAsInt("SculptType", String.Empty); } private static void ProcessShpFlexiSoftness(PrimitiveBaseShape shp, XmlReader reader) { shp.FlexiSoftness = reader.ReadElementContentAsInt("FlexiSoftness", String.Empty); } private static void ProcessShpFlexiTension(PrimitiveBaseShape shp, XmlReader reader) { shp.FlexiTension = reader.ReadElementContentAsFloat("FlexiTension", String.Empty); } private static void ProcessShpFlexiDrag(PrimitiveBaseShape shp, XmlReader reader) { shp.FlexiDrag = reader.ReadElementContentAsFloat("FlexiDrag", String.Empty); } private static void ProcessShpFlexiGravity(PrimitiveBaseShape shp, XmlReader reader) { shp.FlexiGravity = reader.ReadElementContentAsFloat("FlexiGravity", String.Empty); } private static void ProcessShpFlexiWind(PrimitiveBaseShape shp, XmlReader reader) { shp.FlexiWind = reader.ReadElementContentAsFloat("FlexiWind", String.Empty); } private static void ProcessShpFlexiForceX(PrimitiveBaseShape shp, XmlReader reader) { shp.FlexiForceX = reader.ReadElementContentAsFloat("FlexiForceX", String.Empty); } private static void ProcessShpFlexiForceY(PrimitiveBaseShape shp, XmlReader reader) { shp.FlexiForceY = reader.ReadElementContentAsFloat("FlexiForceY", String.Empty); } private static void ProcessShpFlexiForceZ(PrimitiveBaseShape shp, XmlReader reader) { shp.FlexiForceZ = reader.ReadElementContentAsFloat("FlexiForceZ", String.Empty); } private static void ProcessShpLightColorR(PrimitiveBaseShape shp, XmlReader reader) { shp.LightColorR = reader.ReadElementContentAsFloat("LightColorR", String.Empty); } private static void ProcessShpLightColorG(PrimitiveBaseShape shp, XmlReader reader) { shp.LightColorG = reader.ReadElementContentAsFloat("LightColorG", String.Empty); } private static void ProcessShpLightColorB(PrimitiveBaseShape shp, XmlReader reader) { shp.LightColorB = reader.ReadElementContentAsFloat("LightColorB", String.Empty); } private static void ProcessShpLightColorA(PrimitiveBaseShape shp, XmlReader reader) { shp.LightColorA = reader.ReadElementContentAsFloat("LightColorA", String.Empty); } private static void ProcessShpLightRadius(PrimitiveBaseShape shp, XmlReader reader) { shp.LightRadius = reader.ReadElementContentAsFloat("LightRadius", String.Empty); } private static void ProcessShpLightCutoff(PrimitiveBaseShape shp, XmlReader reader) { shp.LightCutoff = reader.ReadElementContentAsFloat("LightCutoff", String.Empty); } private static void ProcessShpLightFalloff(PrimitiveBaseShape shp, XmlReader reader) { shp.LightFalloff = reader.ReadElementContentAsFloat("LightFalloff", String.Empty); } private static void ProcessShpLightIntensity(PrimitiveBaseShape shp, XmlReader reader) { shp.LightIntensity = reader.ReadElementContentAsFloat("LightIntensity", String.Empty); } private static void ProcessShpFlexiEntry(PrimitiveBaseShape shp, XmlReader reader) { shp.FlexiEntry = Util.ReadBoolean(reader); } private static void ProcessShpLightEntry(PrimitiveBaseShape shp, XmlReader reader) { shp.LightEntry = Util.ReadBoolean(reader); } private static void ProcessShpSculptEntry(PrimitiveBaseShape shp, XmlReader reader) { shp.SculptEntry = Util.ReadBoolean(reader); } private static void ProcessShpMedia(PrimitiveBaseShape shp, XmlReader reader) { string value = String.Empty; try { // The STANDARD content of Media elemet is escaped XML string (with &gt; etc). value = reader.ReadElementContentAsString("Media", String.Empty); shp.Media = PrimitiveBaseShape.MediaList.FromXml(value); } catch (XmlException) { // There are versions of OAR files that contain unquoted XML. // ie ONE comercial fork that never wanted their oars to be read by our code try { value = reader.ReadInnerXml(); shp.Media = PrimitiveBaseShape.MediaList.FromXml(value); } catch { m_log.ErrorFormat("[SERIALIZER] Failed parsing halcyon MOAP information"); } } } #endregion ////////// Write ///////// public static void SOGToXml2(XmlTextWriter writer, SceneObjectGroup sog, Dictionary<string, object>options) { writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty); SOPToXml2(writer, sog.RootPart, options); writer.WriteStartElement(String.Empty, "OtherParts", String.Empty); sog.ForEachPart(delegate(SceneObjectPart sop) { if (sop.UUID != sog.RootPart.UUID) SOPToXml2(writer, sop, options); }); writer.WriteEndElement(); if (sog.RootPart.KeyframeMotion != null) { Byte[] data = sog.RootPart.KeyframeMotion.Serialize(); writer.WriteStartElement(String.Empty, "KeyframeMotion", String.Empty); writer.WriteBase64(data, 0, data.Length); writer.WriteEndElement(); } writer.WriteEndElement(); } public static void SOPToXml2(XmlTextWriter writer, SceneObjectPart sop, Dictionary<string, object> options) { writer.WriteStartElement("SceneObjectPart"); writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); writer.WriteAttributeString("xmlns:xsd", "http://www.w3.org/2001/XMLSchema"); writer.WriteElementString("AllowedDrop", sop.AllowedDrop.ToString().ToLower()); WriteUUID(writer, "CreatorID", sop.CreatorID, options); if (!string.IsNullOrEmpty(sop.CreatorData)) writer.WriteElementString("CreatorData", sop.CreatorData); else if (options.ContainsKey("home")) { if (m_UserManagement == null) m_UserManagement = sop.ParentGroup.Scene.RequestModuleInterface<IUserManagement>(); string name = m_UserManagement.GetUserName(sop.CreatorID); writer.WriteElementString("CreatorData", ExternalRepresentationUtils.CalcCreatorData((string)options["home"], name)); } WriteUUID(writer, "FolderID", sop.FolderID, options); writer.WriteElementString("InventorySerial", sop.InventorySerial.ToString()); WriteTaskInventory(writer, sop.TaskInventory, options, sop.ParentGroup.Scene); WriteUUID(writer, "UUID", sop.UUID, options); writer.WriteElementString("LocalId", sop.LocalId.ToString()); writer.WriteElementString("Name", sop.Name); writer.WriteElementString("Material", sop.Material.ToString()); writer.WriteElementString("PassTouches", sop.PassTouches.ToString().ToLower()); writer.WriteElementString("PassCollisions", sop.PassCollisions.ToString().ToLower()); writer.WriteElementString("RegionHandle", sop.RegionHandle.ToString()); writer.WriteElementString("ScriptAccessPin", sop.ScriptAccessPin.ToString()); WriteVector(writer, "GroupPosition", sop.GroupPosition); WriteVector(writer, "OffsetPosition", sop.OffsetPosition); WriteQuaternion(writer, "RotationOffset", sop.RotationOffset); WriteVector(writer, "Velocity", sop.Velocity); WriteVector(writer, "AngularVelocity", sop.AngularVelocity); WriteVector(writer, "Acceleration", sop.Acceleration); writer.WriteElementString("Description", sop.Description); writer.WriteStartElement("Color"); writer.WriteElementString("R", sop.Color.R.ToString(Culture.FormatProvider)); writer.WriteElementString("G", sop.Color.G.ToString(Culture.FormatProvider)); writer.WriteElementString("B", sop.Color.B.ToString(Culture.FormatProvider)); writer.WriteElementString("A", sop.Color.A.ToString(Culture.FormatProvider)); writer.WriteEndElement(); writer.WriteElementString("Text", sop.Text); writer.WriteElementString("SitName", sop.SitName); writer.WriteElementString("TouchName", sop.TouchName); writer.WriteElementString("LinkNum", sop.LinkNum.ToString()); writer.WriteElementString("ClickAction", sop.ClickAction.ToString()); WriteShape(writer, sop.Shape, options); WriteVector(writer, "Scale", sop.Scale); WriteQuaternion(writer, "SitTargetOrientation", sop.SitTargetOrientation); WriteVector(writer, "SitTargetPosition", sop.SitTargetPosition); WriteVector(writer, "SitTargetPositionLL", sop.SitTargetPositionLL); WriteQuaternion(writer, "SitTargetOrientationLL", sop.SitTargetOrientationLL); writer.WriteElementString("ParentID", sop.ParentID.ToString()); writer.WriteElementString("CreationDate", sop.CreationDate.ToString()); writer.WriteElementString("Category", sop.Category.ToString()); writer.WriteElementString("SalePrice", sop.SalePrice.ToString()); writer.WriteElementString("ObjectSaleType", sop.ObjectSaleType.ToString()); writer.WriteElementString("OwnershipCost", sop.OwnershipCost.ToString()); UUID groupID = options.ContainsKey("wipe-owners") ? UUID.Zero : sop.GroupID; WriteUUID(writer, "GroupID", groupID, options); UUID ownerID = options.ContainsKey("wipe-owners") ? UUID.Zero : sop.OwnerID; WriteUUID(writer, "OwnerID", ownerID, options); UUID lastOwnerID = options.ContainsKey("wipe-owners") ? UUID.Zero : sop.LastOwnerID; WriteUUID(writer, "LastOwnerID", lastOwnerID, options); UUID rezzerID = options.ContainsKey("wipe-owners") ? UUID.Zero : sop.RezzerID; WriteUUID(writer, "RezzerID", rezzerID, options); writer.WriteElementString("BaseMask", sop.BaseMask.ToString()); writer.WriteElementString("OwnerMask", sop.OwnerMask.ToString()); writer.WriteElementString("GroupMask", sop.GroupMask.ToString()); writer.WriteElementString("EveryoneMask", sop.EveryoneMask.ToString()); writer.WriteElementString("NextOwnerMask", sop.NextOwnerMask.ToString()); WriteFlags(writer, "Flags", sop.Flags.ToString(), options); WriteUUID(writer, "CollisionSound", sop.CollisionSound, options); writer.WriteElementString("CollisionSoundVolume", sop.CollisionSoundVolume.ToString(Culture.FormatProvider)); if (sop.MediaUrl != null) writer.WriteElementString("MediaUrl", sop.MediaUrl.ToString()); WriteVector(writer, "AttachedPos", sop.AttachedPos); if (sop.DynAttrs.CountNamespaces > 0) { writer.WriteStartElement("DynAttrs"); sop.DynAttrs.WriteXml(writer); writer.WriteEndElement(); } WriteBytes(writer, "TextureAnimation", sop.TextureAnimation); WriteBytes(writer, "ParticleSystem", sop.ParticleSystem); writer.WriteElementString("PayPrice0", sop.PayPrice[0].ToString()); writer.WriteElementString("PayPrice1", sop.PayPrice[1].ToString()); writer.WriteElementString("PayPrice2", sop.PayPrice[2].ToString()); writer.WriteElementString("PayPrice3", sop.PayPrice[3].ToString()); writer.WriteElementString("PayPrice4", sop.PayPrice[4].ToString()); writer.WriteElementString("Buoyancy", sop.Buoyancy.ToString(Culture.FormatProvider)); WriteVector(writer, "Force", sop.Force); WriteVector(writer, "Torque", sop.Torque); writer.WriteElementString("VolumeDetectActive", sop.VolumeDetectActive.ToString().ToLower()); if (sop.VehicleParams != null) sop.VehicleParams.ToXml2(writer); if (sop.PhysicsInertia != null) sop.PhysicsInertia.ToXml2(writer); if(sop.RotationAxisLocks != 0) writer.WriteElementString("RotationAxisLocks", sop.RotationAxisLocks.ToString().ToLower()); writer.WriteElementString("PhysicsShapeType", sop.PhysicsShapeType.ToString().ToLower()); if (sop.Density != 1000.0f) writer.WriteElementString("Density", sop.Density.ToString(Culture.FormatProvider)); if (sop.Friction != 0.6f) writer.WriteElementString("Friction", sop.Friction.ToString(Culture.FormatProvider)); if (sop.Restitution != 0.5f) writer.WriteElementString("Bounce", sop.Restitution.ToString(Culture.FormatProvider)); if (sop.GravityModifier != 1.0f) writer.WriteElementString("GravityModifier", sop.GravityModifier.ToString(Culture.FormatProvider)); WriteVector(writer, "CameraEyeOffset", sop.GetCameraEyeOffset()); WriteVector(writer, "CameraAtOffset", sop.GetCameraAtOffset()); // if (sop.Sound != UUID.Zero) force it till sop crossing does clear it on child prim { WriteUUID(writer, "SoundID", sop.Sound, options); writer.WriteElementString("SoundGain", sop.SoundGain.ToString(Culture.FormatProvider)); writer.WriteElementString("SoundFlags", sop.SoundFlags.ToString().ToLower()); writer.WriteElementString("SoundRadius", sop.SoundRadius.ToString(Culture.FormatProvider)); } writer.WriteElementString("SoundQueueing", sop.SoundQueueing.ToString().ToLower()); writer.WriteEndElement(); } static void WriteUUID(XmlTextWriter writer, string name, UUID id, Dictionary<string, object> options) { writer.WriteStartElement(name); if (options.ContainsKey("old-guids")) writer.WriteElementString("Guid", id.ToString()); else writer.WriteElementString("UUID", id.ToString()); writer.WriteEndElement(); } static void WriteVector(XmlTextWriter writer, string name, Vector3 vec) { writer.WriteStartElement(name); writer.WriteElementString("X", vec.X.ToString(Culture.FormatProvider)); writer.WriteElementString("Y", vec.Y.ToString(Culture.FormatProvider)); writer.WriteElementString("Z", vec.Z.ToString(Culture.FormatProvider)); writer.WriteEndElement(); } static void WriteQuaternion(XmlTextWriter writer, string name, Quaternion quat) { writer.WriteStartElement(name); writer.WriteElementString("X", quat.X.ToString(Culture.FormatProvider)); writer.WriteElementString("Y", quat.Y.ToString(Culture.FormatProvider)); writer.WriteElementString("Z", quat.Z.ToString(Culture.FormatProvider)); writer.WriteElementString("W", quat.W.ToString(Culture.FormatProvider)); writer.WriteEndElement(); } static void WriteBytes(XmlTextWriter writer, string name, byte[] data) { writer.WriteStartElement(name); byte[] d; if (data != null) d = data; else d = Utils.EmptyBytes; writer.WriteBase64(d, 0, d.Length); writer.WriteEndElement(); // name } static void WriteFlags(XmlTextWriter writer, string name, string flagsStr, Dictionary<string, object> options) { // Older versions of serialization can't cope with commas, so we eliminate the commas writer.WriteElementString(name, flagsStr.Replace(",", "")); } public static void WriteTaskInventory(XmlTextWriter writer, TaskInventoryDictionary tinv, Dictionary<string, object> options, Scene scene) { if (tinv.Count > 0) // otherwise skip this { writer.WriteStartElement("TaskInventory"); foreach (TaskInventoryItem item in tinv.Values) { writer.WriteStartElement("TaskInventoryItem"); WriteUUID(writer, "AssetID", item.AssetID, options); writer.WriteElementString("BasePermissions", item.BasePermissions.ToString()); writer.WriteElementString("CreationDate", item.CreationDate.ToString()); WriteUUID(writer, "CreatorID", item.CreatorID, options); if (!string.IsNullOrEmpty(item.CreatorData)) writer.WriteElementString("CreatorData", item.CreatorData); else if (options.ContainsKey("home")) { if (m_UserManagement == null) m_UserManagement = scene.RequestModuleInterface<IUserManagement>(); string name = m_UserManagement.GetUserName(item.CreatorID); writer.WriteElementString("CreatorData", ExternalRepresentationUtils.CalcCreatorData((string)options["home"], name)); } writer.WriteElementString("Description", item.Description); writer.WriteElementString("EveryonePermissions", item.EveryonePermissions.ToString()); writer.WriteElementString("Flags", item.Flags.ToString()); UUID groupID = options.ContainsKey("wipe-owners") ? UUID.Zero : item.GroupID; WriteUUID(writer, "GroupID", groupID, options); writer.WriteElementString("GroupPermissions", item.GroupPermissions.ToString()); writer.WriteElementString("InvType", item.InvType.ToString()); WriteUUID(writer, "ItemID", item.ItemID, options); WriteUUID(writer, "OldItemID", item.OldItemID, options); UUID lastOwnerID = options.ContainsKey("wipe-owners") ? UUID.Zero : item.LastOwnerID; WriteUUID(writer, "LastOwnerID", lastOwnerID, options); writer.WriteElementString("Name", item.Name); writer.WriteElementString("NextPermissions", item.NextPermissions.ToString()); UUID ownerID = options.ContainsKey("wipe-owners") ? UUID.Zero : item.OwnerID; WriteUUID(writer, "OwnerID", ownerID, options); writer.WriteElementString("CurrentPermissions", item.CurrentPermissions.ToString()); WriteUUID(writer, "ParentID", item.ParentID, options); WriteUUID(writer, "ParentPartID", item.ParentPartID, options); WriteUUID(writer, "PermsGranter", item.PermsGranter, options); writer.WriteElementString("PermsMask", item.PermsMask.ToString()); writer.WriteElementString("Type", item.Type.ToString()); bool ownerChanged = options.ContainsKey("wipe-owners") ? false : item.OwnerChanged; writer.WriteElementString("OwnerChanged", ownerChanged.ToString().ToLower()); writer.WriteEndElement(); // TaskInventoryItem } writer.WriteEndElement(); // TaskInventory } } public static void WriteShape(XmlTextWriter writer, PrimitiveBaseShape shp, Dictionary<string, object> options) { if (shp != null) { writer.WriteStartElement("Shape"); writer.WriteElementString("ProfileCurve", shp.ProfileCurve.ToString()); writer.WriteStartElement("TextureEntry"); byte[] te; if (shp.TextureEntry != null) te = shp.TextureEntry; else te = Utils.EmptyBytes; writer.WriteBase64(te, 0, te.Length); writer.WriteEndElement(); // TextureEntry writer.WriteStartElement("ExtraParams"); byte[] ep; if (shp.ExtraParams != null) ep = shp.ExtraParams; else ep = Utils.EmptyBytes; writer.WriteBase64(ep, 0, ep.Length); writer.WriteEndElement(); // ExtraParams writer.WriteElementString("PathBegin", shp.PathBegin.ToString()); writer.WriteElementString("PathCurve", shp.PathCurve.ToString()); writer.WriteElementString("PathEnd", shp.PathEnd.ToString()); writer.WriteElementString("PathRadiusOffset", shp.PathRadiusOffset.ToString()); writer.WriteElementString("PathRevolutions", shp.PathRevolutions.ToString()); writer.WriteElementString("PathScaleX", shp.PathScaleX.ToString()); writer.WriteElementString("PathScaleY", shp.PathScaleY.ToString()); writer.WriteElementString("PathShearX", shp.PathShearX.ToString()); writer.WriteElementString("PathShearY", shp.PathShearY.ToString()); writer.WriteElementString("PathSkew", shp.PathSkew.ToString()); writer.WriteElementString("PathTaperX", shp.PathTaperX.ToString()); writer.WriteElementString("PathTaperY", shp.PathTaperY.ToString()); writer.WriteElementString("PathTwist", shp.PathTwist.ToString()); writer.WriteElementString("PathTwistBegin", shp.PathTwistBegin.ToString()); writer.WriteElementString("PCode", shp.PCode.ToString()); writer.WriteElementString("ProfileBegin", shp.ProfileBegin.ToString()); writer.WriteElementString("ProfileEnd", shp.ProfileEnd.ToString()); writer.WriteElementString("ProfileHollow", shp.ProfileHollow.ToString()); writer.WriteElementString("State", shp.State.ToString()); writer.WriteElementString("LastAttachPoint", shp.LastAttachPoint.ToString()); WriteFlags(writer, "ProfileShape", shp.ProfileShape.ToString(), options); WriteFlags(writer, "HollowShape", shp.HollowShape.ToString(), options); WriteUUID(writer, "SculptTexture", shp.SculptTexture, options); writer.WriteElementString("SculptType", shp.SculptType.ToString()); // Don't serialize SculptData. It's just a copy of the asset, which can be loaded separately using 'SculptTexture'. writer.WriteElementString("FlexiSoftness", shp.FlexiSoftness.ToString()); writer.WriteElementString("FlexiTension", shp.FlexiTension.ToString(Culture.FormatProvider)); writer.WriteElementString("FlexiDrag", shp.FlexiDrag.ToString(Culture.FormatProvider)); writer.WriteElementString("FlexiGravity", shp.FlexiGravity.ToString(Culture.FormatProvider)); writer.WriteElementString("FlexiWind", shp.FlexiWind.ToString(Culture.FormatProvider)); writer.WriteElementString("FlexiForceX", shp.FlexiForceX.ToString(Culture.FormatProvider)); writer.WriteElementString("FlexiForceY", shp.FlexiForceY.ToString(Culture.FormatProvider)); writer.WriteElementString("FlexiForceZ", shp.FlexiForceZ.ToString(Culture.FormatProvider)); writer.WriteElementString("LightColorR", shp.LightColorR.ToString(Culture.FormatProvider)); writer.WriteElementString("LightColorG", shp.LightColorG.ToString(Culture.FormatProvider)); writer.WriteElementString("LightColorB", shp.LightColorB.ToString(Culture.FormatProvider)); writer.WriteElementString("LightColorA", shp.LightColorA.ToString(Culture.FormatProvider)); writer.WriteElementString("LightRadius", shp.LightRadius.ToString(Culture.FormatProvider)); writer.WriteElementString("LightCutoff", shp.LightCutoff.ToString(Culture.FormatProvider)); writer.WriteElementString("LightFalloff", shp.LightFalloff.ToString(Culture.FormatProvider)); writer.WriteElementString("LightIntensity", shp.LightIntensity.ToString(Culture.FormatProvider)); writer.WriteElementString("FlexiEntry", shp.FlexiEntry.ToString().ToLower()); writer.WriteElementString("LightEntry", shp.LightEntry.ToString().ToLower()); writer.WriteElementString("SculptEntry", shp.SculptEntry.ToString().ToLower()); if (shp.Media != null) writer.WriteElementString("Media", shp.Media.ToXml()); writer.WriteEndElement(); // Shape } } public static SceneObjectPart Xml2ToSOP(XmlReader reader) { SceneObjectPart obj = new SceneObjectPart(); reader.ReadStartElement("SceneObjectPart"); bool errors = ExternalRepresentationUtils.ExecuteReadProcessors( obj, m_SOPXmlProcessors, reader, (o, nodeName, e) => { m_log.Debug(string.Format("[SceneObjectSerializer]: Error while parsing element {0} in object {1} {2} ", nodeName, ((SceneObjectPart)o).Name, ((SceneObjectPart)o).UUID), e); }); if (errors) throw new XmlException(string.Format("Error parsing object {0} {1}", obj.Name, obj.UUID)); reader.ReadEndElement(); // SceneObjectPart obj.AggregateInnerPerms(); // m_log.DebugFormat("[SceneObjectSerializer]: parsed SOP {0} {1}", obj.Name, obj.UUID); return obj; } public static TaskInventoryDictionary ReadTaskInventory(XmlReader reader, string name) { TaskInventoryDictionary tinv = new TaskInventoryDictionary(); reader.ReadStartElement(name, String.Empty); while (reader.Name == "TaskInventoryItem") { reader.ReadStartElement("TaskInventoryItem", String.Empty); // TaskInventory TaskInventoryItem item = new TaskInventoryItem(); ExternalRepresentationUtils.ExecuteReadProcessors( item, m_TaskInventoryXmlProcessors, reader); reader.ReadEndElement(); // TaskInventoryItem tinv.Add(item.ItemID, item); } if (reader.NodeType == XmlNodeType.EndElement) reader.ReadEndElement(); // TaskInventory return tinv; } /// <summary> /// Read a shape from xml input /// </summary> /// <param name="reader"></param> /// <param name="name">The name of the xml element containing the shape</param> /// <param name="errors">a list containing the failing node names. If no failures then null.</param> /// <returns>The shape parsed</returns> public static PrimitiveBaseShape ReadShape(XmlReader reader, string name, out List<string> errorNodeNames, SceneObjectPart obj) { List<string> internalErrorNodeNames = null; PrimitiveBaseShape shape = new PrimitiveBaseShape(); if (reader.IsEmptyElement) { reader.Read(); errorNodeNames = null; return shape; } reader.ReadStartElement(name, String.Empty); // Shape ExternalRepresentationUtils.ExecuteReadProcessors( shape, m_ShapeXmlProcessors, reader, (o, nodeName, e) => { m_log.Debug(string.Format("[SceneObjectSerializer]: Error while parsing element {0} in Shape property of object {1} {2} ", nodeName, obj.Name, obj.UUID), e); if (internalErrorNodeNames == null) internalErrorNodeNames = new List<string>(); internalErrorNodeNames.Add(nodeName); }); reader.ReadEndElement(); // Shape errorNodeNames = internalErrorNodeNames; return shape; } #endregion } }
//--------------------------------------------------------------------------- // File: TraceProvider // // A Managed wrapper for Event Tracing for Windows // Based on TraceEvent.cs found in nt\base\wmi\trace.net // Provides an internal Avalon API to replace Microsoft.Windows.EventTracing.dll // //--------------------------------------------------------------------------- #if !SILVERLIGHTXAML using System; using MS.Win32; using MS.Internal; using System.Runtime.InteropServices; using System.Security; using System.Globalization; //for CultureInfo using System.Diagnostics; using MS.Internal.WindowsBase; #pragma warning disable 1634, 1691 //disable warnings about unknown pragma #if SYSTEM_XAML using System.Xaml; namespace MS.Internal.Xaml #else namespace MS.Utility #endif { [StructLayout(LayoutKind.Explicit, Size = 16)] internal struct EventData { [FieldOffset(0)] internal unsafe ulong Ptr; [FieldOffset(8)] internal uint Size; [FieldOffset(12)] internal uint Reserved; } internal abstract class TraceProvider { protected bool _enabled = false; protected EventTrace.Level _level = EventTrace.Level.LogAlways; protected EventTrace.Keyword _keywords = (EventTrace.Keyword)0; /* aka Flags */ protected EventTrace.Keyword _matchAllKeyword = (EventTrace.Keyword)0; /*Vista only*/ protected SecurityCriticalDataForSet<ulong> _registrationHandle; private const int s_basicTypeAllocationBufferSize = sizeof(decimal); private const int s_traceEventMaximumSize = 65482; // maximum buffer size is 64k - header size private const int s_etwMaxNumberArguments = 32; private const int s_etwAPIMaxStringCount = 8; // Arbitrary limit on the number of strings you can emit. This is just to limit allocations so raise it if necessary. private const int ErrorEventTooBig = 2; [SecurityCritical] internal TraceProvider() { _registrationHandle = new SecurityCriticalDataForSet<ulong>(0); } [SecurityCritical] internal abstract void Register(Guid providerGuid); [SecurityCritical] internal unsafe abstract uint EventWrite(EventTrace.Event eventID, EventTrace.Keyword keywords, EventTrace.Level level, int argc, EventData* argv); internal uint TraceEvent(EventTrace.Event eventID, EventTrace.Keyword keywords, EventTrace.Level level) { // Optimization for 0-1 arguments return TraceEvent(eventID, keywords, level, (object)null); } #region Properties and Structs // // Properties // internal EventTrace.Keyword Keywords { get { return _keywords; } } internal EventTrace.Keyword MatchAllKeywords { get { return _matchAllKeyword; } } internal EventTrace.Level Level { get { return _level; } } #endregion internal bool IsEnabled(EventTrace.Keyword keyword, EventTrace.Level level) { return _enabled && (level <= _level) && (keyword & _keywords) != 0 && (keyword & _matchAllKeyword) == _matchAllKeyword; } // Optimization for 0-1 arguments [SecurityCritical, SecurityTreatAsSafe] internal unsafe uint TraceEvent(EventTrace.Event eventID, EventTrace.Keyword keywords, EventTrace.Level level, object eventData) { // It is the responsibility of the caller to check that flags/keywords are enabled before calling this method Debug.Assert(IsEnabled(keywords, level)); uint status = 0; int argCount = 0; EventData userData; userData.Size = 0; string dataString = null; byte* dataBuffer = stackalloc byte[s_basicTypeAllocationBufferSize]; if (eventData != null) { dataString = EncodeObject(ref eventData, &userData, dataBuffer); argCount = 1; } if (userData.Size > s_traceEventMaximumSize) { return ErrorEventTooBig; } if (dataString != null) { fixed(char* pdata = dataString) { userData.Ptr = (ulong)pdata; status = EventWrite(eventID, keywords, level, argCount, &userData); } } else { status = EventWrite(eventID, keywords, level, argCount, &userData); } return status; } [SecurityCritical, SecurityTreatAsSafe] internal unsafe uint TraceEvent(EventTrace.Event eventID, EventTrace.Keyword keywords, EventTrace.Level level, params object[] eventPayload) { // It is the responsibility of the caller to check that flags/keywords are enabled before calling this method Debug.Assert(IsEnabled(keywords, level)); int argCount = eventPayload.Length; Debug.Assert(argCount <= s_etwMaxNumberArguments); uint totalEventSize = 0; int stringIndex = 0; int[] stringPosition = new int[s_etwAPIMaxStringCount]; string [] dataString = new string[s_etwAPIMaxStringCount]; EventData* userData = stackalloc EventData[argCount]; EventData* userDataPtr = userData; byte* dataBuffer = stackalloc byte[s_basicTypeAllocationBufferSize * argCount]; byte* currentBuffer = dataBuffer; for (int index = 0; index < argCount; index++) { if (eventPayload[index] != null) { string isString = EncodeObject(ref eventPayload[index], userDataPtr, currentBuffer); currentBuffer += s_basicTypeAllocationBufferSize; totalEventSize = userDataPtr->Size; userDataPtr++; if (isString != null) { Debug.Assert(stringIndex < s_etwAPIMaxStringCount); // need to increase string count or emit fewer strings dataString[stringIndex] = isString; stringPosition[stringIndex] = index; stringIndex++; } } } if (totalEventSize > s_traceEventMaximumSize) { return ErrorEventTooBig; } fixed(char* s0 = dataString[0], s1 = dataString[1], s2 = dataString[2], s3 = dataString[3], s4 = dataString[4], s5 = dataString[5], s6 = dataString[6], s7 = dataString[7]) { userDataPtr = userData; if (dataString[0] != null) { userDataPtr[stringPosition[0]].Ptr = (ulong)s0; } if (dataString[1] != null) { userDataPtr[stringPosition[1]].Ptr = (ulong)s1; } if (dataString[2] != null) { userDataPtr[stringPosition[2]].Ptr = (ulong)s2; } if (dataString[3] != null) { userDataPtr[stringPosition[3]].Ptr = (ulong)s3; } if (dataString[4] != null) { userDataPtr[stringPosition[4]].Ptr = (ulong)s4; } if (dataString[5] != null) { userDataPtr[stringPosition[5]].Ptr = (ulong)s5; } if (dataString[6] != null) { userDataPtr[stringPosition[6]].Ptr = (ulong)s6; } if (dataString[7] != null) { userDataPtr[stringPosition[7]].Ptr = (ulong)s7; } return EventWrite(eventID, keywords, level, argCount, userData); } } // <SecurityKernel Critical="True" Ring="0"> // <UsesUnsafeCode Name="Local intptrPtr of type: IntPtr*" /> // <UsesUnsafeCode Name="Local intptrPtr of type: Int32*" /> // <UsesUnsafeCode Name="Local longptr of type: Int64*" /> // <UsesUnsafeCode Name="Local uintptr of type: UInt32*" /> // <UsesUnsafeCode Name="Local ulongptr of type: UInt64*" /> // <UsesUnsafeCode Name="Local charptr of type: Char*" /> // <UsesUnsafeCode Name="Local byteptr of type: Byte*" /> // <UsesUnsafeCode Name="Local shortptr of type: Int16*" /> // <UsesUnsafeCode Name="Local sbyteptr of type: SByte*" /> // <UsesUnsafeCode Name="Local ushortptr of type: UInt16*" /> // <UsesUnsafeCode Name="Local floatptr of type: Single*" /> // <UsesUnsafeCode Name="Local doubleptr of type: Double*" /> // <UsesUnsafeCode Name="Local boolptr of type: Boolean*" /> // <UsesUnsafeCode Name="Local guidptr of type: Guid*" /> // <UsesUnsafeCode Name="Local decimalptr of type: Decimal*" /> // <UsesUnsafeCode Name="Local booleanptr of type: Boolean*" /> // <UsesUnsafeCode Name="Parameter dataDescriptor of type: EventData*" /> // <UsesUnsafeCode Name="Parameter dataBuffer of type: Byte*" /> // </SecurityKernel> [SecurityCritical] private static unsafe string EncodeObject(ref object data, EventData* dataDescriptor, byte* dataBuffer) /*++ Routine Description: This routine is used by WriteEvent to unbox the object type and to fill the passed in ETW data descriptor. Arguments: data - argument to be decoded dataDescriptor - pointer to the descriptor to be filled dataBuffer - storage buffer for storing user data, needed because cant get the address of the object Return Value: null if the object is a basic type other than string. String otherwise --*/ { dataDescriptor->Reserved = 0; string sRet = data as string; if (sRet != null) { dataDescriptor->Size = (uint)((sRet.Length + 1) * 2); return sRet; } // If the data is an enum we'll convert it to it's underlying type Type dataType = data.GetType(); if (dataType.IsEnum) { data = Convert.ChangeType(data, Enum.GetUnderlyingType(dataType), CultureInfo.InvariantCulture); } if (data is IntPtr) { dataDescriptor->Size = (uint)sizeof(IntPtr); IntPtr* intptrPtr = (IntPtr*)dataBuffer; *intptrPtr = (IntPtr)data; dataDescriptor->Ptr = (ulong)intptrPtr; } else if (data is int) { dataDescriptor->Size = (uint)sizeof(int); int* intptrPtr = (int*)dataBuffer; *intptrPtr = (int)data; dataDescriptor->Ptr = (ulong)intptrPtr; } else if (data is long) { dataDescriptor->Size = (uint)sizeof(long); long* longptr = (long*)dataBuffer; *longptr = (long)data; dataDescriptor->Ptr = (ulong)longptr; } else if (data is uint) { dataDescriptor->Size = (uint)sizeof(uint); uint* uintptr = (uint*)dataBuffer; *uintptr = (uint)data; dataDescriptor->Ptr = (ulong)uintptr; } else if (data is UInt64) { dataDescriptor->Size = (uint)sizeof(ulong); ulong* ulongptr = (ulong*)dataBuffer; *ulongptr = (ulong)data; dataDescriptor->Ptr = (ulong)ulongptr; } else if (data is char) { dataDescriptor->Size = (uint)sizeof(char); char* charptr = (char*)dataBuffer; *charptr = (char)data; dataDescriptor->Ptr = (ulong)charptr; } else if (data is byte) { dataDescriptor->Size = (uint)sizeof(byte); byte* byteptr = (byte*)dataBuffer; *byteptr = (byte)data; dataDescriptor->Ptr = (ulong)byteptr; } else if (data is short) { dataDescriptor->Size = (uint)sizeof(short); short* shortptr = (short*)dataBuffer; *shortptr = (short)data; dataDescriptor->Ptr = (ulong)shortptr; } else if (data is sbyte) { dataDescriptor->Size = (uint)sizeof(sbyte); sbyte* sbyteptr = (sbyte*)dataBuffer; *sbyteptr = (sbyte)data; dataDescriptor->Ptr = (ulong)sbyteptr; } else if (data is ushort) { dataDescriptor->Size = (uint)sizeof(ushort); ushort* ushortptr = (ushort*)dataBuffer; *ushortptr = (ushort)data; dataDescriptor->Ptr = (ulong)ushortptr; } else if (data is float) { dataDescriptor->Size = (uint)sizeof(float); float* floatptr = (float*)dataBuffer; *floatptr = (float)data; dataDescriptor->Ptr = (ulong)floatptr; } else if (data is double) { dataDescriptor->Size = (uint)sizeof(double); double* doubleptr = (double*)dataBuffer; *doubleptr = (double)data; dataDescriptor->Ptr = (ulong)doubleptr; } else if (data is bool) { dataDescriptor->Size = (uint)sizeof(bool); bool* boolptr = (bool*)dataBuffer; *boolptr = (bool)data; dataDescriptor->Ptr = (ulong)boolptr; } else if (data is Guid) { dataDescriptor->Size = (uint)sizeof(Guid); Guid* guidptr = (Guid*)dataBuffer; *guidptr = (Guid)data; dataDescriptor->Ptr = (ulong)guidptr; } else if (data is decimal) { dataDescriptor->Size = (uint)sizeof(decimal); decimal* decimalptr = (decimal*)dataBuffer; *decimalptr = (decimal)data; dataDescriptor->Ptr = (ulong)decimalptr; } else if (data is Boolean) { dataDescriptor->Size = (uint)sizeof(Boolean); Boolean* booleanptr = (Boolean*)dataBuffer; *booleanptr = (Boolean)data; dataDescriptor->Ptr = (ulong)booleanptr; } else { //To our eyes, everything else is a just a string sRet = data.ToString(); dataDescriptor->Size = (uint)((sRet.Length + 1) * 2); return sRet; } return null; } } // XP internal sealed class ClassicTraceProvider : TraceProvider { private ulong _traceHandle = 0; /// <SecurityNote> /// Critical - Field for critical type ClassicEtw.ControlCallback. /// </SecurityNote> [SecurityCritical] private static ClassicEtw.ControlCallback _etwProc; // Trace Callback function [SecurityCritical] internal ClassicTraceProvider() { } // // Registers the providerGuid with an inbuilt callback // ///<SecurityNote> /// Critical: This calls critical code in UnsafeNativeMethods.EtwTrace /// and sets critical for set field _registrationHandle and _etwProc ///</SecurityNote> [SecurityCritical] internal override unsafe void Register(Guid providerGuid) { ulong registrationHandle; ClassicEtw.TRACE_GUID_REGISTRATION guidReg; Guid dummyGuid = new Guid(0xb4955bf0, 0x3af1, 0x4740, 0xb4,0x75, 0x99,0x05,0x5d,0x3f,0xe9,0xaa); _etwProc = new ClassicEtw.ControlCallback(EtwEnableCallback); // This dummyGuid is there for ETW backward compat issues and is the same for all downlevel trace providers guidReg.Guid = &dummyGuid; guidReg.RegHandle = null; ClassicEtw.RegisterTraceGuidsW(_etwProc, IntPtr.Zero, ref providerGuid, 1, ref guidReg, null, null, out registrationHandle); _registrationHandle.Value = registrationHandle; } // // This callback function is called by ETW to enable or disable this provider // ///<SecurityNote> /// Critical: This calls critical code in ClassicEtw ///</SecurityNote> [SecurityCritical] private unsafe uint EtwEnableCallback(ClassicEtw.WMIDPREQUESTCODE requestCode, IntPtr context, IntPtr bufferSize, ClassicEtw.WNODE_HEADER* buffer) { try { switch (requestCode) { case ClassicEtw.WMIDPREQUESTCODE.EnableEvents: _traceHandle = buffer->HistoricalContext; _keywords = (EventTrace.Keyword)ClassicEtw.GetTraceEnableFlags((ulong)buffer->HistoricalContext); _level = (EventTrace.Level)ClassicEtw.GetTraceEnableLevel((ulong)buffer->HistoricalContext); _enabled = true; break; case ClassicEtw.WMIDPREQUESTCODE.DisableEvents: _enabled = false; _traceHandle = 0; _level = EventTrace.Level.LogAlways; _keywords = 0; break; default: _enabled = false; _traceHandle = 0; break; } return 0; } catch(Exception e) { if (CriticalExceptions.IsCriticalException(e)) { throw; } else { return 0; } } } ///<SecurityNote> /// Critical: This calls critical code in EtwTrace /// TreatAsSafe: the registration handle this passes in to UnregisterTraceGuids /// was generated by the ETW unmanaged API and can't be tampered with from our side ///</SecurityNote> [SecurityCritical, SecurityTreatAsSafe] ~ClassicTraceProvider() { #pragma warning suppress 6031 //presharp suppression ClassicEtw.UnregisterTraceGuids(_registrationHandle.Value); } // pack the argv data and emit the event using TraceEvent [SecurityCritical] internal unsafe override uint EventWrite(EventTrace.Event eventID, EventTrace.Keyword keywords, EventTrace.Level level, int argc, EventData* argv) { ClassicEtw.EVENT_HEADER header; header.Header.ClientContext = 0; header.Header.Flags = ClassicEtw.WNODE_FLAG_TRACED_GUID | ClassicEtw.WNODE_FLAG_USE_MOF_PTR; header.Header.Guid = EventTrace.GetGuidForEvent(eventID); header.Header.Level = (byte)level; header.Header.Type = (byte)EventTrace.GetOpcodeForEvent(eventID); header.Header.Version = (ushort)EventTrace.GetVersionForEvent(eventID); // Extra copy on XP to move argv to the end of the EVENT_HEADER EventData* eventData = &header.Data; if (argc > ClassicEtw.MAX_MOF_FIELDS) { // Data will be lost on XP argc = ClassicEtw.MAX_MOF_FIELDS; } header.Header.Size = (ushort) (argc * sizeof(EventData) + 48); for (int x = 0; x < argc; x++) { eventData[x].Ptr = argv[x].Ptr; eventData[x].Size = argv[x].Size; } return ClassicEtw.TraceEvent(_traceHandle, &header); } } // Vista and above internal class ManifestTraceProvider : TraceProvider { /// <SecurityNote> /// Critical - Field for critical type ManifestEtw.EtwEnableCallback. /// </SecurityNote> [SecurityCritical] private static ManifestEtw.EtwEnableCallback _etwEnabledCallback; [SecurityCritical] internal ManifestTraceProvider() { } /// <SecurityNote> /// Critical - Sets critical _etwEnabledCallback field /// - Calls critical ManifestEtw.EventRegister /// </SecurityNote> [SecurityCritical] internal unsafe override void Register(Guid providerGuid) { _etwEnabledCallback =new ManifestEtw.EtwEnableCallback(EtwEnableCallback); ulong registrationHandle = 0; ManifestEtw.EventRegister(ref providerGuid, _etwEnabledCallback, null, ref registrationHandle); _registrationHandle.Value = registrationHandle; } /// <SecurityNote> /// Critical - Accepts untrusted pointer argument /// </SecurityNote> [SecurityCritical] private unsafe void EtwEnableCallback(ref Guid sourceId, int isEnabled, byte level, long matchAnyKeywords, long matchAllKeywords, ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData, void* callbackContext) { _enabled = isEnabled > 0; _level = (EventTrace.Level)level; _keywords = (EventTrace.Keyword) matchAnyKeywords; _matchAllKeyword = (EventTrace.Keyword) matchAllKeywords; // todo: parse data from EVENT_FILTER_DESCRIPTOR - see CLR EventProvider::GetDataFromController } /// <SecurityNote> /// Critical - Calls critical ManifestEtw.EventUnregister /// TreatAsSafe: Only critical code can create this resource, /// and no input parameters are accepted to this method. /// In fact, this method is not directly callable, but only as /// part of the GC, and the GC ensures that no other rooted /// objects are holding a reference. This method clears the /// handle and skips future calls to unregister the event, which /// protects against resurrection. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] ~ManifestTraceProvider() { if(_registrationHandle.Value != 0) { try { ManifestEtw.EventUnregister(_registrationHandle.Value); } finally { _registrationHandle.Value = 0; } } } /// <SecurityNote> /// Critical - Accepts untrusted pointer argument /// </SecurityNote> [SecurityCritical] internal unsafe override uint EventWrite(EventTrace.Event eventID, EventTrace.Keyword keywords, EventTrace.Level level, int argc, EventData* argv) { ManifestEtw.EventDescriptor eventDescriptor; eventDescriptor.Id = (ushort) eventID; eventDescriptor.Version = EventTrace.GetVersionForEvent(eventID); eventDescriptor.Channel = 0x10; // Since Channel isn't supported on XP we only use a single default channel. eventDescriptor.Level = (byte)level; eventDescriptor.Opcode = EventTrace.GetOpcodeForEvent(eventID); eventDescriptor.Task = EventTrace.GetTaskForEvent(eventID); eventDescriptor.Keywords = (long)keywords; if (argc == 0) { argv = null; } return ManifestEtw.EventWrite(_registrationHandle.Value, ref eventDescriptor, (uint)argc, argv); } } } #endif
using System; using System.Globalization; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using TreeGecko.Library.Geospatial.Geoframeworks.Interfaces; namespace TreeGecko.Library.Geospatial.Geoframeworks.Objects { /// <summary> /// Represents a measurement of an object's rate of travel in a particular direction. /// </summary> /// <remarks> /// <para>Instances of this class are guaranteed to be thread-safe because the class is /// immutable (its properties can only be changed via constructors).</para> /// </remarks> public struct Velocity : IFormattable, IEquatable<Velocity>, ICloneable<Velocity>, IXmlSerializable { private Speed _Speed; private Azimuth _Bearing; #region Fields /// <summary>Represents a velocity with no speed or direction.</summary> public static readonly Velocity Empty = new Velocity(Speed.Empty, Azimuth.Empty); /// <summary>Represents a velocity with an invalid or unspecified speed and direction.</summary> public static readonly Velocity Invalid = new Velocity(Speed.Invalid, Azimuth.Invalid); #endregion #region Constructors public Velocity(Speed speed, Azimuth bearing) { _Speed = speed; _Bearing = bearing; } public Velocity(Speed speed, double bearingDegrees) { _Speed = speed; _Bearing = new Azimuth(bearingDegrees); } public Velocity(double speed, SpeedUnit speedUnits, Azimuth bearing) { _Speed = new Speed(speed, speedUnits); _Bearing = bearing; } public Velocity(double speed, SpeedUnit speedUnits, double bearingDegrees) { _Speed = new Speed(speed, speedUnits); _Bearing = new Azimuth(bearingDegrees); } /// <summary> /// Creates a new instance by parsing speed and bearing from the specified strings. /// </summary> public Velocity(string speed, string bearing) : this(speed, bearing, CultureInfo.CurrentCulture) { } /// <summary> /// Creates a new instance by converting the specified strings using the specific culture. /// </summary> public Velocity(string speed, string bearing, CultureInfo culture) { _Speed = new Speed(speed, culture); _Bearing = new Azimuth(bearing, culture); } public Velocity(XmlReader reader) { // Initialize all fields _Speed = Speed.Invalid; _Bearing = Azimuth.Invalid; // Deserialize the object from XML ReadXml(reader); } #endregion #region Public Properties /// <summary>Gets the objects rate of travel.</summary> public Speed Speed { get { return _Speed; } } /// <summary>Gets the objects direction of travel.</summary> public Azimuth Bearing { get { return _Bearing; } } /// <summary> /// Indicates whether the speed and bearing are both zero. /// </summary> public bool IsEmpty { get { return _Speed.IsEmpty && _Bearing.IsEmpty; } } /// <summary>Indicates whether the speed or bearing is invalid or unspecified.</summary> public bool IsInvalid { get { return _Speed.IsInvalid || _Bearing.IsInvalid; } } #endregion #region Operators public static bool operator ==(Velocity left, Velocity right) { return left.Equals(right); } public static bool operator !=(Velocity left, Velocity right) { return !left.Equals(right); } #endregion #region Overrides public override int GetHashCode() { return _Speed.GetHashCode() ^ _Bearing.GetHashCode(); } public override bool Equals(object obj) { if (obj is Velocity) return Equals((Velocity) obj); return false; } /// <summary>Outputs the current instance as a string using the default format.</summary> /// <returns><para>A <strong>String</strong> representing the current instance.</para></returns> public override string ToString() { return ToString("g", CultureInfo.CurrentCulture); } #endregion #region IEquatable<Velocity> /// <summary> /// Compares the current instance to the specified velocity. /// </summary> /// <param name="other">A <strong>Velocity</strong> object to compare with.</param> /// <returns>A <strong>Boolean</strong>, <strong>True</strong> if the values are identical.</returns> public bool Equals(Velocity other) { return _Speed.Equals(other.Speed) && _Bearing.Equals(other.Bearing); } /// <summary> /// Compares the current instance to the specified velocity using the specified numeric precision. /// </summary> /// <param name="other">A <strong>Velocity</strong> object to compare with.</param> /// <param name="decimals">An <strong>Integer</strong> specifying the number of fractional digits to compare.</param> /// <returns>A <strong>Boolean</strong>, <strong>True</strong> if the values are identical.</returns> public bool Equals(Velocity other, int decimals) { return _Speed.Equals(other.Speed, decimals) && _Bearing.Equals(other.Bearing, decimals); } #endregion #region IFormattable Members /// <summary> /// Outputs the current instance as a string using the specified format and culture information. /// </summary> public string ToString(string format, IFormatProvider formatProvider) { CultureInfo culture = (CultureInfo) formatProvider; if (culture == null) culture = CultureInfo.CurrentCulture; if (format == null || format.Length == 0) format = "G"; // Output as speed and bearing return _Speed.ToString(format, culture) + " " + _Bearing.ToString(format, culture); } #endregion #region IXmlSerializable Members XmlSchema IXmlSerializable.GetSchema() { return null; } public void WriteXml(XmlWriter writer) { writer.WriteStartElement("Speed"); _Speed.WriteXml(writer); writer.WriteEndElement(); writer.WriteStartElement("Bearing"); _Bearing.WriteXml(writer); writer.WriteEndElement(); } public void ReadXml(XmlReader reader) { // Move to the <Speed> element if (!reader.IsStartElement("Speed")) reader.ReadToDescendant("Speed"); reader.ReadStartElement(); _Speed.ReadXml(reader); reader.ReadEndElement(); reader.ReadStartElement(); _Bearing.ReadXml(reader); reader.ReadEndElement(); } #endregion #region ICloneable<Velocity> Members public Velocity Clone() { return new Velocity(_Speed, _Bearing); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Composition.Runtime.Util; using System.Linq; namespace System.Composition.Hosting.Core { /// <summary> /// The link between exports and imports. /// </summary> public sealed class CompositionContract { private readonly Type _contractType; private readonly string _contractName; private readonly IDictionary<string, object> _metadataConstraints; /// <summary> /// Construct a <see cref="CompositionContract"/>. /// </summary> /// <param name="contractType">The type shared between the exporter and importer.</param> public CompositionContract(Type contractType) : this(contractType, null) { } /// <summary> /// Construct a <see cref="CompositionContract"/>. /// </summary> /// <param name="contractType">The type shared between the exporter and importer.</param> /// <param name="contractName">Optionally, a name that discriminates this contract from others with the same type.</param> public CompositionContract(Type contractType, string contractName) : this(contractType, contractName, null) { } /// <summary> /// Construct a <see cref="CompositionContract"/>. /// </summary> /// <param name="contractType">The type shared between the exporter and importer.</param> /// <param name="contractName">Optionally, a name that discriminates this contract from others with the same type.</param> /// <param name="metadataConstraints">Optionally, a non-empty collection of named constraints that apply to the contract.</param> public CompositionContract(Type contractType, string contractName, IDictionary<string, object> metadataConstraints) { if (contractType == null) throw new ArgumentNullException(nameof(contractType)); if (metadataConstraints != null && metadataConstraints.Count == 0) throw new ArgumentOutOfRangeException(nameof(metadataConstraints)); _contractType = contractType; _contractName = contractName; _metadataConstraints = metadataConstraints; } /// <summary> /// The type shared between the exporter and importer. /// </summary> public Type ContractType { get { return _contractType; } } /// <summary> /// A name that discriminates this contract from others with the same type. /// </summary> public string ContractName { get { return _contractName; } } /// <summary> /// Constraints applied to the contract. Instead of using this collection /// directly it is advisable to use the <see cref="TryUnwrapMetadataConstraint"/> method. /// </summary> public IEnumerable<KeyValuePair<string, object>> MetadataConstraints { get { return _metadataConstraints; } } /// <summary> /// Determines equality between two contracts. /// </summary> /// <param name="obj">The contract to test.</param> /// <returns>True if the contracts are equivalent; otherwise, false.</returns> public override bool Equals(object obj) { var contract = obj as CompositionContract; return contract != null && contract._contractType.Equals(_contractType) && (_contractName == null ? contract._contractName == null : _contractName.Equals(contract._contractName)) && ConstraintEqual(_metadataConstraints, contract._metadataConstraints); } /// <summary> /// Gets a hash code for the contract. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { var hc = _contractType.GetHashCode(); if (_contractName != null) hc = hc ^ _contractName.GetHashCode(); if (_metadataConstraints != null) hc = hc ^ ConstraintHashCode(_metadataConstraints); return hc; } /// <summary> /// Creates a string representation of the contract. /// </summary> /// <returns>A string representation of the contract.</returns> public override string ToString() { var result = Formatters.Format(_contractType); if (_contractName != null) result += " " + Formatters.Format(_contractName); if (_metadataConstraints != null) result += string.Format(" {{ {0} }}", string.Join(SR.Formatter_ListSeparatorWithSpace, _metadataConstraints.Select(kv => string.Format("{0} = {1}", kv.Key, Formatters.Format(kv.Value))))); return result; } /// <summary> /// Transform the contract into a matching contract with a /// new contract type (with the same contract name and constraints). /// </summary> /// <param name="newContractType">The contract type for the new contract.</param> /// <returns>A matching contract with a /// new contract type.</returns> public CompositionContract ChangeType(Type newContractType) { if (newContractType == null) throw new ArgumentNullException(nameof(newContractType)); return new CompositionContract(newContractType, _contractName, _metadataConstraints); } /// <summary> /// Check the contract for a constraint with a particular name and value, and, if it exists, /// retrieve both the value and the remainder of the contract with the constraint /// removed. /// </summary> /// <typeparam name="T">The type of the constraint value.</typeparam> /// <param name="constraintName">The name of the constraint.</param> /// <param name="constraintValue">The value if it is present and of the correct type, otherwise null.</param> /// <param name="remainingContract">The contract with the constraint removed if present, otherwise null.</param> /// <returns>True if the constraint is present and of the correct type, otherwise false.</returns> public bool TryUnwrapMetadataConstraint<T>(string constraintName, out T constraintValue, out CompositionContract remainingContract) { if (constraintName == null) throw new ArgumentNullException(nameof(constraintName)); constraintValue = default(T); remainingContract = null; if (_metadataConstraints == null) return false; object value; if (!_metadataConstraints.TryGetValue(constraintName, out value)) return false; if (!(value is T)) return false; constraintValue = (T)value; if (_metadataConstraints.Count == 1) { remainingContract = new CompositionContract(_contractType, _contractName); } else { var remainingConstraints = new Dictionary<string, object>(_metadataConstraints); remainingConstraints.Remove(constraintName); remainingContract = new CompositionContract(_contractType, _contractName, remainingConstraints); } return true; } internal static bool ConstraintEqual(IDictionary<string, object> first, IDictionary<string, object> second) { if (first == second) return true; if (first == null || second == null) return false; if (first.Count != second.Count) return false; foreach (var firstItem in first) { object secondValue; if (!second.TryGetValue(firstItem.Key, out secondValue)) return false; if (firstItem.Value == null && secondValue != null || secondValue == null && firstItem.Value != null) { return false; } else { var firstEnumerable = firstItem.Value as IEnumerable; if (firstEnumerable != null && !(firstEnumerable is string)) { var secondEnumerable = secondValue as IEnumerable; if (secondEnumerable == null || !Enumerable.SequenceEqual(firstEnumerable.Cast<object>(), secondEnumerable.Cast<object>())) return false; } else if (!firstItem.Value.Equals(secondValue)) { return false; } } } return true; } private static int ConstraintHashCode(IDictionary<string, object> metadata) { var result = -1; foreach (var kv in metadata) { result ^= kv.Key.GetHashCode(); if (kv.Value != null) { var sval = kv.Value as string; if (sval != null) { result ^= sval.GetHashCode(); } else { var enumerableValue = kv.Value as IEnumerable; if (enumerableValue != null) { foreach (var ev in enumerableValue) if (ev != null) result ^= ev.GetHashCode(); } else { result ^= kv.Value.GetHashCode(); } } } } return result; } } }
// Copyright 2007-2017 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.AzureServiceBusTransport { using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using GreenPipes; using Logging; using MassTransit.Pipeline; using Microsoft.ServiceBus; using Microsoft.ServiceBus.Messaging; using Settings; using Transport; using Transports; using Util; public class ServiceBusHost : IServiceBusHost, IBusHostControl { static readonly ILog _log = Logger.Get<ServiceBusHost>(); readonly Lazy<Task<MessagingFactory>> _messagingFactory; readonly Lazy<NamespaceManager> _namespaceManager; readonly IReceiveEndpointCollection _receiveEndpoints; readonly Lazy<NamespaceManager> _rootNamespaceManager; readonly Lazy<Task<MessagingFactory>> _sessionMessagingFactory; readonly TaskSupervisor _supervisor; public ServiceBusHost(ServiceBusHostSettings settings) { Settings = settings; _messagingFactory = new Lazy<Task<MessagingFactory>>(CreateMessagingFactory); _sessionMessagingFactory = new Lazy<Task<MessagingFactory>>(CreateNetMessagingFactory); _namespaceManager = new Lazy<NamespaceManager>(CreateNamespaceManager); _rootNamespaceManager = new Lazy<NamespaceManager>(CreateRootNamespaceManager); MessageNameFormatter = new ServiceBusMessageNameFormatter(); _receiveEndpoints = new ReceiveEndpointCollection(); _supervisor = new TaskSupervisor($"{TypeMetadataCache<ServiceBusHost>.ShortName} - {Settings.ServiceUri}"); RetryPolicy = Retry.CreatePolicy(x => { x.Ignore<MessagingEntityNotFoundException>(); x.Ignore<MessagingEntityAlreadyExistsException>(); x.Ignore<MessageNotFoundException>(); x.Ignore<MessageSizeExceededException>(); x.Ignore<NoMatchingSubscriptionException>(); x.Ignore<TransactionSizeExceededException>(); x.Handle<ServerBusyException>(exception => exception.IsTransient || exception.IsWrappedExceptionTransient()); x.Handle<MessagingException>(exception => exception.IsTransient || exception.IsWrappedExceptionTransient()); x.Handle<TimeoutException>(); x.Intervals(100, 500, 1000, 5000, 10000); }); } public IServiceBusReceiveEndpointFactory ReceiveEndpointFactory { private get; set; } public IServiceBusSubscriptionEndpointFactory SubscriptionEndpointFactory { private get; set; } public IReceiveEndpointCollection ReceiveEndpoints => _receiveEndpoints; public async Task<HostHandle> Start() { HostReceiveEndpointHandle[] handles = ReceiveEndpoints.StartEndpoints(); return new Handle(this, _supervisor, handles); } public bool Matches(Uri address) { return Settings.ServiceUri.GetLeftPart(UriPartial.Authority).Equals(address.GetLeftPart(UriPartial.Authority), StringComparison.OrdinalIgnoreCase); } public IRetryPolicy RetryPolicy { get; } Task<MessagingFactory> IServiceBusHost.SessionMessagingFactory => _sessionMessagingFactory.Value; void IProbeSite.Probe(ProbeContext context) { var scope = context.CreateScope("host"); scope.Set(new { Type = "Azure Service Bus", Settings.ServiceUri, Settings.OperationTimeout }); _receiveEndpoints.Probe(scope); } public ServiceBusHostSettings Settings { get; } Task<MessagingFactory> IServiceBusHost.MessagingFactory => _messagingFactory.Value; public NamespaceManager NamespaceManager => _namespaceManager.Value; public NamespaceManager RootNamespaceManager => _rootNamespaceManager.Value; public IMessageNameFormatter MessageNameFormatter { get; } public ITaskSupervisor Supervisor => _supervisor; public string GetQueuePath(QueueDescription queueDescription) { IEnumerable<string> segments = new[] {Settings.ServiceUri.AbsolutePath.Trim('/'), queueDescription.Path.Trim('/')} .Where(x => x.Length > 0); return string.Join("/", segments); } public async Task<QueueDescription> CreateQueue(QueueDescription queueDescription) { var create = true; try { queueDescription = await NamespaceManager.GetQueueAsync(queueDescription.Path).ConfigureAwait(false); create = false; } catch (MessagingEntityNotFoundException) { } if (create) { var created = false; try { if (_log.IsDebugEnabled) _log.DebugFormat("Creating queue {0}", queueDescription.Path); queueDescription = await NamespaceManager.CreateQueueAsync(queueDescription).ConfigureAwait(false); created = true; } catch (MessagingEntityAlreadyExistsException) { } catch (MessagingException mex) { if (mex.Message.Contains("(409)")) { } else { throw; } } if (!created) queueDescription = await NamespaceManager.GetQueueAsync(queueDescription.Path).ConfigureAwait(false); } if (_log.IsDebugEnabled) _log.DebugFormat("Queue: {0} ({1})", queueDescription.Path, string.Join(", ", new[] { queueDescription.EnableExpress ? "express" : "", queueDescription.RequiresDuplicateDetection ? "dupe detect" : "", queueDescription.EnableDeadLetteringOnMessageExpiration ? "dead letter" : "", queueDescription.RequiresSession ? "session" : "" }.Where(x => !string.IsNullOrWhiteSpace(x)))); return queueDescription; } public async Task<TopicDescription> CreateTopic(TopicDescription topicDescription) { var create = true; try { topicDescription = await RootNamespaceManager.GetTopicAsync(topicDescription.Path).ConfigureAwait(false); create = false; } catch (MessagingEntityNotFoundException) { } if (create) { var created = false; try { if (_log.IsDebugEnabled) _log.DebugFormat("Creating topic {0}", topicDescription.Path); topicDescription = await RootNamespaceManager.CreateTopicAsync(topicDescription).ConfigureAwait(false); created = true; } catch (MessagingEntityAlreadyExistsException) { } catch (MessagingException mex) { if (mex.Message.Contains("(409)")) { } else { throw; } } if (!created) topicDescription = await RootNamespaceManager.GetTopicAsync(topicDescription.Path).ConfigureAwait(false); } if (_log.IsDebugEnabled) _log.DebugFormat("Topic: {0} ({1})", topicDescription.Path, string.Join(", ", new[] { topicDescription.EnableExpress ? "express" : "", topicDescription.RequiresDuplicateDetection ? "dupe detect" : "" }.Where(x => !string.IsNullOrWhiteSpace(x)))); return topicDescription; } public async Task<SubscriptionDescription> CreateTopicSubscription(SubscriptionDescription description) { var create = true; SubscriptionDescription subscriptionDescription = null; try { subscriptionDescription = await RootNamespaceManager.GetSubscriptionAsync(description.TopicPath, description.Name).ConfigureAwait(false); if (string.IsNullOrWhiteSpace(description.ForwardTo)) { if (!string.IsNullOrWhiteSpace(subscriptionDescription.ForwardTo)) { if (_log.IsWarnEnabled) _log.WarnFormat("Removing invalid subscription: {0} ({1} -> {2})", subscriptionDescription.Name, subscriptionDescription.TopicPath, subscriptionDescription.ForwardTo); await RootNamespaceManager.DeleteSubscriptionAsync(description.TopicPath, description.Name).ConfigureAwait(false); } } else { if (description.ForwardTo.Equals(subscriptionDescription.ForwardTo)) { if (_log.IsDebugEnabled) _log.DebugFormat("Updating subscription: {0} ({1} -> {2})", subscriptionDescription.Name, subscriptionDescription.TopicPath, subscriptionDescription.ForwardTo); await RootNamespaceManager.UpdateSubscriptionAsync(description).ConfigureAwait(false); create = false; } else { if (_log.IsWarnEnabled) _log.WarnFormat("Removing invalid subscription: {0} ({1} -> {2})", subscriptionDescription.Name, subscriptionDescription.TopicPath, subscriptionDescription.ForwardTo); await RootNamespaceManager.DeleteSubscriptionAsync(description.TopicPath, description.Name).ConfigureAwait(false); } } } catch (MessagingEntityNotFoundException) { } if (create) { var created = false; try { if (_log.IsDebugEnabled) _log.DebugFormat("Creating subscription {0} -> {1}", description.TopicPath, description.ForwardTo); subscriptionDescription = await RootNamespaceManager.CreateSubscriptionAsync(description).ConfigureAwait(false); created = true; } catch (MessagingEntityAlreadyExistsException) { } catch (MessagingException mex) { if (mex.Message.Contains("(409)")) { } else { throw; } } if (!created) subscriptionDescription = await RootNamespaceManager.GetSubscriptionAsync(description.TopicPath, description.Name).ConfigureAwait(false); } if (_log.IsDebugEnabled) _log.DebugFormat("Subscription: {0} ({1} -> {2})", subscriptionDescription.Name, subscriptionDescription.TopicPath, subscriptionDescription.ForwardTo); return subscriptionDescription; } public async Task DeleteTopicSubscription(SubscriptionDescription description) { try { await RootNamespaceManager.DeleteSubscriptionAsync(description.TopicPath, description.Name).ConfigureAwait(false); } catch (MessagingEntityNotFoundException) { } if (_log.IsDebugEnabled) _log.DebugFormat("Subscription Deleted: {0} ({1} -> {2})", description.Name, description.TopicPath, description.ForwardTo); } public HostReceiveEndpointHandle ConnectReceiveEndpoint(Action<IServiceBusReceiveEndpointConfigurator> configure = null) { var queueName = this.GetTemporaryQueueName("endpoint"); return ConnectReceiveEndpoint(queueName, configure); } public HostReceiveEndpointHandle ConnectReceiveEndpoint(string queueName, Action<IServiceBusReceiveEndpointConfigurator> configure = null) { if (ReceiveEndpointFactory == null) throw new ConfigurationException("The receive endpoint factory was not specified"); ReceiveEndpointFactory.CreateReceiveEndpoint(queueName, configure); return _receiveEndpoints.Start(queueName); } public HostReceiveEndpointHandle ConnectSubscriptionEndpoint<T>(string subscriptionName, Action<IServiceBusSubscriptionEndpointConfigurator> configure = null) where T : class { return ConnectSubscriptionEndpoint(subscriptionName, MessageNameFormatter.GetTopicAddress(this, typeof(T)).AbsolutePath.Trim('/'), configure); } public HostReceiveEndpointHandle ConnectSubscriptionEndpoint(string subscriptionName, string topicName, Action<IServiceBusSubscriptionEndpointConfigurator> configure = null) { if (SubscriptionEndpointFactory == null) throw new ConfigurationException("The subscription endpoint factory was not specified"); var settings = new SubscriptionEndpointSettings(topicName, subscriptionName); SubscriptionEndpointFactory.CreateSubscriptionEndpoint(settings, configure); return _receiveEndpoints.Start(settings.Path); } public Uri Address => Settings.ServiceUri; ConnectHandle IConsumeMessageObserverConnector.ConnectConsumeMessageObserver<T>(IConsumeMessageObserver<T> observer) { return _receiveEndpoints.ConnectConsumeMessageObserver(observer); } ConnectHandle IConsumeObserverConnector.ConnectConsumeObserver(IConsumeObserver observer) { return _receiveEndpoints.ConnectConsumeObserver(observer); } ConnectHandle IReceiveObserverConnector.ConnectReceiveObserver(IReceiveObserver observer) { return _receiveEndpoints.ConnectReceiveObserver(observer); } ConnectHandle IReceiveEndpointObserverConnector.ConnectReceiveEndpointObserver(IReceiveEndpointObserver observer) { return _receiveEndpoints.ConnectReceiveEndpointObserver(observer); } ConnectHandle IPublishObserverConnector.ConnectPublishObserver(IPublishObserver observer) { return _receiveEndpoints.ConnectPublishObserver(observer); } ConnectHandle ISendObserverConnector.ConnectSendObserver(ISendObserver observer) { return _receiveEndpoints.ConnectSendObserver(observer); } Task<MessagingFactory> CreateMessagingFactory() { var mfs = new MessagingFactorySettings { TokenProvider = Settings.TokenProvider, OperationTimeout = Settings.OperationTimeout, TransportType = Settings.TransportType }; switch (Settings.TransportType) { case TransportType.NetMessaging: mfs.NetMessagingTransportSettings = Settings.NetMessagingTransportSettings; break; case TransportType.Amqp: mfs.AmqpTransportSettings = Settings.AmqpTransportSettings; break; default: throw new ArgumentOutOfRangeException(); } return CreateFactory(mfs); } async Task<MessagingFactory> CreateFactory(MessagingFactorySettings mfs) { var builder = new UriBuilder(Settings.ServiceUri) {Path = ""}; var messagingFactory = await MessagingFactory.CreateAsync(builder.Uri, mfs).ConfigureAwait(false); messagingFactory.RetryPolicy = new RetryExponential(Settings.RetryMinBackoff, Settings.RetryMaxBackoff, Settings.RetryLimit); return messagingFactory; } Task<MessagingFactory> CreateNetMessagingFactory() { if (Settings.TransportType == TransportType.NetMessaging) return _messagingFactory.Value; var mfs = new MessagingFactorySettings { TokenProvider = Settings.TokenProvider, OperationTimeout = Settings.OperationTimeout, TransportType = TransportType.NetMessaging, NetMessagingTransportSettings = Settings.NetMessagingTransportSettings }; return CreateFactory(mfs); } NamespaceManager CreateNamespaceManager() { var nms = new NamespaceManagerSettings { TokenProvider = Settings.TokenProvider, OperationTimeout = Settings.OperationTimeout }; return new NamespaceManager(Settings.ServiceUri, nms); } NamespaceManager CreateRootNamespaceManager() { var nms = new NamespaceManagerSettings { TokenProvider = Settings.TokenProvider, OperationTimeout = Settings.OperationTimeout }; var builder = new UriBuilder(Settings.ServiceUri) { Path = "" }; return new NamespaceManager(builder.Uri, nms); } class Handle : BaseHostHandle { readonly ServiceBusHost _host; readonly TaskSupervisor _supervisor; public Handle(ServiceBusHost host, TaskSupervisor supervisor, HostReceiveEndpointHandle[] handles) : base(host, handles) { _host = host; _supervisor = supervisor; } public override async Task Stop(CancellationToken cancellationToken) { await base.Stop(cancellationToken).ConfigureAwait(false); try { await _supervisor.Stop("Host stopped", cancellationToken).ConfigureAwait(false); if (_host._messagingFactory.IsValueCreated) { var factory = await _host._messagingFactory.Value.ConfigureAwait(false); if (!factory.IsClosed) await factory.CloseAsync().ConfigureAwait(false); } } catch (Exception ex) { if (_log.IsWarnEnabled) _log.Warn("Exception closing messaging factory", ex); } if (_host._sessionMessagingFactory.IsValueCreated && _host.Settings.TransportType == TransportType.Amqp) try { var factory = await _host._sessionMessagingFactory.Value.ConfigureAwait(false); if (!factory.IsClosed) await factory.CloseAsync().ConfigureAwait(false); } catch (Exception ex) { if (_log.IsWarnEnabled) _log.Warn("Exception closing messaging factory", ex); } } } } }
// // CellRendererTextProgress.cs // // Author: // Stephane Delcroix <stephane@delcroix.org> // Ruben Vermeersch <ruben@savanne.be> // // Copyright (C) 2009-2010 Novell, Inc. // Copyright (C) 2009 Stephane Delcroix // Copyright (C) 2010 Ruben Vermeersch // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Gtk; namespace FSpot.Widgets { /* * Because subclassing of CellRendererText does not to work, we * use a new cellrenderer, which renderes a simple text and a * progress bar below the text similar to the one used in baobab (gnome-utils) */ public class CellRendererTextProgress : CellRenderer { readonly int progress_width; readonly int progress_height; static Gdk.Color green = new Gdk.Color (0xcc, 0x00, 0x00); static Gdk.Color yellow = new Gdk.Color (0xed, 0xd4, 0x00); static Gdk.Color red = new Gdk.Color (0x73, 0xd2, 0x16); public CellRendererTextProgress () : this (70, 8) { } public CellRendererTextProgress (int progress_width, int progress_height) { this.progress_width = progress_width; this.progress_height = progress_height; Xalign = 0.0f; Yalign = 0.5f; Xpad = Ypad = 2; } protected CellRendererTextProgress (IntPtr ptr) : base (ptr) { } int progress_value; [GLib.PropertyAttribute ("value")] public int Value { get { return progress_value; } set { /* normalize value */ progress_value = Math.Max (Math.Min (value, 100), 0); } } Pango.Layout text_layout; string text; [GLib.PropertyAttribute ("text")] public string Text { get { return text; } set { if (text == value) return; text = value; text_layout = null; } } bool use_markup; public bool UseMarkup { get { return use_markup; } set { if (use_markup == value) return; use_markup = value; text_layout = null; } } void UpdateLayout (Widget widget) { text_layout = new Pango.Layout (widget.PangoContext); if (UseMarkup) text_layout.SetMarkup (text); else text_layout.SetText (text); } Gdk.Color GetValueColor () { if (progress_value <= 33) return green; if (progress_value <= 66) return yellow; return red; } public override void GetSize (Gtk.Widget widget, ref Gdk.Rectangle cell_area, out int x_offset, out int y_offset, out int width, out int height) { if (text_layout == null) UpdateLayout (widget); int text_width, text_height; text_layout.GetPixelSize (out text_width, out text_height); width = (int) (2 * Xpad + Math.Max (progress_width, text_width)); height = (int) (3 * Ypad + progress_height + text_height); x_offset = Math.Max ((int) (Xalign * (cell_area.Width - width)), 0); y_offset = Math.Max ((int) (Yalign * (cell_area.Height - height)), 0); } protected override void Render (Gdk.Drawable window, Gtk.Widget widget, Gdk.Rectangle background_area, Gdk.Rectangle cell_area, Gdk.Rectangle expose_area, Gtk.CellRendererState flags) { base.Render (window, widget, background_area, cell_area, expose_area, flags); if (text_layout == null) UpdateLayout (widget); int x, y, width, height, text_width, text_height; /* first render the text */ text_layout.GetPixelSize (out text_width, out text_height); x = (int) (cell_area.X + Xpad + Math.Max ((int) (Xalign * (cell_area.Width - 2 * Xpad - text_width)), 0)); y = (int) (cell_area.Y + Ypad); Style.PaintLayout (widget.Style, window, StateType.Normal, true, cell_area, widget, "cellrenderertextprogress", x, y, text_layout); y += (int) (text_height + Ypad); x = (int) (cell_area.X + Xpad + Math.Max ((int) (Xalign * (cell_area.Width - 2 * Xpad - progress_width)), 0)); /* second render the progress bar */ using (Cairo.Context cairo_context = Gdk.CairoHelper.Create (window)) { width = progress_width; height = progress_height; cairo_context.Rectangle (x, y, width, height); Gdk.CairoHelper.SetSourceColor (cairo_context, widget.Style.Dark (StateType.Normal)); cairo_context.Fill (); x += widget.Style.XThickness; y += widget.Style.XThickness; width -= 2* widget.Style.XThickness; height -= 2 * widget.Style.Ythickness; cairo_context.Rectangle (x, y, width, height); Gdk.CairoHelper.SetSourceColor (cairo_context, widget.Style.Light (StateType.Normal)); cairo_context.Fill (); /* scale the value and ensure, that at least one pixel is drawn, if the value is greater than zero */ int scaled_width = (int) Math.Max (((progress_value * width) / 100.0), (progress_value == 0)? 0 : 1); cairo_context.Rectangle (x, y, scaled_width, height); Gdk.CairoHelper.SetSourceColor (cairo_context, GetValueColor ()); cairo_context.Fill (); } } } }
// Copyright (C) 2012-2017 Luca Piccioni // // 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.Diagnostics; using Khronos; // ReSharper disable RedundantIfElseBlock // ReSharper disable SwitchStatementMissingSomeCases // ReSharper disable InheritdocConsiderUsage namespace OpenGL { /// <inheritdoc /> /// <summary> /// Abstract device context. /// </summary> public abstract class DeviceContext : IDisposable { #region Constructors /// <summary> /// Static constructor. /// </summary> static DeviceContext() { // The default API is GLES2 in the case Egl.IsRequired is initialized to true if (Egl.IsRequired) _DefaultAPI = KhronosVersion.ApiGles2; // Required for correct static initialization sequences Gl.Initialize(); } #endregion #region Factory /// <summary> /// Create a native window. /// </summary> /// <returns> /// It returns a <see cref="INativeWindow"/> that implements a native window on the underlying platform. /// </returns> /// <exception cref='NotSupportedException'> /// Exception thrown if the current platform is not supported. /// </exception> internal static INativeWindow CreateHiddenWindow() { #if !MONODROID if (Egl.IsRequired == false) { switch (Platform.CurrentPlatformId) { case Platform.Id.WindowsNT: return new DeviceContextWGL.NativeWindow(); case Platform.Id.Linux: return new DeviceContextGLX.NativeWindow(); case Platform.Id.MacOS: if (Glx.IsRequired) return new DeviceContextGLX.NativeWindow(); else throw new NotSupportedException("platform MacOS not supported without Glx.IsRequired=true"); default: throw new NotSupportedException($"platform {Platform.CurrentPlatformId} not supported"); } } else { Debug.Assert(DeviceContextEGL.IsPBufferSupported); return new DeviceContextEGL.NativePBuffer(new DevicePixelFormat(24), 1, 1); } #else Debug.Assert(DeviceContextEGL.IsPBufferSupported); return new DeviceContextEGL.NativePBuffer(new DevicePixelFormat(24), 1, 1); #endif } /// <summary> /// Determine whether the hosting platform is able to create a P-Buffer. /// </summary> public static bool IsPBufferSupported { get { #if !MONODROID if (Egl.IsRequired == false) { switch (Platform.CurrentPlatformId) { case Platform.Id.WindowsNT: return DeviceContextWGL.IsPBufferSupported; default: return false; } } else #endif return DeviceContextEGL.IsPBufferSupported; } } /// <summary> /// Create an off-screen buffer. /// </summary> /// <returns> /// It returns a <see cref="INativePBuffer"/> that implements a native P-Buffer on the underlying platform. /// </returns> /// <exception cref='NotSupportedException'> /// Exception thrown if the current platform is not supported. /// </exception> public static INativePBuffer CreatePBuffer(DevicePixelFormat pixelFormat, uint width, uint height) { #if !MONODROID if (Egl.IsRequired == false) { switch (Platform.CurrentPlatformId) { case Platform.Id.WindowsNT: return new DeviceContextWGL.NativePBuffer(pixelFormat, width, height); default: throw new NotSupportedException($"platform {Platform.CurrentPlatformId} not supported"); } } else #endif return new DeviceContextEGL.NativePBuffer(pixelFormat, width, height); } /// <summary> /// Create a device context without a specific window. /// </summary> /// <exception cref='NotSupportedException'> /// Exception thrown if the current platform is not supported. /// </exception> public static DeviceContext Create() { #if !MONODROID if (IsEglRequired == false) { // OPENGL_NET_INIT environment set to NO? if (Gl.NativeWindow == null) throw new InvalidOperationException("OpenGL.Net not initialized", Gl.InitializationException); switch (Platform.CurrentPlatformId) { case Platform.Id.WindowsNT: return new DeviceContextWGL(); case Platform.Id.Linux: return new DeviceContextGLX(); case Platform.Id.MacOS: if (Glx.IsRequired) return new DeviceContextGLX(); else throw new NotSupportedException("platform MacOS not supported without Glx.IsRequired=true"); default: throw new NotSupportedException($"platform {Platform.CurrentPlatformId} not supported"); } } else { #endif // Create a surfaceless context if (Egl.CurrentExtensions == null || Egl.CurrentExtensions.SurfacelessContext_KHR == false) { // OPENGL_NET_INIT environment set to NO? if (Gl.NativeWindow == null) throw new InvalidOperationException("OpenGL.Net not initialized", Gl.InitializationException); INativePBuffer nativeBuffer = Gl.NativeWindow as INativePBuffer; if (nativeBuffer != null) return new DeviceContextEGL(nativeBuffer); INativeWindow nativeWindow = Gl.NativeWindow; if (nativeWindow != null) return new DeviceContextEGL(nativeWindow.Handle); throw new NotSupportedException("EGL surface not supported"); } else return new DeviceContextEGL(IntPtr.Zero); #if !MONODROID } #endif } /// <summary> /// Create a device context on the specified window. /// </summary> /// <param name="display"> /// A <see cref="IntPtr"/> that specifies the display handle associated to <paramref name="windowHandle"/>. Some platforms /// ignore this parameter (i.e. Windows or EGL implementation). /// </param> /// <param name='windowHandle'> /// A <see cref="IntPtr"/> that specifies the window handle used to create the device context. /// </param> /// <exception cref='ArgumentException'> /// Is thrown when <paramref name="windowHandle"/> is <see cref="IntPtr.Zero"/>. /// </exception> /// <exception cref='NotSupportedException'> /// Exception thrown if the current platform is not supported. /// </exception> public static DeviceContext Create(IntPtr display, IntPtr windowHandle) { #if !MONODROID if (IsEglRequired == false) { switch (Platform.CurrentPlatformId) { case Platform.Id.WindowsNT: return new DeviceContextWGL(windowHandle); case Platform.Id.Linux: return new DeviceContextGLX(display, windowHandle); case Platform.Id.MacOS: if (Glx.IsRequired) return new DeviceContextGLX(display, windowHandle); else throw new NotSupportedException("platform MacOS not supported without Glx.IsRequired=true"); default: throw new NotSupportedException($"platform {Platform.CurrentPlatformId} not supported"); } } else #endif return new DeviceContextEGL(display, windowHandle); } /// <summary> /// Create a device context on the specified P-Buffer. /// </summary> /// <param name="nativeBuffer"> /// A <see cref="INativePBuffer"/> created with <see cref="CreatePBuffer(DevicePixelFormat, uint, uint)"/> which /// the created context shall be able to render on. /// </param> /// <exception cref='NotSupportedException'> /// Exception thrown if the current platform is not supported. /// </exception> public static DeviceContext Create(INativePBuffer nativeBuffer) { #if !MONODROID if (IsEglRequired == false) { switch (Platform.CurrentPlatformId) { case Platform.Id.WindowsNT: return new DeviceContextWGL(nativeBuffer); default: throw new NotSupportedException($"platform {Platform.CurrentPlatformId} not supported"); } } else #endif return new DeviceContextEGL(nativeBuffer); } /// <summary> /// Get whether EGL device context is is required for implementing <see cref="DefaultAPI"/>. /// </summary> private static bool IsEglRequired { get { #if !MONODROID // Default API management // - Select eglRequired if EGL is the only device API available // - Select eglRequired if desktop device does not support ES context creation // - Select eglRequired if VG context creation bool eglRequired = Egl.IsRequired; if (eglRequired) return true; switch (_DefaultAPI) { case KhronosVersion.ApiGl: // Leave EGL requirement to the system (i.e. ANDROID or Broadcom) break; case KhronosVersion.ApiGles1: case KhronosVersion.ApiGles2: string[] desktopAvailableApi; switch (Platform.CurrentPlatformId) { case Platform.Id.WindowsNT: desktopAvailableApi = DeviceContextWGL.GetAvailableApis(); break; case Platform.Id.Linux: desktopAvailableApi = DeviceContextGLX.GetAvailableApis(); break; case Platform.Id.MacOS: if (Glx.IsRequired) desktopAvailableApi = DeviceContextGLX.GetAvailableApis(); else throw new NotSupportedException("platform MacOS not supported without Glx.IsRequired=true"); break; default: throw new NotSupportedException($"platform {Platform.CurrentPlatformId} not supported"); } Debug.Assert(desktopAvailableApi != null); if (Array.FindIndex(desktopAvailableApi, item => item == _DefaultAPI) < 0) eglRequired = true; break; case KhronosVersion.ApiVg: // EGL is the only way to access to VG eglRequired = true; break; } return eglRequired; #else return true; #endif } } #endregion #region Referenceable Instance /// <summary> /// Number of shared instances of this IRenderResource. /// </summary> /// <remarks> /// The reference count shall be initially 0 on new instances. /// </remarks> public uint RefCount { get; private set; } /// <summary> /// Increment the shared IRenderResource reference count. /// </summary> /// <remarks> /// Incrementing the reference count for this resource prevents the system to dispose this instance. /// </remarks> public void IncRef() { RefCount++; } /// <summary> /// Decrement the shared IResource reference count. /// </summary> /// <remarks> /// Decrementing the reference count for this resource could cause this instance disposition. In the case /// the reference count equals 0 (with or without decrementing it), this instance will be disposed. /// </remarks> public void DecRef() { // Instance could be never referenced with IncRef if (RefCount > 0) RefCount--; // Automatically dispose when no references are available if (RefCount == 0) Dispose(); } /// <summary> /// Reset the reference count of this instance. /// </summary> /// <remarks> /// <para> /// This should be used in normal code. /// </para> /// <para> /// This routine could be useful in the case the deep-copoy implementation uses <see cref="Object.MemberwiseClone"/>, /// indeed copying the reference count. /// </para> /// </remarks> protected void ResetRefCount() { RefCount = 0; } #endregion #region Default API /// <summary> /// Get or set the default API, driving device context creation using <see cref="Create"/>, /// <see cref="Create(IntPtr, IntPtr)"/> or <see cref="Create(INativePBuffer)"/>. /// </summary> public static string DefaultAPI { get { return _DefaultAPI; } set { switch (value) { case KhronosVersion.ApiGl: case KhronosVersion.ApiGles1: case KhronosVersion.ApiGles2: case KhronosVersion.ApiGlsc2: case KhronosVersion.ApiVg: // Allowed values break; default: throw new InvalidOperationException("unsupported API"); } _DefaultAPI = value; } } /// <summary> /// The default API driving device context creation. /// </summary> private static string _DefaultAPI = KhronosVersion.ApiGl; /// <summary> /// Get or set the current API driving device context creation. /// </summary> public string CurrentAPI { get; protected set; } = _DefaultAPI; #endregion #region Platform Methods /// <summary> /// Get this DeviceContext API version. /// </summary> public abstract KhronosVersion Version { get; } /// <summary> /// Create a simple context. /// </summary> /// <returns> /// A <see cref="IntPtr"/> that represents the handle of the created context. If the context cannot be /// created, it returns IntPtr.Zero. /// </returns> internal abstract IntPtr CreateSimpleContext(); /// <summary> /// Get the APIs available on this host. /// </summary> /// <returns> /// It returns the list of the APIs available on the current host. /// </returns> public static IEnumerable<string> GetAvailableAPIs() { List<string> availableAPIs = new List<string>(); // Uses the default device using (DeviceContext deviceContext = Create()) { availableAPIs.AddRange(deviceContext.AvailableAPIs); } #if INTEGRATES_EGL // Consider EGL availability if (!Egl.IsRequired && Egl.IsAvailable) { // Integrates EGL device context APIss Egl.IsRequired = true; try { if (Egl.IsRequired == true) { using (DeviceContext deviceContext = DeviceContext.Create()) { foreach (string availableAPI in deviceContext.AvailableAPIs) if (!availableAPIs.Contains(availableAPI)) availableAPIs.Add(availableAPI); } } } finally { Egl.IsRequired = false; } } else { } #endif return availableAPIs; } /// <summary> /// Get the APIs available on this device context. The API tokens are space separated, and they can be /// found in <see cref="KhronosVersion"/> definition. The returned value can be null; in this case only /// the explicit API is implemented. /// </summary> public virtual IEnumerable<string> AvailableAPIs { get { throw new NotImplementedException(); } } /// <summary> /// Creates a compatible context. /// </summary> /// <param name="sharedContext"> /// A <see cref="IntPtr"/> that specify a context that will share objects with the returned one. If /// it is IntPtr.Zero, no sharing is performed. /// </param> /// <returns> /// A <see cref="IntPtr"/> that represents the handle of the created context. If the context cannot be /// created, it returns IntPtr.Zero. /// </returns> /// <exception cref="InvalidOperationException"> /// Exception thrown in the case <paramref name="sharedContext"/> is different from IntPtr.Zero, and the objects /// cannot be shared with it. /// </exception>> public abstract IntPtr CreateContext(IntPtr sharedContext); /// <summary> /// Creates a context, specifying attributes, using the default API (see <see cref="DefaultAPI"/>). /// </summary> /// <param name="sharedContext"> /// A <see cref="IntPtr"/> that specify a context that will share objects with the returned one. If /// it is IntPtr.Zero, no sharing is performed. /// </param> /// <param name="attribsList"> /// A <see cref="T:Int32[]"/> that specifies the attributes list. The attribute list is dependent on the actual /// platform and the GL version and extension support. /// </param> /// <returns> /// A <see cref="IntPtr"/> that represents the handle of the created context. If the context cannot be /// created, it returns IntPtr.Zero. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if <paramref name="attribsList"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// Exception thrown if <paramref name="attribsList"/> length is zero or if the last item of <paramref name="attribsList"/> /// is not zero. /// </exception> public abstract IntPtr CreateContextAttrib(IntPtr sharedContext, int[] attribsList); /// <summary> /// Creates a context, specifying attributes. /// </summary> /// <param name="sharedContext"> /// A <see cref="IntPtr"/> that specify a context that will share objects with the returned one. If /// it is IntPtr.Zero, no sharing is performed. /// </param> /// <param name="attribsList"> /// A <see cref="T:Int32[]"/> that specifies the attributes list. The attribute list is dependent on the actual /// platform and the GL version and extension support. /// </param> /// <param name="api"> /// A <see cref="KhronosVersion"/> that specifies the API to be implemented by the returned context. It can be null indicating the /// default API for this DeviceContext implementation. If it is possible, try to determine the API version also. /// </param> /// <returns> /// A <see cref="IntPtr"/> that represents the handle of the created context. If the context cannot be /// created, it returns IntPtr.Zero. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if <see cref="attribsList"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// Exception thrown if <paramref name="attribsList"/> length is zero or if the last item of <paramref name="attribsList"/> /// is not zero. /// </exception> public abstract IntPtr CreateContextAttrib(IntPtr sharedContext, int[] attribsList, KhronosVersion api); /// <summary> /// Makes the context current on the calling thread. /// </summary> /// <param name="ctx"> /// A <see cref="IntPtr"/> that specify the context to be current on the calling thread, bound to /// thise device context. It can be IntPtr.Zero indicating that no context will be current. /// </param> /// <returns> /// It returns a boolean value indicating whether the operation was successful. /// </returns> /// <exception cref="NotSupportedException"> /// Exception thrown if the current platform is not supported. /// </exception> public virtual bool MakeCurrent(IntPtr ctx) { // Basic implementation bool current = MakeCurrentCore(ctx); // Link OpenGL procedures on Gl if (ctx == IntPtr.Zero || current != true) return current; switch (DefaultAPI) { case KhronosVersion.ApiGlsc2: // Special OpenGL SC2 management: loads only SC2 requirements // Note: in order to work, DefaultAPI should stay set to SC2! Otherwise user shall call BindAPI manually Gl.BindAPI(Gl.Version_200_SC, null); break; default: Gl.BindAPI(); break; } return true; } /// <summary> /// Makes the context current on the calling thread. /// </summary> /// <param name="ctx"> /// A <see cref="IntPtr"/> that specify the context to be current on the calling thread, bound to /// thise device context. It can be IntPtr.Zero indicating that no context will be current. /// </param> /// <returns> /// It returns a boolean value indicating whether the operation was successful. /// </returns> /// <exception cref="NotSupportedException"> /// Exception thrown if the current platform is not supported. /// </exception> protected abstract bool MakeCurrentCore(IntPtr ctx); /// <summary> /// Deletes a context. /// </summary> /// <param name="ctx"> /// A <see cref="IntPtr"/> that specify the context to be deleted. /// </param> /// <returns> /// It returns a boolean value indicating whether the operation was successful. If it returns false, /// query the exception by calling <see cref="GetPlatformException"/>. /// </returns> /// <remarks> /// <para>The context <paramref name="ctx"/> must not be current on any thread.</para> /// </remarks> /// <exception cref="ArgumentException"> /// Exception thrown if <paramref name="ctx"/> is IntPtr.Zero. /// </exception> public abstract bool DeleteContext(IntPtr ctx); /// <summary> /// Swap the buffers of a device. /// </summary> public abstract void SwapBuffers(); /// <summary> /// Control the the buffers swap of a device. /// </summary> /// <param name="interval"> /// A <see cref="Int32"/> that specifies the minimum number of video frames that are displayed /// before a buffer swap will occur. /// </param> /// <returns> /// It returns a boolean value indicating whether the operation was successful. /// </returns> public abstract bool SwapInterval(int interval); /// <summary> /// Query platform extensions available. /// </summary> internal abstract void QueryPlatformExtensions(); /// <summary> /// Gets the platform exception relative to the last operation performed. /// </summary> /// <returns> /// The platform exception relative to the last operation performed. /// </returns> /// <exception cref="NotSupportedException"> /// Exception thrown if the current platform is not supported. /// </exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Interoperability", "CA1404:CallGetLastErrorImmediatelyAfterPInvoke")] public abstract Exception GetPlatformException(); /// <summary> /// Get the pixel formats supported by this device. /// </summary> public abstract DevicePixelFormatCollection PixelsFormats { get; } /// <summary> /// Set the device pixel format. /// </summary> /// <param name="pixelFormat"> /// A <see cref="DevicePixelFormat"/> that specifies the pixel format to set. /// </param> public abstract void ChoosePixelFormat(DevicePixelFormat pixelFormat); /// <summary> /// Set the device pixel format. /// </summary> /// <param name="pixelFormat"> /// A <see cref="DevicePixelFormat"/> that specifies the pixel format to set. /// </param> public abstract void SetPixelFormat(DevicePixelFormat pixelFormat); /// <summary> /// Get the flag indicating whether this DeviceContext has a pixel format defined. /// </summary> public bool IsPixelFormatSet { get; protected set; } #endregion #region Get Current Context /// <summary> /// Get the OpenGL context current on the calling thread. /// </summary> /// <returns> /// It returns the handle of the OpenGL context current on the calling thread. It may return <see cref="IntPtr.Zero"/> /// indicating that no OpenGL context is current. /// </returns> public static IntPtr GetCurrentContext() { #if !MONODROID if (Egl.IsRequired == false) { switch (Platform.CurrentPlatformId) { case Platform.Id.WindowsNT: return Wgl.GetCurrentContext(); case Platform.Id.Linux: return Glx.GetCurrentContext(); case Platform.Id.MacOS: if (Glx.IsRequired) return Glx.GetCurrentContext(); else throw new NotSupportedException("platform MacOS not supported without Glx.IsRequired=true"); default: throw new NotSupportedException($"platform {Platform.CurrentPlatformId} not supported"); } } else #endif return Egl.GetCurrentContext(); } #endregion #region IDisposable Implementation /// <summary> /// Finalizer. /// </summary> ~DeviceContext() { Dispose(false); } /// <summary> /// Get whether this instance has been disposed. /// </summary> public bool IsDisposed { get; private set; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting managed/unmanaged resources. /// </summary> /// <param name="disposing"> /// A <see cref="System.Boolean"/> indicating whether the disposition is requested explictly. /// </param> protected virtual void Dispose(bool disposing) { if (!disposing) return; // Mark as disposed IsDisposed = true; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #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 log4net; using OpenMetaverse; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Server.Base; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Xml; namespace OpenSim.Region.CoreModules.World.Estate { public class EstateRequestHandler : BaseStreamHandler { protected XEstateModule m_EstateModule; protected Object m_RequestLock = new Object(); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public EstateRequestHandler(XEstateModule fmodule) : base("POST", "/estate") { m_EstateModule = fmodule; } protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); m_log.DebugFormat("[XESTATE HANDLER]: query String: {0}", body); try { lock (m_RequestLock) { Dictionary<string, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) return FailureResult(); string method = request["METHOD"].ToString(); request.Remove("METHOD"); try { m_EstateModule.InInfoUpdate = false; switch (method) { case "update_covenant": return UpdateCovenant(request); case "update_estate": return UpdateEstate(request); case "estate_message": return EstateMessage(request); case "teleport_home_one_user": return TeleportHomeOneUser(request); case "teleport_home_all_users": return TeleportHomeAllUsers(request); } } finally { m_EstateModule.InInfoUpdate = false; } } } catch (Exception e) { m_log.Debug("[XESTATE]: Exception {0}" + e.ToString()); } return FailureResult(); } private byte[] BoolResult(bool value) { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "RESULT", ""); result.AppendChild(doc.CreateTextNode(value.ToString())); rootElement.AppendChild(result); return DocToBytes(doc); } private byte[] DocToBytes(XmlDocument doc) { MemoryStream ms = new MemoryStream(); XmlTextWriter xw = new XmlTextWriter(ms, null); xw.Formatting = Formatting.Indented; doc.WriteTo(xw); xw.Flush(); return ms.ToArray(); } private byte[] EstateMessage(Dictionary<string, object> request) { UUID FromID = UUID.Zero; string FromName = String.Empty; string Message = String.Empty; int EstateID = 0; if (!request.ContainsKey("FromID") || !request.ContainsKey("FromName") || !request.ContainsKey("Message") || !request.ContainsKey("EstateID")) { return FailureResult(); } if (!UUID.TryParse(request["FromID"].ToString(), out FromID)) return FailureResult(); if (!Int32.TryParse(request["EstateID"].ToString(), out EstateID)) return FailureResult(); FromName = request["FromName"].ToString(); Message = request["Message"].ToString(); foreach (Scene s in m_EstateModule.Scenes) { if (s.RegionInfo.EstateSettings.EstateID == EstateID) { IDialogModule dm = s.RequestModuleInterface<IDialogModule>(); if (dm != null) { dm.SendNotificationToUsersInRegion(FromID, FromName, Message); } } } return SuccessResult(); } private byte[] FailureResult() { return BoolResult(false); } private byte[] SuccessResult() { return BoolResult(true); } private byte[] TeleportHomeAllUsers(Dictionary<string, object> request) { UUID PreyID = UUID.Zero; int EstateID = 0; if (!request.ContainsKey("EstateID")) return FailureResult(); if (!Int32.TryParse(request["EstateID"].ToString(), out EstateID)) return FailureResult(); foreach (Scene s in m_EstateModule.Scenes) { if (s.RegionInfo.EstateSettings.EstateID == EstateID) { s.ForEachScenePresence(delegate(ScenePresence p) { if (p != null && !p.IsChildAgent) { p.ControllingClient.SendTeleportStart(16); s.TeleportClientHome(p.ControllingClient.AgentId, p.ControllingClient); } }); } } return SuccessResult(); } private byte[] TeleportHomeOneUser(Dictionary<string, object> request) { UUID PreyID = UUID.Zero; int EstateID = 0; if (!request.ContainsKey("PreyID") || !request.ContainsKey("EstateID")) { return FailureResult(); } if (!UUID.TryParse(request["PreyID"].ToString(), out PreyID)) return FailureResult(); if (!Int32.TryParse(request["EstateID"].ToString(), out EstateID)) return FailureResult(); foreach (Scene s in m_EstateModule.Scenes) { if (s.RegionInfo.EstateSettings.EstateID == EstateID) { ScenePresence p = s.GetScenePresence(PreyID); if (p != null && !p.IsChildAgent) { p.ControllingClient.SendTeleportStart(16); s.TeleportClientHome(PreyID, p.ControllingClient); } } } return SuccessResult(); } private byte[] UpdateCovenant(Dictionary<string, object> request) { UUID CovenantID = UUID.Zero; int EstateID = 0; if (!request.ContainsKey("CovenantID") || !request.ContainsKey("EstateID")) return FailureResult(); if (!UUID.TryParse(request["CovenantID"].ToString(), out CovenantID)) return FailureResult(); if (!Int32.TryParse(request["EstateID"].ToString(), out EstateID)) return FailureResult(); foreach (Scene s in m_EstateModule.Scenes) { if (s.RegionInfo.EstateSettings.EstateID == (uint)EstateID) s.RegionInfo.RegionSettings.Covenant = CovenantID; } return SuccessResult(); } private byte[] UpdateEstate(Dictionary<string, object> request) { int EstateID = 0; if (!request.ContainsKey("EstateID")) return FailureResult(); if (!Int32.TryParse(request["EstateID"].ToString(), out EstateID)) return FailureResult(); foreach (Scene s in m_EstateModule.Scenes) { if (s.RegionInfo.EstateSettings.EstateID == (uint)EstateID) s.ReloadEstateData(); } return SuccessResult(); } } }
// Copyright (C) 2014 dot42 // // Original filename: Android.Telephony.Gsm.cs // // 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. #pragma warning disable 1717 namespace Android.Telephony.Gsm { /// <java-name> /// android/telephony/gsm/SmsManager /// </java-name> [Dot42.DexImport("android/telephony/gsm/SmsManager", AccessFlags = 49)] public sealed partial class SmsManager /* scope: __dot42__ */ { /// <java-name> /// STATUS_ON_SIM_FREE /// </java-name> [Dot42.DexImport("STATUS_ON_SIM_FREE", "I", AccessFlags = 25)] public const int STATUS_ON_SIM_FREE = 0; /// <java-name> /// STATUS_ON_SIM_READ /// </java-name> [Dot42.DexImport("STATUS_ON_SIM_READ", "I", AccessFlags = 25)] public const int STATUS_ON_SIM_READ = 1; /// <java-name> /// STATUS_ON_SIM_UNREAD /// </java-name> [Dot42.DexImport("STATUS_ON_SIM_UNREAD", "I", AccessFlags = 25)] public const int STATUS_ON_SIM_UNREAD = 3; /// <java-name> /// STATUS_ON_SIM_SENT /// </java-name> [Dot42.DexImport("STATUS_ON_SIM_SENT", "I", AccessFlags = 25)] public const int STATUS_ON_SIM_SENT = 5; /// <java-name> /// STATUS_ON_SIM_UNSENT /// </java-name> [Dot42.DexImport("STATUS_ON_SIM_UNSENT", "I", AccessFlags = 25)] public const int STATUS_ON_SIM_UNSENT = 7; /// <java-name> /// RESULT_ERROR_GENERIC_FAILURE /// </java-name> [Dot42.DexImport("RESULT_ERROR_GENERIC_FAILURE", "I", AccessFlags = 25)] public const int RESULT_ERROR_GENERIC_FAILURE = 1; /// <java-name> /// RESULT_ERROR_RADIO_OFF /// </java-name> [Dot42.DexImport("RESULT_ERROR_RADIO_OFF", "I", AccessFlags = 25)] public const int RESULT_ERROR_RADIO_OFF = 2; /// <java-name> /// RESULT_ERROR_NULL_PDU /// </java-name> [Dot42.DexImport("RESULT_ERROR_NULL_PDU", "I", AccessFlags = 25)] public const int RESULT_ERROR_NULL_PDU = 3; /// <java-name> /// RESULT_ERROR_NO_SERVICE /// </java-name> [Dot42.DexImport("RESULT_ERROR_NO_SERVICE", "I", AccessFlags = 25)] public const int RESULT_ERROR_NO_SERVICE = 4; [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal SmsManager() /* MethodBuilder.Create */ { } /// <java-name> /// getDefault /// </java-name> [Dot42.DexImport("getDefault", "()Landroid/telephony/gsm/SmsManager;", AccessFlags = 25)] public static global::Android.Telephony.Gsm.SmsManager GetDefault() /* MethodBuilder.Create */ { return default(global::Android.Telephony.Gsm.SmsManager); } /// <java-name> /// sendTextMessage /// </java-name> [Dot42.DexImport("sendTextMessage", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Landroid/app/PendingIntent" + ";Landroid/app/PendingIntent;)V", AccessFlags = 17)] public void SendTextMessage(string @string, string string1, string string2, global::Android.App.PendingIntent pendingIntent, global::Android.App.PendingIntent pendingIntent1) /* MethodBuilder.Create */ { } /// <java-name> /// divideMessage /// </java-name> [Dot42.DexImport("divideMessage", "(Ljava/lang/String;)Ljava/util/ArrayList;", AccessFlags = 17, Signature = "(Ljava/lang/String;)Ljava/util/ArrayList<Ljava/lang/String;>;")] public global::Java.Util.ArrayList<string> DivideMessage(string @string) /* MethodBuilder.Create */ { return default(global::Java.Util.ArrayList<string>); } /// <java-name> /// sendMultipartTextMessage /// </java-name> [Dot42.DexImport("sendMultipartTextMessage", "(Ljava/lang/String;Ljava/lang/String;Ljava/util/ArrayList;Ljava/util/ArrayList;Lj" + "ava/util/ArrayList;)V", AccessFlags = 17, Signature = "(Ljava/lang/String;Ljava/lang/String;Ljava/util/ArrayList<Ljava/lang/String;>;Lja" + "va/util/ArrayList<Landroid/app/PendingIntent;>;Ljava/util/ArrayList<Landroid/app" + "/PendingIntent;>;)V")] public void SendMultipartTextMessage(string @string, string string1, global::Java.Util.ArrayList<string> arrayList, global::Java.Util.ArrayList<global::Android.App.PendingIntent> arrayList1, global::Java.Util.ArrayList<global::Android.App.PendingIntent> arrayList2) /* MethodBuilder.Create */ { } /// <java-name> /// sendDataMessage /// </java-name> [Dot42.DexImport("sendDataMessage", "(Ljava/lang/String;Ljava/lang/String;S[BLandroid/app/PendingIntent;Landroid/app/P" + "endingIntent;)V", AccessFlags = 17)] public void SendDataMessage(string @string, string string1, short int16, sbyte[] sByte, global::Android.App.PendingIntent pendingIntent, global::Android.App.PendingIntent pendingIntent1) /* MethodBuilder.Create */ { } /// <java-name> /// sendDataMessage /// </java-name> [Dot42.DexImport("sendDataMessage", "(Ljava/lang/String;Ljava/lang/String;S[BLandroid/app/PendingIntent;Landroid/app/P" + "endingIntent;)V", AccessFlags = 17, IgnoreFromJava = true)] public void SendDataMessage(string @string, string string1, short int16, byte[] @byte, global::Android.App.PendingIntent pendingIntent, global::Android.App.PendingIntent pendingIntent1) /* MethodBuilder.Create */ { } /// <java-name> /// getDefault /// </java-name> public static global::Android.Telephony.Gsm.SmsManager Default { [Dot42.DexImport("getDefault", "()Landroid/telephony/gsm/SmsManager;", AccessFlags = 25)] get{ return GetDefault(); } } } /// <summary> /// <para>Represents the cell location on a GSM phone. </para> /// </summary> /// <java-name> /// android/telephony/gsm/GsmCellLocation /// </java-name> [Dot42.DexImport("android/telephony/gsm/GsmCellLocation", AccessFlags = 33)] public partial class GsmCellLocation : global::Android.Telephony.CellLocation /* scope: __dot42__ */ { /// <summary> /// <para>Empty constructor. Initializes the LAC and CID to -1. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public GsmCellLocation() /* MethodBuilder.Create */ { } /// <summary> /// <para>Initialize the object from a bundle. </para> /// </summary> [Dot42.DexImport("<init>", "(Landroid/os/Bundle;)V", AccessFlags = 1)] public GsmCellLocation(global::Android.Os.Bundle bundle) /* MethodBuilder.Create */ { } /// <summary> /// <para></para> /// </summary> /// <returns> /// <para>gsm location area code, -1 if unknown, 0xffff max legal value </para> /// </returns> /// <java-name> /// getLac /// </java-name> [Dot42.DexImport("getLac", "()I", AccessFlags = 1)] public virtual int GetLac() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para></para> /// </summary> /// <returns> /// <para>gsm cell id, -1 if unknown, 0xffff max legal value </para> /// </returns> /// <java-name> /// getCid /// </java-name> [Dot42.DexImport("getCid", "()I", AccessFlags = 1)] public virtual int GetCid() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Invalidate this object. The location area code and the cell id are set to -1. </para> /// </summary> /// <java-name> /// setStateInvalid /// </java-name> [Dot42.DexImport("setStateInvalid", "()V", AccessFlags = 1)] public virtual void SetStateInvalid() /* MethodBuilder.Create */ { } /// <summary> /// <para>Set the location area code and the cell id. </para> /// </summary> /// <java-name> /// setLacAndCid /// </java-name> [Dot42.DexImport("setLacAndCid", "(II)V", AccessFlags = 1)] public virtual void SetLacAndCid(int lac, int cid) /* MethodBuilder.Create */ { } /// <java-name> /// hashCode /// </java-name> [Dot42.DexImport("hashCode", "()I", AccessFlags = 1)] public override int GetHashCode() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// equals /// </java-name> [Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)] public override bool Equals(object o) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Set intent notifier Bundle based on service state</para><para></para> /// </summary> /// <java-name> /// fillInNotifierBundle /// </java-name> [Dot42.DexImport("fillInNotifierBundle", "(Landroid/os/Bundle;)V", AccessFlags = 1)] public virtual void FillInNotifierBundle(global::Android.Os.Bundle m) /* MethodBuilder.Create */ { } /// <summary> /// <para></para> /// </summary> /// <returns> /// <para>gsm location area code, -1 if unknown, 0xffff max legal value </para> /// </returns> /// <java-name> /// getLac /// </java-name> public int Lac { [Dot42.DexImport("getLac", "()I", AccessFlags = 1)] get{ return GetLac(); } } /// <summary> /// <para></para> /// </summary> /// <returns> /// <para>gsm cell id, -1 if unknown, 0xffff max legal value </para> /// </returns> /// <java-name> /// getCid /// </java-name> public int Cid { [Dot42.DexImport("getCid", "()I", AccessFlags = 1)] get{ return GetCid(); } } } /// <java-name> /// android/telephony/gsm/SmsMessage /// </java-name> [Dot42.DexImport("android/telephony/gsm/SmsMessage", AccessFlags = 33)] public partial class SmsMessage /* scope: __dot42__ */ { /// <java-name> /// ENCODING_UNKNOWN /// </java-name> [Dot42.DexImport("ENCODING_UNKNOWN", "I", AccessFlags = 25)] public const int ENCODING_UNKNOWN = 0; /// <java-name> /// ENCODING_7BIT /// </java-name> [Dot42.DexImport("ENCODING_7BIT", "I", AccessFlags = 25)] public const int ENCODING_7BIT = 1; /// <java-name> /// ENCODING_8BIT /// </java-name> [Dot42.DexImport("ENCODING_8BIT", "I", AccessFlags = 25)] public const int ENCODING_8BIT = 2; /// <java-name> /// ENCODING_16BIT /// </java-name> [Dot42.DexImport("ENCODING_16BIT", "I", AccessFlags = 25)] public const int ENCODING_16BIT = 3; /// <java-name> /// MAX_USER_DATA_BYTES /// </java-name> [Dot42.DexImport("MAX_USER_DATA_BYTES", "I", AccessFlags = 25)] public const int MAX_USER_DATA_BYTES = 140; /// <java-name> /// MAX_USER_DATA_SEPTETS /// </java-name> [Dot42.DexImport("MAX_USER_DATA_SEPTETS", "I", AccessFlags = 25)] public const int MAX_USER_DATA_SEPTETS = 160; /// <java-name> /// MAX_USER_DATA_SEPTETS_WITH_HEADER /// </java-name> [Dot42.DexImport("MAX_USER_DATA_SEPTETS_WITH_HEADER", "I", AccessFlags = 25)] public const int MAX_USER_DATA_SEPTETS_WITH_HEADER = 153; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public SmsMessage() /* MethodBuilder.Create */ { } /// <java-name> /// createFromPdu /// </java-name> [Dot42.DexImport("createFromPdu", "([B)Landroid/telephony/gsm/SmsMessage;", AccessFlags = 9)] public static global::Android.Telephony.Gsm.SmsMessage CreateFromPdu(sbyte[] sByte) /* MethodBuilder.Create */ { return default(global::Android.Telephony.Gsm.SmsMessage); } /// <java-name> /// createFromPdu /// </java-name> [Dot42.DexImport("createFromPdu", "([B)Landroid/telephony/gsm/SmsMessage;", AccessFlags = 9, IgnoreFromJava = true)] public static global::Android.Telephony.Gsm.SmsMessage CreateFromPdu(byte[] @byte) /* MethodBuilder.Create */ { return default(global::Android.Telephony.Gsm.SmsMessage); } /// <java-name> /// getTPLayerLengthForPDU /// </java-name> [Dot42.DexImport("getTPLayerLengthForPDU", "(Ljava/lang/String;)I", AccessFlags = 9)] public static int GetTPLayerLengthForPDU(string @string) /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// calculateLength /// </java-name> [Dot42.DexImport("calculateLength", "(Ljava/lang/CharSequence;Z)[I", AccessFlags = 9)] public static int[] CalculateLength(global::Java.Lang.ICharSequence charSequence, bool boolean) /* MethodBuilder.Create */ { return default(int[]); } /// <java-name> /// calculateLength /// </java-name> [Dot42.DexImport("calculateLength", "(Ljava/lang/String;Z)[I", AccessFlags = 9)] public static int[] CalculateLength(string @string, bool boolean) /* MethodBuilder.Create */ { return default(int[]); } /// <java-name> /// getSubmitPdu /// </java-name> [Dot42.DexImport("getSubmitPdu", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)Landroid/telephony/gsm/S" + "msMessage$SubmitPdu;", AccessFlags = 9)] public static global::Android.Telephony.Gsm.SmsMessage.SubmitPdu GetSubmitPdu(string @string, string string1, string string2, bool boolean) /* MethodBuilder.Create */ { return default(global::Android.Telephony.Gsm.SmsMessage.SubmitPdu); } /// <java-name> /// getSubmitPdu /// </java-name> [Dot42.DexImport("getSubmitPdu", "(Ljava/lang/String;Ljava/lang/String;S[BZ)Landroid/telephony/gsm/SmsMessage$Submi" + "tPdu;", AccessFlags = 9)] public static global::Android.Telephony.Gsm.SmsMessage.SubmitPdu GetSubmitPdu(string @string, string string1, short int16, sbyte[] sByte, bool boolean) /* MethodBuilder.Create */ { return default(global::Android.Telephony.Gsm.SmsMessage.SubmitPdu); } /// <java-name> /// getSubmitPdu /// </java-name> [Dot42.DexImport("getSubmitPdu", "(Ljava/lang/String;Ljava/lang/String;S[BZ)Landroid/telephony/gsm/SmsMessage$Submi" + "tPdu;", AccessFlags = 9, IgnoreFromJava = true)] public static global::Android.Telephony.Gsm.SmsMessage.SubmitPdu GetSubmitPdu(string @string, string string1, short int16, byte[] @byte, bool boolean) /* MethodBuilder.Create */ { return default(global::Android.Telephony.Gsm.SmsMessage.SubmitPdu); } /// <java-name> /// getServiceCenterAddress /// </java-name> [Dot42.DexImport("getServiceCenterAddress", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetServiceCenterAddress() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getOriginatingAddress /// </java-name> [Dot42.DexImport("getOriginatingAddress", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetOriginatingAddress() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getDisplayOriginatingAddress /// </java-name> [Dot42.DexImport("getDisplayOriginatingAddress", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetDisplayOriginatingAddress() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getMessageBody /// </java-name> [Dot42.DexImport("getMessageBody", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetMessageBody() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getMessageClass /// </java-name> [Dot42.DexImport("getMessageClass", "()Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 1)] public virtual global::Android.Telephony.Gsm.SmsMessage.MessageClass GetMessageClass() /* MethodBuilder.Create */ { return default(global::Android.Telephony.Gsm.SmsMessage.MessageClass); } /// <java-name> /// getDisplayMessageBody /// </java-name> [Dot42.DexImport("getDisplayMessageBody", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetDisplayMessageBody() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getPseudoSubject /// </java-name> [Dot42.DexImport("getPseudoSubject", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetPseudoSubject() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getTimestampMillis /// </java-name> [Dot42.DexImport("getTimestampMillis", "()J", AccessFlags = 1)] public virtual long GetTimestampMillis() /* MethodBuilder.Create */ { return default(long); } /// <java-name> /// isEmail /// </java-name> [Dot42.DexImport("isEmail", "()Z", AccessFlags = 1)] public virtual bool IsEmail() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// getEmailBody /// </java-name> [Dot42.DexImport("getEmailBody", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetEmailBody() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getEmailFrom /// </java-name> [Dot42.DexImport("getEmailFrom", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetEmailFrom() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getProtocolIdentifier /// </java-name> [Dot42.DexImport("getProtocolIdentifier", "()I", AccessFlags = 1)] public virtual int GetProtocolIdentifier() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// isReplace /// </java-name> [Dot42.DexImport("isReplace", "()Z", AccessFlags = 1)] public virtual bool IsReplace() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// isCphsMwiMessage /// </java-name> [Dot42.DexImport("isCphsMwiMessage", "()Z", AccessFlags = 1)] public virtual bool IsCphsMwiMessage() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// isMWIClearMessage /// </java-name> [Dot42.DexImport("isMWIClearMessage", "()Z", AccessFlags = 1)] public virtual bool IsMWIClearMessage() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// isMWISetMessage /// </java-name> [Dot42.DexImport("isMWISetMessage", "()Z", AccessFlags = 1)] public virtual bool IsMWISetMessage() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// isMwiDontStore /// </java-name> [Dot42.DexImport("isMwiDontStore", "()Z", AccessFlags = 1)] public virtual bool IsMwiDontStore() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// getUserData /// </java-name> [Dot42.DexImport("getUserData", "()[B", AccessFlags = 1)] public virtual sbyte[] JavaGetUserData() /* MethodBuilder.Create */ { return default(sbyte[]); } /// <java-name> /// getUserData /// </java-name> [Dot42.DexImport("getUserData", "()[B", AccessFlags = 1, IgnoreFromJava = true)] public virtual byte[] GetUserData() /* MethodBuilder.Create */ { return default(byte[]); } /// <java-name> /// getPdu /// </java-name> [Dot42.DexImport("getPdu", "()[B", AccessFlags = 1)] public virtual sbyte[] JavaGetPdu() /* MethodBuilder.Create */ { return default(sbyte[]); } /// <java-name> /// getPdu /// </java-name> [Dot42.DexImport("getPdu", "()[B", AccessFlags = 1, IgnoreFromJava = true)] public virtual byte[] GetPdu() /* MethodBuilder.Create */ { return default(byte[]); } /// <java-name> /// getStatusOnSim /// </java-name> [Dot42.DexImport("getStatusOnSim", "()I", AccessFlags = 1)] public virtual int GetStatusOnSim() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// getIndexOnSim /// </java-name> [Dot42.DexImport("getIndexOnSim", "()I", AccessFlags = 1)] public virtual int GetIndexOnSim() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// getStatus /// </java-name> [Dot42.DexImport("getStatus", "()I", AccessFlags = 1)] public virtual int GetStatus() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// isStatusReportMessage /// </java-name> [Dot42.DexImport("isStatusReportMessage", "()Z", AccessFlags = 1)] public virtual bool IsStatusReportMessage() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// isReplyPathPresent /// </java-name> [Dot42.DexImport("isReplyPathPresent", "()Z", AccessFlags = 1)] public virtual bool IsReplyPathPresent() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// getServiceCenterAddress /// </java-name> public string ServiceCenterAddress { [Dot42.DexImport("getServiceCenterAddress", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetServiceCenterAddress(); } } /// <java-name> /// getOriginatingAddress /// </java-name> public string OriginatingAddress { [Dot42.DexImport("getOriginatingAddress", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetOriginatingAddress(); } } /// <java-name> /// getDisplayOriginatingAddress /// </java-name> public string DisplayOriginatingAddress { [Dot42.DexImport("getDisplayOriginatingAddress", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetDisplayOriginatingAddress(); } } /// <java-name> /// getMessageBody /// </java-name> public string MessageBody { [Dot42.DexImport("getMessageBody", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMessageBody(); } } /// <java-name> /// getDisplayMessageBody /// </java-name> public string DisplayMessageBody { [Dot42.DexImport("getDisplayMessageBody", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetDisplayMessageBody(); } } /// <java-name> /// getPseudoSubject /// </java-name> public string PseudoSubject { [Dot42.DexImport("getPseudoSubject", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetPseudoSubject(); } } /// <java-name> /// getTimestampMillis /// </java-name> public long TimestampMillis { [Dot42.DexImport("getTimestampMillis", "()J", AccessFlags = 1)] get{ return GetTimestampMillis(); } } /// <java-name> /// getEmailBody /// </java-name> public string EmailBody { [Dot42.DexImport("getEmailBody", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetEmailBody(); } } /// <java-name> /// getEmailFrom /// </java-name> public string EmailFrom { [Dot42.DexImport("getEmailFrom", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetEmailFrom(); } } /// <java-name> /// getProtocolIdentifier /// </java-name> public int ProtocolIdentifier { [Dot42.DexImport("getProtocolIdentifier", "()I", AccessFlags = 1)] get{ return GetProtocolIdentifier(); } } /// <java-name> /// getUserData /// </java-name> public byte[] UserData { [Dot42.DexImport("getUserData", "()[B", AccessFlags = 1, IgnoreFromJava = true)] get{ return GetUserData(); } } /// <java-name> /// getPdu /// </java-name> public byte[] Pdu { [Dot42.DexImport("getPdu", "()[B", AccessFlags = 1, IgnoreFromJava = true)] get{ return GetPdu(); } } /// <java-name> /// getStatusOnSim /// </java-name> public int StatusOnSim { [Dot42.DexImport("getStatusOnSim", "()I", AccessFlags = 1)] get{ return GetStatusOnSim(); } } /// <java-name> /// getIndexOnSim /// </java-name> public int IndexOnSim { [Dot42.DexImport("getIndexOnSim", "()I", AccessFlags = 1)] get{ return GetIndexOnSim(); } } /// <java-name> /// getStatus /// </java-name> public int Status { [Dot42.DexImport("getStatus", "()I", AccessFlags = 1)] get{ return GetStatus(); } } /// <java-name> /// android/telephony/gsm/SmsMessage$SubmitPdu /// </java-name> [Dot42.DexImport("android/telephony/gsm/SmsMessage$SubmitPdu", AccessFlags = 9)] public partial class SubmitPdu /* scope: __dot42__ */ { /// <java-name> /// encodedScAddress /// </java-name> [Dot42.DexImport("encodedScAddress", "[B", AccessFlags = 1)] public sbyte[] EncodedScAddress; /// <java-name> /// encodedMessage /// </java-name> [Dot42.DexImport("encodedMessage", "[B", AccessFlags = 1)] public sbyte[] EncodedMessage; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public SubmitPdu() /* MethodBuilder.Create */ { } /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } } /// <java-name> /// android/telephony/gsm/SmsMessage$MessageClass /// </java-name> [Dot42.DexImport("android/telephony/gsm/SmsMessage$MessageClass", AccessFlags = 16409, Signature = "Ljava/lang/Enum<Landroid/telephony/gsm/SmsMessage$MessageClass;>;")] public sealed class MessageClass /* scope: __dot42__ */ { /// <java-name> /// CLASS_0 /// </java-name> [Dot42.DexImport("CLASS_0", "Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 16409)] public static readonly MessageClass CLASS_0; /// <java-name> /// CLASS_1 /// </java-name> [Dot42.DexImport("CLASS_1", "Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 16409)] public static readonly MessageClass CLASS_1; /// <java-name> /// CLASS_2 /// </java-name> [Dot42.DexImport("CLASS_2", "Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 16409)] public static readonly MessageClass CLASS_2; /// <java-name> /// CLASS_3 /// </java-name> [Dot42.DexImport("CLASS_3", "Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 16409)] public static readonly MessageClass CLASS_3; /// <java-name> /// UNKNOWN /// </java-name> [Dot42.DexImport("UNKNOWN", "Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 16409)] public static readonly MessageClass UNKNOWN; private MessageClass() /* TypeBuilder.AddPrivateDefaultCtor */ { } } } }
// *********************************************************************** // 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.Collections; using System.Collections.Generic; namespace NUnit.Framework.Constraints { /// <summary> /// EqualConstraint is able to compare an actual value with the /// expected value provided in its constructor. Two objects are /// considered equal if both are null, or if both have the same /// value. NUnit has special semantics for some object types. /// </summary> public class EqualConstraint : Constraint { #region Static and Instance Fields private readonly object _expected; private Tolerance _tolerance = Tolerance.Default; /// <summary> /// NUnitEqualityComparer used to test equality. /// </summary> private NUnitEqualityComparer _comparer = new NUnitEqualityComparer(); #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="EqualConstraint"/> class. /// </summary> /// <param name="expected">The expected value.</param> public EqualConstraint(object expected) : base(expected) { AdjustArgumentIfNeeded(ref expected); _expected = expected; ClipStrings = true; } #endregion #region Properties // TODO: Remove public properties // They are only used by EqualConstraintResult // EqualConstraint should inject them into the constructor. /// <summary> /// Gets the tolerance for this comparison. /// </summary> /// <value> /// The tolerance. /// </value> public Tolerance Tolerance { get { return _tolerance; } } /// <summary> /// Gets a value indicating whether to compare case insensitive. /// </summary> /// <value> /// <c>true</c> if comparing case insensitive; otherwise, <c>false</c>. /// </value> public bool CaseInsensitive { get { return _comparer.IgnoreCase; } } /// <summary> /// Gets a value indicating whether or not to clip strings. /// </summary> /// <value> /// <c>true</c> if set to clip strings otherwise, <c>false</c>. /// </value> public bool ClipStrings { get; private set; } /// <summary> /// Gets the failure points. /// </summary> /// <value> /// The failure points. /// </value> public IList<NUnitEqualityComparer.FailurePoint> FailurePoints { get { return _comparer.FailurePoints; } } #endregion #region Constraint Modifiers /// <summary> /// Flag the constraint to ignore case and return self. /// </summary> public EqualConstraint IgnoreCase { get { _comparer.IgnoreCase = true; return this; } } /// <summary> /// Flag the constraint to suppress string clipping /// and return self. /// </summary> public EqualConstraint NoClip { get { ClipStrings = false; return this; } } /// <summary> /// Flag the constraint to compare arrays as collections /// and return self. /// </summary> public EqualConstraint AsCollection { get { _comparer.CompareAsCollection = true; return this; } } /// <summary> /// Flag the constraint to use a tolerance when determining equality. /// </summary> /// <param name="amount">Tolerance value to be used</param> /// <returns>Self.</returns> public EqualConstraint Within(object amount) { if (!_tolerance.IsUnsetOrDefault) throw new InvalidOperationException("Within modifier may appear only once in a constraint expression"); _tolerance = new Tolerance(amount); return this; } /// <summary> /// Flags the constraint to include <see cref="DateTimeOffset.Offset"/> /// property in comparison of two <see cref="DateTimeOffset"/> values. /// </summary> /// <remarks> /// Using this modifier does not allow to use the <see cref="Within"/> /// constraint modifier. /// </remarks> public EqualConstraint WithSameOffset { get { _comparer.WithSameOffset = true; return this; } } /// <summary> /// Switches the .Within() modifier to interpret its tolerance as /// a distance in representable _values (see remarks). /// </summary> /// <returns>Self.</returns> /// <remarks> /// Ulp stands for "unit in the last place" and describes the minimum /// amount a given value can change. For any integers, an ulp is 1 whole /// digit. For floating point _values, the accuracy of which is better /// for smaller numbers and worse for larger numbers, an ulp depends /// on the size of the number. Using ulps for comparison of floating /// point results instead of fixed tolerances is safer because it will /// automatically compensate for the added inaccuracy of larger numbers. /// </remarks> public EqualConstraint Ulps { get { _tolerance = _tolerance.Ulps; return this; } } /// <summary> /// Switches the .Within() modifier to interpret its tolerance as /// a percentage that the actual _values is allowed to deviate from /// the expected value. /// </summary> /// <returns>Self</returns> public EqualConstraint Percent { get { _tolerance = _tolerance.Percent; return this; } } /// <summary> /// Causes the tolerance to be interpreted as a TimeSpan in days. /// </summary> /// <returns>Self</returns> public EqualConstraint Days { get { _tolerance = _tolerance.Days; return this; } } /// <summary> /// Causes the tolerance to be interpreted as a TimeSpan in hours. /// </summary> /// <returns>Self</returns> public EqualConstraint Hours { get { _tolerance = _tolerance.Hours; return this; } } /// <summary> /// Causes the tolerance to be interpreted as a TimeSpan in minutes. /// </summary> /// <returns>Self</returns> public EqualConstraint Minutes { get { _tolerance = _tolerance.Minutes; return this; } } /// <summary> /// Causes the tolerance to be interpreted as a TimeSpan in seconds. /// </summary> /// <returns>Self</returns> public EqualConstraint Seconds { get { _tolerance = _tolerance.Seconds; return this; } } /// <summary> /// Causes the tolerance to be interpreted as a TimeSpan in milliseconds. /// </summary> /// <returns>Self</returns> public EqualConstraint Milliseconds { get { _tolerance = _tolerance.Milliseconds; return this; } } /// <summary> /// Causes the tolerance to be interpreted as a TimeSpan in clock ticks. /// </summary> /// <returns>Self</returns> public EqualConstraint Ticks { get { _tolerance = _tolerance.Ticks; return this; } } /// <summary> /// Flag the constraint to use the supplied IComparer object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public EqualConstraint Using(IComparer comparer) { _comparer.ExternalComparers.Add(EqualityAdapter.For(comparer)); return this; } /// <summary> /// Flag the constraint to use the supplied IComparer object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public EqualConstraint Using<T>(IComparer<T> comparer) { _comparer.ExternalComparers.Add(EqualityAdapter.For(comparer)); return this; } /// <summary> /// Flag the constraint to use the supplied Comparison object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public EqualConstraint Using<T>(Comparison<T> comparer) { _comparer.ExternalComparers.Add(EqualityAdapter.For(comparer)); return this; } /// <summary> /// Flag the constraint to use the supplied IEqualityComparer object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public EqualConstraint Using(IEqualityComparer comparer) { _comparer.ExternalComparers.Add(EqualityAdapter.For(comparer)); return this; } /// <summary> /// Flag the constraint to use the supplied IEqualityComparer object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public EqualConstraint Using<T>(IEqualityComparer<T> comparer) { _comparer.ExternalComparers.Add(EqualityAdapter.For(comparer)); return this; } #endregion #region Public Methods /// <summary> /// Test whether the constraint is satisfied by a given value /// </summary> /// <param name="actual">The value to be tested</param> /// <returns>True for success, false for failure</returns> public override ConstraintResult ApplyTo<TActual>(TActual actual) { AdjustArgumentIfNeeded(ref actual); return new EqualConstraintResult(this, actual, _comparer.AreEqual(_expected, actual, ref _tolerance)); } /// <summary> /// The Description of what this constraint tests, for /// use in messages and in the ConstraintResult. /// </summary> public override string Description { get { System.Text.StringBuilder sb = new System.Text.StringBuilder(MsgUtils.FormatValue(_expected)); if (_tolerance != null && !_tolerance.IsUnsetOrDefault) { sb.Append(" +/- "); sb.Append(MsgUtils.FormatValue(_tolerance.Value)); if (_tolerance.Mode != ToleranceMode.Linear) { sb.Append(" "); sb.Append(_tolerance.Mode.ToString()); } } if (_comparer.IgnoreCase) sb.Append(", ignoring case"); return sb.ToString(); } } #endregion #region Helper Methods // Currently, we only adjust for ArraySegments that have a // null array reference. Others could be added in the future. private void AdjustArgumentIfNeeded<T>(ref T arg) { #if !NETCF && !SILVERLIGHT && !PORTABLE if (arg != null) { Type argType = arg.GetType(); Type genericTypeDefinition = argType.IsGenericType ? argType.GetGenericTypeDefinition() : null; if (genericTypeDefinition == typeof(ArraySegment<>) && argType.GetProperty("Array").GetValue(arg, null) == null) { var elementType = argType.GetGenericArguments()[0]; var array = Array.CreateInstance(elementType, 0); var ctor = argType.GetConstructor(new Type[] { array.GetType() }); arg = (T)ctor.Invoke(new object[] { array }); } } #endif } #endregion } }
using System; using System.Collections.Generic; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Platform; using Avalonia.Threading; using Avalonia.UnitTests; using Moq; using Xunit; namespace Avalonia.Controls.UnitTests { public class DesktopStyleApplicationLifetimeTests { [Fact] public void Should_Set_ExitCode_After_Shutdown() { using (UnitTestApplication.Start(TestServices.MockThreadingInterface)) using(var lifetime = new ClassicDesktopStyleApplicationLifetime()) { lifetime.Shutdown(1337); var exitCode = lifetime.Start(Array.Empty<string>()); Assert.Equal(1337, exitCode); } } [Fact] public void Should_Close_All_Remaining_Open_Windows_After_Explicit_Exit_Call() { using (UnitTestApplication.Start(TestServices.StyledWindow)) using(var lifetime = new ClassicDesktopStyleApplicationLifetime()) { var windows = new List<Window> { new Window(), new Window(), new Window(), new Window() }; foreach (var window in windows) { window.Show(); } Assert.Equal(4, lifetime.Windows.Count); lifetime.Shutdown(); Assert.Empty(lifetime.Windows); } } [Fact] public void Should_Only_Exit_On_Explicit_Exit() { using (UnitTestApplication.Start(TestServices.StyledWindow)) using(var lifetime = new ClassicDesktopStyleApplicationLifetime()) { lifetime.ShutdownMode = ShutdownMode.OnExplicitShutdown; var hasExit = false; lifetime.Exit += (s, e) => hasExit = true; var windowA = new Window(); windowA.Show(); var windowB = new Window(); windowB.Show(); windowA.Close(); Assert.False(hasExit); windowB.Close(); Assert.False(hasExit); lifetime.Shutdown(); Assert.True(hasExit); } } [Fact] public void Should_Exit_After_MainWindow_Closed() { using (UnitTestApplication.Start(TestServices.StyledWindow)) using(var lifetime = new ClassicDesktopStyleApplicationLifetime()) { lifetime.ShutdownMode = ShutdownMode.OnMainWindowClose; var hasExit = false; lifetime.Exit += (s, e) => hasExit = true; var mainWindow = new Window(); mainWindow.Show(); lifetime.MainWindow = mainWindow; var window = new Window(); window.Show(); mainWindow.Close(); Assert.True(hasExit); } } [Fact] public void Should_Exit_After_Last_Window_Closed() { using (UnitTestApplication.Start(TestServices.StyledWindow)) using(var lifetime = new ClassicDesktopStyleApplicationLifetime()) { lifetime.ShutdownMode = ShutdownMode.OnLastWindowClose; var hasExit = false; lifetime.Exit += (s, e) => hasExit = true; var windowA = new Window(); windowA.Show(); var windowB = new Window(); windowB.Show(); windowA.Close(); Assert.False(hasExit); windowB.Close(); Assert.True(hasExit); } } [Fact] public void Show_Should_Add_Window_To_OpenWindows() { using (UnitTestApplication.Start(TestServices.StyledWindow)) using(var lifetime = new ClassicDesktopStyleApplicationLifetime()) { var window = new Window(); window.Show(); Assert.Equal(new[] { window }, lifetime.Windows); } } [Fact] public void Window_Should_Be_Added_To_OpenWindows_Only_Once() { using (UnitTestApplication.Start(TestServices.StyledWindow)) using(var lifetime = new ClassicDesktopStyleApplicationLifetime()) { var window = new Window(); window.Show(); window.Show(); window.IsVisible = true; Assert.Equal(new[] { window }, lifetime.Windows); window.Close(); } } [Fact] public void Close_Should_Remove_Window_From_OpenWindows() { using (UnitTestApplication.Start(TestServices.StyledWindow)) using(var lifetime = new ClassicDesktopStyleApplicationLifetime()) { var window = new Window(); window.Show(); Assert.Equal(1, lifetime.Windows.Count); window.Close(); Assert.Empty(lifetime.Windows); } } [Fact] public void Impl_Closing_Should_Remove_Window_From_OpenWindows() { var windowImpl = new Mock<IWindowImpl>(); windowImpl.SetupProperty(x => x.Closed); windowImpl.Setup(x => x.DesktopScaling).Returns(1); windowImpl.Setup(x => x.RenderScaling).Returns(1); var services = TestServices.StyledWindow.With( windowingPlatform: new MockWindowingPlatform(() => windowImpl.Object)); using (UnitTestApplication.Start(services)) using(var lifetime = new ClassicDesktopStyleApplicationLifetime()) { var window = new Window(); window.Show(); Assert.Equal(1, lifetime.Windows.Count); windowImpl.Object.Closed(); Assert.Empty(lifetime.Windows); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; namespace System { public partial class String { public bool Contains(string value) { return (IndexOf(value, StringComparison.Ordinal) >= 0); } // Returns the index of the first occurrence of value in the current instance. // The search starts at startIndex and runs thorough the next count characters. // public int IndexOf(char value) { return IndexOf(value, 0, this.Length); } public int IndexOf(char value, int startIndex) { return IndexOf(value, startIndex, this.Length - startIndex); } public unsafe int IndexOf(char value, int startIndex, int count) { if (startIndex < 0 || startIndex > Length) throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); if (count < 0 || count > Length - startIndex) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; while (count >= 4) { if (*pCh == value) goto ReturnIndex; if (*(pCh + 1) == value) goto ReturnIndex1; if (*(pCh + 2) == value) goto ReturnIndex2; if (*(pCh + 3) == value) goto ReturnIndex3; count -= 4; pCh += 4; } while (count > 0) { if (*pCh == value) goto ReturnIndex; count--; pCh++; } return -1; ReturnIndex3: pCh++; ReturnIndex2: pCh++; ReturnIndex1: pCh++; ReturnIndex: return (int)(pCh - pChars); } } // Returns the index of the first occurrence of any specified character in the current instance. // The search starts at startIndex and runs to startIndex + count - 1. // public int IndexOfAny(char[] anyOf) { return IndexOfAny(anyOf, 0, this.Length); } public int IndexOfAny(char[] anyOf, int startIndex) { return IndexOfAny(anyOf, startIndex, this.Length - startIndex); } public unsafe int IndexOfAny(char[] anyOf, int startIndex, int count) { if (anyOf == null) throw new ArgumentNullException("anyOf"); if (startIndex < 0 || startIndex > Length) throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); if (count < 0 || count > Length - startIndex) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); // use probabilistic map, see InitializeProbabilisticMap uint* charMap = stackalloc uint[PROBABILISTICMAP_SIZE]; InitializeProbabilisticMap(charMap, anyOf); fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; for (int i = 0; i < count; i++) { char thisChar = *pCh++; if (ProbablyContains(charMap, thisChar)) if (ArrayContains(thisChar, anyOf) >= 0) return i + startIndex; } } return -1; } private const int PROBABILISTICMAP_BLOCK_INDEX_MASK = 0x7; private const int PROBABILISTICMAP_BLOCK_INDEX_SHIFT = 0x3; private const int PROBABILISTICMAP_SIZE = 0x8; // A probabilistic map is an optimization that is used in IndexOfAny/ // LastIndexOfAny methods. The idea is to create a bit map of the characters we // are searching for and use this map as a "cheap" check to decide if the // current character in the string exists in the array of input characters. // There are 256 bits in the map, with each character mapped to 2 bits. Every // character is divided into 2 bytes, and then every byte is mapped to 1 bit. // The character map is an array of 8 integers acting as map blocks. The 3 lsb // in each byte in the character is used to index into this map to get the // right block, the value of the remaining 5 msb are used as the bit position // inside this block. private static unsafe void InitializeProbabilisticMap(uint* charMap, char[] anyOf) { for (int i = 0; i < anyOf.Length; ++i) { uint hi, lo; char c = anyOf[i]; hi = ((uint)c >> 8) & 0xFF; lo = (uint)c & 0xFF; uint* value = &charMap[lo & PROBABILISTICMAP_BLOCK_INDEX_MASK]; *value |= (1u << (int)(lo >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT)); value = &charMap[hi & PROBABILISTICMAP_BLOCK_INDEX_MASK]; *value |= (1u << (int)(hi >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT)); } } // Use the probabilistic map to decide if the character value exists in the // map. When this method return false, we are certain the character doesn't // exist, however a true return means it *may* exist. private static unsafe bool ProbablyContains(uint* charMap, char searchValue) { uint lo, hi; lo = (uint)searchValue & 0xFF; uint value = charMap[lo & PROBABILISTICMAP_BLOCK_INDEX_MASK]; if ((value & (1u << (int)(lo >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT))) != 0) { hi = ((uint)searchValue >> 8) & 0xFF; value = charMap[hi & PROBABILISTICMAP_BLOCK_INDEX_MASK]; return (value & (1u << (int)(hi >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT))) != 0; } return false; } private static int ArrayContains(char searchChar, char[] anyOf) { for (int i = 0; i < anyOf.Length; i++) { if (anyOf[i] == searchChar) return i; } return -1; } public int IndexOf(String value) { return IndexOf(value, StringComparison.CurrentCulture); } public int IndexOf(String value, int startIndex, int count) { if (startIndex < 0 || startIndex > this.Length) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (count < 0 || count > this.Length - startIndex) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); } return IndexOf(value, startIndex, count, StringComparison.CurrentCulture); } public int IndexOf(String value, int startIndex) { return IndexOf(value, startIndex, StringComparison.CurrentCulture); } public int IndexOf(String value, StringComparison comparisonType) { return IndexOf(value, 0, this.Length, comparisonType); } public int IndexOf(String value, int startIndex, StringComparison comparisonType) { return IndexOf(value, startIndex, this.Length - startIndex, comparisonType); } public int IndexOf(String value, int startIndex, int count, StringComparison comparisonType) { // Validate inputs if (value == null) throw new ArgumentNullException("value"); if (startIndex < 0 || startIndex > this.Length) throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); if (count < 0 || startIndex > this.Length - count) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); switch (comparisonType) { case StringComparison.CurrentCulture: return FormatProvider.IndexOf(this, value, startIndex, count); case StringComparison.CurrentCultureIgnoreCase: return FormatProvider.IndexOfIgnoreCase(this, value, startIndex, count); case StringComparison.Ordinal: return FormatProvider.OrdinalIndexOf(this, value, startIndex, count); case StringComparison.OrdinalIgnoreCase: return FormatProvider.OrdinalIndexOfIgnoreCase(this, value, startIndex, count); default: throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType"); } } // Returns the index of the last occurrence of a specified character in the current instance. // The search starts at startIndex and runs backwards to startIndex - count + 1. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // public int LastIndexOf(char value) { return LastIndexOf(value, this.Length - 1, this.Length); } public int LastIndexOf(char value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1); } public unsafe int LastIndexOf(char value, int startIndex, int count) { if (Length == 0) return -1; if (startIndex < 0 || startIndex >= Length) throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); if (count < 0 || count - 1 > startIndex) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; //We search [startIndex..EndIndex] while (count >= 4) { if (*pCh == value) goto ReturnIndex; if (*(pCh - 1) == value) goto ReturnIndex1; if (*(pCh - 2) == value) goto ReturnIndex2; if (*(pCh - 3) == value) goto ReturnIndex3; count -= 4; pCh -= 4; } while (count > 0) { if (*pCh == value) goto ReturnIndex; count--; pCh--; } return -1; ReturnIndex3: pCh--; ReturnIndex2: pCh--; ReturnIndex1: pCh--; ReturnIndex: return (int)(pCh - pChars); } } // Returns the index of the last occurrence of any specified character in the current instance. // The search starts at startIndex and runs backwards to startIndex - count + 1. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // //ForceInline ... Jit can't recognize String.get_Length to determine that this is "fluff" public int LastIndexOfAny(char[] anyOf) { return LastIndexOfAny(anyOf, this.Length - 1, this.Length); } //ForceInline ... Jit can't recognize String.get_Length to determine that this is "fluff" public int LastIndexOfAny(char[] anyOf, int startIndex) { return LastIndexOfAny(anyOf, startIndex, startIndex + 1); } public unsafe int LastIndexOfAny(char[] anyOf, int startIndex, int count) { if (anyOf == null) throw new ArgumentNullException("anyOf"); if (Length == 0) return -1; if ((startIndex < 0) || (startIndex >= Length)) throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); if ((count < 0) || ((count - 1) > startIndex)) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); } // use probabilistic map, see InitializeProbabilisticMap uint* charMap = stackalloc uint[PROBABILISTICMAP_SIZE]; InitializeProbabilisticMap(charMap, anyOf); fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; for (int i = 0; i < count; i++) { char thisChar = *pCh--; if (ProbablyContains(charMap, thisChar)) if (ArrayContains(thisChar, anyOf) >= 0) return startIndex - i; } } return -1; } // Returns the index of the last occurrence of any character in value in the current instance. // The search starts at startIndex and runs backwards to startIndex - count + 1. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // public int LastIndexOf(String value) { return LastIndexOf(value, this.Length - 1, this.Length, StringComparison.CurrentCulture); } public int LastIndexOf(String value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1, StringComparison.CurrentCulture); } public int LastIndexOf(String value, int startIndex, int count) { if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); } return LastIndexOf(value, startIndex, count, StringComparison.CurrentCulture); } public int LastIndexOf(String value, StringComparison comparisonType) { return LastIndexOf(value, this.Length - 1, this.Length, comparisonType); } public int LastIndexOf(String value, int startIndex, StringComparison comparisonType) { return LastIndexOf(value, startIndex, startIndex + 1, comparisonType); } public int LastIndexOf(String value, int startIndex, int count, StringComparison comparisonType) { if (value == null) throw new ArgumentNullException("value"); // Special case for 0 length input strings if (this.Length == 0 && (startIndex == -1 || startIndex == 0)) return (value.Length == 0) ? 0 : -1; // Now after handling empty strings, make sure we're not out of range if (startIndex < 0 || startIndex > this.Length) throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); // Make sure that we allow startIndex == this.Length if (startIndex == this.Length) { startIndex--; if (count > 0) count--; } // If we are looking for nothing, just return 0 if (value.Length == 0 && count >= 0 && startIndex - count + 1 >= 0) return startIndex; // 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); switch (comparisonType) { case StringComparison.CurrentCulture: return FormatProvider.LastIndexOf(this, value, startIndex, count); case StringComparison.CurrentCultureIgnoreCase: return FormatProvider.LastIndexOfIgnoreCase(this, value, startIndex, count); case StringComparison.Ordinal: return FormatProvider.OrdinalLastIndexOf(this, value, startIndex, count); case StringComparison.OrdinalIgnoreCase: return FormatProvider.OrdinalLastIndexOfIgnoreCase(this, value, startIndex, count); default: throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType"); } } } }
using UnityEngine; using System.Collections; using CubeWorld.Gameplay; using CubeWorld.Configuration; public class MainMenu { private GameManagerUnity gameManagerUnity; public MainMenu(GameManagerUnity gameManagerUnity) { this.gameManagerUnity = gameManagerUnity; } public enum MainMenuState { NORMAL, GENERATOR, OPTIONS, JOIN_MULTIPLAYER, #if !UNITY_WEBPLAYER LOAD, SAVE, #endif ABOUT } public MainMenuState state = MainMenuState.NORMAL; public void Draw() { MenuSystem.useKeyboard = false; switch (state) { case MainMenuState.NORMAL: DrawMenuNormal(); break; case MainMenuState.GENERATOR: DrawGenerator(); break; case MainMenuState.OPTIONS: DrawOptions(); break; case MainMenuState.ABOUT: DrawMenuAbout(); break; case MainMenuState.JOIN_MULTIPLAYER: DrawJoinMultiplayer(); break; #if !UNITY_WEBPLAYER case MainMenuState.LOAD: DrawMenuLoadSave(true); break; case MainMenuState.SAVE: DrawMenuLoadSave(false); break; #endif } } public void DrawPause() { MenuSystem.useKeyboard = false; switch (state) { case MainMenuState.NORMAL: DrawMenuPause(); break; case MainMenuState.OPTIONS: DrawOptions(); break; #if !UNITY_WEBPLAYER case MainMenuState.LOAD: DrawMenuLoadSave(true); break; case MainMenuState.SAVE: DrawMenuLoadSave(false); break; #endif } } #if !UNITY_WEBPLAYER void DrawMenuLoadSave(bool load) { if (load) MenuSystem.BeginMenu("Load"); else MenuSystem.BeginMenu("Save"); for (int i = 0; i < 5; i++) { System.DateTime fileDateTime = WorldManagerUnity.GetWorldFileInfo(i); if (fileDateTime != System.DateTime.MinValue) { string prefix; if (load) prefix = "Load World "; else prefix = "Overwrite World"; MenuSystem.Button(prefix + (i + 1).ToString() + " [ " + fileDateTime.ToString() + " ]", delegate() { if (load) { gameManagerUnity.worldManagerUnity.LoadWorld(i); state = MainMenuState.NORMAL; } else { gameManagerUnity.worldManagerUnity.SaveWorld(i); state = MainMenuState.NORMAL; } } ); } else { MenuSystem.Button("-- Empty Slot --", delegate() { if (load == false) { gameManagerUnity.worldManagerUnity.SaveWorld(i); state = MainMenuState.NORMAL; } } ); } } MenuSystem.LastButton("Return", delegate() { state = MainMenuState.NORMAL; } ); MenuSystem.EndMenu(); } #endif private CubeWorld.Configuration.Config lastConfig; void DrawMenuPause() { MenuSystem.BeginMenu("Pause"); if (lastConfig != null) { MenuSystem.Button("Re-create Random World", delegate() { gameManagerUnity.worldManagerUnity.CreateRandomWorld(lastConfig); } ); } #if !UNITY_WEBPLAYER MenuSystem.Button("Save World", delegate() { state = MainMenuState.SAVE; } ); #endif MenuSystem.Button("Options", delegate() { state = MainMenuState.OPTIONS; } ); MenuSystem.Button("Exit to Main Menu", delegate() { gameManagerUnity.ReturnToMainMenu(); } ); MenuSystem.LastButton("Return to Game", delegate() { gameManagerUnity.Unpause(); } ); MenuSystem.EndMenu(); } void DrawMenuNormal() { MenuSystem.BeginMenu("Main Menu"); MenuSystem.Button("Create Random World", delegate() { state = MainMenuState.GENERATOR; } ); #if !UNITY_WEBPLAYER MenuSystem.Button("Load Saved World", delegate() { state = MainMenuState.LOAD; } ); #endif MenuSystem.Button("Join Multiplayer", delegate() { state = MainMenuState.JOIN_MULTIPLAYER; } ); MenuSystem.Button("Options", delegate() { state = MainMenuState.OPTIONS; } ); MenuSystem.Button("About", delegate() { state = MainMenuState.ABOUT; } ); if (Application.platform != RuntimePlatform.WebGLPlayer && Application.isEditor == false) { MenuSystem.LastButton("Exit", delegate() { Application.Quit(); } ); } MenuSystem.EndMenu(); } public const string CubeworldWebServerServerList = "http://cubeworldweb.appspot.com/list"; public const string CubeworldWebServerServerRegister = "http://cubeworldweb.appspot.com/register?owner={owner}&description={description}&port={port}"; private WWW wwwRequest; private string[] servers; void DrawJoinMultiplayer() { MenuSystem.BeginMenu("Join Multiplayer"); if (wwwRequest == null && servers == null) wwwRequest = new WWW(CubeworldWebServerServerList); if (servers == null && wwwRequest != null && wwwRequest.isDone) servers = wwwRequest.text.Split(';'); if (wwwRequest != null && wwwRequest.isDone) { foreach (string s in servers) { string[] ss = s.Split(','); if (ss.Length >= 2) { MenuSystem.Button("Join [" + ss[0] + ":" + ss[1] + "]", delegate() { gameManagerUnity.worldManagerUnity.JoinMultiplayerGame(ss[0], System.Int32.Parse(ss[1])); availableConfigurations = null; wwwRequest = null; servers = null; state = MainMenuState.NORMAL; } ); } } MenuSystem.Button("Refresh List", delegate() { wwwRequest = null; servers = null; } ); } else { MenuSystem.TextField("Waiting data from server.."); } MenuSystem.LastButton("Back", delegate() { wwwRequest = null; servers = null; state = MainMenuState.NORMAL; } ); MenuSystem.EndMenu(); } void DrawOptions() { MenuSystem.BeginMenu("Options"); MenuSystem.Button("Draw Distance: " + CubeWorldPlayerPreferences.farClipPlanes[CubeWorldPlayerPreferences.viewDistance], delegate() { CubeWorldPlayerPreferences.viewDistance = (CubeWorldPlayerPreferences.viewDistance + 1) % CubeWorldPlayerPreferences.farClipPlanes.Length; if (gameManagerUnity.playerUnity) gameManagerUnity.playerUnity.mainCamera.farClipPlane = CubeWorldPlayerPreferences.farClipPlanes[CubeWorldPlayerPreferences.viewDistance]; } ); MenuSystem.Button("Show Help: " + CubeWorldPlayerPreferences.showHelp, delegate() { CubeWorldPlayerPreferences.showHelp = !CubeWorldPlayerPreferences.showHelp; } ); MenuSystem.Button("Show FPS: " + CubeWorldPlayerPreferences.showFPS, delegate() { CubeWorldPlayerPreferences.showFPS = !CubeWorldPlayerPreferences.showFPS; } ); MenuSystem.Button("Show Engine Stats: " + CubeWorldPlayerPreferences.showEngineStats, delegate() { CubeWorldPlayerPreferences.showEngineStats = !CubeWorldPlayerPreferences.showEngineStats; } ); MenuSystem.Button("Visible Strategy: " + System.Enum.GetName(typeof(SectorManagerUnity.VisibleStrategy), CubeWorldPlayerPreferences.visibleStrategy), delegate() { if (System.Enum.IsDefined(typeof(SectorManagerUnity.VisibleStrategy), (int)CubeWorldPlayerPreferences.visibleStrategy + 1)) { CubeWorldPlayerPreferences.visibleStrategy = CubeWorldPlayerPreferences.visibleStrategy + 1; } else { CubeWorldPlayerPreferences.visibleStrategy = 0; } } ); MenuSystem.LastButton("Back", delegate() { CubeWorldPlayerPreferences.StorePreferences(); gameManagerUnity.PreferencesUpdated(); state = MainMenuState.NORMAL; } ); MenuSystem.EndMenu(); } private AvailableConfigurations availableConfigurations; private int currentSizeOffset = 0; private int currentGeneratorOffset = 0; private int currentDayInfoOffset = 0; private int currentGameplayOffset = 0; #if !UNITY_WEBPLAYER private bool multiplayer = false; #endif void DrawGenerator() { if (availableConfigurations == null) { availableConfigurations = GameManagerUnity.LoadConfiguration(); currentDayInfoOffset = 0; currentGeneratorOffset = 0; currentSizeOffset = 0; currentGameplayOffset = 0; } MenuSystem.BeginMenu("Random World Generator"); MenuSystem.Button("Gameplay: " + GameplayFactory.AvailableGameplays[currentGameplayOffset].name, delegate() { currentGameplayOffset = (currentGameplayOffset + 1) % GameplayFactory.AvailableGameplays.Length; } ); MenuSystem.Button("World Size: " + availableConfigurations.worldSizes[currentSizeOffset].name, delegate() { currentSizeOffset = (currentSizeOffset + 1) % availableConfigurations.worldSizes.Length; } ); MenuSystem.Button("Day Length: " + availableConfigurations.dayInfos[currentDayInfoOffset].name, delegate() { currentDayInfoOffset = (currentDayInfoOffset + 1) % availableConfigurations.dayInfos.Length; } ); if (GameplayFactory.AvailableGameplays[currentGameplayOffset].hasCustomGenerator == false) { MenuSystem.Button("Generator: " + availableConfigurations.worldGenerators[currentGeneratorOffset].name, delegate() { currentGeneratorOffset = (currentGeneratorOffset + 1) % availableConfigurations.worldGenerators.Length; } ); } #if !UNITY_WEBPLAYER MenuSystem.Button("Host Multiplayer: " + (multiplayer ? "Yes" : "No") , delegate() { multiplayer = !multiplayer; } ); #endif MenuSystem.LastButton("Generate!", delegate() { lastConfig = new CubeWorld.Configuration.Config(); lastConfig.tileDefinitions = availableConfigurations.tileDefinitions; lastConfig.itemDefinitions = availableConfigurations.itemDefinitions; lastConfig.avatarDefinitions = availableConfigurations.avatarDefinitions; lastConfig.dayInfo = availableConfigurations.dayInfos[currentDayInfoOffset]; lastConfig.worldGenerator = availableConfigurations.worldGenerators[currentGeneratorOffset]; lastConfig.worldSize = availableConfigurations.worldSizes[currentSizeOffset]; lastConfig.extraMaterials = availableConfigurations.extraMaterials; lastConfig.gameplay = GameplayFactory.AvailableGameplays[currentGameplayOffset]; #if !UNITY_WEBPLAYER if (multiplayer) { MultiplayerServerGameplay multiplayerServerGameplay = new MultiplayerServerGameplay(lastConfig.gameplay.gameplay, true); GameplayDefinition g = new GameplayDefinition("", "", multiplayerServerGameplay, false); lastConfig.gameplay = g; gameManagerUnity.RegisterInWebServer(); } #endif gameManagerUnity.worldManagerUnity.CreateRandomWorld(lastConfig); availableConfigurations = null; state = MainMenuState.NORMAL; } ); MenuSystem.EndMenu(); } void DrawMenuAbout() { MenuSystem.BeginMenu("Author"); GUI.TextArea(new Rect(10, 40 + 30 * 0, 380, 260), "Work In Progress by Federico D'Angelo (lawebdefederico@gmail.com)"); MenuSystem.LastButton("Back", delegate() { state = MainMenuState.NORMAL; }); MenuSystem.EndMenu(); } public void DrawGeneratingProgress(string description, int progress) { Rect sbPosition = new Rect(40, Screen.height / 2 - 20, Screen.width - 80, 40); GUI.HorizontalScrollbar(sbPosition, 0, progress, 0, 100); Rect dPosition = new Rect(Screen.width / 2 - 200, sbPosition.yMax + 10, 400, 25); GUI.Box(dPosition, description); } }
/*************************************************************************** * ProfileManager.cs * * Copyright (C) 2006 Novell, Inc. * Written by Aaron Bockover <aaron@abock.org> ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * 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.Xml; using System.Collections; using System.Collections.Generic; namespace Banshee.AudioProfiles { public class TestProfileArgs : EventArgs { private bool profile_available = true; private Profile profile; public TestProfileArgs(Profile profile) { this.profile = profile; } public Profile Profile { get { return profile; } } public bool ProfileAvailable { get { return profile_available; } set { profile_available = value; } } } public delegate void TestProfileHandler(object o, TestProfileArgs args); public class ProfileManager : IEnumerable<Profile> { private static System.Globalization.CultureInfo culture_info = new System.Globalization.CultureInfo("en-US"); internal static System.Globalization.CultureInfo CultureInfo { get { return culture_info; } } private XmlDocument document; private List<Profile> profiles = new List<Profile>(); private Dictionary<string, PipelineVariable> preset_variables = new Dictionary<string, PipelineVariable>(); public event TestProfileHandler TestProfile; public ProfileManager(string path) { if(File.Exists(path)) { LoadFromFile(path); } else if(Directory.Exists(path)) { string base_file = Path.Combine(path, "base.xml"); if(File.Exists(base_file)) { LoadFromFile(base_file); } foreach(string file in Directory.GetFiles(path, "*.xml")) { if(Path.GetFileName(file) != "base.xml") { LoadFromFile(file); } } } } private void LoadFromFile(string path) { document = new XmlDocument(); try { document.Load(path); Load(); } catch(Exception e) { Console.WriteLine("Could not load profile: {0}\n{1}", path, e); } document = null; } private void Load() { LoadPresetVariables(document.DocumentElement.SelectSingleNode("/audio-profiles/preset-variables")); LoadProfiles(document.DocumentElement.SelectSingleNode("/audio-profiles/profiles")); } private void LoadPresetVariables(XmlNode node) { if(node == null) { return; } foreach(XmlNode variable_node in node.SelectNodes("variable")) { try { PipelineVariable variable = new PipelineVariable(variable_node); if(!preset_variables.ContainsKey(variable.ID)) { preset_variables.Add(variable.ID, variable); } } catch { } } } private void LoadProfiles(XmlNode node) { if(node == null) { return; } foreach(XmlNode profile_node in node.SelectNodes("profile")) { try { profiles.Add(new Profile(this, profile_node)); } catch(Exception e) { Console.WriteLine(e); } } } public void Add(Profile profile) { profiles.Add(profile); } public void Remove(Profile profile) { profiles.Remove(profile); } public PipelineVariable GetPresetPipelineVariableById(string id) { if(id == null) { throw new ArgumentNullException("id"); } return preset_variables[id]; } protected virtual bool OnTestProfile(Profile profile) { TestProfileHandler handler = TestProfile; if(handler == null) { return true; } TestProfileArgs args = new TestProfileArgs(profile); handler(this, args); return args.ProfileAvailable; } public IEnumerable<Profile> GetAvailableProfiles() { foreach(Profile profile in this) { if(profile.Available == null) { profile.Available = OnTestProfile(profile); } if(profile.Available == true) { yield return profile; } } } public Profile GetConfiguredActiveProfile(string id) { return ProfileConfiguration.LoadActiveProfile(this, id); } public Profile GetConfiguredActiveProfile(string id, string [] mimetypes) { Profile profile = GetConfiguredActiveProfile(id); if(profile != null) { return profile; } foreach(string mimetype in mimetypes) { profile = GetProfileForMimeType(mimetype); if(profile != null) { return profile; } } return null; } public void TestAll() { foreach(Profile profile in this) { profile.Available = OnTestProfile(profile); } } public Profile GetProfileForMimeType(string mimetype) { foreach(Profile profile in GetAvailableProfiles()) { if(profile.HasMimeType(mimetype)) { return profile; } } return null; } public IEnumerator<Profile> GetEnumerator() { return profiles.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return profiles.GetEnumerator(); } public int ProfileCount { get { return profiles.Count; } } public int AvailableProfileCount { get { int count = 0; foreach(Profile profile in GetAvailableProfiles()) { count++; } return count; } } public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append("Preset Pipeline Variables:\n\n"); foreach(PipelineVariable variable in preset_variables.Values) { builder.Append(variable); builder.Append("\n"); } builder.Append("Profiles:\n\n"); foreach(Profile profile in profiles) { builder.Append(profile); builder.Append("\n\n"); } return builder.ToString().Trim(); } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Xml; using System.IO; public class DialogueScript : MonoBehaviour { public TextAsset dialogue; private XmlNode texttoshow; public Text dialogs; public Image characterpic; public GameObject dialarrow; public Sprite[] chara1; public Sprite[] chara2; public Sprite chara3; public Sprite chara4; public Sprite chara5; public Sprite[] chara6; public Sprite[] chara7; public Sprite chara8; public Sprite blankchara; public Image textbox; private string charaname; private RaycastHit hit; private RaycastHit hit2; private bool textcomplete = false; private bool istalking = false; private bool lookatme = false; public AudioSource beepsound; [SerializeField]AudioSource VoiceSource; public AudioClip[] voices; [SerializeField] AudioClip Nextsound; public static string NPCname; public static bool cantalk; private Vector3 center; private Vector3 side1; private Vector3 side2; public MovementController _mScript; public static int _seqNum; public bool hasDialogueEnd; //private bool faceme = false; public Text showname; public Animator charanim; public Animator serikAnim; public Animator achuraAnim; Animator talktarget; public virtual void Start() { textbox.enabled = false; dialogs.enabled = false; characterpic.enabled = false; showname.enabled = false; _mScript = GameObject.FindGameObjectWithTag("Player").GetComponent<MovementController>(); //charanim = GameObject.Find("Character").GetComponent<Animator>(); //serikAnim = GameObject.FindGameObjectWithTag("SerikGhost").GetComponent<Animator>(); } public virtual void Update() { center = transform.position + new Vector3(0, 0.5f, 0); side1 = center + new Vector3(0.2f, 0, 0); side2 = center + new Vector3(-0.2f, 0, 0); Debug.DrawRay(center, transform.forward * 5); Debug.DrawRay(side1, transform.forward * 5); Debug.DrawRay(side2, transform.forward * 5); // Debug.Log(hasDialogueEnd); if (Physics.Raycast(center, transform.forward, out hit, 1) && !istalking || Physics.Raycast(side1, transform.forward, out hit, 1) && !istalking || Physics.Raycast(side2, transform.forward, out hit, 1) && !istalking) { //Vector3 looktarget = transform.position; //looktarget.y = hit.collider.gameObject.transform.position.y; //Quaternion targetrot = Quaternion.LookRotation(looktarget, Vector3.up); //Quaternion newrot = Quaternion.Lerp(hit.collider.gameObject.transform.rotation, targetrot, Time.deltaTime * 2); //hit.collider.gameObject.transform.rotation = newrot; //Debug.Log("turning"); if (GamepadManager.buttonBDown && hit.collider.tag == "talking") { NPCname = hit.collider.name; string textData = dialogue.text; ParseDialogue(textData); if (hit.collider.name != "Grave") { Vector3 looktarget = transform.position; looktarget.y = hit.collider.gameObject.transform.position.y; hit.collider.gameObject.transform.LookAt(looktarget); talktarget = hit.collider.gameObject.GetComponent<Animator>(); talktarget.SetBool("Talking", true); } } } else if (GamepadManager.buttonBDown && textcomplete && istalking) { textcomplete = false; if(texttoshow.NextSibling != null) { //beepsound.PlayOneShot(beep); // hasDialogueEnd = false; string tempstr = Nextnode(texttoshow); StartCoroutine(Printletters(tempstr)); beepsound.PlayOneShot(Nextsound); // Debug.Log(_seqNum + "if"); _seqNum++; } else { if(talktarget != null) talktarget.SetBool("Talking", false); beepsound.PlayOneShot(Nextsound); CheckNames(); hasDialogueEnd = true; dialarrow.SetActive(false); textbox.enabled = false; dialogs.enabled = false; characterpic.enabled = false; showname.enabled = false; istalking = false; _mScript.bForcedMove = false; _seqNum = 0; StopAnim(); // Debug.Log(_seqNum + "else"); //charanim.SetBool("isTalking", false); //charanim.SetBool("bVictory", false); } } else if (GamepadManager.buttonBDown && !textcomplete && istalking) { textcomplete = true; } if (textcomplete) dialarrow.SetActive(true); else if (!textcomplete) dialarrow.SetActive(false); } public void ParseDialogue(string xmlData) { _mScript.bForcedMove = true; textbox.enabled = true; dialogs.enabled = true; characterpic.enabled = true; showname.enabled = true; istalking = true; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(new StringReader(xmlData)); string xmlPathPattern = "//Dialogue"; XmlNodeList myNodeList = xmlDoc.SelectNodes(xmlPathPattern); foreach (XmlNode node in myNodeList) { string tempstr = FirstDialogue(node); StartCoroutine(Printletters(tempstr)); } } private string FirstDialogue(XmlNode node) { XmlNode thenode = node[NPCname]; XmlNode newtext = thenode.FirstChild; Checkchara(newtext); texttoshow = newtext; return newtext.InnerXml; } private string Nextnode(XmlNode node) { XmlNode newtextnext = node.NextSibling; Checkchara(newtextnext); texttoshow = newtextnext; return newtextnext.InnerXml; } private void Checkchara(XmlNode node) { string character = node.Attributes["character"].Value; int expression = 0; int voice = 0; int achuraChat = 0; if(node.Attributes["expression"] != null) { int.TryParse(node.Attributes["expression"].Value, out expression); } if(node.Attributes["voice"] != null) { int.TryParse(node.Attributes["voice"].Value, out voice); } if (node.Attributes["animation"] != null) { int.TryParse(node.Attributes["animation"].Value, out achuraChat); } switch(character) { case "Gulnaz": characterpic.sprite = chara1[expression]; beepsound.Stop(); VoiceSource.PlayOneShot(voices[voice]); showname.text = character; charanim.SetBool("isTalking", true); // Invoke("StopAnim", 0.2f); break; case "Serik": characterpic.sprite = chara2[expression]; beepsound.Stop(); VoiceSource.PlayOneShot(voices[voice]); showname.text = character; break; case "Temir": characterpic.sprite = chara4; showname.text = character; break; case "Ruslan": characterpic.sprite = chara3; showname.text = character; break; case "Inzhu": characterpic.sprite = chara5; showname.text = character; break; case "GhostSerik": characterpic.sprite = chara6[expression]; beepsound.Stop(); VoiceSource.PlayOneShot(voices[voice]); //beepsound.PlayOneShot(voices[voice]); showname.text = "Serik"; serikAnim.SetBool("bSerikTalk", true); // Invoke("StopAnim", 0.2f); break; case "Archura": characterpic.sprite = chara7[expression]; beepsound.Stop(); VoiceSource.PlayOneShot(voices[voice]); //beepsound.PlayOneShot(voices[voice]); showname.text = "Archura"; achuraAnim.SetInteger("ArchuraChat", achuraChat); //Invoke("StopAnim", 0.2f); break; case "Pig": characterpic.sprite = chara8; showname.text = character; break; default: characterpic.sprite = blankchara; showname.text = null; break; } } IEnumerator Printletters(string sentence) { string str = ""; for (int i = 0; i < sentence.Length; i++) { str += sentence[i]; if (i == sentence.Length - 1) { // print("truuuuuueeeee"); textcomplete = true; } if(textcomplete == true) { str = sentence; i = sentence.Length; } dialogs.text = str; yield return new WaitForSeconds(0.04f); } } public virtual void CheckNames() { Debug.Log("checking and changing names"); } void StopAnim() { charanim.SetBool("isTalking", false); charanim.SetBool("bVictory", false); serikAnim.SetBool("bSerikTalk", false); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Collections.Generic; using System.Text; using NUnit.Framework; using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine; using Microsoft.Build.BuildEngine.Shared; namespace Microsoft.Build.UnitTests { [TestFixture] public class FileLogger_Tests { /// <summary> /// Basic test of the file logger. Writes to a log file in the temp directory. /// </summary> /// <owner>RGoel</owner> [Test] public void Basic() { FileLogger fileLogger = new FileLogger(); string logFile = Path.GetTempFileName(); fileLogger.Parameters = "verbosity=Normal;logfile=" + logFile; Project project = ObjectModelHelpers.CreateInMemoryProject(@" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`Build`> <Message Text=`Hello world from the FileLogger`/> </Target> </Project> ", fileLogger); project.Build(); project.ParentEngine.UnregisterAllLoggers(); string log = File.ReadAllText(logFile); Assertion.Assert("Log should have contained message", log.Contains("Hello world from the FileLogger")); File.Delete(logFile); } /// <summary> /// Basic case of logging a message to a file /// Verify it logs and encoding is ANSI /// </summary> [Test] public void BasicNoExistingFile() { string log = null; try { log = GetTempFilename(); SetUpFileLoggerAndLogMessage("logfile=" + log, new BuildMessageEventArgs("message here", null, null, MessageImportance.High)); VerifyFileContent(log, "message here"); // Verify no BOM (ANSI encoding) byte[] content = ReadRawBytes(log); Assertion.AssertEquals((byte)109, content[0]); // 'm' } finally { if (null != log) File.Delete(log); } } /// <summary> /// Invalid file should error nicely /// </summary> [Test] [ExpectedException(typeof(LoggerException))] public void InvalidFile() { string log = null; try { SetUpFileLoggerAndLogMessage("logfile=||invalid||", new BuildMessageEventArgs("message here", null, null, MessageImportance.High)); } finally { if (null != log) File.Delete(log); } } /// <summary> /// Specific verbosity overrides global verbosity /// </summary> [Test] public void SpecificVerbosity() { string log = null; try { log = GetTempFilename(); FileLogger fl = new FileLogger(); EventSource es = new EventSource(); fl.Parameters = "verbosity=diagnostic;logfile=" + log; // diagnostic specific setting fl.Verbosity = LoggerVerbosity.Quiet ; // quiet global setting fl.Initialize(es); fl.MessageHandler(null, new BuildMessageEventArgs("message here", null, null, MessageImportance.High)); fl.Shutdown(); // expect message to appear because diagnostic not quiet verbosity was used VerifyFileContent(log, "message here"); } finally { if (null != log) File.Delete(log); } } /// <summary> /// Test the short hand verbosity settings for the file logger /// </summary> [Test] public void ValidVerbosities() { string[] verbositySettings = new string[] {"Q", "quiet", "m", "minimal", "N", "normal", "d", "detailed", "diag", "DIAGNOSTIC"}; LoggerVerbosity[] verbosityEnumerations = new LoggerVerbosity[] {LoggerVerbosity.Quiet, LoggerVerbosity.Quiet, LoggerVerbosity.Minimal, LoggerVerbosity.Minimal, LoggerVerbosity.Normal, LoggerVerbosity.Normal, LoggerVerbosity.Detailed, LoggerVerbosity.Detailed, LoggerVerbosity.Diagnostic, LoggerVerbosity.Diagnostic}; for (int i = 0; i < verbositySettings.Length; i++) { FileLogger fl = new FileLogger(); fl.Parameters = "verbosity=" + verbositySettings[i] + ";"; EventSource es = new EventSource(); fl.Initialize(es); fl.Shutdown(); Assertion.AssertEquals(fl.Verbosity, verbosityEnumerations[i]); } // Do the same using the v shorthand for (int i = 0; i < verbositySettings.Length; i++) { FileLogger fl = new FileLogger(); fl.Parameters = "v=" + verbositySettings[i] + ";"; EventSource es = new EventSource(); fl.Initialize(es); fl.Shutdown(); Assertion.AssertEquals(fl.Verbosity, verbosityEnumerations[i]); } } /// <summary> /// Invalid verbosity setting /// </summary> [Test] [ExpectedException(typeof(LoggerException))] public void InvalidVerbosity() { FileLogger fl = new FileLogger(); fl.Parameters = "verbosity=CookiesAndCream"; EventSource es = new EventSource(); fl.Initialize(es); } /// <summary> /// Invalid encoding setting /// </summary> [Test] [ExpectedException(typeof(LoggerException))] public void InvalidEncoding() { string log = null; try { log = GetTempFilename(); FileLogger fl = new FileLogger(); EventSource es = new EventSource(); fl.Parameters = "encoding=foo;logfile=" + log; fl.Initialize(es); } finally { if (null != log) File.Delete(log); } } /// <summary> /// Valid encoding setting /// </summary> [Test] public void ValidEncoding() { string log = null; try { log = GetTempFilename(); SetUpFileLoggerAndLogMessage("encoding=utf-16;logfile=" + log, new BuildMessageEventArgs("message here", null, null, MessageImportance.High)); byte[] content = ReadRawBytes(log); // FF FE is the BOM for UTF16 Assertion.AssertEquals((byte)255, content[0]); Assertion.AssertEquals((byte)254, content[1]); } finally { if (null != log) File.Delete(log); } } /// <summary> /// Valid encoding setting /// </summary> [Test] public void ValidEncoding2() { string log = null; try { log = GetTempFilename(); SetUpFileLoggerAndLogMessage("encoding=utf-8;logfile=" + log, new BuildMessageEventArgs("message here", null, null, MessageImportance.High)); byte[] content = ReadRawBytes(log); // EF BB BF is the BOM for UTF8 Assertion.AssertEquals((byte)239, content[0]); Assertion.AssertEquals((byte)187, content[1]); Assertion.AssertEquals((byte)191, content[2]); } finally { if (null != log) File.Delete(log); } } /// <summary> /// Read the raw byte content of a file /// </summary> /// <param name="log"></param> /// <returns></returns> private byte[] ReadRawBytes(string log) { byte[] content; using (FileStream stream = new FileStream(log, FileMode.Open)) { content = new byte[stream.Length]; for (int i = 0; i < stream.Length; i++) { content[i] = (byte)stream.ReadByte(); } } return content; } /// <summary> /// Logging a message to a file that already exists should overwrite it /// </summary> [Test] public void BasicExistingFileNoAppend() { string log = null; try { log = GetTempFilename(); WriteContentToFile(log); SetUpFileLoggerAndLogMessage("logfile=" + log, new BuildMessageEventArgs("message here", null, null, MessageImportance.High)); VerifyFileContent(log, "message here"); } finally { if (null != log) File.Delete(log); } } /// <summary> /// Logging to a file that already exists, with "append" set, should append /// </summary> [Test] public void BasicExistingFileAppend() { string log = null; try { log = GetTempFilename(); WriteContentToFile(log); SetUpFileLoggerAndLogMessage("append;logfile=" + log, new BuildMessageEventArgs("message here", null, null, MessageImportance.High)); VerifyFileContent(log, "existing content\nmessage here"); } finally { if (null != log) File.Delete(log); } } /// <summary> /// Gets a filename for a nonexistent temporary file. /// </summary> /// <returns></returns> private string GetTempFilename() { string path = Path.GetTempFileName(); File.Delete(path); return path; } /// <summary> /// Writes a string to a file. /// </summary> /// <param name="log"></param> private void WriteContentToFile(string log) { using (StreamWriter sw = new StreamWriter(log)) { sw.WriteLine("existing content"); } } /// <summary> /// Creates a FileLogger, sets its parameters and initializes it, /// logs a message to it, and calls shutdown /// </summary> /// <param name="parameters"></param> /// <returns></returns> private void SetUpFileLoggerAndLogMessage(string parameters, BuildMessageEventArgs message) { FileLogger fl = new FileLogger(); EventSource es = new EventSource(); fl.Parameters = parameters; fl.Initialize(es); fl.MessageHandler(null, message); fl.Shutdown(); return; } /// <summary> /// Verifies that a file contains exactly the expected content. /// </summary> /// <param name="file"></param> /// <param name="expectedContent"></param> private void VerifyFileContent(string file, string expectedContent) { string actualContent; using (StreamReader sr = new StreamReader(file)) { actualContent = sr.ReadToEnd(); } string[] actualLines = actualContent.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); string[] expectedLines = expectedContent.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); Assertion.AssertEquals(expectedLines.Length, actualLines.Length); for (int i = 0; i < expectedLines.Length; i++) { Assertion.AssertEquals(expectedLines[i].Trim(), actualLines[i].Trim()); } } #region DistributedLogger /// <summary> /// Check the ability of the distributed logger to correctly tell its internal file logger where to log the file /// </summary> [Test] public void DistributedFileLoggerParameters() { DistributedFileLogger fileLogger = new DistributedFileLogger(); try { fileLogger.NodeId = 0; fileLogger.Initialize(new EventSource()); Assert.IsTrue(string.Compare(fileLogger.InternalFilelogger.Parameters, "ForceNoAlign;ShowEventId;ShowCommandLine;logfile=msbuild0.log;", StringComparison.OrdinalIgnoreCase) == 0); fileLogger.Shutdown(); fileLogger.NodeId = 3; fileLogger.Parameters = "logfile="+Path.Combine(Environment.CurrentDirectory,"mylogfile.log"); fileLogger.Initialize(new EventSource()); Assert.IsTrue(string.Compare(fileLogger.InternalFilelogger.Parameters, "ForceNoAlign;ShowEventId;ShowCommandLine;logfile=" + Path.Combine(Environment.CurrentDirectory, "mylogfile3.log") + ";", StringComparison.OrdinalIgnoreCase) == 0); fileLogger.Shutdown(); fileLogger.NodeId = 4; fileLogger.Parameters = "logfile=" + Path.Combine(Environment.CurrentDirectory, "mylogfile.log"); fileLogger.Initialize(new EventSource()); Assert.IsTrue(string.Compare(fileLogger.InternalFilelogger.Parameters, "ForceNoAlign;ShowEventId;ShowCommandLine;logfile=" + Path.Combine(Environment.CurrentDirectory, "mylogfile4.log") + ";", StringComparison.OrdinalIgnoreCase) == 0); fileLogger.Shutdown(); Directory.CreateDirectory(Path.Combine(Environment.CurrentDirectory, "tempura")); fileLogger.NodeId = 1; fileLogger.Parameters = "logfile=" + Path.Combine(Environment.CurrentDirectory, "tempura\\mylogfile.log"); fileLogger.Initialize(new EventSource()); Assert.IsTrue(string.Compare(fileLogger.InternalFilelogger.Parameters, "ForceNoAlign;ShowEventId;ShowCommandLine;logfile=" + Path.Combine(Environment.CurrentDirectory, "tempura\\mylogfile1.log") + ";", StringComparison.OrdinalIgnoreCase) == 0); fileLogger.Shutdown(); } finally { if(Directory.Exists(Path.Combine(Environment.CurrentDirectory, "tempura"))) { File.Delete(Path.Combine(Environment.CurrentDirectory, "tempura\\mylogfile1.log")); Directory.Delete(Path.Combine(Environment.CurrentDirectory, "tempura")); } File.Delete(Path.Combine(Environment.CurrentDirectory, "mylogfile0.log")); File.Delete(Path.Combine(Environment.CurrentDirectory, "mylogfile3.log")); File.Delete(Path.Combine(Environment.CurrentDirectory, "mylogfile4.log")); } } [Test] [ExpectedException(typeof(LoggerException))] public void DistributedLoggerBadPath() { DistributedFileLogger fileLogger = new DistributedFileLogger(); fileLogger.NodeId = 0; fileLogger.Initialize(new EventSource()); fileLogger.NodeId = 1; fileLogger.Parameters = "logfile=" + Path.Combine(Environment.CurrentDirectory, "\\DONTEXIST\\mylogfile.log"); fileLogger.Initialize(new EventSource()); Assert.IsTrue(string.Compare(fileLogger.InternalFilelogger.Parameters, ";ShowCommandLine;logfile=" + Path.Combine(Environment.CurrentDirectory, "\\DONTEXIST\\mylogfile2.log"), StringComparison.OrdinalIgnoreCase) == 0); } [Test] [ExpectedException(typeof(LoggerException))] public void DistributedLoggerNullEmpty() { DistributedFileLogger fileLogger = new DistributedFileLogger(); fileLogger.NodeId = 0; fileLogger.Initialize(new EventSource()); fileLogger.NodeId = 1; fileLogger.Parameters = "logfile="; fileLogger.Initialize(new EventSource()); Assert.Fail(); } #endregion } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace EduHub.Data.Entities { /// <summary> /// Standard and Last Pays /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class PEPS : EduHubEntity { #region Navigation Property Cache private PE Cache_CODE_PE; private PI Cache_PAYITEM_PI; private PS Cache_PAY_STEP_PS; private PF Cache_SUPER_FUND_PF; private PC Cache_TRCENTRE_PC; private KGLSUB Cache_SUBPROGRAM_KGLSUB; private KGLINIT Cache_INITIATIVE_KGLINIT; #endregion /// <inheritdoc /> public override DateTime? EntityLastModified { get { return LW_DATE; } } #region Field Properties /// <summary> /// Transaction ID (unique) /// </summary> public int TID { get; internal set; } /// <summary> /// Employee code /// [Uppercase Alphanumeric (10)] /// </summary> public string CODE { get; internal set; } /// <summary> /// Pay item code /// </summary> public short? PAYITEM { get; internal set; } /// <summary> /// Pay rate /// </summary> public double? TRCOST { get; internal set; } /// <summary> /// Hours /// </summary> public double? TRQTY { get; internal set; } /// <summary> /// Dollar value /// </summary> public decimal? TRAMT { get; internal set; } /// <summary> /// Detail /// [Alphanumeric (30)] /// </summary> public string TRDET { get; internal set; } /// <summary> /// S = Standard L = Last /// [Uppercase Alphanumeric (1)] /// </summary> public string FLAG { get; internal set; } /// <summary> /// No. of pay spans /// </summary> public short? TRPAYSPAN { get; internal set; } /// <summary> /// No. of tax spans /// </summary> public short? TRTAXSPAN { get; internal set; } /// <summary> /// Date of Pay /// </summary> public DateTime? TRDATE { get; internal set; } /// <summary> /// Timesheet Number /// [Alphanumeric (15)] /// </summary> public string TIMESHEET_NO { get; internal set; } /// <summary> /// Pay Rate Step /// </summary> public short? PAY_STEP { get; internal set; } /// <summary> /// Super fund key /// [Uppercase Alphanumeric (10)] /// </summary> public string SUPER_FUND { get; internal set; } /// <summary> /// Super fund member number /// [Uppercase Alphanumeric (20)] /// </summary> public string SUPER_MEMBER { get; internal set; } /// <summary> /// Percentage contribution /// </summary> public double? SUPER_PERCENT { get; internal set; } /// <summary> /// Cost Centre /// [Uppercase Alphanumeric (10)] /// </summary> public string TRCENTRE { get; internal set; } /// <summary> /// For every transaction there is a subprogram /// [Uppercase Alphanumeric (4)] /// </summary> public string SUBPROGRAM { get; internal set; } /// <summary> /// A subprogram always belongs to a program /// [Uppercase Alphanumeric (3)] /// </summary> public string GLPROGRAM { get; internal set; } /// <summary> /// Transaction might belong to an Initiative /// [Uppercase Alphanumeric (3)] /// </summary> public string INITIATIVE { get; internal set; } /// <summary> /// Holiday pay split precentage, Normal or LPA. Used for leave accruals /// </summary> public double? SPLIT_PERCENT { get; internal set; } /// <summary> /// Alter hours, used in PE31001 to assist with LPA/Annual split calc /// </summary> public double? ALTER_TRQTY { get; internal set; } /// <summary> /// Last write date /// </summary> public DateTime? LW_DATE { get; internal set; } /// <summary> /// Last write time /// </summary> public short? LW_TIME { get; internal set; } /// <summary> /// Last operator /// [Uppercase Alphanumeric (128)] /// </summary> public string LW_USER { get; internal set; } #endregion #region Navigation Properties /// <summary> /// PE (Employees) related entity by [PEPS.CODE]-&gt;[PE.PEKEY] /// Employee code /// </summary> public PE CODE_PE { get { if (Cache_CODE_PE == null) { Cache_CODE_PE = Context.PE.FindByPEKEY(CODE); } return Cache_CODE_PE; } } /// <summary> /// PI (Pay Items) related entity by [PEPS.PAYITEM]-&gt;[PI.PIKEY] /// Pay item code /// </summary> public PI PAYITEM_PI { get { if (PAYITEM == null) { return null; } if (Cache_PAYITEM_PI == null) { Cache_PAYITEM_PI = Context.PI.FindByPIKEY(PAYITEM.Value); } return Cache_PAYITEM_PI; } } /// <summary> /// PS (Pay Steps or Pay Class) related entity by [PEPS.PAY_STEP]-&gt;[PS.PSKEY] /// Pay Rate Step /// </summary> public PS PAY_STEP_PS { get { if (PAY_STEP == null) { return null; } if (Cache_PAY_STEP_PS == null) { Cache_PAY_STEP_PS = Context.PS.FindByPSKEY(PAY_STEP.Value); } return Cache_PAY_STEP_PS; } } /// <summary> /// PF (Superannuation Funds) related entity by [PEPS.SUPER_FUND]-&gt;[PF.PFKEY] /// Super fund key /// </summary> public PF SUPER_FUND_PF { get { if (SUPER_FUND == null) { return null; } if (Cache_SUPER_FUND_PF == null) { Cache_SUPER_FUND_PF = Context.PF.FindByPFKEY(SUPER_FUND); } return Cache_SUPER_FUND_PF; } } /// <summary> /// PC (Cost Centres) related entity by [PEPS.TRCENTRE]-&gt;[PC.PCKEY] /// Cost Centre /// </summary> public PC TRCENTRE_PC { get { if (TRCENTRE == null) { return null; } if (Cache_TRCENTRE_PC == null) { Cache_TRCENTRE_PC = Context.PC.FindByPCKEY(TRCENTRE); } return Cache_TRCENTRE_PC; } } /// <summary> /// KGLSUB (General Ledger Sub Programs) related entity by [PEPS.SUBPROGRAM]-&gt;[KGLSUB.SUBPROGRAM] /// For every transaction there is a subprogram /// </summary> public KGLSUB SUBPROGRAM_KGLSUB { get { if (SUBPROGRAM == null) { return null; } if (Cache_SUBPROGRAM_KGLSUB == null) { Cache_SUBPROGRAM_KGLSUB = Context.KGLSUB.FindBySUBPROGRAM(SUBPROGRAM); } return Cache_SUBPROGRAM_KGLSUB; } } /// <summary> /// KGLINIT (General Ledger Initiatives) related entity by [PEPS.INITIATIVE]-&gt;[KGLINIT.INITIATIVE] /// Transaction might belong to an Initiative /// </summary> public KGLINIT INITIATIVE_KGLINIT { get { if (INITIATIVE == null) { return null; } if (Cache_INITIATIVE_KGLINIT == null) { Cache_INITIATIVE_KGLINIT = Context.KGLINIT.FindByINITIATIVE(INITIATIVE); } return Cache_INITIATIVE_KGLINIT; } } #endregion } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.SqlClient; namespace WebApplication2 { /// <summary> /// Summary description for frmEmergencyProcedures. /// </summary> public partial class frmServiceEvents: System.Web.UI.Page { private static string strURL = System.Configuration.ConfigurationSettings.AppSettings["local_url"]; private static string strDB = System.Configuration.ConfigurationSettings.AppSettings["local_db"]; protected System.Web.UI.WebControls.Label Label2; public SqlConnection epsDbConn=new SqlConnection(strDB); protected void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if (Session["startForm"].ToString() == "frmMainProfileMgr") { if (Session["Section"].ToString() == "I") { lblTitle.Text = "Service Models"; lblProfilesName.Text = "Service Delivered: " + Session["ServiceName"].ToString(); DataGrid1.Columns[9].Visible = true; DataGrid1.Columns[2].Visible = false; DataGrid1.Columns[4].Visible = false; lblContent2.Text = "Listed below are various deliverables that may possibly result" + " from the service indicated above"; lblContent1.Text = ""; } else { DataGrid1.Columns[2].Visible = false; DataGrid1.Columns[4].Visible = false; if (Session["ProfileType"] == "Consumer") { lblTitle.Text = "Individual/Household Characteristics"; lblProfilesName.Text = "Type of Characteristic: " + Session["ProfilesName"].ToString(); lblServiceName.Text = "Stage: " + Session["ServiceName"].ToString(); DataGrid1.Columns[3].HeaderText = "Events"; lblContent2.Text = "Listed below are various Events that are" + " that are provided for the above stage."; lblContent1.Text = ""; btnAddE.Visible = false; } else if (Session["ProfileType"] == "Producer") { lblTitle.Text = "Business Models"; lblProfilesName.Text = "Business: " + Session["ProfilesName"].ToString(); lblServiceName.Text = "Service Delivered: " + Session["ServiceName"].ToString(); lblContent2.Text = "Listed below are various deliverables that form" + " part of the service indicated above" + " in various types of organizations." + " If this list does not include all deliverables resulting from this service, use the 'Add Deliverables' button to add to the list as needed."; lblContent1.Text = ""; } } /*else if (Session["startForm"].ToString() == "frmMainControl") { if (Session["CSEvents"].ToString() == "frmProfileServiceEvents") { DataGrid1.Columns[9].Visible=true; DataGrid1.Columns[2].Visible=false; DataGrid1.Columns[4].Visible=false; btnAddE.Visible=false; lblContent1.Text="Listed below are various deliverables that may result" + " as part of the service titled '" + Session["ServiceName"].ToString() + "' in similar organizations as yours." + " Select all such deliverables for your organization."; lblContent2.Visible=false; } else if (Session["CSEvents"].ToString() == "frmServiceTypes") { DataGrid1.Columns[9].Visible=false; DataGrid1.Columns[2].Visible=true; DataGrid1.Columns[4].Visible=true; btnAddE.Visible=true; lblContent1.Text="Listed below are various events that trigger" + " delivery of the service titled '" + Session["ServiceName"].ToString() + "' in various types of organizations." + " Review the list below to ensure that it includes all such events." + " Use the 'Add Events' button to add to the list as needed."; lblContent2.Text="There may be more than process involved in delivering" + " a given service in response to a given event." + " Thus, e.g. a service may require a 'Preparation Process'" + " that is undertaken in anticipation of a given type of event, followed by a 'Response Stage'" + " that is undertaken when an event actually occurs." + " Click on the button titled 'Procedures' to identify the Procedures" + " related to each event."; } }*/ } Load_Procedures(); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand); } #endregion private void Load_Procedures() { if (!IsPostBack) { loadData(); } } private void loadData () { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="wms_RetrieveSEvents"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@ServicesId",SqlDbType.Int); cmd.Parameters["@ServicesId"].Value=Session["ServicesId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter(cmd); da.Fill(ds,"SEvents"); Session["ds"] = ds; DataGrid1.DataSource=ds; DataGrid1.DataBind(); if (Session["CSEvents"].ToString() == "frmProfileServiceEvents") { refreshGrid1(); } else if (Session["CSEvents"].ToString() == "frmServiceTypes") { refreshGrid2(); } } private void refreshGrid1() { foreach (DataGridItem i in DataGrid1.Items) { CheckBox cb = (CheckBox)(i.Cells[9].FindControl("cbxSel")); SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.Text; cmd.CommandText="Select Id from ProfileServiceEvents" + " Where EventsId = " + i.Cells[1].Text + " and ProfileServicesId = " + Session["ProfileServicesId"].ToString(); cmd.Connection.Open(); if (cmd.ExecuteScalar() != null) { cb.Checked = true; cb.Enabled=false; } cmd.Connection.Close(); } } private void refreshGrid2() { foreach (DataGridItem i in DataGrid1.Items) { Button bt = (Button) (i.Cells[4].FindControl ("btnUpdate")); TextBox tb = (TextBox) (i.Cells[2].FindControl("txtSeq")); if (i.Cells[8].Text == "&nbsp;") { tb.Text="99"; } else tb.Text=i.Cells[8].Text; if (Session["OrgId"].ToString() == i.Cells[5].Text) { bt.Visible=true; } else { bt.Visible=false; i.Cells[5].Text = "Externally Mainained"; } } } private void updateGrid2() { foreach (DataGridItem i in DataGrid1.Items) { TextBox tb = (TextBox) (i.Cells[2].FindControl("txtSeq")); { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="wms_UpdateSESeqNo"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add("@Id", SqlDbType.Int); cmd.Parameters ["@Id"].Value=i.Cells[0].Text; cmd.Parameters.Add("@Seq", SqlDbType.Int); if (tb.Text != "") { cmd.Parameters["@Seq"].Value = Int32.Parse(tb.Text); } else { cmd.Parameters["@Seq"].Value = 0; } cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } } private void updateGrid1() { foreach (DataGridItem i in DataGrid1.Items) { CheckBox cb = (CheckBox)(i.Cells[9].FindControl("cbxSel")); if ((cb.Checked) & (cb.Enabled)) { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.Connection=this.epsDbConn; cmd.CommandText="wms_AddPSEvents"; cmd.Parameters.Add("@ProfileServicesId", SqlDbType.Int); cmd.Parameters ["@ProfileServicesId"].Value=Session["ProfileServicesId"].ToString(); cmd.Parameters.Add("@EventsId", SqlDbType.Int); cmd.Parameters ["@EventsId"].Value=i.Cells[1].Text; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } } protected void btnExit_Click(object sender, System.EventArgs e) { if (Session["CSEvents"].ToString() == "frmProfileServiceEvents") { updateGrid1(); } else if (Session["CSEvents"].ToString() == "frmServiceTypes") { updateGrid2(); } Exit(); } private void Exit() { Response.Redirect (strURL + Session["CSEvents"].ToString() + ".aspx?"); } private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { if (e.CommandName == "Procs") { Session["ServiceEventsId"]=e.Item.Cells[0].Text; Session["EventsName"]=e.Item.Cells[3].Text; Session["CSEProcs"]="frmServiceEvents"; Response.Redirect (strURL + "frmSEProcs.aspx?"); } else if (e.CommandName == "Update") { Session["CUpdEvent"]="frmServiceEvents"; Response.Redirect (strURL + "frmUpdEvent.aspx?" + "&btnAction=" + "Update" + "&Id=" + e.Item.Cells[1].Text + "&Name=" + e.Item.Cells[3].Text + "&OrgId=" + e.Item.Cells[5].Text + "&Desc=" + e.Item.Cells[6].Text + "&Vis=" + e.Item.Cells[7].Text ); } else if (e.CommandName == "Remove") { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="wms_DeleteServiceEvents"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@Id",SqlDbType.Int); cmd.Parameters["@Id"].Value=e.Item.Cells[0].Text; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); loadData(); } } protected void btnAddS_Click(object sender, System.EventArgs e) { updateGrid2(); Session["CEventsAll"]="frmServiceEvents"; Response.Redirect (strURL + "frmEventsAll.aspx?"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests { public class OrderedSubsetting : EnumerableTests { [Fact] public void FirstMultipleTruePredicateResult() { Assert.Equal(10, Enumerable.Range(1, 99).OrderBy(i => i).First(x => x % 10 == 0)); Assert.Equal(100, Enumerable.Range(1, 999).Concat(Enumerable.Range(1001, 3)).OrderByDescending(i => i.ToString().Length).ThenBy(i => i).First(x => x % 10 == 0)); } [Fact] public void FirstOrDefaultMultipleTruePredicateResult() { Assert.Equal(10, Enumerable.Range(1, 99).OrderBy(i => i).FirstOrDefault(x => x % 10 == 0)); Assert.Equal(100, Enumerable.Range(1, 999).Concat(Enumerable.Range(1001, 3)).OrderByDescending(i => i.ToString().Length).ThenBy(i => i).FirstOrDefault(x => x % 10 == 0)); } [Fact] public void FirstNoTruePredicateResult() { Assert.Throws<InvalidOperationException>(() => Enumerable.Range(1, 99).OrderBy(i => i).First(x => x > 1000)); } [Fact] public void FirstEmptyOrderedEnumerable() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().OrderBy(i => i).First()); Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().OrderBy(i => i).First(x => true)); } [Fact] public void FirstOrDefaultNoTruePredicateResult() { Assert.Equal(0, Enumerable.Range(1, 99).OrderBy(i => i).FirstOrDefault(x => x > 1000)); } [Fact] public void FirstOrDefaultEmptyOrderedEnumerable() { Assert.Equal(0, Enumerable.Empty<int>().OrderBy(i => i).FirstOrDefault()); Assert.Equal(0, Enumerable.Empty<int>().OrderBy(i => i).FirstOrDefault(x => true)); } [Fact] public void Last() { Assert.Equal(10, Enumerable.Range(1, 99).Reverse().OrderByDescending(i => i).Last(x => x % 10 == 0)); Assert.Equal(100, Enumerable.Range(1, 999).Concat(Enumerable.Range(1001, 3)).Reverse().OrderBy(i => i.ToString().Length).ThenByDescending(i => i).Last(x => x % 10 == 0)); Assert.Equal(10, Enumerable.Range(1, 10).OrderBy(i => 1).Last()); } [Fact] public void LastMultipleTruePredicateResult() { Assert.Equal(90, Enumerable.Range(1, 99).OrderBy(i => i).Last(x => x % 10 == 0)); Assert.Equal(90, Enumerable.Range(1, 999).Concat(Enumerable.Range(1001, 3)).OrderByDescending(i => i.ToString().Length).ThenBy(i => i).Last(x => x % 10 == 0)); } [Fact] public void LastOrDefaultMultipleTruePredicateResult() { Assert.Equal(90, Enumerable.Range(1, 99).OrderBy(i => i).LastOrDefault(x => x % 10 == 0)); Assert.Equal(90, Enumerable.Range(1, 999).Concat(Enumerable.Range(1001, 3)).OrderByDescending(i => i.ToString().Length).ThenBy(i => i).LastOrDefault(x => x % 10 == 0)); } [Fact] public void LastNoTruePredicateResult() { Assert.Throws<InvalidOperationException>(() => Enumerable.Range(1, 99).OrderBy(i => i).Last(x => x > 1000)); } [Fact] public void LastEmptyOrderedEnumerable() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().OrderBy(i => i).Last()); Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().OrderBy(i => i).Last(x => true)); } [Fact] public void LastOrDefaultNoTruePredicateResult() { Assert.Equal(0, Enumerable.Range(1, 99).OrderBy(i => i).LastOrDefault(x => x > 1000)); } [Fact] public void LastOrDefaultEmptyOrderedEnumerable() { Assert.Equal(0, Enumerable.Empty<int>().OrderBy(i => i).LastOrDefault()); Assert.Equal(0, Enumerable.Empty<int>().OrderBy(i => i).LastOrDefault(x => true)); } [Fact] public void Take() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(Enumerable.Range(0, 20), ordered.Take(20)); Assert.Equal(Enumerable.Range(0, 30), ordered.Take(50).Take(30)); Assert.Empty(ordered.Take(0)); Assert.Empty(ordered.Take(-1)); Assert.Empty(ordered.Take(int.MinValue)); Assert.Equal(new int[] { 0 }, ordered.Take(1)); Assert.Equal(Enumerable.Range(0, 100), ordered.Take(101)); Assert.Equal(Enumerable.Range(0, 100), ordered.Take(int.MaxValue)); Assert.Equal(Enumerable.Range(0, 100), ordered.Take(100)); Assert.Equal(Enumerable.Range(0, 99), ordered.Take(99)); Assert.Equal(Enumerable.Range(0, 100), ordered); } [Fact] public void TakeThenFirst() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(0, ordered.Take(20).First()); Assert.Equal(0, ordered.Take(20).FirstOrDefault()); } [Fact] public void TakeThenLast() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(19, ordered.Take(20).Last()); Assert.Equal(19, ordered.Take(20).LastOrDefault()); } [Fact] public void Skip() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(Enumerable.Range(20, 80), ordered.Skip(20)); Assert.Equal(Enumerable.Range(80, 20), ordered.Skip(50).Skip(30)); Assert.Equal(20, ordered.Skip(20).First()); Assert.Equal(20, ordered.Skip(20).FirstOrDefault()); Assert.Equal(Enumerable.Range(0, 100), ordered.Skip(0)); Assert.Equal(Enumerable.Range(0, 100), ordered.Skip(-1)); Assert.Equal(Enumerable.Range(0, 100), ordered.Skip(int.MinValue)); Assert.Equal(new int[] { 99 }, ordered.Skip(99)); Assert.Empty(ordered.Skip(101)); Assert.Empty(ordered.Skip(int.MaxValue)); Assert.Empty(ordered.Skip(100)); Assert.Equal(Enumerable.Range(1, 99), ordered.Skip(1)); Assert.Equal(Enumerable.Range(0, 100), ordered); } [Fact] public void SkipThenFirst() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(20, ordered.Skip(20).First()); Assert.Equal(20, ordered.Skip(20).FirstOrDefault()); } [Fact] public void SkipExcessiveThenFirstThrows() { Assert.Throws<InvalidOperationException>(() => Enumerable.Range(2, 10).Shuffle().OrderBy(i => i).Skip(20).First()); } [Fact] public void SkipExcessiveThenFirstOrDefault() { Assert.Equal(0, Enumerable.Range(2, 10).Shuffle().OrderBy(i => i).Skip(20).FirstOrDefault()); } [Fact] public void SkipExcessiveEmpty() { Assert.Empty(Enumerable.Range(0, 10).Shuffle().OrderBy(i => i).Skip(42)); } [Fact] public void SkipThenLast() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(99, ordered.Skip(20).Last()); Assert.Equal(99, ordered.Skip(20).LastOrDefault()); } [Fact] public void SkipExcessiveThenLastThrows() { Assert.Throws<InvalidOperationException>(() => Enumerable.Range(2, 10).Shuffle().OrderBy(i => i).Skip(20).Last()); } [Fact] public void SkipExcessiveThenLastOrDefault() { Assert.Equal(0, Enumerable.Range(2, 10).Shuffle().OrderBy(i => i).Skip(20).LastOrDefault()); } [Fact] public void SkipAndTake() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(Enumerable.Range(20, 60), ordered.Skip(20).Take(60)); Assert.Equal(Enumerable.Range(30, 20), ordered.Skip(20).Skip(10).Take(50).Take(20)); Assert.Equal(Enumerable.Range(30, 20), ordered.Skip(20).Skip(10).Take(20).Take(int.MaxValue)); Assert.Empty(ordered.Skip(10).Take(9).Take(0)); Assert.Empty(ordered.Skip(200).Take(10)); Assert.Empty(ordered.Skip(3).Take(0)); } [Fact] public void TakeAndSkip() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Empty(ordered.Skip(100).Take(20)); Assert.Equal(Enumerable.Range(10, 20), ordered.Take(30).Skip(10)); Assert.Equal(Enumerable.Range(10, 1), ordered.Take(11).Skip(10)); Assert.Empty(Enumerable.Range(0, int.MaxValue).Take(int.MaxValue).OrderBy(i => i).Skip(int.MaxValue - 4).Skip(15)); } [Fact] public void TakeThenTakeExcessive() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(ordered.Take(20), ordered.Take(20).Take(100)); } [Fact] public void TakeThenSkipAll() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Empty(ordered.Take(20).Skip(30)); } [Fact] public void SkipAndTakeThenFirst() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(20, ordered.Skip(20).Take(60).First()); Assert.Equal(20, ordered.Skip(20).Take(60).FirstOrDefault()); } [Fact] public void SkipAndTakeThenLast() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(79, ordered.Skip(20).Take(60).Last()); Assert.Equal(79, ordered.Skip(20).Take(60).LastOrDefault()); } [Fact] public void ElementAt() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(42, ordered.ElementAt(42)); Assert.Equal(93, ordered.ElementAt(93)); Assert.Equal(99, ordered.ElementAt(99)); Assert.Equal(42, ordered.ElementAtOrDefault(42)); Assert.Equal(93, ordered.ElementAtOrDefault(93)); Assert.Equal(99, ordered.ElementAtOrDefault(99)); Assert.Throws<ArgumentOutOfRangeException>(() => ordered.ElementAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => ordered.ElementAt(100)); Assert.Throws<ArgumentOutOfRangeException>(() => ordered.ElementAt(1000)); Assert.Throws<ArgumentOutOfRangeException>(() => ordered.ElementAt(int.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => ordered.ElementAt(int.MaxValue)); Assert.Equal(0, ordered.ElementAtOrDefault(-1)); Assert.Equal(0, ordered.ElementAtOrDefault(100)); Assert.Equal(0, ordered.ElementAtOrDefault(1000)); Assert.Equal(0, ordered.ElementAtOrDefault(int.MinValue)); Assert.Equal(0, ordered.ElementAtOrDefault(int.MaxValue)); var skipped = ordered.Skip(10).Take(80); Assert.Equal(52, skipped.ElementAt(42)); Assert.Equal(83, skipped.ElementAt(73)); Assert.Equal(89, skipped.ElementAt(79)); Assert.Equal(52, skipped.ElementAtOrDefault(42)); Assert.Equal(83, skipped.ElementAtOrDefault(73)); Assert.Equal(89, skipped.ElementAtOrDefault(79)); Assert.Throws<ArgumentOutOfRangeException>(() => skipped.ElementAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => skipped.ElementAt(80)); Assert.Throws<ArgumentOutOfRangeException>(() => skipped.ElementAt(1000)); Assert.Throws<ArgumentOutOfRangeException>(() => skipped.ElementAt(int.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => skipped.ElementAt(int.MaxValue)); Assert.Equal(0, skipped.ElementAtOrDefault(-1)); Assert.Equal(0, skipped.ElementAtOrDefault(80)); Assert.Equal(0, skipped.ElementAtOrDefault(1000)); Assert.Equal(0, skipped.ElementAtOrDefault(int.MinValue)); Assert.Equal(0, skipped.ElementAtOrDefault(int.MaxValue)); skipped = ordered.Skip(1000).Take(20); Assert.Throws<ArgumentOutOfRangeException>(() => skipped.ElementAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => skipped.ElementAt(0)); Assert.Throws<InvalidOperationException>(() => skipped.First()); Assert.Throws<InvalidOperationException>(() => skipped.Last()); Assert.Equal(0, skipped.ElementAtOrDefault(-1)); Assert.Equal(0, skipped.ElementAtOrDefault(0)); Assert.Equal(0, skipped.FirstOrDefault()); Assert.Equal(0, skipped.LastOrDefault()); } [Fact] public void ToArray() { Assert.Equal(Enumerable.Range(10, 20), Enumerable.Range(0, 100).Shuffle().OrderBy(i => i).Skip(10).Take(20).ToArray()); } [Fact] public void ToList() { Assert.Equal(Enumerable.Range(10, 20), Enumerable.Range(0, 100).Shuffle().OrderBy(i => i).Skip(10).Take(20).ToList()); } [Fact] public void Count() { Assert.Equal(20, Enumerable.Range(0, 100).Shuffle().OrderBy(i => i).Skip(10).Take(20).Count()); Assert.Equal(1, Enumerable.Range(0, 100).Shuffle().OrderBy(i => i).Take(2).Skip(1).Count()); } [Fact] public void SkipTakesOnlyOne() { Assert.Equal(new[] { 1 }, Enumerable.Range(1, 10).Shuffle().OrderBy(i => i).Take(1)); Assert.Equal(new[] { 2 }, Enumerable.Range(1, 10).Shuffle().OrderBy(i => i).Skip(1).Take(1)); Assert.Equal(new[] { 3 }, Enumerable.Range(1, 10).Shuffle().OrderBy(i => i).Take(3).Skip(2)); Assert.Equal(new[] { 1 }, Enumerable.Range(1, 10).Shuffle().OrderBy(i => i).Take(3).Take(1)); } [Fact] public void EmptyToArray() { Assert.Empty(Enumerable.Range(0, 100).Shuffle().OrderBy(i => i).Skip(100).ToArray()); } [Fact] public void EmptyToList() { Assert.Empty(Enumerable.Range(0, 100).Shuffle().OrderBy(i => i).Skip(100).ToList()); } [Fact] public void EmptyCount() { Assert.Equal(0, Enumerable.Range(0, 100).Shuffle().OrderBy(i => i).Skip(100).Count()); Assert.Equal(0, Enumerable.Range(0, 100).Shuffle().OrderBy(i => i).Take(0).Count()); } [Fact] public void AttemptedMoreArray() { Assert.Equal(Enumerable.Range(0, 20), Enumerable.Range(0, 20).Shuffle().OrderBy(i => i).Take(30).ToArray()); } [Fact] public void AttemptedMoreList() { Assert.Equal(Enumerable.Range(0, 20), Enumerable.Range(0, 20).Shuffle().OrderBy(i => i).Take(30).ToList()); } [Fact] public void AttemptedMoreCount() { Assert.Equal(20, Enumerable.Range(0, 20).Shuffle().OrderBy(i => i).Take(30).Count()); } [Fact] public void SingleElementToArray() { Assert.Equal(Enumerable.Repeat(10, 1), Enumerable.Range(0, 20).Shuffle().OrderBy(i => i).Skip(10).Take(1).ToArray()); } [Fact] public void SingleElementToList() { Assert.Equal(Enumerable.Repeat(10, 1), Enumerable.Range(0, 20).Shuffle().OrderBy(i => i).Skip(10).Take(1).ToList()); } [Fact] public void SingleElementCount() { Assert.Equal(1, Enumerable.Range(0, 20).Shuffle().OrderBy(i => i).Skip(10).Take(1).Count()); } [Fact] public void EnumeratorDoesntContinue() { var enumerator = NumberRangeGuaranteedNotCollectionType(0, 3).Shuffle().OrderBy(i => i).Skip(1).GetEnumerator(); while (enumerator.MoveNext()) { } Assert.False(enumerator.MoveNext()); } [Fact] public void Select() { Assert.Equal(new[] { 0, 2, 4, 6, 8 }, Enumerable.Range(-1, 8).Shuffle().OrderBy(i => i).Skip(1).Take(5).Select(i => i * 2)); } [Fact] public void SelectForcedToEnumeratorDoesntEnumerate() { var iterator = Enumerable.Range(-1, 8).Shuffle().OrderBy(i => i).Skip(1).Take(5).Select(i => i * 2); // Don't insist on this behaviour, but check it's correct if it happens var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void SelectElementAt() { var source = Enumerable.Range(0, 9).Shuffle().OrderBy(i => i).Skip(1).Take(5).Select(i => i * 2); Assert.Equal(6, source.ElementAt(2)); Assert.Equal(8, source.ElementAtOrDefault(3)); Assert.Equal(0, source.ElementAtOrDefault(8)); Assert.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(-2)); } [Fact] public void SelectFirst() { var source = Enumerable.Range(0, 9).Shuffle().OrderBy(i => i).Skip(1).Take(5).Select(i => i * 2); Assert.Equal(2, source.First()); Assert.Equal(2, source.FirstOrDefault()); source = source.Skip(20); Assert.Equal(0, source.FirstOrDefault()); Assert.Throws<InvalidOperationException>(() => source.First()); } [Fact] public void SelectLast() { var source = Enumerable.Range(0, 9).Shuffle().OrderBy(i => i).Skip(1).Take(5).Select(i => i * 2); Assert.Equal(10, source.Last()); Assert.Equal(10, source.LastOrDefault()); source = source.Skip(20); Assert.Equal(0, source.LastOrDefault()); Assert.Throws<InvalidOperationException>(() => source.Last()); } [Fact] public void SelectArray() { var source = Enumerable.Range(0, 9).Shuffle().OrderBy(i => i).Skip(1).Take(5).Select(i => i * 2); Assert.Equal(new[] { 2, 4, 6, 8, 10 }, source.ToArray()); } [Fact] public void SelectList() { var source = Enumerable.Range(0, 9).Shuffle().OrderBy(i => i).Skip(1).Take(5).Select(i => i * 2); Assert.Equal(new[] { 2, 4, 6, 8, 10 }, source.ToList()); } [Fact] public void SelectCount() { var source = Enumerable.Range(0, 9).Shuffle().OrderBy(i => i).Skip(1).Take(5).Select(i => i * 2); Assert.Equal(5, source.Count()); source = Enumerable.Range(0, 9).Shuffle().OrderBy(i => i).Skip(1).Take(1000).Select(i => i * 2); Assert.Equal(8, source.Count()); } [Fact] public void RunOnce() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); Assert.Equal(Enumerable.Range(30, 20), source.RunOnce().OrderBy(i => i).Skip(20).Skip(10).Take(50).Take(20)); Assert.Empty(source.RunOnce().OrderBy(i => i).Skip(10).Take(9).Take(0)); Assert.Equal(20, source.RunOnce().OrderBy(i => i).Skip(20).Take(60).First()); Assert.Equal(79, source.RunOnce().OrderBy(i => i).Skip(20).Take(60).Last()); Assert.Equal(93, source.RunOnce().OrderBy(i => i).ElementAt(93)); Assert.Equal(42, source.RunOnce().OrderBy(i => i).ElementAtOrDefault(42)); Assert.Equal(20, source.RunOnce().OrderBy(i => i).Skip(10).Take(20).Count()); Assert.Equal(1, source.RunOnce().OrderBy(i => i).Take(2).Skip(1).Count()); } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Archiver.Codecs { public class PurgeSegmentsRequestDecoder { public const ushort BLOCK_LENGTH = 32; public const ushort TEMPLATE_ID = 55; public const ushort SCHEMA_ID = 101; public const ushort SCHEMA_VERSION = 6; private PurgeSegmentsRequestDecoder _parentMessage; private IDirectBuffer _buffer; protected int _offset; protected int _limit; protected int _actingBlockLength; protected int _actingVersion; public PurgeSegmentsRequestDecoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public PurgeSegmentsRequestDecoder Wrap( IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { this._buffer = buffer; this._offset = offset; this._actingBlockLength = actingBlockLength; this._actingVersion = actingVersion; Limit(offset + actingBlockLength); return this; } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int ControlSessionIdId() { return 1; } public static int ControlSessionIdSinceVersion() { return 0; } public static int ControlSessionIdEncodingOffset() { return 0; } public static int ControlSessionIdEncodingLength() { return 8; } public static string ControlSessionIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long ControlSessionIdNullValue() { return -9223372036854775808L; } public static long ControlSessionIdMinValue() { return -9223372036854775807L; } public static long ControlSessionIdMaxValue() { return 9223372036854775807L; } public long ControlSessionId() { return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian); } public static int CorrelationIdId() { return 2; } public static int CorrelationIdSinceVersion() { return 0; } public static int CorrelationIdEncodingOffset() { return 8; } public static int CorrelationIdEncodingLength() { return 8; } public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public long CorrelationId() { return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian); } public static int RecordingIdId() { return 3; } public static int RecordingIdSinceVersion() { return 0; } public static int RecordingIdEncodingOffset() { return 16; } public static int RecordingIdEncodingLength() { return 8; } public static string RecordingIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long RecordingIdNullValue() { return -9223372036854775808L; } public static long RecordingIdMinValue() { return -9223372036854775807L; } public static long RecordingIdMaxValue() { return 9223372036854775807L; } public long RecordingId() { return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian); } public static int NewStartPositionId() { return 4; } public static int NewStartPositionSinceVersion() { return 0; } public static int NewStartPositionEncodingOffset() { return 24; } public static int NewStartPositionEncodingLength() { return 8; } public static string NewStartPositionMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long NewStartPositionNullValue() { return -9223372036854775808L; } public static long NewStartPositionMinValue() { return -9223372036854775807L; } public static long NewStartPositionMaxValue() { return 9223372036854775807L; } public long NewStartPosition() { return _buffer.GetLong(_offset + 24, ByteOrder.LittleEndian); } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { int originalLimit = Limit(); Limit(_offset + _actingBlockLength); builder.Append("[PurgeSegmentsRequest](sbeTemplateId="); builder.Append(TEMPLATE_ID); builder.Append("|sbeSchemaId="); builder.Append(SCHEMA_ID); builder.Append("|sbeSchemaVersion="); if (_parentMessage._actingVersion != SCHEMA_VERSION) { builder.Append(_parentMessage._actingVersion); builder.Append('/'); } builder.Append(SCHEMA_VERSION); builder.Append("|sbeBlockLength="); if (_actingBlockLength != BLOCK_LENGTH) { builder.Append(_actingBlockLength); builder.Append('/'); } builder.Append(BLOCK_LENGTH); builder.Append("):"); //Token{signal=BEGIN_FIELD, name='controlSessionId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("ControlSessionId="); builder.Append(ControlSessionId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("CorrelationId="); builder.Append(CorrelationId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='recordingId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("RecordingId="); builder.Append(RecordingId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='newStartPosition', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=24, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=24, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("NewStartPosition="); builder.Append(NewStartPosition()); Limit(originalLimit); return builder; } } }
#region Copyright & License // // Copyright 2001-2005 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using log4net.ObjectRenderer; using log4net.Core; using log4net.Util; namespace log4net.Repository.Hierarchy { #region LoggerCreationEvent /// <summary> /// Delegate used to handle logger creation event notifications. /// </summary> /// <param name="sender">The <see cref="Hierarchy"/> in which the <see cref="Logger"/> has been created.</param> /// <param name="e">The <see cref="LoggerCreationEventArgs"/> event args that hold the <see cref="Logger"/> instance that has been created.</param> /// <remarks> /// <para> /// Delegate used to handle logger creation event notifications. /// </para> /// </remarks> public delegate void LoggerCreationEventHandler(object sender, LoggerCreationEventArgs e); /// <summary> /// Provides data for the <see cref="Hierarchy.LoggerCreatedEvent"/> event. /// </summary> /// <remarks> /// <para> /// A <see cref="Hierarchy.LoggerCreatedEvent"/> event is raised every time a /// <see cref="Logger"/> is created. /// </para> /// </remarks> public class LoggerCreationEventArgs : EventArgs { /// <summary> /// The <see cref="Logger"/> created /// </summary> private Logger m_log; /// <summary> /// Constructor /// </summary> /// <param name="log">The <see cref="Logger"/> that has been created.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="LoggerCreationEventArgs" /> event argument /// class,with the specified <see cref="Logger"/>. /// </para> /// </remarks> public LoggerCreationEventArgs(Logger log) { m_log = log; } /// <summary> /// Gets the <see cref="Logger"/> that has been created. /// </summary> /// <value> /// The <see cref="Logger"/> that has been created. /// </value> /// <remarks> /// <para> /// The <see cref="Logger"/> that has been created. /// </para> /// </remarks> public Logger Logger { get { return m_log; } } } #endregion LoggerCreationEvent /// <summary> /// Hierarchical organization of loggers /// </summary> /// <remarks> /// <para> /// <i>The casual user should not have to deal with this class /// directly.</i> /// </para> /// <para> /// This class is specialized in retrieving loggers by name and /// also maintaining the logger hierarchy. Implements the /// <see cref="ILoggerRepository"/> interface. /// </para> /// <para> /// The structure of the logger hierarchy is maintained by the /// <see cref="GetLogger(string)"/> method. The hierarchy is such that children /// link to their parent but parents do not have any references to their /// children. Moreover, loggers can be instantiated in any order, in /// particular descendant before ancestor. /// </para> /// <para> /// In case a descendant is created before a particular ancestor, /// then it creates a provision node for the ancestor and adds itself /// to the provision node. Other descendants of the same ancestor add /// themselves to the previously created provision node. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public class Hierarchy : LoggerRepositorySkeleton, IBasicRepositoryConfigurator, IXmlRepositoryConfigurator { #region Public Events /// <summary> /// Event used to notify that a logger has been created. /// </summary> /// <remarks> /// <para> /// Event raised when a logger is created. /// </para> /// </remarks> public event LoggerCreationEventHandler LoggerCreatedEvent { add { m_loggerCreatedEvent += value; } remove { m_loggerCreatedEvent -= value; } } #endregion Public Events #region Public Instance Constructors /// <summary> /// Default constructor /// </summary> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="Hierarchy" /> class. /// </para> /// </remarks> public Hierarchy() : this(new DefaultLoggerFactory()) { } /// <summary> /// Construct with properties /// </summary> /// <param name="properties">The properties to pass to this repository.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="Hierarchy" /> class. /// </para> /// </remarks> public Hierarchy(PropertiesDictionary properties) : this(properties, new DefaultLoggerFactory()) { } /// <summary> /// Construct with a logger factory /// </summary> /// <param name="loggerFactory">The factory to use to create new logger instances.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="Hierarchy" /> class with /// the specified <see cref="ILoggerFactory" />. /// </para> /// </remarks> public Hierarchy(ILoggerFactory loggerFactory) : this(new PropertiesDictionary(), loggerFactory) { } /// <summary> /// Construct with properties and a logger factory /// </summary> /// <param name="properties">The properties to pass to this repository.</param> /// <param name="loggerFactory">The factory to use to create new logger instances.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="Hierarchy" /> class with /// the specified <see cref="ILoggerFactory" />. /// </para> /// </remarks> public Hierarchy(PropertiesDictionary properties, ILoggerFactory loggerFactory) : base(properties) { if (loggerFactory == null) { throw new ArgumentNullException("loggerFactory"); } m_defaultFactory = loggerFactory; m_ht = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); } #endregion Public Instance Constructors #region Public Instance Properties /// <summary> /// Has no appender warning been emitted /// </summary> /// <remarks> /// <para> /// Flag to indicate if we have already issued a warning /// about not having an appender warning. /// </para> /// </remarks> public bool EmittedNoAppenderWarning { get { return m_emittedNoAppenderWarning; } set { m_emittedNoAppenderWarning = value; } } /// <summary> /// Get the root of this hierarchy /// </summary> /// <remarks> /// <para> /// Get the root of this hierarchy. /// </para> /// </remarks> public Logger Root { get { if (m_root == null) { lock(this) { if (m_root == null) { // Create the root logger Logger root = m_defaultFactory.CreateLogger(null); root.Hierarchy = this; // Store root m_root = root; } } } return m_root; } } /// <summary> /// Gets or sets the default <see cref="ILoggerFactory" /> instance. /// </summary> /// <value>The default <see cref="ILoggerFactory" /></value> /// <remarks> /// <para> /// The logger factory is used to create logger instances. /// </para> /// </remarks> public ILoggerFactory LoggerFactory { get { return m_defaultFactory; } set { if (value == null) { throw new ArgumentNullException("value"); } m_defaultFactory = value; } } #endregion Public Instance Properties #region Override Implementation of LoggerRepositorySkeleton /// <summary> /// Test if a logger exists /// </summary> /// <param name="name">The name of the logger to lookup</param> /// <returns>The Logger object with the name specified</returns> /// <remarks> /// <para> /// Check if the named logger exists in the hierarchy. If so return /// its reference, otherwise returns <c>null</c>. /// </para> /// </remarks> override public ILogger Exists(string name) { if (name == null) { throw new ArgumentNullException("name"); } return m_ht[new LoggerKey(name)] as Logger; } /// <summary> /// Returns all the currently defined loggers in the hierarchy as an Array /// </summary> /// <returns>All the defined loggers</returns> /// <remarks> /// <para> /// Returns all the currently defined loggers in the hierarchy as an Array. /// The root logger is <b>not</b> included in the returned /// enumeration. /// </para> /// </remarks> override public ILogger[] GetCurrentLoggers() { // The accumulation in loggers is necessary because not all elements in // ht are Logger objects as there might be some ProvisionNodes // as well. System.Collections.ArrayList loggers = new System.Collections.ArrayList(m_ht.Count); // Iterate through m_ht values foreach(object node in m_ht.Values) { if (node is Logger) { loggers.Add(node); } } return (Logger[])loggers.ToArray(typeof(Logger)); } /// <summary> /// Return a new logger instance named as the first parameter using /// the default factory. /// </summary> /// <remarks> /// <para> /// Return a new logger instance named as the first parameter using /// the default factory. /// </para> /// <para> /// If a logger of that name already exists, then it will be /// returned. Otherwise, a new logger will be instantiated and /// then linked with its existing ancestors as well as children. /// </para> /// </remarks> /// <param name="name">The name of the logger to retrieve</param> /// <returns>The logger object with the name specified</returns> override public ILogger GetLogger(string name) { if (name == null) { throw new ArgumentNullException("name"); } return GetLogger(name, m_defaultFactory); } /// <summary> /// Shutting down a hierarchy will <i>safely</i> close and remove /// all appenders in all loggers including the root logger. /// </summary> /// <remarks> /// <para> /// Shutting down a hierarchy will <i>safely</i> close and remove /// all appenders in all loggers including the root logger. /// </para> /// <para> /// Some appenders need to be closed before the /// application exists. Otherwise, pending logging events might be /// lost. /// </para> /// <para> /// The <c>Shutdown</c> method is careful to close nested /// appenders before closing regular appenders. This is allows /// configurations where a regular appender is attached to a logger /// and again to a nested appender. /// </para> /// </remarks> override public void Shutdown() { LogLog.Debug("Hierarchy: Shutdown called on Hierarchy ["+this.Name+"]"); // begin by closing nested appenders Root.CloseNestedAppenders(); lock(m_ht) { ILogger[] currentLoggers = this.GetCurrentLoggers(); foreach(Logger logger in currentLoggers) { logger.CloseNestedAppenders(); } // then, remove all appenders Root.RemoveAllAppenders(); foreach(Logger logger in currentLoggers) { logger.RemoveAllAppenders(); } } base.Shutdown(); } /// <summary> /// Reset all values contained in this hierarchy instance to their default. /// </summary> /// <remarks> /// <para> /// Reset all values contained in this hierarchy instance to their /// default. This removes all appenders from all loggers, sets /// the level of all non-root loggers to <c>null</c>, /// sets their additivity flag to <c>true</c> and sets the level /// of the root logger to <see cref="Level.Debug"/>. Moreover, /// message disabling is set its default "off" value. /// </para> /// <para> /// Existing loggers are not removed. They are just reset. /// </para> /// <para> /// This method should be used sparingly and with care as it will /// block all logging until it is completed. /// </para> /// </remarks> override public void ResetConfiguration() { Root.Level = Level.Debug; Threshold = Level.All; // the synchronization is needed to prevent hashtable surprises lock(m_ht) { Shutdown(); // nested locks are OK foreach(Logger l in this.GetCurrentLoggers()) { l.Level = null; l.Additivity = true; } } base.ResetConfiguration(); // Notify listeners OnConfigurationChanged(null); } /// <summary> /// Log the logEvent through this hierarchy. /// </summary> /// <param name="logEvent">the event to log</param> /// <remarks> /// <para> /// This method should not normally be used to log. /// The <see cref="ILog"/> interface should be used /// for routine logging. This interface can be obtained /// using the <see cref="log4net.LogManager.GetLogger(string)"/> method. /// </para> /// <para> /// The <c>logEvent</c> is delivered to the appropriate logger and /// that logger is then responsible for logging the event. /// </para> /// </remarks> override public void Log(LoggingEvent logEvent) { if (logEvent == null) { throw new ArgumentNullException("logEvent"); } this.GetLogger(logEvent.LoggerName, m_defaultFactory).Log(logEvent); } /// <summary> /// Returns all the Appenders that are currently configured /// </summary> /// <returns>An array containing all the currently configured appenders</returns> /// <remarks> /// <para> /// Returns all the <see cref="log4net.Appender.IAppender"/> instances that are currently configured. /// All the loggers are searched for appenders. The appenders may also be containers /// for appenders and these are also searched for additional loggers. /// </para> /// <para> /// The list returned is unordered but does not contain duplicates. /// </para> /// </remarks> override public log4net.Appender.IAppender[] GetAppenders() { System.Collections.ArrayList appenderList = new System.Collections.ArrayList(); CollectAppenders(appenderList, Root); foreach(Logger logger in GetCurrentLoggers()) { CollectAppenders(appenderList, logger); } return (log4net.Appender.IAppender[])appenderList.ToArray(typeof(log4net.Appender.IAppender)); } #endregion Override Implementation of LoggerRepositorySkeleton /// <summary> /// Collect the appenders from an <see cref="IAppenderAttachable"/>. /// The appender may also be a container. /// </summary> /// <param name="appenderList"></param> /// <param name="appender"></param> private static void CollectAppender(System.Collections.ArrayList appenderList, log4net.Appender.IAppender appender) { if (!appenderList.Contains(appender)) { appenderList.Add(appender); IAppenderAttachable container = appender as IAppenderAttachable; if (container != null) { CollectAppenders(appenderList, container); } } } /// <summary> /// Collect the appenders from an <see cref="IAppenderAttachable"/> container /// </summary> /// <param name="appenderList"></param> /// <param name="container"></param> private static void CollectAppenders(System.Collections.ArrayList appenderList, IAppenderAttachable container) { foreach(log4net.Appender.IAppender appender in container.Appenders) { CollectAppender(appenderList, appender); } } #region Implementation of IBasicRepositoryConfigurator /// <summary> /// Initialize the log4net system using the specified appender /// </summary> /// <param name="appender">the appender to use to log all logging events</param> void IBasicRepositoryConfigurator.Configure(log4net.Appender.IAppender appender) { BasicRepositoryConfigure(appender); } /// <summary> /// Initialize the log4net system using the specified appender /// </summary> /// <param name="appender">the appender to use to log all logging events</param> /// <remarks> /// <para> /// This method provides the same functionality as the /// <see cref="IBasicRepositoryConfigurator.Configure"/> method implemented /// on this object, but it is protected and therefore can be called by subclasses. /// </para> /// </remarks> protected void BasicRepositoryConfigure(log4net.Appender.IAppender appender) { Root.AddAppender(appender); Configured = true; // Notify listeners OnConfigurationChanged(null); } #endregion Implementation of IBasicRepositoryConfigurator #region Implementation of IXmlRepositoryConfigurator /// <summary> /// Initialize the log4net system using the specified config /// </summary> /// <param name="element">the element containing the root of the config</param> void IXmlRepositoryConfigurator.Configure(System.Xml.XmlElement element) { XmlRepositoryConfigure(element); } /// <summary> /// Initialize the log4net system using the specified config /// </summary> /// <param name="element">the element containing the root of the config</param> /// <remarks> /// <para> /// This method provides the same functionality as the /// <see cref="IBasicRepositoryConfigurator.Configure"/> method implemented /// on this object, but it is protected and therefore can be called by subclasses. /// </para> /// </remarks> protected void XmlRepositoryConfigure(System.Xml.XmlElement element) { XmlHierarchyConfigurator config = new XmlHierarchyConfigurator(this); config.Configure(element); Configured = true; // Notify listeners OnConfigurationChanged(null); } #endregion Implementation of IXmlRepositoryConfigurator #region Public Instance Methods /// <summary> /// Test if this hierarchy is disabled for the specified <see cref="Level"/>. /// </summary> /// <param name="level">The level to check against.</param> /// <returns> /// <c>true</c> if the repository is disabled for the level argument, <c>false</c> otherwise. /// </returns> /// <remarks> /// <para> /// If this hierarchy has not been configured then this method will /// always return <c>true</c>. /// </para> /// <para> /// This method will return <c>true</c> if this repository is /// disabled for <c>level</c> object passed as parameter and /// <c>false</c> otherwise. /// </para> /// <para> /// See also the <see cref="ILoggerRepository.Threshold"/> property. /// </para> /// </remarks> public bool IsDisabled(Level level) { // Cast level to object for performance if ((object)level == null) { throw new ArgumentNullException("level"); } if (Configured) { return Threshold > level; } else { // If not configured the hierarchy is effectively disabled return true; } } /// <summary> /// Clear all logger definitions from the internal hashtable /// </summary> /// <remarks> /// <para> /// This call will clear all logger definitions from the internal /// hashtable. Invoking this method will irrevocably mess up the /// logger hierarchy. /// </para> /// <para> /// You should <b>really</b> know what you are doing before /// invoking this method. /// </para> /// </remarks> public void Clear() { m_ht.Clear(); } /// <summary> /// Return a new logger instance named as the first parameter using /// <paramref name="factory"/>. /// </summary> /// <param name="name">The name of the logger to retrieve</param> /// <param name="factory">The factory that will make the new logger instance</param> /// <returns>The logger object with the name specified</returns> /// <remarks> /// <para> /// If a logger of that name already exists, then it will be /// returned. Otherwise, a new logger will be instantiated by the /// <paramref name="factory"/> parameter and linked with its existing /// ancestors as well as children. /// </para> /// </remarks> public Logger GetLogger(string name, ILoggerFactory factory) { if (name == null) { throw new ArgumentNullException("name"); } if (factory == null) { throw new ArgumentNullException("factory"); } LoggerKey key = new LoggerKey(name); // Synchronize to prevent write conflicts. Read conflicts (in // GetEffectiveLevel() method) are possible only if variable // assignments are non-atomic. Logger logger; lock(m_ht) { Object node = m_ht[key]; if (node == null) { logger = factory.CreateLogger(name); logger.Hierarchy = this; m_ht[key] = logger; UpdateParents(logger); OnLoggerCreationEvent(logger); return logger; } Logger nodeLogger = node as Logger; if (nodeLogger != null) { return nodeLogger; } ProvisionNode nodeProvisionNode = node as ProvisionNode; if (nodeProvisionNode != null) { logger = factory.CreateLogger(name); logger.Hierarchy = this; m_ht[key] = logger; UpdateChildren(nodeProvisionNode, logger); UpdateParents(logger); OnLoggerCreationEvent(logger); return logger; } // It should be impossible to arrive here but let's keep the compiler happy. return null; } } #endregion Public Instance Methods #region Protected Instance Methods /// <summary> /// Sends a logger creation event to all registered listeners /// </summary> /// <param name="logger">The newly created logger</param> /// <remarks> /// Raises the logger creation event. /// </remarks> protected virtual void OnLoggerCreationEvent(Logger logger) { LoggerCreationEventHandler handler = m_loggerCreatedEvent; if (handler != null) { handler(this, new LoggerCreationEventArgs(logger)); } } #endregion Protected Instance Methods #region Private Instance Methods /// <summary> /// Updates all the parents of the specified logger /// </summary> /// <param name="log">The logger to update the parents for</param> /// <remarks> /// <para> /// This method loops through all the <i>potential</i> parents of /// <paramref name="log"/>. There 3 possible cases: /// </para> /// <list type="number"> /// <item> /// <term>No entry for the potential parent of <paramref name="log"/> exists</term> /// <description> /// We create a ProvisionNode for this potential /// parent and insert <paramref name="log"/> in that provision node. /// </description> /// </item> /// <item> /// <term>The entry is of type Logger for the potential parent.</term> /// <description> /// The entry is <paramref name="log"/>'s nearest existing parent. We /// update <paramref name="log"/>'s parent field with this entry. We also break from /// he loop because updating our parent's parent is our parent's /// responsibility. /// </description> /// </item> /// <item> /// <term>The entry is of type ProvisionNode for this potential parent.</term> /// <description> /// We add <paramref name="log"/> to the list of children for this /// potential parent. /// </description> /// </item> /// </list> /// </remarks> private void UpdateParents(Logger log) { string name = log.Name; int length = name.Length; bool parentFound = false; // if name = "w.x.y.z", loop through "w.x.y", "w.x" and "w", but not "w.x.y.z" for(int i = name.LastIndexOf('.', length-1); i >= 0; i = name.LastIndexOf('.', i-1)) { string substr = name.Substring(0, i); LoggerKey key = new LoggerKey(substr); // simple constructor Object node = m_ht[key]; // Create a provision node for a future parent. if (node == null) { ProvisionNode pn = new ProvisionNode(log); m_ht[key] = pn; } else { Logger nodeLogger = node as Logger; if (nodeLogger != null) { parentFound = true; log.Parent = nodeLogger; break; // no need to update the ancestors of the closest ancestor } else { ProvisionNode nodeProvisionNode = node as ProvisionNode; if (nodeProvisionNode != null) { nodeProvisionNode.Add(log); } else { LogLog.Error("Hierarchy: Unexpected object type ["+node.GetType()+"] in ht.", new LogException()); } } } } // If we could not find any existing parents, then link with root. if (!parentFound) { log.Parent = this.Root; } } /// <summary> /// Replace a <see cref="ProvisionNode"/> with a <see cref="Logger"/> in the hierarchy. /// </summary> /// <param name="pn"></param> /// <param name="log"></param> /// <remarks> /// <para> /// We update the links for all the children that placed themselves /// in the provision node 'pn'. The second argument 'log' is a /// reference for the newly created Logger, parent of all the /// children in 'pn'. /// </para> /// <para> /// We loop on all the children 'c' in 'pn'. /// </para> /// <para> /// If the child 'c' has been already linked to a child of /// 'log' then there is no need to update 'c'. /// </para> /// <para> /// Otherwise, we set log's parent field to c's parent and set /// c's parent field to log. /// </para> /// </remarks> private void UpdateChildren(ProvisionNode pn, Logger log) { for(int i = 0; i < pn.Count; i++) { Logger childLogger = (Logger)pn[i]; // Unless this child already points to a correct (lower) parent, // make log.Parent point to childLogger.Parent and childLogger.Parent to log. if (!childLogger.Parent.Name.StartsWith(log.Name)) { log.Parent = childLogger.Parent; childLogger.Parent = log; } } } /// <summary> /// Define or redefine a Level using the values in the <see cref="LevelEntry"/> argument /// </summary> /// <param name="levelEntry">the level values</param> /// <remarks> /// <para> /// Define or redefine a Level using the values in the <see cref="LevelEntry"/> argument /// </para> /// <para> /// Supports setting levels via the configuration file. /// </para> /// </remarks> internal void AddLevel(LevelEntry levelEntry) { if (levelEntry == null) throw new ArgumentNullException("levelEntry"); if (levelEntry.Name == null) throw new ArgumentNullException("levelEntry.Name"); // Lookup replacement value if (levelEntry.Value == -1) { Level previousLevel = LevelMap[levelEntry.Name]; if (previousLevel == null) { throw new InvalidOperationException("Cannot redefine level ["+levelEntry.Name+"] because it is not defined in the LevelMap. To define the level supply the level value."); } levelEntry.Value = previousLevel.Value; } LevelMap.Add(levelEntry.Name, levelEntry.Value, levelEntry.DisplayName); } /// <summary> /// A class to hold the value, name and display name for a level /// </summary> /// <remarks> /// <para> /// A class to hold the value, name and display name for a level /// </para> /// </remarks> internal class LevelEntry { private int m_levelValue = -1; private string m_levelName = null; private string m_levelDisplayName = null; /// <summary> /// Value of the level /// </summary> /// <remarks> /// <para> /// If the value is not set (defaults to -1) the value will be looked /// up for the current level with the same name. /// </para> /// </remarks> public int Value { get { return m_levelValue; } set { m_levelValue = value; } } /// <summary> /// Name of the level /// </summary> /// <value> /// The name of the level /// </value> /// <remarks> /// <para> /// The name of the level. /// </para> /// </remarks> public string Name { get { return m_levelName; } set { m_levelName = value; } } /// <summary> /// Display name for the level /// </summary> /// <value> /// The display name of the level /// </value> /// <remarks> /// <para> /// The display name of the level. /// </para> /// </remarks> public string DisplayName { get { return m_levelDisplayName; } set { m_levelDisplayName = value; } } /// <summary> /// Override <c>Object.ToString</c> to return sensible debug info /// </summary> /// <returns>string info about this object</returns> public override string ToString() { return "LevelEntry(Value="+m_levelValue+", Name="+m_levelName+", DisplayName="+m_levelDisplayName+")"; } } /// <summary> /// Set a Property using the values in the <see cref="LevelEntry"/> argument /// </summary> /// <param name="propertyEntry">the property value</param> /// <remarks> /// <para> /// Set a Property using the values in the <see cref="LevelEntry"/> argument. /// </para> /// <para> /// Supports setting property values via the configuration file. /// </para> /// </remarks> internal void AddProperty(PropertyEntry propertyEntry) { if (propertyEntry == null) throw new ArgumentNullException("propertyEntry"); if (propertyEntry.Key == null) throw new ArgumentNullException("propertyEntry.Key"); Properties[propertyEntry.Key] = propertyEntry.Value; } /// <summary> /// A class to hold the key and data for a property set in the config file /// </summary> /// <remarks> /// <para> /// A class to hold the key and data for a property set in the config file /// </para> /// </remarks> internal class PropertyEntry { private string m_key = null; private object m_value = null; /// <summary> /// Property Key /// </summary> /// <value> /// Property Key /// </value> /// <remarks> /// <para> /// Property Key. /// </para> /// </remarks> public string Key { get { return m_key; } set { m_key = value; } } /// <summary> /// Property Value /// </summary> /// <value> /// Property Value /// </value> /// <remarks> /// <para> /// Property Value. /// </para> /// </remarks> public object Value { get { return m_value; } set { m_value = value; } } /// <summary> /// Override <c>Object.ToString</c> to return sensible debug info /// </summary> /// <returns>string info about this object</returns> public override string ToString() { return "PropertyEntry(Key="+m_key+", Value="+m_value+")"; } } #endregion Private Instance Methods #region Private Instance Fields private ILoggerFactory m_defaultFactory; private System.Collections.Hashtable m_ht; private Logger m_root; private bool m_emittedNoAppenderWarning = false; private event LoggerCreationEventHandler m_loggerCreatedEvent; #endregion Private Instance Fields } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using Xunit; using Microsoft.Xunit.Performance; namespace System.Text.Primitives.Tests { public partial class PrimitiveParserPerfTests { private static readonly string[] s_UInt32TextArray = new string[10] { "42", "429496", "429496729", "42949", "4", "42949672", "4294", "429", "4294967295", "4294967" }; private static readonly string[] s_UInt32TextArrayHex = new string[8] { "A2", "A29496", "A2949", "A", "A2949672", "A294", "A29", "A294967" }; [Benchmark] [InlineData("2134567890")] // standard parse [InlineData("4294967295")] // max value [InlineData("0")] // min value private static void BaselineSimpleByteStarToUInt32(string text) { foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { uint value; uint.TryParse(text, out value); DoNotIgnore(value, 0); } } } } [Benchmark] private static void BaselineSimpleByteStarToUInt32_VariableLength() { foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { uint value; uint.TryParse(s_UInt32TextArray[i % 10], out value); DoNotIgnore(value, 0); } } } } [Benchmark] [InlineData("2134567890")] // standard parse [InlineData("4294967295")] // max value [InlineData("0")] // min value private static void BaselineByteStarToUInt32(string text) { foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { uint value; uint.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out value); DoNotIgnore(value, 0); } } } } [Benchmark] private static void BaselineByteStarToUInt32_VariableLength() { foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { uint value; uint.TryParse(s_UInt32TextArray[i % 10], NumberStyles.None, CultureInfo.InvariantCulture, out value); DoNotIgnore(value, 0); } } } } [Benchmark] [InlineData("abcdef")] // standard parse [InlineData("ffffffff")] // max value [InlineData("0")] // min value private static void BaselineByteStarToUInt32Hex(string text) { foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { uint value; uint.TryParse(text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out value); DoNotIgnore(value, 0); } } } } [Benchmark] private static void BaselineByteStarToUInt32Hex_VariableLength() { foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { uint value; uint.TryParse(s_UInt32TextArrayHex[i % 8], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out value); DoNotIgnore(value, 0); } } } } [Benchmark] [InlineData("2134567890")] // standard parse [InlineData("4294967295")] // max value [InlineData("0")] // min value private unsafe static void PrimitiveParserByteStarToUInt32(string text) { int length = text.Length; byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text); foreach (var iteration in Benchmark.Iterations) { fixed (byte* utf8ByteStar = utf8ByteArray) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { uint value; PrimitiveParser.InvariantUtf8.TryParseUInt32(utf8ByteStar, length, out value); DoNotIgnore(value, 0); } } } } } [Benchmark] private unsafe static void PrimitiveParserByteStarToUInt32_VariableLength() { List<byte[]> byteArrayList = new List<byte[]>(); foreach (string text in s_UInt32TextArray) { byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text); byteArrayList.Add(utf8ByteArray); } foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { byte[] utf8ByteArray = byteArrayList[i % 10]; fixed (byte* utf8ByteStar = utf8ByteArray) { uint value; PrimitiveParser.InvariantUtf8.TryParseUInt32(utf8ByteStar, utf8ByteArray.Length, out value); DoNotIgnore(value, 0); } } } } } [Benchmark] [InlineData("2134567890")] // standard parse [InlineData("4294967295")] // max value [InlineData("0")] // min value private unsafe static void PrimitiveParserByteStarToUInt32_BytesConsumed(string text) { int length = text.Length; byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text); foreach (var iteration in Benchmark.Iterations) { fixed (byte* utf8ByteStar = utf8ByteArray) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { uint value; int bytesConsumed; PrimitiveParser.InvariantUtf8.TryParseUInt32(utf8ByteStar, length, out value, out bytesConsumed); DoNotIgnore(value, bytesConsumed); } } } } } [Benchmark] private unsafe static void PrimitiveParserByteStarToUInt32_BytesConsumed_VariableLength() { List<byte[]> byteArrayList = new List<byte[]>(); foreach (string text in s_UInt32TextArray) { byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text); byteArrayList.Add(utf8ByteArray); } foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { byte[] utf8ByteArray = byteArrayList[i % 10]; fixed (byte* utf8ByteStar = utf8ByteArray) { uint value; int bytesConsumed; PrimitiveParser.InvariantUtf8.TryParseUInt32(utf8ByteStar, utf8ByteArray.Length, out value, out bytesConsumed); DoNotIgnore(value, bytesConsumed); } } } } } [Benchmark] [InlineData("2134567890")] // standard parse [InlineData("4294967295")] // max value [InlineData("0")] // min value private unsafe static void PrimitiveParserByteSpanToUInt32(string text) { byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text); var utf8ByteSpan = new ReadOnlySpan<byte>(utf8ByteArray); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { uint value; PrimitiveParser.InvariantUtf8.TryParseUInt32(utf8ByteSpan, out value); DoNotIgnore(value, 0); } } } } [Benchmark] private unsafe static void PrimitiveParserByteSpanToUInt32_VariableLength() { int textLength = s_UInt32TextArray.Length; byte[][] utf8ByteArray = (byte[][])Array.CreateInstance(typeof(byte[]), textLength); for (var i = 0; i < textLength; i++) { utf8ByteArray[i] = Text.Encoding.UTF8.GetBytes(s_UInt32TextArray[i]); } foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { ReadOnlySpan<byte> utf8ByteSpan = utf8ByteArray[i % textLength]; uint value; PrimitiveParser.InvariantUtf8.TryParseUInt32(utf8ByteSpan, out value); DoNotIgnore(value, 0); } } } } [Benchmark] [InlineData("2134567890")] // standard parse [InlineData("4294967295")] // max value [InlineData("0")] // min value private unsafe static void PrimitiveParserByteSpanToUInt32_BytesConsumed(string text) { byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text); var utf8ByteSpan = new ReadOnlySpan<byte>(utf8ByteArray); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { uint value; int bytesConsumed; PrimitiveParser.InvariantUtf8.TryParseUInt32(utf8ByteSpan, out value, out bytesConsumed); DoNotIgnore(value, bytesConsumed); } } } } [Benchmark] private unsafe static void PrimitiveParserByteSpanToUInt32_BytesConsumed_VariableLength() { int textLength = s_UInt32TextArray.Length; byte[][] utf8ByteArray = (byte[][])Array.CreateInstance(typeof(byte[]), textLength); for (var i = 0; i < textLength; i++) { utf8ByteArray[i] = Text.Encoding.UTF8.GetBytes(s_UInt32TextArray[i]); } foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { ReadOnlySpan<byte> utf8ByteSpan = utf8ByteArray[i % textLength]; uint value; int bytesConsumed; PrimitiveParser.InvariantUtf8.TryParseUInt32(utf8ByteSpan, out value, out bytesConsumed); DoNotIgnore(value, bytesConsumed); } } } } [Benchmark] [InlineData("abcdef")] // standard parse [InlineData("ffffffff")] // max value [InlineData("0")] // min value private unsafe static void PrimitiveParserByteStarToUInt32Hex(string text) { int length = text.Length; byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text); foreach (var iteration in Benchmark.Iterations) { fixed (byte* utf8ByteStar = utf8ByteArray) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { uint value; PrimitiveParser.InvariantUtf8.Hex.TryParseUInt32(utf8ByteStar, length, out value); DoNotIgnore(value, 0); } } } } } [Benchmark] private unsafe static void PrimitiveParserByteStarToUInt32Hex_VariableLength() { List<byte[]> byteArrayList = new List<byte[]>(); foreach (string text in s_UInt32TextArrayHex) { byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text); byteArrayList.Add(utf8ByteArray); } foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { byte[] utf8ByteArray = byteArrayList[i % 8]; fixed (byte* utf8ByteStar = utf8ByteArray) { uint value; PrimitiveParser.InvariantUtf8.Hex.TryParseUInt32(utf8ByteStar, utf8ByteArray.Length, out value); DoNotIgnore(value, 0); } } } } } [Benchmark] [InlineData("abcdef")] // standard parse [InlineData("ffffffff")] // max value [InlineData("0")] // min value private unsafe static void PrimitiveParserByteStarToUInt32Hex_BytesConsumed(string text) { int length = text.Length; byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text); foreach (var iteration in Benchmark.Iterations) { fixed (byte* utf8ByteStar = utf8ByteArray) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { uint value; int bytesConsumed; PrimitiveParser.InvariantUtf8.Hex.TryParseUInt32(utf8ByteStar, length, out value, out bytesConsumed); DoNotIgnore(value, bytesConsumed); } } } } } [Benchmark] private unsafe static void PrimitiveParserByteStarToUInt32Hex_BytesConsumed_VariableLength() { List<byte[]> byteArrayList = new List<byte[]>(); foreach (string text in s_UInt32TextArrayHex) { byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text); byteArrayList.Add(utf8ByteArray); } foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { byte[] utf8ByteArray = byteArrayList[i % 8]; fixed (byte* utf8ByteStar = utf8ByteArray) { uint value; int bytesConsumed; PrimitiveParser.InvariantUtf8.Hex.TryParseUInt32(utf8ByteStar, utf8ByteArray.Length, out value, out bytesConsumed); DoNotIgnore(value, bytesConsumed); } } } } } [Benchmark] [InlineData("abcdef")] // standard parse [InlineData("ffffffff")] // max value [InlineData("0")] // min value private unsafe static void PrimitiveParserByteSpanToUInt32Hex(string text) { byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text); var utf8ByteSpan = new ReadOnlySpan<byte>(utf8ByteArray); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { uint value; PrimitiveParser.InvariantUtf8.Hex.TryParseUInt32(utf8ByteSpan, out value); DoNotIgnore(value, 0); } } } } [Benchmark] private unsafe static void PrimitiveParserByteSpanToUInt32Hex_VariableLength() { int textLength = s_UInt32TextArrayHex.Length; byte[][] utf8ByteArray = (byte[][])Array.CreateInstance(typeof(byte[]), textLength); for (var i = 0; i < textLength; i++) { utf8ByteArray[i] = Text.Encoding.UTF8.GetBytes(s_UInt32TextArrayHex[i]); } foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { ReadOnlySpan<byte> utf8ByteSpan = utf8ByteArray[i % textLength]; uint value; PrimitiveParser.InvariantUtf8.Hex.TryParseUInt32(utf8ByteSpan, out value); DoNotIgnore(value, 0); } } } } [Benchmark] [InlineData("abcdef")] // standard parse [InlineData("ffffffff")] // max value [InlineData("0")] // min value private unsafe static void PrimitiveParserByteSpanToUInt32Hex_BytesConsumed(string text) { byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text); var utf8ByteSpan = new ReadOnlySpan<byte>(utf8ByteArray); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { uint value; int bytesConsumed; PrimitiveParser.InvariantUtf8.Hex.TryParseUInt32(utf8ByteSpan, out value, out bytesConsumed); DoNotIgnore(value, bytesConsumed); } } } } [Benchmark] private unsafe static void PrimitiveParserByteSpanToUInt32Hex_BytesConsumed_VariableLength() { int textLength = s_UInt32TextArrayHex.Length; byte[][] utf8ByteArray = (byte[][])Array.CreateInstance(typeof(byte[]), textLength); for (var i = 0; i < textLength; i++) { utf8ByteArray[i] = Text.Encoding.UTF8.GetBytes(s_UInt32TextArrayHex[i]); } foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { ReadOnlySpan<byte> utf8ByteSpan = utf8ByteArray[i % textLength]; uint value; int bytesConsumed; PrimitiveParser.InvariantUtf8.Hex.TryParseUInt32(utf8ByteSpan, out value, out bytesConsumed); DoNotIgnore(value, bytesConsumed); } } } } } }
// 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.Diagnostics; using System.IO.Pipelines; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; namespace Microsoft.AspNetCore.Http.Connections.Client.Internal { internal partial class LongPollingTransport : ITransport { private readonly HttpClient _httpClient; private readonly ILogger _logger; private readonly HttpConnectionOptions _httpConnectionOptions; private IDuplexPipe? _application; private IDuplexPipe? _transport; // Volatile so that the poll loop sees the updated value set from a different thread private volatile Exception? _error; private readonly CancellationTokenSource _transportCts = new CancellationTokenSource(); internal Task Running { get; private set; } = Task.CompletedTask; public PipeReader Input => _transport!.Input; public PipeWriter Output => _transport!.Output; public LongPollingTransport(HttpClient httpClient, HttpConnectionOptions? httpConnectionOptions = null, ILoggerFactory? loggerFactory = null) { _httpClient = httpClient; _logger = (loggerFactory ?? NullLoggerFactory.Instance).CreateLogger<LongPollingTransport>(); _httpConnectionOptions = httpConnectionOptions ?? new(); } public async Task StartAsync(Uri url, TransferFormat transferFormat, CancellationToken cancellationToken = default) { if (transferFormat != TransferFormat.Binary && transferFormat != TransferFormat.Text) { throw new ArgumentException($"The '{transferFormat}' transfer format is not supported by this transport.", nameof(transferFormat)); } Log.StartTransport(_logger, transferFormat); // Make initial long polling request // Server uses first long polling request to finish initializing connection and it returns without data var request = new HttpRequestMessage(HttpMethod.Get, url); using (var response = await _httpClient.SendAsync(request, cancellationToken)) { response.EnsureSuccessStatusCode(); } // Create the pipe pair (Application's writer is connected to Transport's reader, and vice versa) var pair = DuplexPipe.CreateConnectionPair(_httpConnectionOptions.TransportPipeOptions, _httpConnectionOptions.AppPipeOptions); _transport = pair.Transport; _application = pair.Application; Running = ProcessAsync(url); } private async Task ProcessAsync(Uri url) { Debug.Assert(_application != null); // Start sending and polling (ask for binary if the server supports it) var receiving = Poll(url, _transportCts.Token); var sending = SendUtils.SendMessages(url, _application, _httpClient, _logger); // Wait for send or receive to complete var trigger = await Task.WhenAny(receiving, sending); if (trigger == receiving) { // We don't need to DELETE here because the poll completed, which means the server shut down already. // We're waiting for the application to finish and there are 2 things it could be doing // 1. Waiting for application data // 2. Waiting for an outgoing send (this should be instantaneous) // Cancel the application so that ReadAsync yields _application.Input.CancelPendingRead(); await sending; } else { // Set the sending error so we communicate that to the application _error = sending.IsFaulted ? sending.Exception!.InnerException : null; // Cancel the poll request _transportCts.Cancel(); // Cancel any pending flush so that we can quit _application.Output.CancelPendingFlush(); await receiving; // Send the DELETE request to clean-up the connection on the server. await SendDeleteRequest(url); } } public async Task StopAsync() { Log.TransportStopping(_logger); if (_application == null) { // We never started return; } _application.Input.CancelPendingRead(); try { await Running; } catch (Exception ex) { Log.TransportStopped(_logger, ex); throw; } _transport!.Output.Complete(); _transport!.Input.Complete(); Log.TransportStopped(_logger, null); } private async Task Poll(Uri pollUrl, CancellationToken cancellationToken) { Debug.Assert(_application != null); Log.StartReceive(_logger); // Allocate this once for the duration of the transport so we can continuously write to it var applicationStream = new PipeWriterStream(_application.Output); try { while (!cancellationToken.IsCancellationRequested) { var request = new HttpRequestMessage(HttpMethod.Get, pollUrl); HttpResponseMessage response; try { response = await _httpClient.SendAsync(request, cancellationToken); } catch (OperationCanceledException) { // SendAsync will throw the OperationCanceledException if the passed cancellationToken is canceled // or if the http request times out due to HttpClient.Timeout expiring. In the latter case we // just want to start a new poll. continue; } catch (WebException ex) when (!OperatingSystem.IsBrowser() && ex.Status == WebExceptionStatus.RequestCanceled) { // SendAsync on .NET Framework doesn't reliably throw OperationCanceledException. // Catch the WebException and test it. // https://github.com/dotnet/corefx/issues/26335 continue; } Log.PollResponseReceived(_logger, response); response.EnsureSuccessStatusCode(); if (response.StatusCode == HttpStatusCode.NoContent || cancellationToken.IsCancellationRequested) { Log.ClosingConnection(_logger); // Transport closed or polling stopped, we're done break; } else { Log.ReceivedMessages(_logger); #if NETCOREAPP await response.Content.CopyToAsync(applicationStream, cancellationToken); #else await response.Content.CopyToAsync(applicationStream); #endif var flushResult = await _application.Output.FlushAsync(cancellationToken); // We canceled in the middle of applying back pressure // or if the consumer is done if (flushResult.IsCanceled || flushResult.IsCompleted) { break; } } } } catch (OperationCanceledException) { // transport is being closed Log.ReceiveCanceled(_logger); } catch (Exception ex) { Log.ErrorPolling(_logger, pollUrl, ex); _error = ex; } finally { _application.Output.Complete(_error); Log.ReceiveStopped(_logger); } } private async Task SendDeleteRequest(Uri url) { try { Log.SendingDeleteRequest(_logger, url); var response = await _httpClient.DeleteAsync(url); if (response.StatusCode == HttpStatusCode.NotFound) { Log.ConnectionAlreadyClosedSendingDeleteRequest(_logger, url); } else { // Check for non-404 errors response.EnsureSuccessStatusCode(); Log.DeleteRequestAccepted(_logger, url); } } catch (Exception ex) { Log.ErrorSendingDeleteRequest(_logger, url, ex); } } } }
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // 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.CodeDom.Compiler; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using SharpGen.Logging; namespace SharpGen.TextTemplating { /// <summary> /// Lightweight implementation of T4 engine, using Tokenizer from MonoDevelop.TextTemplating. /// </summary> public class TemplateEngine { private StringBuilder _doTemplateCode; private StringBuilder _doTemplateClassCode; private bool _isTemplateClassCode; private List<Directive> _directives; private Dictionary<string, ParameterValueType> _parameters; /// <summary> /// Occurs when an include needs to be found. /// </summary> public event EventHandler<TemplateIncludeArgs> OnInclude; /// <summary> /// Template code. /// Parameter {0} = List of import namespaces. /// Parameter {1} = List of parameters declaration. /// Parameter {2} = Body of template code /// Parameter {3} = Body of template class level code /// </summary> private const string GenericTemplateCodeText = @" using System; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; {0} public class TemplateImpl : SharpGen.TextTemplating.Templatizer {{ {1} public override void Process() {{ // DoTemplate code {2} }} // DoTemplateClass code {3} }} "; public TemplateEngine() { _parameters = new Dictionary<string, ParameterValueType>(); // templateCodePath = Path.Combine(Path.GetDirectoryName(GetType().Assembly.Location), "..\\..\\"); } /// <summary> /// Adds a text to Templatizer.Process section . /// </summary> /// <param name="location">The location.</param> /// <param name="content">The content.</param> private void AddDoTemplateCode(Location location, string content) { if (_isTemplateClassCode) throw new InvalidOperationException(string.Format(System.Globalization.CultureInfo.InvariantCulture, "Cannot add Process code [{0}] after Process Class level code", content)); _doTemplateCode.AppendLine().AppendFormat("#line {0} \"{1}\"", location.Line, location.FileName).AppendLine(); _doTemplateCode.Append(content); } /// <summary> /// Adds a text to at Templatizer class level. /// </summary> /// <param name="location">The location.</param> /// <param name="content">The content.</param> private void AddDoTemplateClassCode(Location location, string content) { _doTemplateClassCode.AppendLine().AppendFormat("#line {0} \"{1}\"", location.Line, location.FileName).AppendLine(); _doTemplateClassCode.Append(content); } /// <summary> /// Adds some code to the current /// </summary> /// <param name="location">The location.</param> /// <param name="code">The code.</param> private void AddCode(Location location, string code) { if (_isTemplateClassCode) AddDoTemplateClassCode(location, code); else AddDoTemplateCode(location, code); } /// <summary> /// Add a multiline string to the template code. /// This methods decompose a string in lines and generate template code for each line /// using Templatizer.Write/WriteLine methods. /// </summary> /// <param name="location">The location in the text template file.</param> /// <param name="content">The content to add to the code.</param> private void AddContent(Location location, string content) { content = content.Replace("\"", "\\\""); var reader = new StringReader(content); var lines = new List<string>(); string line; while ((line = reader.ReadLine()) != null) lines.Add(line); Location fromLocation = location; for (int i = 0; i < lines.Count;i++) { line = lines[i]; location = new Location(fromLocation.FileName, fromLocation.Line + i, fromLocation.Column); if ((i + 1) == lines.Count) { if (content.EndsWith(line)) { if (!string.IsNullOrEmpty(line)) AddCode(location, "Write(\"" + line + "\");\n"); } else AddCode(location, "WriteLine(\"" + line + "\");\n"); } else { AddCode(location, "WriteLine(\"" + line + "\");\n"); } } } private void AddExpression(Location location, string content) { AddCode(location, "Write(" + content + ");\n"); } /// <summary> /// Gets or sets the name of the template file being processed (for debug purpose). /// </summary> /// <value>The name of the template file.</value> public string TemplateFileName { get; set; } /// <summary> /// Process a template and returns the processed file. /// </summary> /// <param name="templateText">The template text.</param> /// <returns></returns> public string ProcessTemplate(string templateText) { // Initialize TemplateEngine state _doTemplateCode = new StringBuilder(); _doTemplateClassCode = new StringBuilder(); _isTemplateClassCode = false; Assembly templateAssembly = null; _directives = new List<Directive>(); // Parse the T4 template text Parse(templateText); // Build parameters for template var parametersCode = new StringBuilder(); foreach (var parameterValueType in _parameters.Values) parametersCode.Append(string.Format(System.Globalization.CultureInfo.InvariantCulture, "public {0} {1} {{ get; set; }}\n", parameterValueType.Type.FullName, parameterValueType.Name)); // Build import namespaces for template var importNamespaceCode = new StringBuilder(); foreach (var directive in _directives) { if (directive.Name == "import") importNamespaceCode.Append("using " + directive.Attributes["namespace"] + ";\n"); } // Expand final template class code // Parameter {0} = List of import namespaces. // Parameter {1} = List of parameters declaration. // Parameter {2} = Body of template code // Parameter {3} = Body of template class level code string templateSourceCode = string.Format(GenericTemplateCodeText, importNamespaceCode, parametersCode, _doTemplateCode, _doTemplateClassCode); // Creates the C# compiler, compiling for 3.5 //var codeProvider = new Microsoft.CSharp.CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } }); var codeProvider = new Microsoft.CSharp.CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } }); var compilerParameters = new CompilerParameters { GenerateInMemory = true, GenerateExecutable = false }; // Adds assembly from CurrentDomain // TODO, implement T4 directive "assembly"? foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { try { string location = assembly.Location; if (!String.IsNullOrEmpty(location)) compilerParameters.ReferencedAssemblies.Add(location); } catch (NotSupportedException) { // avoid problem with previous dynamic assemblies } } // Compiles the code var compilerResults = codeProvider.CompileAssemblyFromSource(compilerParameters, templateSourceCode); // Output any errors foreach (var compilerError in compilerResults.Errors) Logger.Error(compilerError.ToString()); // If successful, gets the compiled assembly if (compilerResults.Errors.Count == 0 && compilerResults.CompiledAssembly != null) { templateAssembly = compilerResults.CompiledAssembly; // File.WriteAllText(templateFile + ".txt", src); } else { Logger.Fatal("Template [{0}] contains error", TemplateFileName); } // Get a new templatizer instance var templatizer = (Templatizer)Activator.CreateInstance(templateAssembly.GetType("TemplateImpl")); // Set all parameters for the template foreach (var parameterValueType in _parameters.Values) { var propertyInfo = templatizer.GetType().GetProperty(parameterValueType.Name); propertyInfo.SetValue(templatizer, parameterValueType.Value, null); } // Run the templatizer templatizer.Process(); // Returns the text return templatizer.ToString(); } /// <summary> /// Adds a parameter with the object to this template. /// </summary> /// <param name="name">The name.</param> /// <param name="value">an object.</param> /// <exception cref="ArgumentNullException">If value is null</exception> public void SetParameter(string name, object value) { if (value == null) throw new ArgumentNullException("value"); SetParameter(name, value, value.GetType()); } /// <summary> /// Adds a parameter with the object to this template. /// </summary> /// <param name="name">The name.</param> /// <param name="value">an object.</param> /// <param name="typeOf">Type of the object.</param> /// <exception cref="ArgumentNullException">If typeOf is null</exception> public void SetParameter(string name, object value, Type typeOf) { if (typeOf == null) throw new ArgumentNullException("typeOf"); if (_parameters.ContainsKey(name)) _parameters.Remove(name); _parameters.Add(name, new ParameterValueType { Name = name, Type = typeOf, Value = value }); } /// <summary> /// An association between a Value and a Type. /// </summary> private class ParameterValueType { public string Name; public Type Type; public object Value; } /// <summary> /// Parses the specified template text. /// </summary> /// <param name="templateText">The template text.</param> private void Parse(string templateText) { //var filePath = Path.GetFullPath(Path.Combine(templateCodePath, TemplateFileName)); var tokeniser = new Tokeniser(TemplateFileName, templateText); AddCode(tokeniser.Location, ""); bool skip = false; while ((skip || tokeniser.Advance()) && tokeniser.State != State.EOF) { skip = false; switch (tokeniser.State) { case State.Block: if (!String.IsNullOrEmpty(tokeniser.Value)) AddDoTemplateCode(tokeniser.Location, tokeniser.Value); break; case State.Content: if (!String.IsNullOrEmpty(tokeniser.Value)) AddContent(tokeniser.Location, tokeniser.Value); break; case State.Expression: if (!String.IsNullOrEmpty(tokeniser.Value)) AddExpression(tokeniser.Location, tokeniser.Value); break; case State.Helper: _isTemplateClassCode = true; if (!String.IsNullOrEmpty(tokeniser.Value)) AddDoTemplateClassCode(tokeniser.Location, tokeniser.Value); break; case State.Directive: Directive directive = null; string attName = null; while (!skip && tokeniser.Advance()) { switch (tokeniser.State) { case State.DirectiveName: if (directive == null) directive = new Directive {Name = tokeniser.Value.ToLower()}; else attName = tokeniser.Value; break; case State.DirectiveValue: if (attName != null && directive != null) directive.Attributes.Add(attName.ToLower(), tokeniser.Value); attName = null; break; case State.Directive: //if (directive != null) // directive.EndLocation = tokeniser.TagEndLocation; break; default: skip = true; break; } } if (directive != null) { if (directive.Name == "include") { string includeFile = directive.Attributes["file"]; if (OnInclude == null) throw new InvalidOperationException("Include file found. OnInclude event must be implemented"); var includeArgs = new TemplateIncludeArgs() {IncludeName = includeFile}; OnInclude(this, includeArgs); Parse(includeArgs.Text ?? ""); } _directives.Add(directive); } break; default: throw new InvalidOperationException(); } } } /// <summary> /// T4 Directive /// </summary> private class Directive { public Directive() { Attributes = new Dictionary<string, string>(); } public string Name { get; set; } public Dictionary<string, string> Attributes { get; set; } } } }
/* ** $Id: ldblib.c,v 1.104.1.3 2008/01/21 13:11:21 roberto Exp $ ** Interface from Lua to its debug API ** See Copyright Notice in lua.h */ using System; using System.Collections.Generic; using System.Text; namespace SharpLua { public partial class Lua { private static int db_getregistry(LuaState L) { lua_pushvalue(L, LUA_REGISTRYINDEX); return 1; } private static int db_getmetatable(LuaState L) { luaL_checkany(L, 1); if (lua_getmetatable(L, 1) == 0) { lua_pushnil(L); /* no metatable */ } return 1; } private static int db_setmetatable(LuaState L) { int t = lua_type(L, 2); luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2, "nil or table expected"); lua_settop(L, 2); lua_pushboolean(L, lua_setmetatable(L, 1)); return 1; } private static int db_getfenv(LuaState L) { luaL_checkany(L, 1); lua_getfenv(L, 1); return 1; } private static int db_setfenv(LuaState L) { luaL_checktype(L, 2, LUA_TTABLE); lua_settop(L, 2); if (lua_setfenv(L, 1) == 0) luaL_error(L, LUA_QL("setfenv") + " cannot change environment of given object"); return 1; } private static void settabss(LuaState L, CharPtr i, CharPtr v) { lua_pushstring(L, v); lua_setfield(L, -2, i); } private static void settabsi(LuaState L, CharPtr i, int v) { lua_pushinteger(L, v); lua_setfield(L, -2, i); } private static LuaState getthread(LuaState L, out int arg) { if (lua_isthread(L, 1)) { arg = 1; return lua_tothread(L, 1); } else { arg = 0; return L; } } private static void treatstackoption(LuaState L, LuaState L1, CharPtr fname) { if (L == L1) { lua_pushvalue(L, -2); lua_remove(L, -3); } else lua_xmove(L1, L, 1); lua_setfield(L, -2, fname); } private static int db_getinfo(LuaState L) { lua_Debug ar = new lua_Debug(); int arg; LuaState L1 = getthread(L, out arg); CharPtr options = luaL_optstring(L, arg + 2, "flnSu"); if (lua_isnumber(L, arg + 1) != 0) { if (lua_getstack(L1, (int)lua_tointeger(L, arg + 1), ar) == 0) { lua_pushnil(L); /* level out of range */ return 1; } } else if (lua_isfunction(L, arg + 1)) { lua_pushfstring(L, ">%s", options); options = lua_tostring(L, -1); lua_pushvalue(L, arg + 1); lua_xmove(L, L1, 1); } else return luaL_argerror(L, arg + 1, "function or level expected"); if (lua_getinfo(L1, options, ar) == 0) return luaL_argerror(L, arg + 2, "invalid option"); lua_createtable(L, 0, 2); if (strchr(options, 'S') != null) { settabss(L, "source", ar.source); settabss(L, "short_src", ar.short_src); settabsi(L, "linedefined", ar.linedefined); settabsi(L, "lastlinedefined", ar.lastlinedefined); settabss(L, "what", ar.what); } if (strchr(options, 'l') != null) settabsi(L, "currentline", ar.currentline); if (strchr(options, 'u') != null) settabsi(L, "nups", ar.nups); if (strchr(options, 'n') != null) { settabss(L, "name", ar.name); settabss(L, "namewhat", ar.namewhat); } if (strchr(options, 'L') != null) treatstackoption(L, L1, "activelines"); if (strchr(options, 'f') != null) treatstackoption(L, L1, "func"); return 1; /* return table */ } private static int db_getlocal(LuaState L) { int arg; LuaState L1 = getthread(L, out arg); lua_Debug ar = new lua_Debug(); CharPtr name; if (lua_getstack(L1, luaL_checkint(L, arg + 1), ar) == 0) /* out of range? */ return luaL_argerror(L, arg + 1, "level out of range"); name = lua_getlocal(L1, ar, luaL_checkint(L, arg + 2)); if (name != null) { lua_xmove(L1, L, 1); lua_pushstring(L, name); lua_pushvalue(L, -2); return 2; } else { lua_pushnil(L); return 1; } } private static int db_setlocal(LuaState L) { int arg; LuaState L1 = getthread(L, out arg); lua_Debug ar = new lua_Debug(); if (lua_getstack(L1, luaL_checkint(L, arg + 1), ar) == 0) /* out of range? */ return luaL_argerror(L, arg + 1, "level out of range"); luaL_checkany(L, arg + 3); lua_settop(L, arg + 3); lua_xmove(L, L1, 1); lua_pushstring(L, lua_setlocal(L1, ar, luaL_checkint(L, arg + 2))); return 1; } private static int auxupvalue(LuaState L, int get) { CharPtr name; int n = luaL_checkint(L, 2); luaL_checktype(L, 1, LUA_TFUNCTION); if (lua_iscfunction(L, 1)) return 0; /* cannot touch C upvalues from Lua */ name = (get != 0) ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n); if (name == null) return 0; lua_pushstring(L, name); lua_insert(L, -(get + 1)); return get + 1; } private static int db_getupvalue(LuaState L) { return auxupvalue(L, 1); } private static int db_setupvalue(LuaState L) { luaL_checkany(L, 3); return auxupvalue(L, 0); } private const string KEY_HOOK = "h"; private static readonly string[] hooknames = { "call", "return", "line", "count", "tail return" }; private static void hookf(LuaState L, lua_Debug ar) { lua_pushlightuserdata(L, KEY_HOOK); lua_rawget(L, LUA_REGISTRYINDEX); lua_pushlightuserdata(L, L); lua_rawget(L, -2); if (lua_isfunction(L, -1)) { lua_pushstring(L, hooknames[(int)ar.event_]); if (ar.currentline >= 0) lua_pushinteger(L, ar.currentline); else lua_pushnil(L); lua_assert(lua_getinfo(L, "lS", ar)); lua_call(L, 2, 0); } } private static int makemask(CharPtr smask, int count) { int mask = 0; if (strchr(smask, 'c') != null) mask |= LUA_MASKCALL; if (strchr(smask, 'r') != null) mask |= LUA_MASKRET; if (strchr(smask, 'l') != null) mask |= LUA_MASKLINE; if (count > 0) mask |= LUA_MASKCOUNT; return mask; } private static CharPtr unmakemask(int mask, CharPtr smask) { int i = 0; if ((mask & LUA_MASKCALL) != 0) smask[i++] = 'c'; if ((mask & LUA_MASKRET) != 0) smask[i++] = 'r'; if ((mask & LUA_MASKLINE) != 0) smask[i++] = 'l'; smask[i] = '\0'; return smask; } private static void gethooktable(LuaState L) { lua_pushlightuserdata(L, KEY_HOOK); lua_rawget(L, LUA_REGISTRYINDEX); if (!lua_istable(L, -1)) { lua_pop(L, 1); lua_createtable(L, 0, 1); lua_pushlightuserdata(L, KEY_HOOK); lua_pushvalue(L, -2); lua_rawset(L, LUA_REGISTRYINDEX); } } private static int db_sethook(LuaState L) { int arg, mask, count; lua_Hook func; LuaState L1 = getthread(L, out arg); if (lua_isnoneornil(L, arg + 1)) { lua_settop(L, arg + 1); func = null; mask = 0; count = 0; /* turn off hooks */ } else { CharPtr smask = luaL_checkstring(L, arg + 2); luaL_checktype(L, arg + 1, LUA_TFUNCTION); count = luaL_optint(L, arg + 3, 0); func = hookf; mask = makemask(smask, count); } gethooktable(L); lua_pushlightuserdata(L, L1); lua_pushvalue(L, arg + 1); lua_rawset(L, -3); /* set new hook */ lua_pop(L, 1); /* remove hook table */ lua_sethook(L1, func, mask, count); /* set hooks */ return 0; } private static int db_gethook(LuaState L) { int arg; LuaState L1 = getthread(L, out arg); CharPtr buff = new char[5]; int mask = lua_gethookmask(L1); lua_Hook hook = lua_gethook(L1); if (hook != null && hook != hookf) /* external hook? */ lua_pushliteral(L, "external hook"); else { gethooktable(L); lua_pushlightuserdata(L, L1); lua_rawget(L, -2); /* get hook */ lua_remove(L, -2); /* remove hook table */ } lua_pushstring(L, unmakemask(mask, buff)); lua_pushinteger(L, lua_gethookcount(L1)); return 3; } private static int db_debug(LuaState L) { for (; ; ) { CharPtr buffer = new char[250]; fputs("lua_debug> ", stderr); if (fgets(buffer, stdin) == null || strcmp(buffer, "cont\n") == 0) return 0; if (luaL_loadbuffer(L, buffer, (uint)strlen(buffer), "=(debug command)") != 0 || lua_pcall(L, 0, 0, 0) != 0) { fputs(lua_tostring(L, -1), stderr); fputs("\n", stderr); } lua_settop(L, 0); /* remove eventual returns */ } } public const int LEVELS1 = 12; /* size of the first part of the stack */ public const int LEVELS2 = 10; /* size of the second part of the stack */ internal static int db_errorfb(LuaState L) { int level; bool firstpart = true; /* still before eventual `...' */ int arg; LuaState L1 = getthread(L, out arg); lua_Debug ar = new lua_Debug(); if (lua_isnumber(L, arg + 2) != 0) { level = (int)lua_tointeger(L, arg + 2); lua_pop(L, 1); } else level = (L == L1) ? 1 : 0; /* level 0 may be this own function */ if (lua_gettop(L) == arg) lua_pushliteral(L, ""); else if (lua_isstring(L, arg + 1) == 0) return 1; /* message is not a string */ else lua_pushliteral(L, "\n"); lua_pushliteral(L, "stack traceback:"); while (lua_getstack(L1, level++, ar) != 0) { if (level > LEVELS1 && firstpart) { /* no more than `LEVELS2' more levels? */ if (lua_getstack(L1, level + LEVELS2, ar) == 0) level--; /* keep going */ else { lua_pushliteral(L, "\n\t..."); /* too many levels */ while (lua_getstack(L1, level + LEVELS2, ar) != 0) /* find last levels */ level++; } firstpart = false; continue; } lua_pushliteral(L, "\n\t"); lua_getinfo(L1, "Snl", ar); lua_pushfstring(L, "%s:", ar.short_src); if (ar.currentline > 0) lua_pushfstring(L, "%d:", ar.currentline); if (ar.namewhat != '\0') /* is there a name? */ lua_pushfstring(L, " in function " + LUA_QS, ar.name); else { if (ar.what == 'm') /* main? */ lua_pushfstring(L, " in main chunk"); else if (ar.what == "CLR" || ar.what == 't') { lua_pushliteral(L, " ?"); /* C function or tail call */ } else lua_pushfstring(L, " in function <%s:%d>", ar.short_src, ar.linedefined); } lua_concat(L, lua_gettop(L) - arg); } lua_concat(L, lua_gettop(L) - arg); return 1; } private readonly static luaL_Reg[] dblib = { new luaL_Reg("debug", db_debug), new luaL_Reg("getfenv", db_getfenv), new luaL_Reg("gethook", db_gethook), new luaL_Reg("getinfo", db_getinfo), new luaL_Reg("getlocal", db_getlocal), new luaL_Reg("getregistry", db_getregistry), new luaL_Reg("getmetatable", db_getmetatable), new luaL_Reg("getupvalue", db_getupvalue), new luaL_Reg("setfenv", db_setfenv), new luaL_Reg("sethook", db_sethook), new luaL_Reg("setlocal", db_setlocal), new luaL_Reg("setmetatable", db_setmetatable), new luaL_Reg("setupvalue", db_setupvalue), new luaL_Reg("traceback", db_errorfb), new luaL_Reg(null, null) }; public static int luaopen_debug(LuaState L) { luaL_register(L, LUA_DBLIBNAME, dblib); return 1; } } }
// =============================================================================== // Microsoft Data Access Application Block for .NET 3.0 // // Oldedb.cs // // This file contains the implementations of the AdoHelper supporting OleDb. // // For more information see the Documentation. // =============================================================================== // Release history // VERSION DESCRIPTION // 2.0 Added support for FillDataset, UpdateDataset and "Param" helper methods // 3.0 New abstract class supporting the same methods using ADO.NET interfaces // // =============================================================================== // Copyright (C) 2000-2001 Microsoft Corporation // All rights reserved. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR // FITNESS FOR A PARTICULAR PURPOSE. // ============================================================================== using System; using System.Collections; using System.Data; using System.Data.OleDb; using System.Text.RegularExpressions; using System.Xml; using System.IO; namespace org.swyn.foundation.db { /// <summary> /// The OleDb class is intended to encapsulate high performance, scalable best practices for /// common uses of the OleDb ADO.NET provider. It is created using the abstract factory in AdoHelper /// </summary> public class OleDb : AdoHelper { /// <summary> /// Create an OleDb Helper. Needs to be a default constructor so that the Factory can create it /// </summary> public OleDb() { } #region Overrides /// <summary> /// Returns an array of OleDbParameters of the specified size /// </summary> /// <param name="size">size of the array</param> /// <returns>The array of OdbcParameters</returns> protected override IDataParameter[] GetDataParameters(int size) { return new OleDbParameter[size]; } /// <summary> /// Returns an OleDbConnection object for the given connection string /// </summary> /// <param name="connectionString">The connection string to be used to create the connection</param> /// <returns>An OleDbConnection object</returns> public override IDbConnection GetConnection( string connectionString ) { return new OleDbConnection( connectionString ); } /// <summary> /// Returns an OleDbDataAdapter object /// </summary> /// <returns>The OleDbDataAdapter</returns> public override IDbDataAdapter GetDataAdapter() { return new OleDbDataAdapter(); } /// <summary> /// Calls the CommandBuilder.DeriveParameters method for the specified provider, doing any setup and cleanup necessary /// </summary> /// <param name="cmd">The IDbCommand referencing the stored procedure from which the parameter information is to be derived. The derived parameters are added to the Parameters collection of the IDbCommand. </param> public override void DeriveParameters( IDbCommand cmd ) { bool mustCloseConnection = false; if( !( cmd is OleDbCommand ) ) throw new ArgumentException( "The command provided is not a OleDbCommand instance.", "cmd" ); if (cmd.Connection.State != ConnectionState.Open) { cmd.Connection.Open(); mustCloseConnection = true; } OleDbCommandBuilder.DeriveParameters( (OleDbCommand)cmd ); if (mustCloseConnection) { cmd.Connection.Close(); } } /// <summary> /// Returns an OleDbParameter object /// </summary> /// <returns>The OleDbParameter object</returns> public override IDataParameter GetParameter() { return new OleDbParameter(); } /// <summary> /// This cleans up the parameter syntax for an OleDb call. This was split out from PrepareCommand so that it could be called independently. /// </summary> /// <param name="command">An IDbCommand object containing the CommandText to clean.</param> public override void CleanParameterSyntax(IDbCommand command) { } /// <summary> /// Execute an IDbCommand (that returns a resultset) against the provided IDbConnection. /// </summary> /// <example> /// <code> /// XmlReader r = helper.ExecuteXmlReader(command); /// </code></example> /// <param name="command">The IDbCommand to execute</param> /// <returns>An XmlReader containing the resultset generated by the command</returns> public override XmlReader ExecuteXmlReader(IDbCommand command) { bool mustCloseConnection = false; if (command.Connection.State != ConnectionState.Open) { command.Connection.Open(); mustCloseConnection = true; } CleanParameterSyntax(command); OleDbDataAdapter da = new OleDbDataAdapter((OleDbCommand)command); DataSet ds = new DataSet(); da.MissingSchemaAction = MissingSchemaAction.AddWithKey; da.Fill(ds); StringReader stream = new StringReader(ds.GetXml()); if (mustCloseConnection) { command.Connection.Close(); } return new XmlTextReader(stream); } /// <summary> /// Provider specific code to set up the updating/ed event handlers used by UpdateDataset /// </summary> /// <param name="dataAdapter">DataAdapter to attach the event handlers to</param> /// <param name="rowUpdatingHandler">The handler to be called when a row is updating</param> /// <param name="rowUpdatedHandler">The handler to be called when a row is updated</param> protected override void AddUpdateEventHandlers(IDbDataAdapter dataAdapter, RowUpdatingHandler rowUpdatingHandler, RowUpdatedHandler rowUpdatedHandler) { if (rowUpdatingHandler != null) { this.m_rowUpdating = rowUpdatingHandler; ((OleDbDataAdapter)dataAdapter).RowUpdating += new OleDbRowUpdatingEventHandler(RowUpdating); } if (rowUpdatedHandler != null) { this.m_rowUpdated = rowUpdatedHandler; ((OleDbDataAdapter)dataAdapter).RowUpdated += new OleDbRowUpdatedEventHandler(RowUpdated); } } /// <summary> /// Handles the RowUpdating event /// </summary> /// <param name="obj">The object that published the event</param> /// <param name="e">The OleDbRowUpdatingEventArgs</param> protected void RowUpdating(object obj, OleDbRowUpdatingEventArgs e) { base.RowUpdating(obj, e); } /// <summary> /// Handles the RowUpdated event /// </summary> /// <param name="obj">The object that published the event</param> /// <param name="e">The OleDbRowUpdatedEventArgs</param> protected void RowUpdated(object obj, OleDbRowUpdatedEventArgs e) { base.RowUpdated(obj, e); } /// <summary> /// Handle any provider-specific issues with BLOBs here by "washing" the IDataParameter and returning a new one that is set up appropriately for the provider. /// </summary> /// <param name="connection">The IDbConnection to use in cleansing the parameter</param> /// <param name="p">The parameter before cleansing</param> /// <returns>The parameter after it's been cleansed.</returns> protected override IDataParameter GetBlobParameter(IDbConnection connection, IDataParameter p) { // nothing special needed for OleDb...as far as we know now return p; } #endregion } }
/* Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2021 the ZAP development team * * 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; /* * This file was automatically generated. */ namespace OWASPZAPDotNetAPI.Generated { public class Spider { private ClientApi api = null; public Spider(ClientApi api) { this.api = api; } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse status(string scanid) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("scanId", scanid); return api.CallApi("spider", "view", "status", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse results(string scanid) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("scanId", scanid); return api.CallApi("spider", "view", "results", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse fullResults(string scanid) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("scanId", scanid); return api.CallApi("spider", "view", "fullResults", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse scans() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "scans", parameters); } /// <summary> ///Gets the regexes of URLs excluded from the spider scans. /// </summary> /// <returns></returns> public IApiResponse excludedFromScan() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "excludedFromScan", parameters); } /// <summary> ///Returns a list of unique URLs from the history table based on HTTP messages added by the Spider. /// </summary> /// <returns></returns> public IApiResponse allUrls() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "allUrls", parameters); } /// <summary> ///Returns a list of the names of the nodes added to the Sites tree by the specified scan. /// </summary> /// <returns></returns> public IApiResponse addedNodes(string scanid) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("scanId", scanid); return api.CallApi("spider", "view", "addedNodes", parameters); } /// <summary> ///Gets all the domains that are always in scope. For each domain the following are shown: the index, the value (domain), if enabled, and if specified as a regex. /// </summary> /// <returns></returns> public IApiResponse domainsAlwaysInScope() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "domainsAlwaysInScope", parameters); } /// <summary> ///Use view domainsAlwaysInScope instead. /// [Obsolete] /// </summary> /// <returns></returns> [Obsolete] public IApiResponse optionDomainsAlwaysInScope() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionDomainsAlwaysInScope", parameters); } /// <summary> ///Use view domainsAlwaysInScope instead. /// [Obsolete] /// </summary> /// <returns></returns> [Obsolete] public IApiResponse optionDomainsAlwaysInScopeEnabled() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionDomainsAlwaysInScopeEnabled", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse optionHandleParameters() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionHandleParameters", parameters); } /// <summary> ///Gets the maximum number of child nodes (per node) that can be crawled, 0 means no limit. /// </summary> /// <returns></returns> public IApiResponse optionMaxChildren() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionMaxChildren", parameters); } /// <summary> ///Gets the maximum depth the spider can crawl, 0 if unlimited. /// </summary> /// <returns></returns> public IApiResponse optionMaxDepth() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionMaxDepth", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse optionMaxDuration() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionMaxDuration", parameters); } /// <summary> ///Gets the maximum size, in bytes, that a response might have to be parsed. /// </summary> /// <returns></returns> public IApiResponse optionMaxParseSizeBytes() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionMaxParseSizeBytes", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse optionMaxScansInUI() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionMaxScansInUI", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse optionRequestWaitTime() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionRequestWaitTime", parameters); } /// <summary> /// /// [Obsolete] Option no longer in effective use. /// </summary> /// <returns></returns> [Obsolete("Option no longer in effective use.")] public IApiResponse optionScope() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionScope", parameters); } /// <summary> /// /// [Obsolete] Option no longer in effective use. /// </summary> /// <returns></returns> [Obsolete("Option no longer in effective use.")] public IApiResponse optionScopeText() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionScopeText", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse optionSkipURLString() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionSkipURLString", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse optionThreadCount() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionThreadCount", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse optionUserAgent() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionUserAgent", parameters); } /// <summary> ///Gets whether or not a spider process should accept cookies while spidering. /// </summary> /// <returns></returns> public IApiResponse optionAcceptCookies() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionAcceptCookies", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse optionHandleODataParametersVisited() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionHandleODataParametersVisited", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse optionParseComments() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionParseComments", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse optionParseGit() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionParseGit", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse optionParseRobotsTxt() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionParseRobotsTxt", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse optionParseSVNEntries() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionParseSVNEntries", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse optionParseSitemapXml() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionParseSitemapXml", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse optionPostForm() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionPostForm", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse optionProcessForm() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionProcessForm", parameters); } /// <summary> ///Gets whether or not the 'Referer' header should be sent while spidering. /// </summary> /// <returns></returns> public IApiResponse optionSendRefererHeader() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionSendRefererHeader", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse optionShowAdvancedDialog() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "view", "optionShowAdvancedDialog", parameters); } /// <summary> ///Runs the spider against the given URL (or context). Optionally, the 'maxChildren' parameter can be set to limit the number of children scanned, the 'recurse' parameter can be used to prevent the spider from seeding recursively, the parameter 'contextName' can be used to constrain the scan to a Context and the parameter 'subtreeOnly' allows to restrict the spider under a site's subtree (using the specified 'url'). /// </summary> /// <returns></returns> public IApiResponse scan(string url, string maxchildren, string recurse, string contextname, string subtreeonly) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("url", url); parameters.Add("maxChildren", maxchildren); parameters.Add("recurse", recurse); parameters.Add("contextName", contextname); parameters.Add("subtreeOnly", subtreeonly); return api.CallApi("spider", "action", "scan", parameters); } /// <summary> ///Runs the spider from the perspective of a User, obtained using the given Context ID and User ID. See 'scan' action for more details. /// </summary> /// <returns></returns> public IApiResponse scanAsUser(string contextid, string userid, string url, string maxchildren, string recurse, string subtreeonly) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("contextId", contextid); parameters.Add("userId", userid); parameters.Add("url", url); parameters.Add("maxChildren", maxchildren); parameters.Add("recurse", recurse); parameters.Add("subtreeOnly", subtreeonly); return api.CallApi("spider", "action", "scanAsUser", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse pause(string scanid) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("scanId", scanid); return api.CallApi("spider", "action", "pause", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse resume(string scanid) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("scanId", scanid); return api.CallApi("spider", "action", "resume", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse stop(string scanid) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("scanId", scanid); return api.CallApi("spider", "action", "stop", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse removeScan(string scanid) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("scanId", scanid); return api.CallApi("spider", "action", "removeScan", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse pauseAllScans() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "action", "pauseAllScans", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse resumeAllScans() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "action", "resumeAllScans", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse stopAllScans() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "action", "stopAllScans", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse removeAllScans() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "action", "removeAllScans", parameters); } /// <summary> ///Clears the regexes of URLs excluded from the spider scans. /// </summary> /// <returns></returns> public IApiResponse clearExcludedFromScan() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "action", "clearExcludedFromScan", parameters); } /// <summary> ///Adds a regex of URLs that should be excluded from the spider scans. /// </summary> /// <returns></returns> public IApiResponse excludeFromScan(string regex) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("regex", regex); return api.CallApi("spider", "action", "excludeFromScan", parameters); } /// <summary> ///Adds a new domain that's always in scope, using the specified value. Optionally sets if the new entry is enabled (default, true) and whether or not the new value is specified as a regex (default, false). /// </summary> /// <returns></returns> public IApiResponse addDomainAlwaysInScope(string value, string isregex, string isenabled) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("value", value); parameters.Add("isRegex", isregex); parameters.Add("isEnabled", isenabled); return api.CallApi("spider", "action", "addDomainAlwaysInScope", parameters); } /// <summary> ///Modifies a domain that's always in scope. Allows to modify the value, if enabled or if a regex. The domain is selected with its index, which can be obtained with the view domainsAlwaysInScope. /// </summary> /// <returns></returns> public IApiResponse modifyDomainAlwaysInScope(string idx, string value, string isregex, string isenabled) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("idx", idx); parameters.Add("value", value); parameters.Add("isRegex", isregex); parameters.Add("isEnabled", isenabled); return api.CallApi("spider", "action", "modifyDomainAlwaysInScope", parameters); } /// <summary> ///Removes a domain that's always in scope, with the given index. The index can be obtained with the view domainsAlwaysInScope. /// </summary> /// <returns></returns> public IApiResponse removeDomainAlwaysInScope(string idx) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("idx", idx); return api.CallApi("spider", "action", "removeDomainAlwaysInScope", parameters); } /// <summary> ///Enables all domains that are always in scope. /// </summary> /// <returns></returns> public IApiResponse enableAllDomainsAlwaysInScope() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "action", "enableAllDomainsAlwaysInScope", parameters); } /// <summary> ///Disables all domains that are always in scope. /// </summary> /// <returns></returns> public IApiResponse disableAllDomainsAlwaysInScope() { Dictionary<string, string> parameters = null; return api.CallApi("spider", "action", "disableAllDomainsAlwaysInScope", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse setOptionHandleParameters(string str) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("String", str); return api.CallApi("spider", "action", "setOptionHandleParameters", parameters); } /// <summary> ///Use actions [add|modify|remove]DomainAlwaysInScope instead. /// [Obsolete] Option no longer in effective use. /// </summary> /// <returns></returns> [Obsolete("Option no longer in effective use.")] public IApiResponse setOptionScopeString(string str) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("String", str); return api.CallApi("spider", "action", "setOptionScopeString", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse setOptionSkipURLString(string str) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("String", str); return api.CallApi("spider", "action", "setOptionSkipURLString", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse setOptionUserAgent(string str) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("String", str); return api.CallApi("spider", "action", "setOptionUserAgent", parameters); } /// <summary> ///Sets whether or not a spider process should accept cookies while spidering. /// </summary> /// <returns></returns> public IApiResponse setOptionAcceptCookies(bool boolean) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("Boolean", Convert.ToString(boolean)); return api.CallApi("spider", "action", "setOptionAcceptCookies", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse setOptionHandleODataParametersVisited(bool boolean) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("Boolean", Convert.ToString(boolean)); return api.CallApi("spider", "action", "setOptionHandleODataParametersVisited", parameters); } /// <summary> ///Sets the maximum number of child nodes (per node) that can be crawled, 0 means no limit. /// </summary> /// <returns></returns> public IApiResponse setOptionMaxChildren(int i) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("Integer", Convert.ToString(i)); return api.CallApi("spider", "action", "setOptionMaxChildren", parameters); } /// <summary> ///Sets the maximum depth the spider can crawl, 0 for unlimited depth. /// </summary> /// <returns></returns> public IApiResponse setOptionMaxDepth(int i) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("Integer", Convert.ToString(i)); return api.CallApi("spider", "action", "setOptionMaxDepth", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse setOptionMaxDuration(int i) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("Integer", Convert.ToString(i)); return api.CallApi("spider", "action", "setOptionMaxDuration", parameters); } /// <summary> ///Sets the maximum size, in bytes, that a response might have to be parsed. This allows the spider to skip big responses/files. /// </summary> /// <returns></returns> public IApiResponse setOptionMaxParseSizeBytes(int i) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("Integer", Convert.ToString(i)); return api.CallApi("spider", "action", "setOptionMaxParseSizeBytes", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse setOptionMaxScansInUI(int i) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("Integer", Convert.ToString(i)); return api.CallApi("spider", "action", "setOptionMaxScansInUI", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse setOptionParseComments(bool boolean) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("Boolean", Convert.ToString(boolean)); return api.CallApi("spider", "action", "setOptionParseComments", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse setOptionParseGit(bool boolean) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("Boolean", Convert.ToString(boolean)); return api.CallApi("spider", "action", "setOptionParseGit", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse setOptionParseRobotsTxt(bool boolean) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("Boolean", Convert.ToString(boolean)); return api.CallApi("spider", "action", "setOptionParseRobotsTxt", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse setOptionParseSVNEntries(bool boolean) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("Boolean", Convert.ToString(boolean)); return api.CallApi("spider", "action", "setOptionParseSVNEntries", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse setOptionParseSitemapXml(bool boolean) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("Boolean", Convert.ToString(boolean)); return api.CallApi("spider", "action", "setOptionParseSitemapXml", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse setOptionPostForm(bool boolean) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("Boolean", Convert.ToString(boolean)); return api.CallApi("spider", "action", "setOptionPostForm", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse setOptionProcessForm(bool boolean) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("Boolean", Convert.ToString(boolean)); return api.CallApi("spider", "action", "setOptionProcessForm", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse setOptionRequestWaitTime(int i) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("Integer", Convert.ToString(i)); return api.CallApi("spider", "action", "setOptionRequestWaitTime", parameters); } /// <summary> ///Sets whether or not the 'Referer' header should be sent while spidering. /// </summary> /// <returns></returns> public IApiResponse setOptionSendRefererHeader(bool boolean) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("Boolean", Convert.ToString(boolean)); return api.CallApi("spider", "action", "setOptionSendRefererHeader", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse setOptionShowAdvancedDialog(bool boolean) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("Boolean", Convert.ToString(boolean)); return api.CallApi("spider", "action", "setOptionShowAdvancedDialog", parameters); } /// <summary> /// /// </summary> /// <returns></returns> public IApiResponse setOptionThreadCount(int i) { Dictionary<string, string> parameters = null; parameters = new Dictionary<string, string>(); parameters.Add("Integer", Convert.ToString(i)); return api.CallApi("spider", "action", "setOptionThreadCount", parameters); } } }
using J2N.Text; using Lucene.Net.Analysis; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using Lucene.Net.Search; using Lucene.Net.Search.Similarities; using Lucene.Net.Store; using System; using System.Collections.Generic; using System.Globalization; using System.Text; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ internal class DocHelper { public static FieldType CustomType { get; private set; } = new FieldType(TextField.TYPE_STORED); public const string FIELD_1_TEXT = "field one text"; public const string TEXT_FIELD_1_KEY = "textField1"; public static Field TextField1 = new Field(TEXT_FIELD_1_KEY, FIELD_1_TEXT, CustomType); public static FieldType CustomType2 { get; private set; } = new FieldType(TextField.TYPE_STORED) { StoreTermVectors = true, StoreTermVectorPositions = true, StoreTermVectorOffsets = true }; public const string FIELD_2_TEXT = "field field field two text"; //Fields will be lexicographically sorted. So, the order is: field, text, two public static readonly int[] FIELD_2_FREQS = new int[] { 3, 1, 1 }; public const string TEXT_FIELD_2_KEY = "textField2"; public static Field TextField2 { get; set; } = new Field(TEXT_FIELD_2_KEY, FIELD_2_TEXT, CustomType2); public static FieldType CustomType3 { get; private set; } = new FieldType(TextField.TYPE_STORED) { OmitNorms = true }; public const string FIELD_3_TEXT = "aaaNoNorms aaaNoNorms bbbNoNorms"; public const string TEXT_FIELD_3_KEY = "textField3"; public static Field TextField3 { get; set; } = new Field(TEXT_FIELD_3_KEY, FIELD_3_TEXT, CustomType3); public const string KEYWORD_TEXT = "Keyword"; public const string KEYWORD_FIELD_KEY = "keyField"; public static Field KeyField { get; set; } = new StringField(KEYWORD_FIELD_KEY, KEYWORD_TEXT, Field.Store.YES); public static FieldType CustomType5 { get; private set; } = new FieldType(TextField.TYPE_STORED) { OmitNorms = true, IsTokenized = false }; public const string NO_NORMS_TEXT = "omitNormsText"; public const string NO_NORMS_KEY = "omitNorms"; public static Field NoNormsField { get; set; } = new Field(NO_NORMS_KEY, NO_NORMS_TEXT, CustomType5); public static FieldType CustomType6 { get; private set; } = new FieldType(TextField.TYPE_STORED) { IndexOptions = IndexOptions.DOCS_ONLY }; public const string NO_TF_TEXT = "analyzed with no tf and positions"; public const string NO_TF_KEY = "omitTermFreqAndPositions"; public static Field NoTFField { get; set; } = new Field(NO_TF_KEY, NO_TF_TEXT, CustomType6); public static FieldType CustomType7 { get; private set; } = new FieldType { IsStored = true }; public const string UNINDEXED_FIELD_TEXT = "unindexed field text"; public const string UNINDEXED_FIELD_KEY = "unIndField"; public static Field UnIndField { get; set; } = new Field(UNINDEXED_FIELD_KEY, UNINDEXED_FIELD_TEXT, CustomType7); public const string UNSTORED_1_FIELD_TEXT = "unstored field text"; public const string UNSTORED_FIELD_1_KEY = "unStoredField1"; public static Field UnStoredField1 { get; set; } = new TextField(UNSTORED_FIELD_1_KEY, UNSTORED_1_FIELD_TEXT, Field.Store.NO); public static FieldType CustomType8 { get; private set; } = new FieldType(TextField.TYPE_NOT_STORED) { StoreTermVectors = true }; public const string UNSTORED_2_FIELD_TEXT = "unstored field text"; public const string UNSTORED_FIELD_2_KEY = "unStoredField2"; public static Field UnStoredField2 { get; set; } = new Field(UNSTORED_FIELD_2_KEY, UNSTORED_2_FIELD_TEXT, CustomType8); public const string LAZY_FIELD_BINARY_KEY = "lazyFieldBinary"; public static byte[] LAZY_FIELD_BINARY_BYTES; public static Field LazyFieldBinary { get; set; } public const string LAZY_FIELD_KEY = "lazyField"; public const string LAZY_FIELD_TEXT = "These are some field bytes"; public static Field LazyField { get; set; } = new Field(LAZY_FIELD_KEY, LAZY_FIELD_TEXT, CustomType); public const string LARGE_LAZY_FIELD_KEY = "largeLazyField"; public static string LARGE_LAZY_FIELD_TEXT; public static Field LargeLazyField { get; set; } //From Issue 509 public const string FIELD_UTF1_TEXT = "field one \u4e00text"; public const string TEXT_FIELD_UTF1_KEY = "textField1Utf8"; public static Field TextUtfField1 { get; set; } = new Field(TEXT_FIELD_UTF1_KEY, FIELD_UTF1_TEXT, CustomType); public const string FIELD_UTF2_TEXT = "field field field \u4e00two text"; //Fields will be lexicographically sorted. So, the order is: field, text, two public static readonly int[] FIELD_UTF2_FREQS = new int[] { 3, 1, 1 }; public const string TEXT_FIELD_UTF2_KEY = "textField2Utf8"; public static Field TextUtfField2 { get; set; } = new Field(TEXT_FIELD_UTF2_KEY, FIELD_UTF2_TEXT, CustomType2); public static IDictionary<string, object> NameValues { get; set; } = null; // ordered list of all the fields... // could use LinkedHashMap for this purpose if Java1.4 is OK public static Field[] Fields = new Field[] // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006) { TextField1, TextField2, TextField3, KeyField, NoNormsField, NoTFField, UnIndField, UnStoredField1, UnStoredField2, TextUtfField1, TextUtfField2, LazyField, LazyFieldBinary, LargeLazyField }; public static IDictionary<string, IIndexableField> All { get; set; } = new Dictionary<string, IIndexableField>(); public static IDictionary<string, IIndexableField> Indexed { get; set; } = new Dictionary<string, IIndexableField>(); public static IDictionary<string, IIndexableField> Stored { get; set; } = new Dictionary<string, IIndexableField>(); public static IDictionary<string, IIndexableField> Unstored { get; set; } = new Dictionary<string, IIndexableField>(); public static IDictionary<string, IIndexableField> Unindexed { get; set; } = new Dictionary<string, IIndexableField>(); public static IDictionary<string, IIndexableField> Termvector { get; set; } = new Dictionary<string, IIndexableField>(); public static IDictionary<string, IIndexableField> Notermvector { get; set; } = new Dictionary<string, IIndexableField>(); public static IDictionary<string, IIndexableField> Lazy { get; set; } = new Dictionary<string, IIndexableField>(); public static IDictionary<string, IIndexableField> NoNorms { get; set; } = new Dictionary<string, IIndexableField>(); public static IDictionary<string, IIndexableField> NoTf { get; set; } = new Dictionary<string, IIndexableField>(); private static void Add(IDictionary<string, IIndexableField> map, IIndexableField field) { map[field.Name] = field; } /// <summary> /// Adds the fields above to a document </summary> /// <param name="doc"> The document to write </param> public static void SetupDoc(Document doc) { for (int i = 0; i < Fields.Length; i++) { doc.Add(Fields[i]); } } /// <summary> /// Writes the document to the directory using a segment /// named "test"; returns the <see cref="SegmentInfo"/> describing the new /// segment. /// </summary> public static SegmentCommitInfo WriteDoc(Random random, Directory dir, Document doc) { return WriteDoc(random, dir, new MockAnalyzer(random, MockTokenizer.WHITESPACE, false), null, doc); } /// <summary> /// Writes the document to the directory using the analyzer /// and the similarity score; returns the <see cref="SegmentInfo"/> /// describing the new segment. /// </summary> #pragma warning disable IDE0060 // Remove unused parameter public static SegmentCommitInfo WriteDoc(Random random, Directory dir, Analyzer analyzer, Similarity similarity, Document doc) #pragma warning restore IDE0060 // Remove unused parameter { using IndexWriter writer = new IndexWriter(dir, (new IndexWriterConfig(Util.LuceneTestCase.TEST_VERSION_CURRENT, analyzer)).SetSimilarity(similarity ?? IndexSearcher.DefaultSimilarity)); //writer.SetNoCFSRatio(0.0); writer.AddDocument(doc); writer.Commit(); SegmentCommitInfo info = writer.NewestSegment(); return info; } public static int NumFields(Document doc) { return doc.Fields.Count; } public static Document CreateDocument(int n, string indexName, int numFields) { StringBuilder sb = new StringBuilder(); FieldType customType = new FieldType(TextField.TYPE_STORED); customType.StoreTermVectors = true; customType.StoreTermVectorPositions = true; customType.StoreTermVectorOffsets = true; FieldType customType1 = new FieldType(StringField.TYPE_STORED); customType1.StoreTermVectors = true; customType1.StoreTermVectorPositions = true; customType1.StoreTermVectorOffsets = true; Document doc = new Document(); doc.Add(new Field("id", Convert.ToString(n, CultureInfo.InvariantCulture), customType1)); doc.Add(new Field("indexname", indexName, customType1)); sb.Append("a"); sb.Append(n); doc.Add(new Field("field1", sb.ToString(), customType)); sb.Append(" b"); sb.Append(n); for (int i = 1; i < numFields; i++) { doc.Add(new Field("field" + (i + 1), sb.ToString(), customType)); } return doc; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1810:Initialize reference type static fields inline", Justification = "Complexity")] static DocHelper() { //Initialize the large Lazy Field StringBuilder buffer = new StringBuilder(); for (int i = 0; i < 10000; i++) { buffer.Append("Lazily loading lengths of language in lieu of laughing "); } try { LAZY_FIELD_BINARY_BYTES = "These are some binary field bytes".GetBytes(Encoding.UTF8); } catch (EncoderFallbackException) { } LazyFieldBinary = new StoredField(LAZY_FIELD_BINARY_KEY, LAZY_FIELD_BINARY_BYTES); Fields[Fields.Length - 2] = LazyFieldBinary; LARGE_LAZY_FIELD_TEXT = buffer.ToString(); LargeLazyField = new Field(LARGE_LAZY_FIELD_KEY, LARGE_LAZY_FIELD_TEXT, CustomType); Fields[Fields.Length - 1] = LargeLazyField; for (int i = 0; i < Fields.Length; i++) { IIndexableField f = Fields[i]; Add(All, f); if (f.IndexableFieldType.IsIndexed) { Add(Indexed, f); } else { Add(Unindexed, f); } if (f.IndexableFieldType.StoreTermVectors) { Add(Termvector, f); } if (f.IndexableFieldType.IsIndexed && !f.IndexableFieldType.StoreTermVectors) { Add(Notermvector, f); } if (f.IndexableFieldType.IsStored) { Add(Stored, f); } else { Add(Unstored, f); } if (f.IndexableFieldType.IndexOptions == IndexOptions.DOCS_ONLY) { Add(NoTf, f); } if (f.IndexableFieldType.OmitNorms) { Add(NoNorms, f); } if (f.IndexableFieldType.IndexOptions == IndexOptions.DOCS_ONLY) { Add(NoTf, f); } //if (f.isLazy()) add(lazy, f); } NameValues = new Dictionary<string, object> { { TEXT_FIELD_1_KEY, FIELD_1_TEXT }, { TEXT_FIELD_2_KEY, FIELD_2_TEXT }, { TEXT_FIELD_3_KEY, FIELD_3_TEXT }, { KEYWORD_FIELD_KEY, KEYWORD_TEXT }, { NO_NORMS_KEY, NO_NORMS_TEXT }, { NO_TF_KEY, NO_TF_TEXT }, { UNINDEXED_FIELD_KEY, UNINDEXED_FIELD_TEXT }, { UNSTORED_FIELD_1_KEY, UNSTORED_1_FIELD_TEXT }, { UNSTORED_FIELD_2_KEY, UNSTORED_2_FIELD_TEXT }, { LAZY_FIELD_KEY, LAZY_FIELD_TEXT }, { LAZY_FIELD_BINARY_KEY, LAZY_FIELD_BINARY_BYTES }, { LARGE_LAZY_FIELD_KEY, LARGE_LAZY_FIELD_TEXT }, { TEXT_FIELD_UTF1_KEY, FIELD_UTF1_TEXT }, { TEXT_FIELD_UTF2_KEY, FIELD_UTF2_TEXT } }; } } }
#region Using directives using System.Collections.Generic; using System; #endregion namespace SimpleFramework.Xml.Util { public class LanguageConverter : Replace { private const List<Class<? : ConversionPhase>> STAGE_ONE = new ArrayList<Class<? : ConversionPhase>>(); private const List<Class<? : SubstitutionPhase>> STAGE_TWO = new ArrayList<Class<? : SubstitutionPhase>>(); private const Map<String, String> NAMESPACE = new LinkedHashMap<String, String>(); private const Map<String, String> USING = new LinkedHashMap<String, String>(); private const Map<String, String> FILES = new LinkedHashMap<String, String>(); private static Map<String, String> IMPORT_TO_USING = new LinkedHashMap<String, String>(); private const String INDENT = " "; static { IMPORT_TO_USING.put("SimpleFramework.Xml.Core.*", "using SimpleFramework.Xml.Core;"); IMPORT_TO_USING.put("SimpleFramework.Xml.Util.*", "using SimpleFramework.Xml.Convert;"); IMPORT_TO_USING.put("SimpleFramework.Xml.Strategy.*", "using SimpleFramework.Xml.Strategy;"); IMPORT_TO_USING.put("SimpleFramework.Xml.Filter.*", "using SimpleFramework.Xml.Filter;"); IMPORT_TO_USING.put("SimpleFramework.Xml.Stream.*", "using SimpleFramework.Xml.Stream;"); IMPORT_TO_USING.put("SimpleFramework.Xml.transform.*", "using SimpleFramework.Xml.Transform;"); IMPORT_TO_USING.put("SimpleFramework.Xml.Util.*", "using SimpleFramework.Xml.Util;"); IMPORT_TO_USING.put("SimpleFramework.Xml.Util.*", "using SimpleFramework.Xml;"); IMPORT_TO_USING.put("java.util.*","using System.Collections.Generic;"); IMPORT_TO_USING.put("junit.framework.*", "using SimpleFramework.Xml;"); } static { FILES.put("C:\\Users\\niall\\Workspace\\xml\\src\\test\\java\\org\\simpleframework\\xml", "C:\\Users\\niall\\Workspace\\SimpleFramework\\SimpleFramework\\SimpleFramework\\src\\main\\Xml"); FILES.put("C:\\Users\\niall\\Workspace\\xml\\src\\test\\java\\org\\simpleframework\\xml\\core", "C:\\Users\\niall\\Workspace\\SimpleFramework\\SimpleFramework\\SimpleFramework\\src\\main\\Xml\\Core"); //FILES.put("C:\\Users\\niall\\Workspace\\xml\\src\\test\\java\\org\\simpleframework\\xml\\filter", "C:\\Users\\niall\\Workspace\\SimpleFramework\\SimpleFramework\\SimpleFramework\\src\\main\\Xml\\Filter"); FILES.put("C:\\Users\\niall\\Workspace\\xml\\src\\test\\java\\org\\simpleframework\\xml\\strategy", "C:\\Users\\niall\\Workspace\\SimpleFramework\\SimpleFramework\\SimpleFramework\\src\\main\\Xml\\Strategy"); FILES.put("C:\\Users\\niall\\Workspace\\xml\\src\\test\\java\\org\\simpleframework\\xml\\stream", "C:\\Users\\niall\\Workspace\\SimpleFramework\\SimpleFramework\\SimpleFramework\\src\\main\\Xml\\Stream"); FILES.put("C:\\Users\\niall\\Workspace\\xml\\src\\test\\java\\org\\simpleframework\\xml\\convert", "C:\\Users\\niall\\Workspace\\SimpleFramework\\SimpleFramework\\SimpleFramework\\src\\main\\Xml\\Convert"); FILES.put("C:\\Users\\niall\\Workspace\\xml\\src\\test\\java\\org\\simpleframework\\xml\\transform", "C:\\Users\\niall\\Workspace\\SimpleFramework\\SimpleFramework\\SimpleFramework\\src\\main\\Xml\\Transform"); FILES.put("C:\\Users\\niall\\Workspace\\xml\\src\\test\\java\\org\\simpleframework\\xml\\util", "C:\\Users\\niall\\Workspace\\SimpleFramework\\SimpleFramework\\SimpleFramework\\src\\main\\Xml\\Util"); FILES.put("C:\\Users\\niall\\Workspace\\xml\\src\\main\\java\\org\\simpleframework\\xml", "C:\\Users\\niall\\Workspace\\SimpleFramework\\SimpleFramework\\SimpleFramework\\src\\main\\Xml"); FILES.put("C:\\Users\\niall\\Workspace\\xml\\src\\main\\java\\org\\simpleframework\\xml\\core", "C:\\Users\\niall\\Workspace\\SimpleFramework\\SimpleFramework\\SimpleFramework\\src\\main\\Xml\\Core"); //FILES.put("C:\\Users\\niall\\Workspace\\xml\\src\\main\\java\\org\\simpleframework\\xml\\filter", "C:\\Users\\niall\\Workspace\\SimpleFramework\\SimpleFramework\\SimpleFramework\\src\\main\\Xml\\Filter"); FILES.put("C:\\Users\\niall\\Workspace\\xml\\src\\main\\java\\org\\simpleframework\\xml\\strategy", "C:\\Users\\niall\\Workspace\\SimpleFramework\\SimpleFramework\\SimpleFramework\\src\\main\\Xml\\Strategy"); FILES.put("C:\\Users\\niall\\Workspace\\xml\\src\\main\\java\\org\\simpleframework\\xml\\stream", "C:\\Users\\niall\\Workspace\\SimpleFramework\\SimpleFramework\\SimpleFramework\\src\\main\\Xml\\Stream"); FILES.put("C:\\Users\\niall\\Workspace\\xml\\src\\main\\java\\org\\simpleframework\\xml\\convert", "C:\\Users\\niall\\Workspace\\SimpleFramework\\SimpleFramework\\SimpleFramework\\src\\main\\Xml\\Convert"); FILES.put("C:\\Users\\niall\\Workspace\\xml\\src\\main\\java\\org\\simpleframework\\xml\\transform", "C:\\Users\\niall\\Workspace\\SimpleFramework\\SimpleFramework\\SimpleFramework\\src\\main\\Xml\\Transform"); FILES.put("C:\\Users\\niall\\Workspace\\xml\\src\\main\\java\\org\\simpleframework\\xml\\util", "C:\\Users\\niall\\Workspace\\SimpleFramework\\SimpleFramework\\SimpleFramework\\src\\main\\Xml\\Util"); } static { USING.put("import SimpleFramework.Xml.Util.*","using SimpleFramework.Xml.Util;"); USING.put("import SimpleFramework.Xml.Filter.*", "using SimpleFramework.Xml.Filter;"); USING.put("import SimpleFramework.Xml.Strategy.*", "using SimpleFramework.Xml.Strategy;"); USING.put("import SimpleFramework.Xml.Core.*","using SimpleFramework.Xml.Core;"); USING.put("import SimpleFramework.Xml.Util.*", "using SimpleFramework.Xml.Util;"); USING.put("import SimpleFramework.Xml.Stream.*","using SimpleFramework.Xml.Stream;"); USING.put("import SimpleFramework.Xml.*","using SimpleFramework.Xml;"); USING.put("import java.util.*","using System.Collections.Generic;"); } static { NAMESPACE.put("package SimpleFramework.Xml;","namespace SimpleFramework.Xml {"); NAMESPACE.put("package SimpleFramework.Xml.Util;","namespace SimpleFramework.Xml.Util {"); NAMESPACE.put("package SimpleFramework.Xml.Filter;", "namespace SimpleFramework.Xml.Filter {"); NAMESPACE.put("package SimpleFramework.Xml.Strategy;", "namespace SimpleFramework.Xml.Strategy {"); NAMESPACE.put("package SimpleFramework.Xml.Core;","namespace SimpleFramework.Xml.Core {"); NAMESPACE.put("package SimpleFramework.Xml.Util;", "namespace SimpleFramework.Xml.Util {"); NAMESPACE.put("package SimpleFramework.Xml.Stream;","namespace SimpleFramework.Xml.Stream {"); } static { STAGE_ONE.Add(CanonicalizeFile.class); STAGE_ONE.Add(DefineType.class); STAGE_ONE.Add(PopulateUsing.class); STAGE_ONE.Add(StripImports.class); STAGE_ONE.Add(AddUsing.class); STAGE_ONE.Add(CreateNamespace.class); STAGE_ONE.Add(GetFields.class); STAGE_ONE.Add(ConvertAnnotationAttributes.class); STAGE_ONE.Add(ReplaceComments.class); STAGE_ONE.Add(ReplaceDocumentation.class); STAGE_ONE.Add(ReplaceKeyWords.class); STAGE_ONE.Add(ReplaceMethodConventions.class); STAGE_ONE.Add(StripCrap.class); STAGE_ONE.Add(ReplaceLicense.class); STAGE_ONE.Add(SubstituteAnnotations.class); STAGE_ONE.Add(SetAnnotationAttributes.class); STAGE_ONE.Add(ConvertClassBeanMethods.class); STAGE_ONE.Add(ReplaceAnnotations.class); } static { STAGE_TWO.Add(SubstituteMethods.class); //STAGE_TWO.Add(StripPublicFromInterfaces.class); } public void Main(String list[]) { Set<String> filesDone = new HashSet<String>(); SourceProject project = new SourceProject(); for(String from : FILES.keySet()) { List<File> files = getFiles(new File(from), false); String to = FILES.get(from); for(File file : files) { File result = new File(to, file.Name.replaceAll("\\.java", ".cs")); if(filesDone.contains(file.getCanonicalPath())) { throw new IllegalStateException("File '"+file.getCanonicalPath()+"' has already been examined"); } if(filesDone.contains(result.getCanonicalPath())) { throw new IllegalStateException("Result '"+result.getCanonicalPath()+"' has already been written"); } filesDone.Add(file.getCanonicalPath()); filesDone.Add(result.getCanonicalPath()); SourceDetails details = new SourceDetails(file, result); String text = getFile(file); details.Text = text; for(Class<? : ConversionPhase> phaseType : STAGE_ONE) { Constructor<? : ConversionPhase> factory = phaseType.getDeclaredConstructor(); if(!factory.isAccessible()) { factory.setAccessible(true); } ConversionPhase phase = factory.newInstance(); details.setText(phase.Convert(details.Text, details)); } project.AddSource(details); } } for(SourceDetails details : project.GetDetails()) { for(Class<? : SubstitutionPhase> phaseType : STAGE_TWO) { Constructor<? : SubstitutionPhase> factory = phaseType.getDeclaredConstructor(); if(!factory.isAccessible()) { factory.setAccessible(true); } SubstitutionPhase phase = factory.newInstance(); details.setText(phase.Convert(details.Text, details, project)); } } List<String> newFiles = new ArrayList<String>(); for(SourceDetails details : project.GetDetails()) { File saveAs = details.Destination; save(saveAs, details.Text); if(!filesDone.contains(saveAs.getCanonicalPath())) { throw new IllegalStateException("Can not save to '"+saveAs.getCanonicalPath()+"' it has not a valid path"); } newFiles.Add(saveAs.getCanonicalPath().replaceAll("^.*src", "src")); } for(String entry : newFiles) { System.out.println(" <Compile Include=\""+entry+"\"/>"); } } public String ConvertMethod(String originalMethod, MethodType type) { if(type == null || type == MethodType.NORMAL) { if(originalMethod != null && !Character.isUpperCase(originalMethod.charAt(0))){ StringBuilder builder = new StringBuilder(originalMethod.length()); char first = originalMethod.charAt(0); builder.append(Character.toUpperCase(first)); builder.append(originalMethod.substring(1)); return builder.ToString(); } } else if(type == MethodType.GET) { if(originalMethod != null){ return originalMethod.substring(3); } } else if(type == MethodType.SET) { if(originalMethod != null){ return originalMethod.substring(3); } } return originalMethod; } private static enum SourceType { ANNOTATION, INTERFACE, CLASS, ENUM } private static class SourceDetails { private Set<String> using = new TreeSet<String>(); private Map<String, String> attributes = new LinkedHashMap<String, String>(); private Map<String, String> fields = new LinkedHashMap<String, String>(); private List<String> imports = new ArrayList<String>(); private List<MethodSignature> methods = new ArrayList<MethodSignature>(); private String packageName; private SourceType type; private String name; private File destination; private File source; private String text; public SourceDetails(File source, File destination) { this.using.Add("using System;"); this.destination = destination; this.source = source; } public String Text { get { return text; } } //public String GetText() { // return text; //} this.text = text; } public File Destination { get { return destination; } } //public File GetDestination() { // return destination; //} return source; } public String Name { get { return name; } } //public String GetName() { // return name; //} this.name = name; } public String Package { get { return packageName; } } //public String GetPackage() { // return packageName; //} this.packageName = packageName; } public String FullyQualifiedName { get { return String.format("%s.%s", packageName, name); } } //public String GetFullyQualifiedName() { // return String.format("%s.%s", packageName, name); //} return type; } public SourceType Type { set { this.type = value; } } //public void SetType(SourceType type) { // this.type = type; //} return using; } public void AddMethod(MethodSignature method) { methods.Add(method); } public List<MethodSignature> Methods { get { return methods; } } //public List<MethodSignature> GetMethods() { // return methods; //} for(String pattern : IMPORT_TO_USING.keySet()) { if(importClass.matches(pattern)) { using.Add(IMPORT_TO_USING.get(pattern)); } } imports.Add(importClass); } public List<String> Imports { get { return imports; } } //public List<String> GetImports() { // return imports; //} return attributes; } public void AddAttribute(String type, String attribute) { attributes.put(attribute, type); } public void AddUsing(String usingValue) { using.Add(usingValue); } public Map<String, String> getFields() { return fields; } public void AddField(String name, String type) { fields.put(name, type); } } private static enum MethodType { GET, SET, NORMAL } private static class MethodSignature { private readonly String name; private readonly String value; private readonly MethodType type; public MethodSignature(String name, MethodType type, String value) { this.name = name; this.type = type; this.value = value; } public String ToString() { return String.format("[%s][%s][%s]", name, type, value); } } private static class SourceProject { private Map<String, List<SourceDetails>> packages = new HashMap<String, List<SourceDetails>>(); private Map<String, SourceDetails> names = new HashMap<String, SourceDetails>(); private List<SourceDetails> all = new ArrayList<SourceDetails>(); public List<SourceDetails> Details { get { return all; } } //public List<SourceDetails> GetDetails() { // return all; //} String packageName = details.Package; String name = details.Name; List<SourceDetails> packageFiles = packages.get(packageName); if(packageFiles == null) { packageFiles = new ArrayList<SourceDetails>(); packages.put(packageName, packageFiles); } packageFiles.Add(details); all.Add(details); names.put(name, details); } public SourceDetails GetDetails(String name) { return names.get(name); } } private static abstract class SubstitutionPhase { public Map<String, String> calculateSubstututions(SourceDetails details, SourceProject project) { Map<String, String> substitutes = new HashMap<String, String>(); for(String field : details.getFields().keySet()) { String type = details.getFields().get(field); SourceDetails fieldDetails = project.GetDetails(type); if(fieldDetails != null) { PopulateFrom(fieldDetails, field, substitutes); } } PopulateFrom(details, null, substitutes); return substitutes; } public void PopulateFrom(SourceDetails details, String field, Map<String, String> substitutes) { List<MethodSignature> methods = details.Methods; for(MethodSignature originalMethod : details.Methods) { if(originalMethod.type == MethodType.GET) { substitutes.put(originalMethod.name+"\\(\\)", ConvertMethod(originalMethod.name, originalMethod.type)); } else if(originalMethod.type == MethodType.SET) { substitutes.put(originalMethod.name+"\\([a-zA-Z\\s]+\\)", ConvertMethod(originalMethod.name, originalMethod.type) + " = "+originalMethod.value); } else { substitutes.put(originalMethod.name+"\\(", ConvertMethod(originalMethod.name, MethodType.NORMAL)+"\\("); } } if(field != null && !field.equals("")) { for(MethodSignature originalMethod : methods) { String originalToken = String.format("%s.%s", field, originalMethod.name); if(originalMethod.type == MethodType.GET) { String token = String.format("%s.%s", field, ConvertMethod(originalMethod.name, originalMethod.type)); substitutes.put(originalToken+"\\(\\)", token); } else if(originalMethod.type == MethodType.SET) { String token = String.format("%s.%s = %s", field, ConvertMethod(originalMethod.name, originalMethod.type), originalMethod.value); substitutes.put(originalToken+"\\([a-zA-Z\\s]+\\)", token); } else { String token = String.format("%s.%s\\(", field, ConvertMethod(originalMethod.name, MethodType.NORMAL)); substitutes.put(originalToken+"\\(", token); } } } } public abstract String Convert(String source, SourceDetails details, SourceProject project); } public static class SubstituteMethods : SubstitutionPhase { public String Convert(String source, SourceDetails details, SourceProject project) { List<String> lines = stripLines(source); Map<String, String> substitutions = calculateSubstututions(details, project); StringWriter writer = new StringWriter(); for(String line : lines) { for(String substitute : substitutions.keySet()) { line = line.replaceAll(substitute, substitutions.get(substitute)); } writer.append(line); writer.append("\n"); } return writer.ToString(); } } public static class StripPublicFromInterfaces : SubstitutionPhase { public String Convert(String source, SourceDetails details, SourceProject project) { if(details.Type == SourceType.INTERFACE) { Pattern pattern = Pattern.compile("^(\\s+)public\\s+(.*\\)\\s*;.*$)"); List<String> lines = stripLines(source); StringWriter writer = new StringWriter(); for(String line : lines) { Matcher matcher = pattern.matcher(line); if(matcher.matches()) { String indent = matcher.group(1); String remainder = matcher.group(2); writer.append(indent); writer.append(remainder); writer.append("\n"); } else { writer.append(line); writer.append("\n"); } } return writer.ToString(); } return source; } } private static interface ConversionPhase { public String Convert(String source, SourceDetails details); } public static class CanonicalizeFile : ConversionPhase { public String Convert(String source, SourceDetails details) { return source.replaceAll("\r\n", "\n").replaceAll("\r", "\n"); } } public static class GetFields : ConversionPhase { private const List<String> MODIFIERS = new ArrayList<String>(); static { MODIFIERS.Add("private readonly"); MODIFIERS.Add("private"); MODIFIERS.Add("protected"); MODIFIERS.Add("protected readonly"); } public String Convert(String source, SourceDetails details) { List<Pattern> patterns = new ArrayList<Pattern>(); for(String modifier : MODIFIERS) { patterns.Add(Pattern.compile("^\\s+"+modifier+"\\s+([a-zA-Z]+)\\s+([a-zA-Z]+)\\s*;.*$")); } List<String> lines = stripLines(source); for(String line : lines) { for(Pattern pattern : patterns) { Matcher matcher = pattern.matcher(line); if(matcher.matches()) { String type = matcher.group(1); String name = matcher.group(2); details.AddField(name, type); break; } } } return source; } } public static class ConvertAnnotationAttributes : ConversionPhase { public String Convert(String source, SourceDetails details) { Pattern pattern = Pattern.compile("^(\\s+)public\\s+(.*)\\s+([a-zA-Z]+)\\(\\)\\s+default\\s+.+;.*$"); List<String> lines = stripLines(source); StringWriter writer = new StringWriter(); for(String line : lines) { Matcher matcher = pattern.matcher(line); if(matcher.matches()) { String indent = matcher.group(1); String type = matcher.group(2); String method = matcher.group(3); String attribute = method.toLowerCase(); details.AddAttribute(type, attribute); writer.append(indent); writer.append("public "); writer.append(type); writer.append(" "); writer.append(ConvertMethod(method, MethodType.NORMAL)); writer.append(" {\n"); writer.append(indent); writer.append(" get {\n"); writer.append(indent); writer.append(" return ").append(attribute).append(";\n"); writer.append(indent); writer.append(" }\n"); writer.append(indent); writer.append(" set {\n"); writer.append(indent); writer.append(" ").append(attribute).append(" = value;\n"); writer.append(indent); writer.append(" }\n"); writer.append(indent); writer.append("}\n"); } else { writer.append(line); writer.append("\n"); } } return writer.ToString(); } } private static class ConvertClassBeanMethods : ConversionPhase { private const Pattern RIGHT_BRACE = Pattern.compile("^.*\\{.*$"); private const Pattern LEFT_BRACE = Pattern.compile("^.*\\}.*$"); private const List<String> TYPE_MODIFIERS = new ArrayList<String>(); private const List<String> METHOD_MODIFIERS = new ArrayList<String>(); static { TYPE_MODIFIERS.Add("class"); TYPE_MODIFIERS.Add("public class"); TYPE_MODIFIERS.Add("abstract class"); TYPE_MODIFIERS.Add("static class"); TYPE_MODIFIERS.Add("sealed class"); TYPE_MODIFIERS.Add("private static abstract class"); TYPE_MODIFIERS.Add("private sealed class"); TYPE_MODIFIERS.Add("private class"); TYPE_MODIFIERS.Add("private static sealed class"); TYPE_MODIFIERS.Add("private static class"); TYPE_MODIFIERS.Add("public sealed class"); TYPE_MODIFIERS.Add("public static sealed class"); TYPE_MODIFIERS.Add("public static class"); TYPE_MODIFIERS.Add("protected sealed class"); TYPE_MODIFIERS.Add("protected class"); TYPE_MODIFIERS.Add("protected static sealed class"); TYPE_MODIFIERS.Add("protected static class"); TYPE_MODIFIERS.Add("static sealed class"); } static { METHOD_MODIFIERS.Add("public abstract"); METHOD_MODIFIERS.Add("public"); METHOD_MODIFIERS.Add("protected abstract"); METHOD_MODIFIERS.Add("protected"); METHOD_MODIFIERS.Add("private"); } public Matcher Match(String line, MethodType type) { for(String modifier : METHOD_MODIFIERS) { if(type == MethodType.GET) { Pattern pattern = Pattern.compile("^(\\s+)"+modifier+"\\s+(.*)\\s+Get([a-zA-Z]+)\\(\\)\\s*.*$"); Matcher matcher = pattern.matcher(line); if(matcher.matches()) { return matcher; } } else if(type == MethodType.SET) { Pattern pattern = Pattern.compile("^(\\s+)"+modifier+"\\s+void\\s+Set([a-zA-Z]+)\\((.*)\\s+([a-zA-Z]+)\\)\\s*.*$"); Matcher matcher = pattern.matcher(line); if(matcher.matches()) { return matcher; } } } return null; } public String Convert(String source, SourceDetails details) { if(details.Type == SourceType.CLASS || details.Type == SourceType.INTERFACE) { List<String> lines = stripLines(source); PropertyMap properties = new PropertyMap(details); StringWriter writer = new StringWriter(); String qualifier = ""; Extract(source, details, properties); for(int i = 0; i < lines.size(); i++) { String line = lines.get(i); qualifier += Qualifier(line); Matcher getter = Match(line, MethodType.GET); if(getter != null) { String name = getter.group(3); String fullName = qualifier+"."+name; Property property = properties.GetProperty(fullName); if(!property.IsGettable()) { throw new IllegalStateException("The line '"+line+"' was not extracted from "+details.FullyQualifiedName); } if(!property.IsDone()) { Write(details, property..indent, property, writer); } String indent = property..indent; int indentLength = indent.length(); for(int j = 0; j <= property..lineCount; j++) { line = lines.get(i++); writer.append(indent); writer.append("//"); if(line.length() < indentLength) { throw new IllegalStateException("Line '"+line+"' is out of place in " + writer.ToString()); } writer.append(line.substring(indentLength)); writer.append("\n"); } } else { Matcher setter = Match(line, MethodType.SET); if(setter != null) { String name = setter.group(2); String fullName = qualifier+"."+name; Property property = properties.GetProperty(fullName); if(!property.IsSettable()) { throw new IllegalStateException("The line '"+line+"' was not extracted from "+details.FullyQualifiedName); } if(!property.IsDone()) { Write(details, property.Set().indent, property, writer); } if(property.Set() == null) { throw new IllegalStateException("Can not find setter '"+fullName+"' from line '"+line+"' from "+writer.ToString()); } String indent = property.Set().indent; int indentLength = indent.length(); for(int j = 0; j <= property.Set().lineCount; j++) { line = lines.get(i++); writer.append(indent); writer.append("//"); if(line.length() < indentLength) { throw new IllegalStateException("Line '"+line+"' is out of place in " + writer.ToString()); } writer.append(line.substring(indentLength)); writer.append("\n"); } } else { writer.append(line); writer.append("\n"); } } } return writer.ToString(); } return source; } public void Write(SourceDetails details, String indent, Property property, StringWriter writer) { if(property.Verify()) { if(property.get != null) { writer.append(property.get.indent); writer.append("public "); if(property.get.isAbstract && details.Type == SourceType.CLASS) { writer.append("abstract "); } writer.append(property.get.type); writer.append(" "); writer.append(property.get.name); writer.append(" {\n"); writer.append(property.get.indent); if(property.get.isAbstract) { writer.append(" get;\n"); } else { writer.append(" get {\n"); List<String> lines = stripLines(property.get.content); for(String line : lines) { writer.append(" "); writer.append(line); writer.append("\n"); } } } if(property.set != null) { if(property.get == null) { writer.append(property.set.indent); writer.append("public "); if(property.set.isAbstract && details.Type == SourceType.CLASS) { writer.append("abstract "); } writer.append(property.set.type); writer.append(" "); writer.append(property.set.name); writer.append(" {\n"); } writer.append(property.set.indent); if(property.set.isAbstract) { writer.append(" set;\n"); } else { writer.append(" set {\n"); List<String> lines = stripLines(property.set.content); for(String line : lines) { writer.append(" "); writer.append(line); writer.append("\n"); } } } writer.append(indent); writer.append("}"); writer.append("\n"); } property.Done(); } public void Extract(String source, SourceDetails details, PropertyMap properties) { List<String> lines = stripLines(source); String qualifier = ""; for(int i = 0; i < lines.size(); i++) { String line = lines.get(i); qualifier += Qualifier(line); Matcher getter = Match(line, MethodType.GET); if(getter != null) { String indent = getter.group(1); String type = getter.group(2); String name = getter.group(3); StringBuilder writer = new StringBuilder(); bool isAbstract = false; int lineCount = 0; int braces = 0; i++; if(!line.matches(".*;\\s*$") && !line.matches(".*abstract.*")) { // abstract ends in ; for(; braces >= 0 && i < lines.size(); i++) { line = lines.get(i); Matcher right = RIGHT_BRACE.matcher(line); if(right.matches()) { braces++; } Matcher left = LEFT_BRACE.matcher(line); if(left.matches()) { braces--; } writer.append(line); writer.append("\n"); lineCount++; } } else { isAbstract = true; } String fullName = qualifier+"."+name; if(properties.GetProperty(fullName) != null && properties.GetProperty(fullName).IsGettable()) { throw new IllegalStateException("The property '"+fullName+"' is defined twice in "+details.FullyQualifiedName+" on line '"+line+"' in "+writer.ToString()); } properties.AddGetProperty(fullName, new MethodDetail(name, type, indent, writer.ToString(), lineCount, isAbstract)); } else { Matcher setter = Match(line, MethodType.SET); if(setter != null) { String indent = setter.group(1); String name = setter.group(2); String type = setter.group(3); String value = setter.group(4); StringBuilder writer = new StringBuilder(); bool isAbstract = false; int lineCount = 0; int braces = 0; i++; if(!line.matches(".*;\\s*$") && !line.matches(".*abstract.*")) { // abstract ends in ; for(; braces >= 0 && i < lines.size(); i++) { line = lines.get(i); Matcher right = RIGHT_BRACE.matcher(line); if(right.matches()) { braces++; } Matcher left = LEFT_BRACE.matcher(line); if(left.matches()) { braces--; } writer.append(line); writer.append("\n"); lineCount++; } } else { isAbstract = true; } String fullName = qualifier+"."+name; if(properties.GetProperty(fullName) != null && properties.GetProperty(fullName).IsSettable()) { throw new IllegalStateException("The property '"+fullName+"' is defined twice in "+details.FullyQualifiedName); } String content = writer.ToString(); content = content.replaceAll(" value\\)", " _value)"); content = content.replaceAll(" value;", " _value;"); content = content.replaceAll(" value=", " _value=\\"); content = content.replaceAll(" value\\.", " _value."); content = content.replaceAll("\\(value\\)", "(_value)"); content = content.replaceAll("\\(value\\.", "(_value."); content = content.replaceAll("=value;", "=_value;"); content = content.replaceAll("=value\\.", "=_value."); content = content.replaceAll(" "+value+"\\)", " value)"); content = content.replaceAll(" "+value+";", " value;"); content = content.replaceAll(" "+value+"=", " value=\\"); content = content.replaceAll(" "+value+"\\.", " value."); content = content.replaceAll("\\("+value+"\\)", "(value)"); content = content.replaceAll("\\("+value+"\\.", "(value."); content = content.replaceAll("="+value+";", "=value;"); content = content.replaceAll("="+value+"\\.", "=value."); properties.AddSetProperty(fullName, new MethodDetail(name, type, indent, content, lineCount, isAbstract)); } } } } public String Qualifier(String line) { for(String modifier : TYPE_MODIFIERS) { Pattern pattern = Pattern.compile("^\\s*"+modifier+"\\s+([a-zA-Z]+).*$"); Matcher matcher = pattern.matcher(line); if(matcher.matches()) { return "."+matcher.group(1); } } return ""; } private class MethodDetail { public readonly String type; public readonly String name; public readonly String indent; public readonly String content; public readonly int lineCount; public readonly bool isAbstract; public MethodDetail(String name, String type, String indent, String content, int lineCount, bool isAbstract) { this.name = name; this.type = type; this.indent = indent; this.content = content; this.lineCount = lineCount; this.isAbstract = isAbstract; } public String ToString() { return String.format("[%s][%s][%s]", name, type, isAbstract); } } private class PropertyMap { private Map<String, Property> properties = new HashMap<String, Property>(); private SourceDetails details; public PropertyMap(SourceDetails details) { this.details = details; } public Property GetProperty(String name) { return properties.get(name); } public void AddSetProperty(String name, MethodDetail detail) { Property property = properties.get(name); if(property == null) { property = new Property(); properties.put(name, property); } if(property.Set() != null) { throw new IllegalStateException("The property '"+name+"' is defined twice in "+details.FullyQualifiedName); } if(detail == null) { throw new IllegalStateException("Can not set a null property"); } property.AddSetMethod(detail); } public void AddGetProperty(String name, MethodDetail detail) { Property property = properties.get(name); if(property == null) { property = new Property(); properties.put(name, property); } if(property. != null) { throw new IllegalStateException("The property '"+name+"' is defined twice in "+details.FullyQualifiedName); } if(detail == null) { throw new IllegalStateException("Can not set a null property"); } property.AddGetMethod(detail); } } private class Property { private MethodDetail get; private MethodDetail set; private bool done; public MethodDetail Get() { return get; } public MethodDetail Set() { return set; } public bool IsGettable() { return get != null; } public bool IsSettable() { return set != null; } public void AddSetMethod(MethodDetail detail) { this.set = detail; } public void AddGetMethod(MethodDetail detail) { this.get = detail; } public bool IsDone() { return done; } public void Done() { done = true; } public bool Verify() { if(get != null && set != null) { if(!get.name.equals(set.name)) { throw new IllegalStateException("Property names do not match for '"+get.name+"' and '"+set.name+"'"); } if(!get.type.equals(set.type)) { throw new IllegalStateException("Property types do not match for '"+get.type+"' and '"+set.type+"'"); } } return true; } public String ToString() { return String.format("GET -> %s SET -> %s", get, set); } } } public static class SetAnnotationAttributes : ConversionPhase { public String Convert(String source, SourceDetails details) { if(details.Type == SourceType.ANNOTATION) { Pattern pattern = Pattern.compile("^(\\s+)public\\s+class\\s+[a-zA-Z]+.*$"); List<String> lines = stripLines(source); StringWriter writer = new StringWriter(); Map<String, String> attributes = details.getAttributes(); for(String line : lines) { Matcher matcher = pattern.matcher(line); if(matcher.matches()) { String indent = matcher.group(1); writer.append(line); writer.append("\n"); for(String attribute : attributes.keySet()){ String type = attributes.get(attribute); writer.append(indent); writer.append(" private "); writer.append(type); writer.append(" "); writer.append(attribute); writer.append(";\n"); } } else { writer.append(line); writer.append("\n"); } } return writer.ToString(); } return source; } } private static class DefineType : ConversionPhase { private const Map<Pattern, SourceType> PATTERNS = new HashMap<Pattern, SourceType>(); static { PATTERNS.put(Pattern.compile("^public\\s+class\\s+([a-zA-Z]*).*"), SourceType.CLASS); PATTERNS.put(Pattern.compile("^public\\s+readonly\\s+class\\s+([a-zA-Z]*).*"), SourceType.CLASS); PATTERNS.put(Pattern.compile("^class\\s+([a-zA-Z]*).*"), SourceType.CLASS); PATTERNS.put(Pattern.compile("^public\\s+abstract\\s+class\\s+([a-zA-Z]*).*"), SourceType.CLASS); PATTERNS.put(Pattern.compile("^abstract\\s+class\\s+([a-zA-Z]*).*"), SourceType.CLASS); PATTERNS.put(Pattern.compile("^readonly\\s+class\\s+([a-zA-Z]*).*"), SourceType.CLASS); PATTERNS.put(Pattern.compile("^public\\s+@interface\\s+([a-zA-Z]*).*"), SourceType.ANNOTATION); PATTERNS.put(Pattern.compile("^@interface\\s+([a-zA-Z]*).*"), SourceType.ANNOTATION); PATTERNS.put(Pattern.compile("^public\\s+interface\\s+([a-zA-Z]*).*"), SourceType.INTERFACE); PATTERNS.put(Pattern.compile("^interface\\s+([a-zA-Z]*).*"), SourceType.INTERFACE); PATTERNS.put(Pattern.compile("^public\\s+enum\\s+([a-zA-Z]*).*"), SourceType.ENUM); PATTERNS.put(Pattern.compile("^enum\\s+([a-zA-Z]*).*"), SourceType.ENUM); } public String Convert(String source, SourceDetails details) { List<String> lines = stripLines(source); for(String line : lines) { for(Pattern pattern : PATTERNS.keySet()) { Matcher matcher = pattern.matcher(line); if(matcher.matches()) { SourceType type = PATTERNS.get(pattern); String name = matcher.group(1); details.Type = type; details.Name = name; return source; } } } throw new IllegalStateException("File can not be classified " + details.Source); } } private static class PopulateUsing : ConversionPhase { public String Convert(String source, SourceDetails details) { List<String> lines = stripLines(source); for(String line : lines) { if(line.matches("^import.*")) { line = line.trim(); for(String importName : USING.keySet()) { if(line.matches(importName)) { importName = USING.get(importName); details.AddUsing(importName); break; } } } } return source; } } private static class AddUsing : ConversionPhase { public String Convert(String source, SourceDetails details) { Pattern pattern = Pattern.compile("^package\\s+([a-zA-Z\\.]*)\\s*;.*"); List<String> lines = stripLines(source); StringWriter writer = new StringWriter(); bool importsDone = false; for(String line : lines) { if(!importsDone) { Matcher matcher = pattern.matcher(line); if(matcher.matches()) { String packageName = matcher.group(1); writer.append("\n#region Using directives\n"); for(String using : details.Using) { writer.append(using); writer.append("\n"); } writer.append("\n#endregion\n"); details.Package = packageName; importsDone = true; } } writer.append(line); writer.append("\n"); } return writer.ToString(); } } private static class StripImports : ConversionPhase { public String Convert(String source, SourceDetails details) { Pattern pattern = Pattern.compile("^import\\s+([a-zA-Z\\.]*)\\s*;.*$"); List<String> lines = stripLines(source); StringWriter writer = new StringWriter(); for(String line : lines) { Matcher matcher = pattern.matcher(line); if(matcher.matches()) { String importClass = matcher.group(1); details.AddImport(importClass); } else { writer.append(line); writer.append("\n"); } } return writer.ToString(); } } private static class CreateNamespace : ConversionPhase { public String Convert(String source, SourceDetails details) { List<String> lines = stripLines(source); StringWriter writer = new StringWriter(); String indent = ""; for(String line : lines) { line = line.replaceAll("\\s*$", ""); writer.append(indent); if(indent == null || indent.equals("")){ for(String packageName : NAMESPACE.keySet()) { if(line.matches(packageName + ".*")) { indent = INDENT; line = NAMESPACE.get(packageName); break; } } } writer.append(line); writer.append("\n"); } writer.append("}"); return writer.ToString(); } } private static class ReplaceAnnotations : ConversionPhase { public String Convert(String source, SourceDetails details) { Pattern withAttributes = Pattern.compile("(\\s+)@([a-zA-Z]+)\\((.*)\\).*"); Pattern withoutAttributes = Pattern.compile("(\\s+)@([a-zA-Z]+).*"); List<String> lines = stripLines(source); StringWriter writer = new StringWriter(); for(String line : lines) { Matcher with = withAttributes.matcher(line); if(with.matches()) { String indent = with.group(1); String name = with.group(2); String signature = with.group(3); writer.append(indent); writer.append("["); writer.append(name); if(signature != null && !signature.equals("")) { writer.append("("); String[] attributes = signature.split("\\s*,\\s*"); String separator = ""; for(String attribute : attributes) { writer.append(separator); writer.append(ConvertMethod(attribute, MethodType.NORMAL)); separator = ", "; } writer.append(")"); } writer.append("]\n"); } else { Matcher without = withoutAttributes.matcher(line); if(without.matches()) { String indent = without.group(1); String name = without.group(2); writer.append(indent); writer.append("["); writer.append(name); writer.append("]\n"); } else { writer.append(line); writer.append("\n"); } } } return writer.ToString(); } } private static class ReplaceMethodConventions : ConversionPhase { private const List<String> MODIFIERS = new ArrayList<String>(); static { MODIFIERS.Add("public static"); MODIFIERS.Add("private static"); MODIFIERS.Add("protected static"); MODIFIERS.Add("public"); MODIFIERS.Add("private"); MODIFIERS.Add("protected");; } public String Convert(String source, SourceDetails details) { List<String> lines = stripLines(source); StringWriter writer = new StringWriter(); main: for(String line : lines) { for(String modifier : MODIFIERS) { Pattern methodMatch = Pattern.compile("^(\\s*)"+modifier+"\\s+([a-zA-Z\\[\\]\\<\\>\\s]+)\\s+([a-zA-Z]+)\\((.*)\\).*$"); Matcher matcher = methodMatch.matcher(line); if(matcher.matches()) { String indent = matcher.group(1); String type = matcher.group(2); String originalMethod = matcher.group(3);; String signature = matcher.group(4); String method = ConvertMethod(originalMethod, MethodType.NORMAL); writer.append(indent); writer.append("public "); writer.append(type); writer.append(" "); writer.append(method); writer.append("("); writer.append(signature); if(line.matches(".*;\\s*") || details.Type == SourceType.INTERFACE) { writer.append(");\n"); } else { writer.append(") {\n"); } Add(details, originalMethod, signature, type); continue main; } } writer.append(line); writer.append("\n"); } return writer.ToString(); } public void Add(SourceDetails details, String originalMethod, String signature, String type) { if(originalMethod.startsWith("get")) { if(signature == null || signature.equals("")) { details.AddMethod(new MethodSignature(originalMethod, MethodType.GET, null)); } else { details.AddMethod(new MethodSignature(originalMethod, MethodType.NORMAL, null)); } } else if(originalMethod.startsWith("set")) { if(signature != null && signature.indexOf(" ") != -1 && signature.indexOf(",") == -1 && type.equals("void")) { details.AddMethod(new MethodSignature(originalMethod, MethodType.SET, signature.split("\\s+")[1])); }else { details.AddMethod(new MethodSignature(originalMethod, MethodType.NORMAL, null)); } } else { details.AddMethod(new MethodSignature(originalMethod, MethodType.NORMAL, null)); } } } private static class StripCrap : ConversionPhase { private const List<String> TOKENS = new ArrayList<String>(); static { TOKENS.Add("^\\s*\\/\\/\\/\\s*$"); TOKENS.Add("^\\s*$"); } public String Convert(String source, SourceDetails details) { List<String> lines = stripLines(source); StringWriter writer = new StringWriter(); main: for(String line : lines) { for(String token : TOKENS) { if(token.startsWith("^") && line.matches(token)) { continue main; } } writer.append(line); writer.append("\n"); } return writer.ToString(); } } private static class ReplaceKeyWords : ConversionPhase { private const Map<String, String> TOKENS = new LinkedHashMap<String, String>(); static { TOKENS.put("<c>", "<c>"); TOKENS.put("</c>", "</c>"); TOKENS.put("</code>", "</c>"); TOKENS.put("</code>", "</c>"); TOKENS.put("\\(List ", "(List "); TOKENS.put(" List ", " List "); TOKENS.put(",List ", ",List "); TOKENS.put("Dictionary ", "Dictionary "); TOKENS.put("\\(Dictionary ", "(Dictionary "); TOKENS.put(" Dictionary ", " Dictionary "); TOKENS.put(",Dictionary ", ",Dictionary "); TOKENS.put("List ", "List "); TOKENS.put("const", "const"); TOKENS.put("readonly", "readonly"); TOKENS.put("finally", "finally"); TOKENS.put("sealed class", "sealed class"); TOKENS.put("sealed class", "sealed class"); TOKENS.put("bool", "bool"); TOKENS.put(":", ":"); TOKENS.put(":", ":"); TOKENS.put("\\)\\s*throws\\s.*\\{", ") {"); TOKENS.put("\\)\\s*throws\\s.*;", ");"); TOKENS.put("assertEquals\\(", "AssertEquals("); TOKENS.put("assertNull\\(", "AssertNull("); TOKENS.put("assertNotNull\\(", "AssertNotNull("); TOKENS.put("SimpleFramework.Xml.Util","SimpleFramework.Xml.Util"); TOKENS.put("SimpleFramework.Xml.Filter", "SimpleFramework.Xml.Filter"); TOKENS.put("SimpleFramework.Xml.Strategy", "SimpleFramework.Xml.Strategy"); TOKENS.put("SimpleFramework.Xml.Core","SimpleFramework.Xml.Core"); TOKENS.put("SimpleFramework.Xml.Util", "SimpleFramework.Xml.Util"); TOKENS.put("SimpleFramework.Xml.Stream","SimpleFramework.Xml.Stream"); TOKENS.put("SimpleFramework.Xml","SimpleFramework.Xml"); TOKENS.put("@Retention\\(RetentionPolicy.RUNTIME\\)", "[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Method)]"); } public String Convert(String source, SourceDetails details) { List<String> lines = stripLines(source); StringWriter writer = new StringWriter(); for(String line : lines) { for(String token : TOKENS.keySet()) { String value = TOKENS.get(token); if(line.startsWith("^") && line.matches(token)) { line = line.replaceAll(token, value); } else if(line.matches(".*" +token+".*")) { line = line.replaceAll(token, value); } } writer.append(line); writer.append("\n"); } return writer.ToString(); } } private static class ReplaceDocumentation : ConversionPhase { private const Map<String, String> TOKENS = new HashMap<String, String>(); static { TOKENS.put("return", "returns"); TOKENS.put("see", "seealso"); } public String Convert(String source, SourceDetails details) { Pattern paramComment = Pattern.compile("^(\\s*)///.*@param\\s*([a-zA-Z]*)\\s*(.*)$"); List<String> lines = stripLines(source); StringWriter writer = new StringWriter(); main: for(String line : lines) { Matcher paramMatcher = paramComment.matcher(line); if(paramMatcher.matches()) { String indent = paramMatcher.group(1); String name = paramMatcher.group(2); String description = paramMatcher.group(3); writer.append(indent); writer.append("/// <param name=\""); writer.append(name); writer.append("\">\n"); writer.append(indent); writer.append("/// "); writer.append(description); writer.append("\n"); writer.append(indent); writer.append("/// </param>\n"); } else { for(String token : TOKENS.keySet()) { Pattern tokenComment = Pattern.compile("^(\\s*)///.*@"+token+"\\s(.*)$"); Matcher tokenMatcher = tokenComment.matcher(line); if(tokenMatcher.matches()) { String replace = TOKENS.get(token); String indent = tokenMatcher.group(1); String description = tokenMatcher.group(2); writer.append(indent); writer.append("/// <"+replace+">\n"); writer.append(indent); writer.append("/// "); writer.append(description); writer.append("\n"); writer.append(indent); writer.append("/// </"+replace+">\n"); continue main; } } writer.append(line); writer.append("\n"); } } return writer.ToString(); } } private static class ReplaceComments : ConversionPhase { public String Convert(String source, SourceDetails details) { List<String> lines = stripLines(source); Iterator<String> iterator = lines.iterator(); StringWriter writer = new StringWriter(); while(iterator.hasNext()) { String line = iterator.next(); if(line.matches("\\s*\\/\\*\\*")) { Comment(iterator, writer, line); } else { writer.append(line); writer.append("\n"); } } return writer.ToString(); } public void Comment(Iterator<String> lines, StringWriter writer, String line) { Pattern normalComment = Pattern.compile("^(\\s*)\\*.*$"); Pattern parameterComment = Pattern.compile("^(\\s*)\\*.*@.*$"); bool endSummary = false; writer.append(line.replaceAll("\\/\\*\\*", "/// <summary>")); writer.append("\n"); while(lines.hasNext()) { String nextLine = lines.next(); nextLine = nextLine.substring(1); if(nextLine.matches("^\\s*\\*\\/")) { if(!endSummary) { writer.append(nextLine.replaceAll("\\*\\/", "/// </summary>")); } else { writer.append(nextLine.replaceAll("\\*\\/", "///")); } writer.append("\n"); return; } if(!endSummary) { Matcher parameterMatch = parameterComment.matcher(nextLine); if(parameterMatch.matches()) { writer.append(parameterMatch.group(1)); writer.append("/// </summary>"); writer.append("\n"); writer.append(parameterMatch.group(1)); writer.append(nextLine.replaceAll("^\\s*\\*", "///")); writer.append("\n"); endSummary = true; } else { Matcher normalMatch = normalComment.matcher(nextLine); if(normalMatch.matches()) { writer.append(normalMatch.group(1)); writer.append(nextLine.replaceAll("^\\s*\\*", "///")); writer.append("\n"); } } } else { Matcher normalMatch = normalComment.matcher(nextLine); if(normalMatch.matches()) { writer.append(normalMatch.group(1)); writer.append(nextLine.replaceAll("^\\s*\\*", "///")); writer.append("\n"); }else { throw new IllegalStateException("Comment does not end well " + nextLine); } } } } } private static class ReplaceLicense : ConversionPhase { public String Convert(String source, SourceDetails details) { List<String> lines = stripLines(source); Iterator<String> iterator = lines.iterator(); StringWriter writer = new StringWriter(); bool licenseDone = false; while(iterator.hasNext()) { String line = iterator.next(); if(!licenseDone && line.matches("\\s*\\/\\*")) { writer.append("#region License\n"); License(details, iterator, writer, line); writer.append("#endregion\n"); licenseDone = true; } else { if(!line.matches("^\\s*$")) { licenseDone = true; // no license found } writer.append(line); writer.append("\n"); } } return writer.ToString(); } public void License(SourceDetails details, Iterator<String> lines, StringWriter writer, String line) { Pattern comment = Pattern.compile("^(\\s*)\\*.*$"); writer.append(line.replaceAll("\\/\\*", "//")); writer.append("\n"); while(lines.hasNext()) { String nextLine = lines.next(); nextLine = nextLine.substring(1); if(nextLine.matches("^\\s*\\*\\/")) { writer.append(nextLine.replaceAll("\\*\\/", "//")); writer.append("\n"); return; } Matcher matcher = comment.matcher(nextLine); if(matcher.matches()) { if(nextLine.matches(".*\\.java.*")) { nextLine = nextLine.replaceAll("\\.java", ".cs"); } writer.append(matcher.group(1)); writer.append(nextLine.replaceAll("^\\s*\\*", "//")); writer.append("\n"); }else { throw new IllegalStateException("Comment does not end well '" + nextLine+"' in file "+details.Source.getCanonicalPath()); } } } } private static class SubstituteAnnotations : ConversionPhase { public String Convert(String source, SourceDetails details) { Pattern pattern = Pattern.compile("^(.+) class (.+)\\: System.Attribute { List<String> lines = stripLines(source); StringWriter writer = new StringWriter(); for(String line : lines) { Matcher matcher = pattern.matcher(line); if(matcher.matches()) { String start = matcher.group(1); String type = matcher.group(2); writer.append(start); writer.append(" class "); writer.append(type); writer.append(": System.Attribute {\n"); } else { writer.append(line); writer.append("\n"); } } return writer.ToString(); } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: SerializationEventsCache ** ** ** Purpose: Caches the various serialization events such as On(De)Seriliz(ed)ing ** ** ============================================================*/ namespace System.Runtime.Serialization { using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Globalization; using System.Diagnostics.Contracts; internal class SerializationEvents { private List<MethodInfo> m_OnSerializingMethods = null; private List<MethodInfo> m_OnSerializedMethods = null; private List<MethodInfo> m_OnDeserializingMethods = null; private List<MethodInfo> m_OnDeserializedMethods = null; private List<MethodInfo> GetMethodsWithAttribute(Type attribute, Type t) { List<MethodInfo> mi = new List<MethodInfo>(); Type baseType = t; // Traverse the hierarchy to find all methods with the particular attribute while (baseType != null && baseType != typeof(Object)) { RuntimeType rt = (RuntimeType)baseType; // Get all methods which are declared on this type, instance and public or nonpublic MethodInfo[] mis = baseType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); #if _DEBUG bool found = false; #endif foreach(MethodInfo m in mis) { // For each method find if attribute is present, the return type is void and the method is not virtual if (m.IsDefined(attribute, false)) { #if _DEBUG Contract.Assert(m.ReturnType == typeof(void) && !m.IsVirtual, "serialization events methods cannot be virtual and need to have void return"); ParameterInfo[] paramInfo = m.GetParameters(); // Only add it if this method has one parameter of type StreamingContext if (paramInfo.Length == 1 && paramInfo[0].ParameterType == typeof(StreamingContext)) { if (found) Contract.Assert(false, "Mutliple methods with same serialization attribute"); #endif mi.Add(m); #if _DEBUG found = true; } else Contract.Assert(false, "Incorrect serialization event signature"); #endif } } #if _DEBUG found = false; #endif baseType = baseType.BaseType; } mi.Reverse(); // We should invoke the methods starting from base return (mi.Count == 0) ? null : mi; } internal SerializationEvents(Type t) { // Initialize all events m_OnSerializingMethods = GetMethodsWithAttribute(typeof(OnSerializingAttribute), t); m_OnSerializedMethods = GetMethodsWithAttribute(typeof(OnSerializedAttribute), t); m_OnDeserializingMethods = GetMethodsWithAttribute(typeof(OnDeserializingAttribute), t); m_OnDeserializedMethods = GetMethodsWithAttribute(typeof(OnDeserializedAttribute), t); } internal bool HasOnSerializingEvents { get { return m_OnSerializingMethods != null || m_OnSerializedMethods != null; } } [System.Security.SecuritySafeCritical] internal void InvokeOnSerializing(Object obj, StreamingContext context) { Contract.Assert(obj != null, "object should have been initialized"); // Invoke all OnSerializingMethods if (m_OnSerializingMethods != null) { Object[] p = new Object[] {context}; SerializationEventHandler handler = null; foreach(MethodInfo m in m_OnSerializingMethods) { SerializationEventHandler onSerializing = (SerializationEventHandler)Delegate.CreateDelegateNoSecurityCheck((RuntimeType)typeof(SerializationEventHandler), obj, m); handler = (SerializationEventHandler)Delegate.Combine(handler, onSerializing); } handler(context); } } [System.Security.SecuritySafeCritical] internal void InvokeOnDeserializing(Object obj, StreamingContext context) { Contract.Assert(obj != null, "object should have been initialized"); // Invoke all OnDeserializingMethods if (m_OnDeserializingMethods != null) { Object[] p = new Object[] {context}; SerializationEventHandler handler = null; foreach(MethodInfo m in m_OnDeserializingMethods) { SerializationEventHandler onDeserializing = (SerializationEventHandler)Delegate.CreateDelegateNoSecurityCheck((RuntimeType)typeof(SerializationEventHandler), obj, m); handler = (SerializationEventHandler)Delegate.Combine(handler, onDeserializing); } handler(context); } } [System.Security.SecuritySafeCritical] internal void InvokeOnDeserialized(Object obj, StreamingContext context) { Contract.Assert(obj != null, "object should have been initialized"); // Invoke all OnDeserializingMethods if (m_OnDeserializedMethods != null) { Object[] p = new Object[] {context}; SerializationEventHandler handler = null; foreach(MethodInfo m in m_OnDeserializedMethods) { SerializationEventHandler onDeserialized = (SerializationEventHandler)Delegate.CreateDelegateNoSecurityCheck((RuntimeType)typeof(SerializationEventHandler), obj, m); handler = (SerializationEventHandler)Delegate.Combine(handler, onDeserialized); } handler(context); } } [System.Security.SecurityCritical] internal SerializationEventHandler AddOnSerialized(Object obj, SerializationEventHandler handler) { // Add all OnSerialized methods to a delegate if (m_OnSerializedMethods != null) { foreach(MethodInfo m in m_OnSerializedMethods) { SerializationEventHandler onSerialized = (SerializationEventHandler)Delegate.CreateDelegateNoSecurityCheck((RuntimeType)typeof(SerializationEventHandler), obj, m); handler = (SerializationEventHandler)Delegate.Combine(handler, onSerialized); } } return handler; } [System.Security.SecurityCritical] internal SerializationEventHandler AddOnDeserialized(Object obj, SerializationEventHandler handler) { // Add all OnDeserialized methods to a delegate if (m_OnDeserializedMethods != null) { foreach(MethodInfo m in m_OnDeserializedMethods) { SerializationEventHandler onDeserialized = (SerializationEventHandler)Delegate.CreateDelegateNoSecurityCheck((RuntimeType)typeof(SerializationEventHandler), obj, m); handler = (SerializationEventHandler)Delegate.Combine(handler, onDeserialized); } } return handler; } } internal static class SerializationEventsCache { private static Hashtable cache = new Hashtable(); internal static SerializationEvents GetSerializationEventsForType(Type t) { SerializationEvents events; if ((events = (SerializationEvents)cache[t]) == null) { lock(cache.SyncRoot) { if ((events = (SerializationEvents)cache[t]) == null) { events = new SerializationEvents(t); cache[t] = events; // Add this to the cache. } } } return events; } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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.Reflection; #pragma warning disable 1591 #pragma warning disable 3001 namespace MbUnit.Framework { /// <summary> /// Reflection Assertion class /// </summary> [Obsolete("Use Assert instead.")] public static class OldReflectionAssert { /// <summary> /// Asserts whether an instance of the <paramref name="parent"/> /// can be assigned from an instance of <paramref name="child"/>. /// </summary> /// <param name="parent"> /// Parent <see cref="Type"/> instance. /// </param> /// <param name="child"> /// Child <see cref="Type"/> instance. /// </param> public static void IsAssignableFrom(Type parent, Type child) { OldAssert.IsNotNull(parent); OldAssert.IsNotNull(child); OldAssert.IsTrue(parent.IsAssignableFrom(child), "{0} is not assignable from {1}", parent, child ); } /// <summary> /// Asserts whether <paramref name="child"/> is an instance of the /// <paramref name="type"/>. /// </summary> /// <param name="type"> /// <see cref="Type"/> instance. /// </param> /// <param name="child"> /// Child instance. /// </param> public static void IsInstanceOf(Type type, Object child) { OldAssert.IsNotNull(type); OldAssert.IsNotNull(child); OldAssert.IsTrue(type.IsInstanceOfType(child), "{0} is not an instance of {1}", type, child ); } /// <summary> /// Asserts that the type has a default public constructor /// </summary> public static void HasDefaultConstructor(Type type) { HasConstructor(type, Type.EmptyTypes); } /// <summary> /// Asserts that the type has a public instance constructor with a signature defined by parameters. /// </summary> public static void HasConstructor(Type type, params Type[] parameters) { HasConstructor(type,BindingFlags.Public | BindingFlags.Instance,parameters); } /// <summary> /// Asserts that the type has a constructor, with the specified bindind flags, with a signature defined by parameters. /// </summary> public static void HasConstructor(Type type, BindingFlags flags, params Type[] parameters) { OldAssert.IsNotNull(type); OldAssert.IsNotNull(type.GetConstructor(flags,null,parameters,null), "{0} does not have matching constructor", type.FullName ); } /// <summary> /// Asserts that the type has a public instance method with a signature defined by parameters. /// </summary> public static void HasMethod(Type type, string name, params Type[] parameters) { HasMethod(type,BindingFlags.Public | BindingFlags.Instance,name,parameters); } /// <summary> /// Asserts that the type has a method, with the specified bindind flags, with a signature defined by parameters. /// </summary> public static void HasMethod(Type type, BindingFlags flags, string name, params Type[] parameters) { OldAssert.IsNotNull(type, "Type is null"); OldStringAssert.IsNonEmpty(name); OldAssert.IsNotNull(type.GetMethod(name,parameters), "Method {0} of type {1} not found with matching arguments", name, type ); } /// <summary> /// Asserts that the type has a public field method with a signature defined by parameters. /// </summary> public static void HasField(Type type, string name) { HasField(type, BindingFlags.Public | BindingFlags.Instance,name ); } /// <summary> /// Asserts that the type has a field, with the specified bindind flags, with a signature defined by parameters. /// </summary> public static void HasField(Type type, BindingFlags flags,string name) { OldAssert.IsNotNull(type, "Type is null"); OldStringAssert.IsNonEmpty(name); OldAssert.IsNotNull(type.GetField(name), "Field {0} of type {1} not found with binding flags {2}", name, type, flags ); } public static void ReadOnlyProperty(Type t, string propertyName) { OldAssert.IsNotNull(t); OldAssert.IsNotNull(propertyName); PropertyInfo pi = t.GetProperty(propertyName); OldAssert.IsNotNull(pi, "Type {0} does not contain property {1}", t.FullName, propertyName); ReadOnlyProperty(pi); } public static void ReadOnlyProperty(PropertyInfo pi) { OldAssert.IsNotNull(pi); OldAssert.IsFalse(pi.CanWrite, "Property {0}.{1} is not read-only", pi.DeclaringType.Name, pi.Name ); } public static void WriteOnlyProperty(Type t, string propertyName) { OldAssert.IsNotNull(t); OldAssert.IsNotNull(propertyName); PropertyInfo pi = t.GetProperty(propertyName); OldAssert.IsNotNull(pi, "Type {0} does not contain property {1}", t.FullName, propertyName); WriteOnlyProperty(pi); } public static void WriteOnlyProperty(PropertyInfo pi) { OldAssert.IsNotNull(pi); OldAssert.IsFalse(pi.CanRead, "Property {0}.{1} is not read-only", pi.DeclaringType.FullName, pi.Name ); } public static void IsSealed(Type t) { OldAssert.IsNotNull(t); OldAssert.IsTrue(t.IsSealed, "Type {0} is not sealed", t.FullName); } public static void NotCreatable(Type t) { OldAssert.IsNotNull(t); foreach(ConstructorInfo ci in t.GetConstructors()) { OldAssert.Fail( "Non-private constructor found in class {0} that must not be creatable", t.FullName); } } } }
namespace YAF.Core.Model { using System; using System.Collections.Generic; using System.Data; using System.Linq; using ServiceStack.OrmLite; using YAF.Types; using YAF.Types.Extensions; using YAF.Types.Extensions.Data; using YAF.Types.Interfaces.Data; using YAF.Types.Models; using YAF.Utils.Helpers; /// <summary> /// The PMessage Repository Extensions /// </summary> public static class PMessageRepositoryExtensions { #region Public Methods and Operators /// <summary> /// The get replies. /// </summary> /// <param name="repository"> /// The repository. /// </param> /// <param name="message"> /// The message. /// </param> /// <param name="replyTo"> /// The reply to. /// </param> /// <returns> /// The <see cref="DataTable"/>. /// </returns> public static DataTable GetReplies(this IRepository<PMessage> repository, PMessage message, int replyTo) { var messages = repository.ListAsDataTable(null, null, replyTo); var originalMessage = messages.GetFirstRow(); if (originalMessage == null) { return messages; } var originalPMMessage = new PMessage { ReplyTo = originalMessage["ReplyTo"].ToType<int>(), ID = originalMessage["PMessageID"].ToType<int>() }; if (message.ID == originalPMMessage.ID) { messages.Rows.RemoveAt(0); } if (!originalMessage["IsReply"].ToType<bool>()) { return messages; } var replies1 = repository.GetReplies(originalPMMessage, originalPMMessage.ReplyTo.Value); if (replies1 != null) { messages.Merge(replies1); } return messages; } /// <summary> /// Prune All Private Messages /// </summary> /// <param name="repository"> /// The repository. /// </param> /// <param name="daysRead"> /// The days read. /// </param> /// <param name="daysUnread"> /// The days unread. /// </param> public static void PruneAll(this IRepository<PMessage> repository, DateTime daysRead, DateTime daysUnread) { CodeContracts.VerifyNotNull(repository, "repository"); repository.DbFunction.Query.pmessage_prune( DaysRead: daysRead, DaysUnread: daysUnread, UTCTIMESTAMP: DateTime.UtcNow); } /// <summary> /// Gets the User Message Count /// </summary> /// <param name="repository"> /// The repository. /// </param> /// <param name="userId"> /// The user id. /// </param> /// <returns> /// The <see cref="DataTable"/>. /// </returns> public static DataTable UserMessageCount(this IRepository<PMessage> repository, int userId) { return repository.DbFunction.GetAsDataTable(cdb => cdb.user_pmcount(UserID: userId)); } /// <summary> /// archive message. /// </summary> /// <param name="repository"> /// The repository. /// </param> /// <param name="userPMessageID"> /// The user p message id. /// </param> public static void ArchiveMessage(this IRepository<PMessage> repository, [NotNull] object userPMessageID) { CodeContracts.VerifyNotNull(repository, "repository"); repository.DbFunction.Scalar.pmessage_archive(UserPMessageID: userPMessageID); } /// <summary> /// Deletes the Private Message /// </summary> /// <param name="repository"> /// The repository. /// </param> /// <param name="messageId"> /// The message id. /// </param> /// <param name="deleteFromOutbox"> /// The delete From Outbox. /// </param> public static void DeleteMessage(this IRepository<PMessage> repository, int messageId, bool deleteFromOutbox) { CodeContracts.VerifyNotNull(repository, "repository"); repository.DbFunction.Scalar.pmessage_delete(UserPMessageID: messageId, FromOutbox: deleteFromOutbox); } /// <summary> /// The send message. /// </summary> /// <param name="repository"> /// The repository. /// </param> /// <param name="fromUserID"> /// The from user id. /// </param> /// <param name="toUserID"> /// The to user id. /// </param> /// <param name="subject"> /// The subject. /// </param> /// <param name="body"> /// The body. /// </param> /// <param name="flags"> /// The flags. /// </param> /// <param name="replyTo"> /// The reply to. /// </param> public static void SendMessage( this IRepository<PMessage> repository, int fromUserID, int toUserID, [NotNull] string subject, [NotNull] string body, [NotNull] int flags, [CanBeNull] int? replyTo) { CodeContracts.VerifyNotNull(repository, "repository"); repository.DbFunction.Scalar.pmessage_save( FromUserID: fromUserID, ToUserID: toUserID, Subject: subject, Body: body, Flags: flags, ReplyTo: replyTo, UTCTIMESTAMP: DateTime.UtcNow); } /// <summary> /// Gets the list of Private Messages /// </summary> /// <param name="repository"> /// The repository. /// </param> /// <param name="toUserID"> /// The to User ID. /// </param> /// <param name="fromUserID"> /// The from User ID. /// </param> /// <param name="userPMessageID"> /// The user P Message ID. /// </param> /// <returns> /// Returns a list of private messages based on the arguments specified. /// If pMessageID != null, returns the PM of id pMessageId. /// If toUserID != null, returns the list of PMs sent to the user with the given ID. /// If fromUserID != null, returns the list of PMs sent by the user of the given ID. /// </returns> public static DataTable ListAsDataTable( this IRepository<PMessage> repository, [NotNull] object toUserID, [NotNull] object fromUserID, [NotNull] object userPMessageID) { return repository.DbFunction.GetData.pmessage_list( ToUserID: toUserID, FromUserID: fromUserID, UserPMessageID: userPMessageID); } /// <summary> /// Gets the list of Private Messages /// </summary> /// <param name="repository"> /// The repository. /// </param> /// <param name="userPMessageID"> /// The user Private Message ID. /// </param> /// <returns> /// Returns a list of private messages based on the arguments specified. /// If pMessageID != null, returns the PM of id pMessageId. /// If toUserID != null, returns the list of PMs sent to the user with the given ID. /// If fromUserID != null, returns the list of PMs sent by the user of the given ID. /// </returns> public static DataTable ListAsDataTable( this IRepository<PMessage> repository, [NotNull] object userPMessageID) { return repository.ListAsDataTable(null, null, userPMessageID); } #endregion } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.IO; using Google.Protobuf.TestProtos; using NUnit.Framework; namespace Google.Protobuf { public class CodedInputStreamTest { /// <summary> /// Helper to construct a byte array from a bunch of bytes. The inputs are /// actually ints so that I can use hex notation and not get stupid errors /// about precision. /// </summary> private static byte[] Bytes(params int[] bytesAsInts) { byte[] bytes = new byte[bytesAsInts.Length]; for (int i = 0; i < bytesAsInts.Length; i++) { bytes[i] = (byte) bytesAsInts[i]; } return bytes; } /// <summary> /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() /// </summary> private static void AssertReadVarint(byte[] data, ulong value) { CodedInputStream input = new CodedInputStream(data); Assert.AreEqual((uint) value, input.ReadRawVarint32()); input = new CodedInputStream(data); Assert.AreEqual(value, input.ReadRawVarint64()); Assert.IsTrue(input.IsAtEnd); // Try different block sizes. for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) { input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize)); Assert.AreEqual((uint) value, input.ReadRawVarint32()); input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize)); Assert.AreEqual(value, input.ReadRawVarint64()); Assert.IsTrue(input.IsAtEnd); } // Try reading directly from a MemoryStream. We want to verify that it // doesn't read past the end of the input, so write an extra byte - this // lets us test the position at the end. MemoryStream memoryStream = new MemoryStream(); memoryStream.Write(data, 0, data.Length); memoryStream.WriteByte(0); memoryStream.Position = 0; Assert.AreEqual((uint) value, CodedInputStream.ReadRawVarint32(memoryStream)); Assert.AreEqual(data.Length, memoryStream.Position); } /// <summary> /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and /// expects them to fail with an InvalidProtocolBufferException whose /// description matches the given one. /// </summary> private static void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data) { CodedInputStream input = new CodedInputStream(data); var exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint32()); Assert.AreEqual(expected.Message, exception.Message); input = new CodedInputStream(data); exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint64()); Assert.AreEqual(expected.Message, exception.Message); // Make sure we get the same error when reading directly from a Stream. exception = Assert.Throws<InvalidProtocolBufferException>(() => CodedInputStream.ReadRawVarint32(new MemoryStream(data))); Assert.AreEqual(expected.Message, exception.Message); } [Test] public void ReadVarint() { AssertReadVarint(Bytes(0x00), 0); AssertReadVarint(Bytes(0x01), 1); AssertReadVarint(Bytes(0x7f), 127); // 14882 AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7)); // 2961488830 AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b), (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | (0x0bL << 28)); // 64-bit // 7256456126 AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b), (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | (0x1bL << 28)); // 41256202580718336 AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49), (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49)); // 11964378330978735131 AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01), (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | (0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) | (0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63)); // Failures AssertReadVarintFailure( InvalidProtocolBufferException.MalformedVarint(), Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00)); AssertReadVarintFailure( InvalidProtocolBufferException.TruncatedMessage(), Bytes(0x80)); } /// <summary> /// Parses the given bytes using ReadRawLittleEndian32() and checks /// that the result matches the given value. /// </summary> private static void AssertReadLittleEndian32(byte[] data, uint value) { CodedInputStream input = new CodedInputStream(data); Assert.AreEqual(value, input.ReadRawLittleEndian32()); Assert.IsTrue(input.IsAtEnd); // Try different block sizes. for (int blockSize = 1; blockSize <= 16; blockSize *= 2) { input = new CodedInputStream( new SmallBlockInputStream(data, blockSize)); Assert.AreEqual(value, input.ReadRawLittleEndian32()); Assert.IsTrue(input.IsAtEnd); } } /// <summary> /// Parses the given bytes using ReadRawLittleEndian64() and checks /// that the result matches the given value. /// </summary> private static void AssertReadLittleEndian64(byte[] data, ulong value) { CodedInputStream input = new CodedInputStream(data); Assert.AreEqual(value, input.ReadRawLittleEndian64()); Assert.IsTrue(input.IsAtEnd); // Try different block sizes. for (int blockSize = 1; blockSize <= 16; blockSize *= 2) { input = new CodedInputStream( new SmallBlockInputStream(data, blockSize)); Assert.AreEqual(value, input.ReadRawLittleEndian64()); Assert.IsTrue(input.IsAtEnd); } } [Test] public void ReadLittleEndian() { AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678); AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0); AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12), 0x123456789abcdef0L); AssertReadLittleEndian64( Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL); } [Test] public void DecodeZigZag32() { Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(0)); Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(1)); Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(2)); Assert.AreEqual(-2, CodedInputStream.DecodeZigZag32(3)); Assert.AreEqual(0x3FFFFFFF, CodedInputStream.DecodeZigZag32(0x7FFFFFFE)); Assert.AreEqual(unchecked((int) 0xC0000000), CodedInputStream.DecodeZigZag32(0x7FFFFFFF)); Assert.AreEqual(0x7FFFFFFF, CodedInputStream.DecodeZigZag32(0xFFFFFFFE)); Assert.AreEqual(unchecked((int) 0x80000000), CodedInputStream.DecodeZigZag32(0xFFFFFFFF)); } [Test] public void DecodeZigZag64() { Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(0)); Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(1)); Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(2)); Assert.AreEqual(-2, CodedInputStream.DecodeZigZag64(3)); Assert.AreEqual(0x000000003FFFFFFFL, CodedInputStream.DecodeZigZag64(0x000000007FFFFFFEL)); Assert.AreEqual(unchecked((long) 0xFFFFFFFFC0000000L), CodedInputStream.DecodeZigZag64(0x000000007FFFFFFFL)); Assert.AreEqual(0x000000007FFFFFFFL, CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFEL)); Assert.AreEqual(unchecked((long) 0xFFFFFFFF80000000L), CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFFL)); Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL)); Assert.AreEqual(unchecked((long) 0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL)); } [Test] public void ReadWholeMessage_VaryingBlockSizes() { TestAllTypes message = SampleMessages.CreateFullTestAllTypes(); byte[] rawBytes = message.ToByteArray(); Assert.AreEqual(rawBytes.Length, message.CalculateSize()); TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(rawBytes); Assert.AreEqual(message, message2); // Try different block sizes. for (int blockSize = 1; blockSize < 256; blockSize *= 2) { message2 = TestAllTypes.Parser.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize)); Assert.AreEqual(message, message2); } } [Test] public void ReadHugeBlob() { // Allocate and initialize a 1MB blob. byte[] blob = new byte[1 << 20]; for (int i = 0; i < blob.Length; i++) { blob[i] = (byte) i; } // Make a message containing it. var message = new TestAllTypes { SingleBytes = ByteString.CopyFrom(blob) }; // Serialize and parse it. Make sure to parse from an InputStream, not // directly from a ByteString, so that CodedInputStream uses buffered // reading. TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(message.ToByteString()); Assert.AreEqual(message, message2); } [Test] public void ReadMaliciouslyLargeBlob() { MemoryStream ms = new MemoryStream(); CodedOutputStream output = new CodedOutputStream(ms); uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); output.WriteRawVarint32(tag); output.WriteRawVarint32(0x7FFFFFFF); output.WriteRawBytes(new byte[32]); // Pad with a few random bytes. output.Flush(); ms.Position = 0; CodedInputStream input = new CodedInputStream(ms); Assert.AreEqual(tag, input.ReadTag()); Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes()); } // Representations of a tag for field 0 with various wire types [Test] [TestCase(0)] [TestCase(1)] [TestCase(2)] [TestCase(3)] [TestCase(4)] [TestCase(5)] public void ReadTag_ZeroFieldRejected(byte tag) { CodedInputStream cis = new CodedInputStream(new byte[] { tag }); Assert.Throws<InvalidProtocolBufferException>(() => cis.ReadTag()); } internal static TestRecursiveMessage MakeRecursiveMessage(int depth) { if (depth == 0) { return new TestRecursiveMessage { I = 5 }; } else { return new TestRecursiveMessage { A = MakeRecursiveMessage(depth - 1) }; } } internal static void AssertMessageDepth(TestRecursiveMessage message, int depth) { if (depth == 0) { Assert.IsNull(message.A); Assert.AreEqual(5, message.I); } else { Assert.IsNotNull(message.A); AssertMessageDepth(message.A, depth - 1); } } [Test] public void MaliciousRecursion() { ByteString data64 = MakeRecursiveMessage(64).ToByteString(); ByteString data65 = MakeRecursiveMessage(65).ToByteString(); AssertMessageDepth(TestRecursiveMessage.Parser.ParseFrom(data64), 64); Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(data65)); CodedInputStream input = CodedInputStream.CreateWithLimits(new MemoryStream(data64.ToByteArray()), 1000000, 63); Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(input)); } [Test] public void SizeLimit() { // Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't // apply to the latter case. MemoryStream ms = new MemoryStream(SampleMessages.CreateFullTestAllTypes().ToByteArray()); CodedInputStream input = CodedInputStream.CreateWithLimits(ms, 16, 100); Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(input)); } /// <summary> /// Tests that if we read an string that contains invalid UTF-8, no exception /// is thrown. Instead, the invalid bytes are replaced with the Unicode /// "replacement character" U+FFFD. /// </summary> [Test] public void ReadInvalidUtf8() { MemoryStream ms = new MemoryStream(); CodedOutputStream output = new CodedOutputStream(ms); uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); output.WriteRawVarint32(tag); output.WriteRawVarint32(1); output.WriteRawBytes(new byte[] {0x80}); output.Flush(); ms.Position = 0; CodedInputStream input = new CodedInputStream(ms); Assert.AreEqual(tag, input.ReadTag()); string text = input.ReadString(); Assert.AreEqual('\ufffd', text[0]); } /// <summary> /// A stream which limits the number of bytes it reads at a time. /// We use this to make sure that CodedInputStream doesn't screw up when /// reading in small blocks. /// </summary> private sealed class SmallBlockInputStream : MemoryStream { private readonly int blockSize; public SmallBlockInputStream(byte[] data, int blockSize) : base(data) { this.blockSize = blockSize; } public override int Read(byte[] buffer, int offset, int count) { return base.Read(buffer, offset, Math.Min(count, blockSize)); } } [Test] public void TestNegativeEnum() { byte[] bytes = { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 }; CodedInputStream input = new CodedInputStream(bytes); Assert.AreEqual((int)SampleEnum.NegativeValue, input.ReadEnum()); Assert.IsTrue(input.IsAtEnd); } //Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily [Test] public void TestSlowPathAvoidance() { using (var ms = new MemoryStream()) { CodedOutputStream output = new CodedOutputStream(ms); output.WriteTag(1, WireFormat.WireType.LengthDelimited); output.WriteBytes(ByteString.CopyFrom(new byte[100])); output.WriteTag(2, WireFormat.WireType.LengthDelimited); output.WriteBytes(ByteString.CopyFrom(new byte[100])); output.Flush(); ms.Position = 0; CodedInputStream input = new CodedInputStream(ms, new byte[ms.Length / 2], 0, 0, false); uint tag = input.ReadTag(); Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag)); Assert.AreEqual(100, input.ReadBytes().Length); tag = input.ReadTag(); Assert.AreEqual(2, WireFormat.GetTagFieldNumber(tag)); Assert.AreEqual(100, input.ReadBytes().Length); } } [Test] public void Tag0Throws() { var input = new CodedInputStream(new byte[] { 0 }); Assert.Throws<InvalidProtocolBufferException>(() => input.ReadTag()); } [Test] public void SkipGroup() { // Create an output stream with a group in: // Field 1: string "field 1" // Field 2: group containing: // Field 1: fixed int32 value 100 // Field 2: string "ignore me" // Field 3: nested group containing // Field 1: fixed int64 value 1000 // Field 3: string "field 3" var stream = new MemoryStream(); var output = new CodedOutputStream(stream); output.WriteTag(1, WireFormat.WireType.LengthDelimited); output.WriteString("field 1"); // The outer group... output.WriteTag(2, WireFormat.WireType.StartGroup); output.WriteTag(1, WireFormat.WireType.Fixed32); output.WriteFixed32(100); output.WriteTag(2, WireFormat.WireType.LengthDelimited); output.WriteString("ignore me"); // The nested group... output.WriteTag(3, WireFormat.WireType.StartGroup); output.WriteTag(1, WireFormat.WireType.Fixed64); output.WriteFixed64(1000); // Note: Not sure the field number is relevant for end group... output.WriteTag(3, WireFormat.WireType.EndGroup); // End the outer group output.WriteTag(2, WireFormat.WireType.EndGroup); output.WriteTag(3, WireFormat.WireType.LengthDelimited); output.WriteString("field 3"); output.Flush(); stream.Position = 0; // Now act like a generated client var input = new CodedInputStream(stream); Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag()); Assert.AreEqual("field 1", input.ReadString()); Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag()); input.SkipLastField(); // Should consume the whole group, including the nested one. Assert.AreEqual(WireFormat.MakeTag(3, WireFormat.WireType.LengthDelimited), input.ReadTag()); Assert.AreEqual("field 3", input.ReadString()); } [Test] public void SkipGroup_WrongEndGroupTag() { // Create an output stream with: // Field 1: string "field 1" // Start group 2 // Field 3: fixed int32 // End group 4 (should give an error) var stream = new MemoryStream(); var output = new CodedOutputStream(stream); output.WriteTag(1, WireFormat.WireType.LengthDelimited); output.WriteString("field 1"); // The outer group... output.WriteTag(2, WireFormat.WireType.StartGroup); output.WriteTag(3, WireFormat.WireType.Fixed32); output.WriteFixed32(100); output.WriteTag(4, WireFormat.WireType.EndGroup); output.Flush(); stream.Position = 0; // Now act like a generated client var input = new CodedInputStream(stream); Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag()); Assert.AreEqual("field 1", input.ReadString()); Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag()); Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); } [Test] public void RogueEndGroupTag() { // If we have an end-group tag without a leading start-group tag, generated // code will just call SkipLastField... so that should fail. var stream = new MemoryStream(); var output = new CodedOutputStream(stream); output.WriteTag(1, WireFormat.WireType.EndGroup); output.Flush(); stream.Position = 0; var input = new CodedInputStream(stream); Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.EndGroup), input.ReadTag()); Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); } [Test] public void EndOfStreamReachedWhileSkippingGroup() { var stream = new MemoryStream(); var output = new CodedOutputStream(stream); output.WriteTag(1, WireFormat.WireType.StartGroup); output.WriteTag(2, WireFormat.WireType.StartGroup); output.WriteTag(2, WireFormat.WireType.EndGroup); output.Flush(); stream.Position = 0; // Now act like a generated client var input = new CodedInputStream(stream); input.ReadTag(); Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); } [Test] public void RecursionLimitAppliedWhileSkippingGroup() { var stream = new MemoryStream(); var output = new CodedOutputStream(stream); for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++) { output.WriteTag(1, WireFormat.WireType.StartGroup); } for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++) { output.WriteTag(1, WireFormat.WireType.EndGroup); } output.Flush(); stream.Position = 0; // Now act like a generated client var input = new CodedInputStream(stream); Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.StartGroup), input.ReadTag()); Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); } [Test] public void Construction_Invalid() { Assert.Throws<ArgumentNullException>(() => new CodedInputStream((byte[]) null)); Assert.Throws<ArgumentNullException>(() => new CodedInputStream(null, 0, 0)); Assert.Throws<ArgumentNullException>(() => new CodedInputStream((Stream) null)); Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 100, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 5, 10)); } [Test] public void CreateWithLimits_InvalidLimits() { var stream = new MemoryStream(); Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 0, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 1, 0)); } [Test] public void Dispose_DisposesUnderlyingStream() { var memoryStream = new MemoryStream(); Assert.IsTrue(memoryStream.CanRead); using (var cis = new CodedInputStream(memoryStream)) { } Assert.IsFalse(memoryStream.CanRead); // Disposed } [Test] public void Dispose_WithLeaveOpen() { var memoryStream = new MemoryStream(); Assert.IsTrue(memoryStream.CanRead); using (var cis = new CodedInputStream(memoryStream, true)) { } Assert.IsTrue(memoryStream.CanRead); // We left the stream open } [Test] public void Dispose_FromByteArray() { var stream = new CodedInputStream(new byte[10]); stream.Dispose(); } [Test] public void TestParseMessagesCloseTo2G() { byte[] serializedMessage = GenerateBigSerializedMessage(); // How many of these big messages do we need to take us near our 2GB limit? int count = Int32.MaxValue / serializedMessage.Length; // Now make a MemoryStream that will fake a near-2GB stream of messages by returning // our big serialized message 'count' times. using (RepeatingMemoryStream stream = new RepeatingMemoryStream(serializedMessage, count)) { Assert.DoesNotThrow(()=>TestAllTypes.Parser.ParseFrom(stream)); } } [Test] public void TestParseMessagesOver2G() { byte[] serializedMessage = GenerateBigSerializedMessage(); // How many of these big messages do we need to take us near our 2GB limit? int count = Int32.MaxValue / serializedMessage.Length; // Now add one to take us over the 2GB limit count++; // Now make a MemoryStream that will fake a near-2GB stream of messages by returning // our big serialized message 'count' times. using (RepeatingMemoryStream stream = new RepeatingMemoryStream(serializedMessage, count)) { Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(stream), "Protocol message was too large. May be malicious. " + "Use CodedInputStream.SetSizeLimit() to increase the size limit."); } } /// <returns>A serialized big message</returns> private static byte[] GenerateBigSerializedMessage() { byte[] value = new byte[16 * 1024 * 1024]; TestAllTypes message = SampleMessages.CreateFullTestAllTypes(); message.SingleBytes = ByteString.CopyFrom(value); return message.ToByteArray(); } /// <summary> /// A MemoryStream that repeats a byte arrays' content a number of times. /// Simulates really large input without consuming loads of memory. Used above /// to test the parsing behavior when the input size exceeds 2GB or close to it. /// </summary> private class RepeatingMemoryStream: MemoryStream { private readonly byte[] bytes; private readonly int maxIterations; private int index = 0; public RepeatingMemoryStream(byte[] bytes, int maxIterations) { this.bytes = bytes; this.maxIterations = maxIterations; } public override int Read(byte[] buffer, int offset, int count) { if (bytes.Length == 0) { return 0; } int numBytesCopiedTotal = 0; while (numBytesCopiedTotal < count && index < maxIterations) { int numBytesToCopy = Math.Min(bytes.Length - (int)Position, count); Array.Copy(bytes, (int)Position, buffer, offset, numBytesToCopy); numBytesCopiedTotal += numBytesToCopy; offset += numBytesToCopy; count -= numBytesCopiedTotal; Position += numBytesToCopy; if (Position >= bytes.Length) { Position = 0; index++; } } return numBytesCopiedTotal; } } } }
// Copyright 2006 Herre Kuijpers - <herre@xs4all.nl> // // This source file(s) may be redistributed, altered and customized // by any means PROVIDING the authors name and all copyright // notices remain intact. // THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED. USE IT AT YOUR OWN RISK. THE AUTHOR ACCEPTS NO // LIABILITY FOR ANY DATA DAMAGE/LOSS THAT THIS PRODUCT MAY CAUSE. //----------------------------------------------------------------------- using System; using System.Windows.Forms; namespace Xnlab.SQLMon.Controls.OutlookGrid { #region IOutlookGridGroup - declares the arrange/grouping interface here /// <summary> /// IOutlookGridGroup specifies the interface of any implementation of a OutlookGridGroup class /// Each implementation of the IOutlookGridGroup can override the behaviour of the grouping mechanism /// Notice also that ICloneable must be implemented. The OutlookGrid makes use of the Clone method of the Group /// to create new Group clones. Related to this is the OutlookGrid.GroupTemplate property, which determines what /// type of Group must be cloned. /// </summary> public interface IOutlookGridGroup : IComparable, ICloneable { /// <summary> /// the text to be displayed in the group row /// </summary> string Text { get; set; } /// <summary> /// determines the value of the current group. this is used to compare the group value /// against each item's value. /// </summary> object Value { get; set; } /// <summary> /// indicates whether the group is collapsed. If it is collapsed, it group items (rows) will /// not be displayed. /// </summary> bool Collapsed { get; set; } /// <summary> /// specifies which column is associated with this group /// </summary> DataGridViewColumn Column { get; set; } /// <summary> /// specifies the number of items that are part of the current group /// this value is automatically filled each time the grid is re-drawn /// e.g. after sorting the grid. /// </summary> int ItemCount { get; set; } /// <summary> /// specifies the default height of the group /// each group is cloned from the GroupStyle object. Setting the height of this object /// will also set the default height of each group. /// </summary> int Height { get; set; } } #endregion define the arrange/grouping interface here #region OutlookgGridDefaultGroup - implementation of the default grouping style /// <summary> /// each arrange/grouping class must implement the IOutlookGridGroup interface /// the Group object will determine for each object in the grid, whether it /// falls in or outside its group. /// It uses the IComparable.CompareTo function to determine if the item is in the group. /// </summary> public class OutlookgGridDefaultGroup : IOutlookGridGroup { protected object Val; protected string text; protected bool collapsed; protected DataGridViewColumn column; protected int itemCount; protected int height; public OutlookgGridDefaultGroup() { Val = null; this.column = null; height = 34; // default height } #region IOutlookGridGroup Members public virtual string Text { get { if (column == null) return string.Format("Unbound group: {0} ({1})", Value.ToString(), itemCount == 1 ? "1 item" : itemCount.ToString() + " items"); else return string.Format("{0}: {1} ({2})", column.HeaderText, Value.ToString(), itemCount == 1 ? "1 item" : itemCount.ToString() + " items"); } set { text = value; } } public virtual object Value { get { return Val; } set { Val = value; } } public virtual bool Collapsed { get { return collapsed; } set { collapsed = value; } } public virtual DataGridViewColumn Column { get { return column; } set { column = value; } } public virtual int ItemCount { get { return itemCount; } set { itemCount = value; } } public virtual int Height { get { return height; } set { height = value; } } #endregion #region ICloneable Members public virtual object Clone() { var gr = new OutlookgGridDefaultGroup(); gr.column = this.column; gr.Val = this.Val; gr.collapsed = this.collapsed; gr.text = this.text; gr.height = this.height; return gr; } #endregion #region IComparable Members /// <summary> /// this is a basic string comparison operation. /// all items are grouped and categorised based on their string-appearance. /// </summary> /// <param name="obj">the value in the related column of the item to compare to</param> /// <returns></returns> public virtual int CompareTo(object obj) { return string.Compare(Val.ToString(), obj.ToString()); } #endregion } #endregion OutlookgGridDefaultGroup - implementation of the default grouping style #region OutlookGridAlphabeticGroup - an alphabet group implementation /// <summary> /// this group simple example of an implementation which groups the items into Alphabetic categories /// based only on the first letter of each item /// /// for this we need to override the Value property (used for comparison) /// and the CompareTo function. /// Also the Clone method must be overriden, so this Group object can create clones of itself. /// Cloning of the group is used by the OutlookGrid /// </summary> public class OutlookGridAlphabeticGroup : OutlookgGridDefaultGroup { public OutlookGridAlphabeticGroup() : base() { } public override string Text { get { return string.Format("Alphabetic: {1} ({2})", column.HeaderText, Value.ToString(), itemCount == 1 ? "1 item" : itemCount.ToString() + " items"); } set { text = value; } } public override object Value { get { return Val; } set { Val = value.ToString().Substring(0,1).ToUpper(); } } #region ICloneable Members /// <summary> /// each group class must implement the clone function /// </summary> /// <returns></returns> public override object Clone() { var gr = new OutlookGridAlphabeticGroup(); gr.column = this.column; gr.Val = this.Val; gr.collapsed = this.collapsed; gr.text = this.text; gr.height = this.height; return gr; } #endregion #region IComparable Members /// <summary> /// overide the CompareTo, so only the first character is compared, instead of the whole string /// this will result in classifying each item into a letter of the Alphabet. /// for instance, this is usefull when grouping names, they will be categorized under the letters A, B, C etc.. /// </summary> /// <param name="obj"></param> /// <returns></returns> public override int CompareTo(object obj) { return string.Compare(Val.ToString(), obj.ToString().Substring(0, 1).ToUpper()); } #endregion IComparable Members } #endregion OutlookGridAlphabeticGroup - an alphabet group implementation }
#region Header // // Creator.cs - model line creator helper class // // Copyright (C) 2008-2021 by Jeremy Tammik, // Autodesk Inc. All rights reserved. // // Keywords: The Building Coder Revit API C# .NET add-in. // #endregion // Header #region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Autodesk.Revit.Creation; using Autodesk.Revit.DB; using Document = Autodesk.Revit.Creation.Document; #endregion // Namespaces namespace BuildingCoder { internal class Creator { private readonly Document _credoc; private readonly Autodesk.Revit.DB.Document _doc; // these are // Autodesk.Revit.Creation // objects! private Application _creapp; public Creator(Autodesk.Revit.DB.Document doc) { _doc = doc; _credoc = doc.Create; _creapp = doc.Application.Create; } /// <summary> /// Determine the plane that a given curve resides in and return its normal vector. /// Ask the curve for its start and end points and some point in the middle. /// The latter can be obtained by asking the curve for its parameter range and /// evaluating it in the middle, or by tessellation. In case of tessellation, /// you could iterate through the tessellation points and use each one together /// with the start and end points to try and determine a valid plane. /// Once one is found, you can add debug assertions to ensure that the other /// tessellation points (if there are any more) are in the same plane. /// In the case of the line, the tessellation only returns two points. /// I once heard that that is the only element that can do that, all /// non-linear curves return at least three. So you could use this property /// to determine that a line is a line (and add an assertion as well, if you like). /// Update, later: please note that the Revit API provides an overload of the /// NewPlane method taking a CurveArray argument. /// </summary> private XYZ GetCurveNormal(Curve curve) { var pts = curve.Tessellate(); var n = pts.Count; Debug.Assert(1 < n, "expected at least two points " + "from curve tessellation"); var p = pts[0]; var q = pts[n - 1]; var v = q - p; XYZ w, normal = null; if (2 == n) { Debug.Assert(curve is Line, "expected non-line element to have " + "more than two tessellation points"); // For non-vertical lines, use Z axis to // span the plane, otherwise Y axis: var dxy = Math.Abs(v.X) + Math.Abs(v.Y); w = dxy > Util.TolPointOnPlane ? XYZ.BasisZ : XYZ.BasisY; normal = v.CrossProduct(w).Normalize(); } else { var i = 0; while (++i < n - 1) { w = pts[i] - p; normal = v.CrossProduct(w); if (!normal.IsZeroLength()) { normal = normal.Normalize(); break; } } #if DEBUG { XYZ normal2; while (++i < n - 1) { w = pts[i] - p; normal2 = v.CrossProduct(w); Debug.Assert(normal2.IsZeroLength() || Util.IsZero(normal2.AngleTo(normal)), "expected all points of curve to " + "lie in same plane"); } } #endif // DEBUG } return normal; } /// <summary> /// Create a model line between the two given points. /// Internally, it creates an arbitrary sketch /// plane given the model line end points. /// </summary> public static ModelLine CreateModelLine( Autodesk.Revit.DB.Document doc, XYZ p, XYZ q) { if (p.DistanceTo(q) < Util.MinLineLength) return null; // Create sketch plane; for non-vertical lines, // use Z-axis to span the plane, otherwise Y-axis: var v = q - p; var dxy = Math.Abs(v.X) + Math.Abs(v.Y); var w = dxy > Util.TolPointOnPlane ? XYZ.BasisZ : XYZ.BasisY; var norm = v.CrossProduct(w).Normalize(); //Autodesk.Revit.Creation.Application creApp // = doc.Application.Create; //Plane plane = creApp.NewPlane( norm, p ); // 2014 //Plane plane = new Plane( norm, p ); // 2015, 2016 var plane = Plane.CreateByNormalAndOrigin(norm, p); // 2017 //SketchPlane sketchPlane = creDoc.NewSketchPlane( plane ); // 2013 var sketchPlane = SketchPlane.Create(doc, plane); // 2014 //Line line = creApp.NewLine( p, q, true ); // 2013 var line = Line.CreateBound(p, q); // 2014 // The following line is only valid in a project // document. In a family, it will throw an exception // saying "Document.Create can only be used with // project documents. Use Document.FamilyCreate // in the Family Editor." //Autodesk.Revit.Creation.Document creDoc // = doc.Create; //return creDoc.NewModelCurve( // //creApp.NewLine( p, q, true ), // 2013 // Line.CreateBound( p, q ), // 2014 // sketchPlane ) as ModelLine; var curve = doc.IsFamilyDocument ? doc.FamilyCreate.NewModelCurve(line, sketchPlane) : doc.Create.NewModelCurve(line, sketchPlane); return curve as ModelLine; } private SketchPlane NewSketchPlanePassLine( Line line) { var p = line.GetEndPoint(0); var q = line.GetEndPoint(1); XYZ norm; if (p.X == q.X) norm = XYZ.BasisX; else if (p.Y == q.Y) norm = XYZ.BasisY; else norm = XYZ.BasisZ; //Plane plane = _creapp.NewPlane( norm, p ); // 2016 var plane = Plane.CreateByNormalAndOrigin(norm, p); // 2017 //return _credoc.NewSketchPlane( plane ); // 2013 return SketchPlane.Create(_doc, plane); // 2014 } //public void CreateModelLine( XYZ p, XYZ q ) //{ // if( p.IsAlmostEqualTo( q ) ) // { // throw new ArgumentException( // "Expected two different points." ); // } // Line line = Line.CreateBound( p, q ); // if( null == line ) // { // throw new Exception( // "Geometry line creation failed." ); // } // _credoc.NewModelCurve( line, // NewSketchPlanePassLine( line ) ); //} /// <summary> /// Return a new sketch plane containing the given curve. /// Update, later: please note that the Revit API provides /// an overload of the NewPlane method taking a CurveArray /// argument, which could presumably be used instead. /// </summary> private SketchPlane NewSketchPlaneContainCurve( Curve curve) { var p = curve.GetEndPoint(0); var normal = GetCurveNormal(curve); //Plane plane = _creapp.NewPlane( normal, p ); // 2016 var plane = Plane.CreateByNormalAndOrigin(normal, p); // 2017 #if DEBUG if (!(curve is Line)) { //CurveArray a = _creapp.NewCurveArray(); //a.Append( curve ); //Plane plane2 = _creapp.NewPlane( a ); // 2016 var a = new List<Curve>(1); a.Add(curve); var b = CurveLoop.Create(a); var plane2 = b.GetPlane(); // 2017 Debug.Assert(Util.IsParallel(plane2.Normal, plane.Normal), "expected equal planes"); Debug.Assert(Util.IsZero(plane2.SignedDistanceTo( plane.Origin)), "expected equal planes"); } #endif // DEBUG //return _credoc.NewSketchPlane( plane ); // 2013 return SketchPlane.Create(_doc, plane); // 2014 } public ModelCurve CreateModelCurve(Curve curve) { return _credoc.NewModelCurve(curve, NewSketchPlaneContainCurve(curve)); } private ModelCurve CreateModelCurve( Curve curve, XYZ origin, XYZ normal) { //Plane plane = _creapp.NewPlane( normal, origin ); // 2016 var plane = Plane.CreateByNormalAndOrigin( normal, origin); // 2017 var sketchPlane = SketchPlane.Create( _doc, plane); return _credoc.NewModelCurve( curve, sketchPlane); } public ModelCurveArray CreateModelCurves( Curve curve) { var array = new ModelCurveArray(); var line = curve as Line; if (line != null) { array.Append(CreateModelLine(_doc, curve.GetEndPoint(0), curve.GetEndPoint(1))); return array; } var arc = curve as Arc; if (arc != null) { var origin = arc.Center; var normal = arc.Normal; array.Append(CreateModelCurve( arc, origin, normal)); return array; } var ellipse = curve as Ellipse; if (ellipse != null) { var origin = ellipse.Center; var normal = ellipse.Normal; array.Append(CreateModelCurve( ellipse, origin, normal)); return array; } var points = curve.Tessellate(); var p = points.First(); foreach (var q in points.Skip(1)) { array.Append(CreateModelLine(_doc, p, q)); p = q; } return array; } public void DrawPolygon( List<XYZ> loop) { var p1 = XYZ.Zero; var q = XYZ.Zero; var first = true; foreach (var p in loop) { if (first) { p1 = p; first = false; } else { CreateModelLine(_doc, p, q); } q = p; } CreateModelLine(_doc, q, p1); } public void DrawPolygons( List<List<XYZ>> loops) { foreach (var loop in loops) DrawPolygon(loop); } public void DrawFaceTriangleNormals(Face f) { var mesh = f.Triangulate(); var n = mesh.NumTriangles; var s = "{0} face triangulation returns " + "mesh triangle{1} and normal vector{1}:"; Debug.Print( s, n, Util.PluralSuffix(n)); for (var i = 0; i < n; ++i) { var t = mesh.get_Triangle(i); var p = (t.get_Vertex(0) + t.get_Vertex(1) + t.get_Vertex(2)) / 3; var v = t.get_Vertex(1) - t.get_Vertex(0); var w = t.get_Vertex(2) - t.get_Vertex(0); var normal = v.CrossProduct(w).Normalize(); Debug.Print( "{0} {1} --> {2}", i, Util.PointString(p), Util.PointString(normal)); CreateModelLine(_doc, p, p + normal); } } /// <summary> /// Create a TextNote on the specified XYZ. /// This function is useful during debugging to attach /// a label to points in space /// </summary> public static TextNote CreateTextNote(string text, XYZ origin, Autodesk.Revit.DB.Document doc) { var options = new TextNoteOptions { HorizontalAlignment = HorizontalTextAlignment.Center, VerticalAlignment = VerticalTextAlignment.Middle, TypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType) }; return TextNote.Create(doc, doc.ActiveView.Id, origin, text, options); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using FluentNHibernate.Automapping.TestFixtures; using FluentNHibernate.Automapping.TestFixtures.CustomTypes; using FluentNHibernate.Conventions.Helpers.Builders; using FluentNHibernate.Conventions.Instances; using FluentNHibernate.Mapping; using FluentNHibernate.MappingModel; using FluentNHibernate.MappingModel.Collections; using FluentNHibernate.Testing.FluentInterfaceTests; using NUnit.Framework; namespace FluentNHibernate.Testing.ConventionsTests.ApplyingToModel { [TestFixture] public class HasManyCollectionConventionTests { private PersistenceModel model; [SetUp] public void CreatePersistenceModel() { model = new PersistenceModel(); } [Test] public void ShouldSetAccessProperty() { Convention(x => x.Access.Property()); VerifyModel(x => x.Access.ShouldEqual("property")); } [Test] public void ShouldSetBatchSizeProperty() { Convention(x => x.BatchSize(100)); VerifyModel(x => x.BatchSize.ShouldEqual(100)); } [Test] public void ShouldSetCacheProperty() { Convention(x => x.Cache.ReadWrite()); VerifyModel(x => x.Cache.Usage.ShouldEqual("read-write")); } [Test] public void ShouldSetCascadeProperty() { Convention(x => x.Cascade.None()); VerifyModel(x => x.Cascade.ShouldEqual("none")); } [Test] public void ShouldSetCheckConstraintProperty() { Convention(x => x.Check("constraint = 0")); VerifyModel(x => x.Check.ShouldEqual("constraint = 0")); } [Test] public void ShouldSetCollectionTypeProperty() { Convention(x => x.CollectionType<string>()); VerifyModel(x => x.CollectionType.GetUnderlyingSystemType().ShouldEqual(typeof(string))); } [Test] public void ShouldSetFetchProperty() { Convention(x => x.Fetch.Select()); VerifyModel(x => x.Fetch.ShouldEqual("select")); } [Test] public void ShouldSetGenericProperty() { Convention(x => x.Generic()); VerifyModel(x => x.Generic.ShouldBeTrue()); } [Test] public void ShouldSetInverseProperty() { Convention(x => x.Inverse()); VerifyModel(x => x.Inverse.ShouldBeTrue()); } [Test] public void ShouldSetKeyColumnNameProperty() { Convention(x => x.Key.Column("xxx")); VerifyModel(x => x.Key.Columns.First().Name.ShouldEqual("xxx")); } [Test] public void ShouldSetElementColumnNameProperty() { Convention(x => x.Element.Column("xxx")); VerifyModel(x => x.Element.Columns.First().Name.ShouldEqual("xxx")); } [Test] public void ShouldSetElementTypePropertyUsingGeneric() { Convention(x => x.Element.Type<string>()); VerifyModel(x => x.Element.Type.GetUnderlyingSystemType().ShouldEqual(typeof(string))); } [Test] public void ShouldSetElementTypePropertyUsingTypeOf() { Convention(x => x.Element.Type(typeof(string))); VerifyModel(x => x.Element.Type.GetUnderlyingSystemType().ShouldEqual(typeof(string))); } [Test] public void ShouldSetElementTypePropertyUsingString() { Convention(x => x.Element.Type(typeof(string).AssemblyQualifiedName)); VerifyModel(x => x.Element.Type.GetUnderlyingSystemType().ShouldEqual(typeof(string))); } [Test] public void ShouldSetLazyProperty() { Convention(x => x.LazyLoad()); VerifyModel(x => x.Lazy.ShouldEqual(Lazy.True)); } [Test] public void ShouldSetOptimisticLockProperty() { Convention(x => x.OptimisticLock()); VerifyModel(x => x.OptimisticLock.ShouldEqual(true)); } [Test] public void ShouldSetPersisterProperty() { Convention(x => x.Persister<SecondCustomPersister>()); VerifyModel(x => x.Persister.GetUnderlyingSystemType().ShouldEqual(typeof(SecondCustomPersister))); } [Test] public void ShouldSetSchemaProperty() { Convention(x => x.Schema("test")); VerifyModel(x => x.Schema.ShouldEqual("test")); } [Test] public void ShouldSetWhereProperty() { Convention(x => x.Where("y = 2")); VerifyModel(x => x.Where.ShouldEqual("y = 2")); } [Test] public void ShouldSetForeignKeyProperty() { Convention(x => x.Key.ForeignKey("xxx")); VerifyModel(x => x.Key.ForeignKey.ShouldEqual("xxx")); } [Test] public void ShouldSetPropertyRefProperty() { Convention(x => x.Key.PropertyRef("xxx")); VerifyModel(x => x.Key.PropertyRef.ShouldEqual("xxx")); } [Test] public void KeyNullableShouldSetModelValue() { Convention(x => x.KeyNullable()); VerifyModel(x => x.Key.NotNull.ShouldBeFalse()); } [Test] public void KeyNotNullableShouldSetModelValue() { Convention(x => x.Not.KeyNullable()); VerifyModel(x => x.Key.NotNull.ShouldBeTrue()); } [Test] public void KeyUpdateShouldSetModelValue() { Convention(x => x.KeyUpdate()); VerifyModel(x => x.Key.Update.ShouldBeTrue()); } [Test] public void KeyNotUpdateShouldSetModelValue() { Convention(x => x.Not.KeyUpdate()); VerifyModel(x => x.Key.Update.ShouldBeFalse()); } [Test] public void ShouldSetTableNameProperty() { Convention(x => x.Table("xxx")); VerifyModel(x => x.TableName.ShouldEqual("xxx")); } [Test] public void ShouldChangeCollectionTypeToList() { Convention(x => { x.AsList(); x.Index.Column("position"); } ); VerifyModel(x => { x.Collection.ShouldEqual(Collection.List); x.Index.ShouldNotBeNull(); // a list without index will result in wrong xml }); } #region Helpers private void Convention(Action<ICollectionInstance> convention) { model.Conventions.Add(new CollectionConventionBuilder().Always(convention)); } private void VerifyModel(Action<CollectionMapping> modelVerification) { var classMap = new ClassMap<ExampleInheritedClass>(); classMap.Id(x => x.Id); var map = classMap.HasMany(x => x.Children); model.Add(classMap); var generatedModels = model.BuildMappings(); var modelInstance = generatedModels .First(x => x.Classes.FirstOrDefault(c => c.Type == typeof(ExampleInheritedClass)) != null) .Classes.First() .Collections.First(); modelVerification(modelInstance); } #endregion } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Numerics; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.PythonTools.Debugger.Concord.Proxies; using Microsoft.PythonTools.Debugger.Concord.Proxies.Structs; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Parsing; using Microsoft.PythonTools.Parsing.Ast; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.CallStack; using Microsoft.VisualStudio.Debugger.Evaluation; namespace Microsoft.PythonTools.Debugger.Concord { internal class ExpressionEvaluator : DkmDataItem { // Value of this constant must always remain in sync with DebuggerHelper/trace.cpp. private const int ExpressionEvaluationBufferSize = 0x1000; private const int MaxDebugChildren = 1000; private const int ExpressionEvaluationTimeout = 3000; // ms private readonly DkmProcess _process; private readonly UInt64Proxy _evalLoopThreadId, _evalLoopFrame, _evalLoopResult, _evalLoopExcType, _evalLoopExcValue, _evalLoopExcStr; private readonly UInt32Proxy _evalLoopSEHCode; private readonly CStringProxy _evalLoopInput; public ExpressionEvaluator(DkmProcess process) { _process = process; var pyrtInfo = process.GetPythonRuntimeInfo(); _evalLoopThreadId = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt64Proxy>("evalLoopThreadId"); _evalLoopFrame = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt64Proxy>("evalLoopFrame"); _evalLoopResult = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt64Proxy>("evalLoopResult"); _evalLoopExcType = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt64Proxy>("evalLoopExcType"); _evalLoopExcValue = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt64Proxy>("evalLoopExcValue"); _evalLoopExcStr = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt64Proxy>("evalLoopExcStr"); _evalLoopSEHCode = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt32Proxy>("evalLoopSEHCode"); _evalLoopInput = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<CStringProxy>("evalLoopInput"); LocalComponent.CreateRuntimeDllExportedFunctionBreakpoint(pyrtInfo.DLLs.DebuggerHelper, "OnEvalComplete", OnEvalComplete, enable: true); } private interface IPythonEvaluationResult { List<DkmEvaluationResult> GetChildren(ExpressionEvaluator exprEval, DkmEvaluationResult result, DkmInspectionContext inspectionContext); } private interface IPythonEvaluationResultAsync { void GetChildren(DkmEvaluationResult result, DkmWorkList workList, int initialRequestSize, DkmInspectionContext inspectionContext, DkmCompletionRoutine<DkmGetChildrenAsyncResult> completionRoutine); } private class RawEvaluationResult : DkmDataItem { public object Value { get; set; } } /// <summary> /// Data item attached to a <see cref="DkmEvaluationResult"/> that represents a Python object (a variable, field of another object, collection item etc). /// </summary> private class PyObjectEvaluationResult : DkmDataItem, IPythonEvaluationResult { // Maps CLR types as returned from IValueStore.Read() to corresponding Python types. // Used to compute the expected Python type for a T_* slot of a native object, since we don't have the actual PyObject value yet. private static readonly Dictionary<Type, string> _typeMapping = new Dictionary<Type, string>() { { typeof(sbyte), "int" }, { typeof(byte), "int" }, { typeof(short), "int" }, { typeof(ushort), "int" }, { typeof(int), "int" }, { typeof(uint), "int" }, { typeof(long), "int" }, { typeof(ulong), "int" }, { typeof(float), "float" }, { typeof(double), "float" }, { typeof(Complex), "complex" }, { typeof(bool), "bool" }, { typeof(string), "str" }, { typeof(AsciiString), "bytes" }, }; // 2.x-specific mappings that override the ones above. private static readonly Dictionary<Type, string> _typeMapping2x = new Dictionary<Type, string>() { { typeof(string), "unicode" }, { typeof(AsciiString), "str" }, }; public PyObjectEvaluationResult(DkmProcess process, string fullName, IValueStore<PyObject> valueStore, string cppTypeName, bool hasCppView, bool isOwned) { Process = process; FullName = fullName; ValueStore = valueStore; CppTypeName = cppTypeName; HasCppView = hasCppView; IsOwned = isOwned; } public DkmProcess Process { get; private set; } public string FullName { get; private set; } public IValueStore<PyObject> ValueStore { get; private set; } /// <summary> /// Should this object show a child [C++ view] node? /// </summary> public bool HasCppView { get; private set; } /// <summary> /// Name of the C++ struct type corresponding to this object value. /// </summary> public string CppTypeName { get; private set; } /// <summary> /// Name of the native module containing <see cref="CppTypeName"/>. /// </summary> public string CppTypeModuleName { get; private set; } /// <summary> /// Whether this object needs to be decref'd once the evaluation result goes away. /// </summary> public bool IsOwned { get; private set; } protected override void OnClose() { base.OnClose(); if (IsOwned) { var obj = ValueStore.Read(); Process.GetDataItem<PyObjectAllocator>().QueueForDecRef(obj); } } public List<DkmEvaluationResult> GetChildren(ExpressionEvaluator exprEval, DkmEvaluationResult result, DkmInspectionContext inspectionContext) { var stackFrame = result.StackFrame; var cppEval = new CppExpressionEvaluator(inspectionContext, stackFrame); var obj = ValueStore.Read(); var evalResults = new List<DkmEvaluationResult>(); var reprOptions = new ReprOptions(inspectionContext); var reprBuilder = new ReprBuilder(reprOptions); if (DebuggerOptions.ShowCppViewNodes && !HasCppView) { if (CppTypeName == null) { // Try to guess the object's C++ type by looking at function pointers in its PyTypeObject. If they are pointing // into a module for which symbols are available, C++ EE should be able to resolve them into something like // "0x1e120d50 {python33_d.dll!list_dealloc(PyListObject *)}". If we are lucky, one of those functions will have // the first argument declared as a strongly typed pointer, rather than PyObject* or void*. CppTypeName = "PyObject"; CppTypeModuleName = Process.GetPythonRuntimeInfo().DLLs.Python.Name; foreach (string methodField in _methodFields) { var funcPtrEvalResult = cppEval.TryEvaluateObject(CppTypeModuleName, "PyObject", obj.Address, ".ob_type->" + methodField) as DkmSuccessEvaluationResult; if (funcPtrEvalResult == null || funcPtrEvalResult.Value.IndexOf('{') < 0) { continue; } var match = _cppFirstArgTypeFromFuncPtrRegex.Match(funcPtrEvalResult.Value); string module = match.Groups["module"].Value; string firstArgType = match.Groups["type"].Value; if (firstArgType != "void" && firstArgType != "PyObject" && firstArgType != "_object") { CppTypeName = firstArgType; CppTypeModuleName = module; break; } } } string cppExpr = CppExpressionEvaluator.GetExpressionForObject(CppTypeModuleName, CppTypeName, obj.Address, ",!"); var evalResult = DkmIntermediateEvaluationResult.Create( inspectionContext, stackFrame, "[C++ view]", "{C++}" + cppExpr, cppExpr, CppExpressionEvaluator.CppLanguage, stackFrame.Process.GetNativeRuntimeInstance(), null); evalResults.Add(evalResult); } int i = 0; foreach (var child in obj.GetDebugChildren(reprOptions).Take(MaxDebugChildren)) { if (child.Name == null) { reprBuilder.Clear(); reprBuilder.AppendFormat("[{0:PY}]", i++); child.Name = reprBuilder.ToString(); } DkmEvaluationResult evalResult; if (child.ValueStore is IValueStore<PyObject>) { evalResult = exprEval.CreatePyObjectEvaluationResult(inspectionContext, stackFrame, FullName, child, cppEval); } else { var value = child.ValueStore.Read(); reprBuilder.Clear(); reprBuilder.AppendLiteral(value); string type = null; if (Process.GetPythonRuntimeInfo().LanguageVersion <= PythonLanguageVersion.V27) { _typeMapping2x.TryGetValue(value.GetType(), out type); } if (type == null) { _typeMapping.TryGetValue(value.GetType(), out type); } var flags = DkmEvaluationResultFlags.ReadOnly; if (value is string) { flags |= DkmEvaluationResultFlags.RawString; } string childFullName = child.Name; if (FullName != null) { if (childFullName.EndsWithOrdinal("()")) { // len() childFullName = childFullName.Substring(0, childFullName.Length - 2) + "(" + FullName + ")"; } else { if (!childFullName.StartsWithOrdinal("[")) { // [0], ['fob'] etc childFullName = "." + childFullName; } childFullName = FullName + childFullName; } } evalResult = DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, child.Name, childFullName, flags, reprBuilder.ToString(), null, type, child.Category, child.AccessType, child.StorageType, child.TypeModifierFlags, null, null, null, new RawEvaluationResult { Value = value }); } evalResults.Add(evalResult); } return evalResults; } } /// <summary> /// Data item attached to the <see cref="DkmEvaluationResult"/> representing the [Globals] node. /// </summary> private class GlobalsEvaluationResult : DkmDataItem, IPythonEvaluationResult { public PyDictObject Globals { get; set; } public List<DkmEvaluationResult> GetChildren(ExpressionEvaluator exprEval, DkmEvaluationResult result, DkmInspectionContext inspectionContext) { var stackFrame = result.StackFrame; var cppEval = new CppExpressionEvaluator(inspectionContext, stackFrame); var evalResults = new List<DkmEvaluationResult>(); foreach (var pair in Globals.ReadElements()) { var name = pair.Key as IPyBaseStringObject; if (name == null) { continue; } var evalResult = exprEval.CreatePyObjectEvaluationResult(inspectionContext, stackFrame, null, new PythonEvaluationResult(pair.Value, name.ToString()), cppEval); evalResults.Add(evalResult); } return evalResults.OrderBy(er => er.Name).ToList(); } } /// <summary> /// Data item attached to the <see cref="DkmEvaluationResult"/> representing the [C++ view] node. /// </summary> private class CppViewEvaluationResult : DkmDataItem, IPythonEvaluationResultAsync { public DkmSuccessEvaluationResult CppEvaluationResult { get; set; } public void GetChildren(DkmEvaluationResult result, DkmWorkList workList, int initialRequestSize, DkmInspectionContext inspectionContext, DkmCompletionRoutine<DkmGetChildrenAsyncResult> completionRoutine) { CppEvaluationResult.GetChildren(workList, initialRequestSize, CppEvaluationResult.InspectionContext, (cppResult) => { completionRoutine(cppResult); }); } } private class EvaluationResults : DkmDataItem { public IEnumerable<DkmEvaluationResult> Results { get; set; } } // Names of fields of PyTypeObject struct that contain function pointers corresponding to standard methods of the type. // These are in rough descending order of probability of being non-null and strongly typed (so that we don't waste time eval'ing unnecessary). private static readonly string[] _methodFields = { "tp_init", "tp_dealloc", "tp_repr", "tp_hash", "tp_str", "tp_call", "tp_iter", "tp_iternext", "tp_richcompare", "tp_print", "tp_del", "tp_clear", "tp_traverse", "tp_getattr", "tp_setattr", "tp_getattro", "tp_setattro", }; // Given something like "0x1e120d50 {python33_d.dll!list_dealloc(PyListObject *)}", extract "python33_d.dll" and "PyListObject". private static readonly Regex _cppFirstArgTypeFromFuncPtrRegex = new Regex(@"^.*?\{(?<module>.*?)\!.*?\((?<type>[0-9A-Za-z_:]*?)\s*\*(,.*?)?\)\}$", RegexOptions.CultureInvariant); /// <summary> /// Create a DkmEvaluationResult representing a Python object. /// </summary> /// <param name="cppEval">C++ evaluator to use to provide the [C++ view] node for this object.</param> /// <param name="cppTypeName"> /// C++ struct name corresponding to this object type, for use by [C++ view] node. If not specified, it will be inferred from values of /// various function pointers in <c>ob_type</c>, if possible. <c>PyObject</c> is the ultimate fallback. /// </param> public DkmEvaluationResult CreatePyObjectEvaluationResult(DkmInspectionContext inspectionContext, DkmStackWalkFrame stackFrame, string parentName, PythonEvaluationResult pyEvalResult, CppExpressionEvaluator cppEval, string cppTypeName = null, bool hasCppView = false, bool isOwned = false) { var name = pyEvalResult.Name; var valueStore = pyEvalResult.ValueStore as IValueStore<PyObject>; if (valueStore == null) { Debug.Fail("Non-PyObject PythonEvaluationResult passed to CreateEvaluationResult."); throw new ArgumentException(); } var valueObj = valueStore.Read(); string typeName = valueObj.ob_type.Read().tp_name.Read().ReadUnicode(); var reprOptions = new ReprOptions(inspectionContext); string repr = valueObj.Repr(reprOptions); var flags = pyEvalResult.Flags; if (DebuggerOptions.ShowCppViewNodes || valueObj.GetDebugChildren(reprOptions).Any()) { flags |= DkmEvaluationResultFlags.Expandable; } if (!(valueStore is IWritableDataProxy)) { flags |= DkmEvaluationResultFlags.ReadOnly; } if (valueObj is IPyBaseStringObject) { flags |= DkmEvaluationResultFlags.RawString; } var boolObj = valueObj as IPyBoolObject; if (boolObj != null) { flags |= DkmEvaluationResultFlags.Boolean; if (boolObj.ToBoolean()) { flags |= DkmEvaluationResultFlags.BooleanTrue; } } string fullName = name; if (parentName != null) { if (!fullName.StartsWithOrdinal("[")) { fullName = "." + fullName; } fullName = parentName + fullName; } var pyObjEvalResult = new PyObjectEvaluationResult(stackFrame.Process, fullName, valueStore, cppTypeName, hasCppView, isOwned); return DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, name, fullName, flags, repr, null, typeName, pyEvalResult.Category, pyEvalResult.AccessType, pyEvalResult.StorageType, pyEvalResult.TypeModifierFlags, null, null, null, pyObjEvalResult); } public void GetFrameLocals(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmStackWalkFrame stackFrame, DkmCompletionRoutine<DkmGetFrameLocalsAsyncResult> completionRoutine) { var pythonFrame = PyFrameObject.TryCreate(stackFrame); if (pythonFrame == null) { Debug.Fail("Non-Python frame passed to GetFrameLocals."); throw new NotSupportedException(); } var cppEval = new CppExpressionEvaluator(inspectionContext, stackFrame); var evalResults = new List<DkmEvaluationResult>(); var f_code = pythonFrame.f_code.Read(); var f_localsplus = pythonFrame.f_localsplus; // Process cellvars and freevars first, because function arguments can appear in both cellvars and varnames if the argument is captured by a closure, // in which case we want to use the cellvar because the regular var slot will then be unused by Python (and in Python 3.4+, nulled out). var namesSeen = new HashSet<string>(); var cellNames = f_code.co_cellvars.Read().ReadElements().Concat(f_code.co_freevars.Read().ReadElements()); var cellSlots = f_localsplus.Skip(f_code.co_nlocals.Read()); foreach (var pair in cellNames.Zip(cellSlots, (nameObj, cellSlot) => new { nameObj, cellSlot = cellSlot })) { var nameObj = pair.nameObj; var cellSlot = pair.cellSlot; var name = (nameObj.Read() as IPyBaseStringObject).ToStringOrNull(); if (name == null) { continue; } namesSeen.Add(name); if (cellSlot.IsNull) { continue; } var cell = cellSlot.Read() as PyCellObject; if (cell == null) { continue; } var localPtr = cell.ob_ref; if (localPtr.IsNull) { continue; } var evalResult = CreatePyObjectEvaluationResult(inspectionContext, stackFrame, null, new PythonEvaluationResult(localPtr, name), cppEval); evalResults.Add(evalResult); } PyTupleObject co_varnames = f_code.co_varnames.Read(); foreach (var pair in co_varnames.ReadElements().Zip(f_localsplus, (nameObj, varSlot) => new { nameObj, cellSlot = varSlot })) { var nameObj = pair.nameObj; var varSlot = pair.cellSlot; var name = (nameObj.Read() as IPyBaseStringObject).ToStringOrNull(); if (name == null) { continue; } // Check for function argument that was promoted to a cell. if (!namesSeen.Add(name)) { continue; } if (varSlot.IsNull) { continue; } var evalResult = CreatePyObjectEvaluationResult(inspectionContext, stackFrame, null, new PythonEvaluationResult(varSlot, name), cppEval); evalResults.Add(evalResult); } var globals = pythonFrame.f_globals.TryRead(); if (globals != null) { var globalsEvalResult = new GlobalsEvaluationResult { Globals = globals }; // TODO: Localization: is it safe to localize [Globals] ? Appears twice in this file DkmEvaluationResult evalResult = DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, "[Globals]", null, DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.Expandable, null, null, null, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.None, DkmEvaluationResultStorageType.None, DkmEvaluationResultTypeModifierFlags.None, null, null, null, globalsEvalResult); // If it is a top-level module frame, show globals inline; otherwise, show them under the [Globals] node. if (f_code.co_name.Read().ToStringOrNull() == "<module>") { evalResults.AddRange(globalsEvalResult.GetChildren(this, evalResult, inspectionContext)); } else { evalResults.Add(evalResult); // Show any globals that are directly referenced by the function inline even in local frames. var globalVars = (from pair in globals.ReadElements() let nameObj = pair.Key as IPyBaseStringObject where nameObj != null select new { Name = nameObj.ToString(), Value = pair.Value } ).ToLookup(v => v.Name, v => v.Value); PyTupleObject co_names = f_code.co_names.Read(); foreach (var nameObj in co_names.ReadElements()) { var name = (nameObj.Read() as IPyBaseStringObject).ToStringOrNull(); if (name == null) { continue; } // If this is a used name but it was not in varnames or freevars, it is a directly referenced global. if (!namesSeen.Add(name)) { continue; } var varSlot = globalVars[name].FirstOrDefault(); if (varSlot.Process != null) { evalResult = CreatePyObjectEvaluationResult(inspectionContext, stackFrame, null, new PythonEvaluationResult(varSlot, name), cppEval); evalResults.Add(evalResult); } } } } var enumContext = DkmEvaluationResultEnumContext.Create(evalResults.Count, stackFrame, inspectionContext, new EvaluationResults { Results = evalResults.OrderBy(er => er.Name) }); completionRoutine(new DkmGetFrameLocalsAsyncResult(enumContext)); } public void GetChildren(DkmEvaluationResult result, DkmWorkList workList, int initialRequestSize, DkmInspectionContext inspectionContext, DkmCompletionRoutine<DkmGetChildrenAsyncResult> completionRoutine) { var asyncEvalResult = result.GetDataItem<CppViewEvaluationResult>(); if (asyncEvalResult != null) { asyncEvalResult.GetChildren(result, workList, initialRequestSize, inspectionContext, completionRoutine); return; } var pyEvalResult = (IPythonEvaluationResult)result.GetDataItem<PyObjectEvaluationResult>() ?? (IPythonEvaluationResult)result.GetDataItem<GlobalsEvaluationResult>(); if (pyEvalResult != null) { var childResults = pyEvalResult.GetChildren(this, result, inspectionContext); completionRoutine( new DkmGetChildrenAsyncResult( childResults.Take(initialRequestSize).ToArray(), DkmEvaluationResultEnumContext.Create( childResults.Count, result.StackFrame, inspectionContext, new EvaluationResults { Results = childResults.ToArray() }))); return; } Debug.Fail("GetChildren called on an unsupported DkmEvaluationResult."); throw new NotSupportedException(); } public void GetItems(DkmEvaluationResultEnumContext enumContext, DkmWorkList workList, int startIndex, int count, DkmCompletionRoutine<DkmEvaluationEnumAsyncResult> completionRoutine) { var evalResults = enumContext.GetDataItem<EvaluationResults>(); if (evalResults == null) { Debug.Fail("GetItems called on a DkmEvaluationResultEnumContext without an associated EvaluationResults."); throw new NotSupportedException(); } var result = evalResults.Results.Skip(startIndex).Take(count).ToArray(); completionRoutine(new DkmEvaluationEnumAsyncResult(result)); } public void EvaluateExpression(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmLanguageExpression expression, DkmStackWalkFrame stackFrame, DkmCompletionRoutine<DkmEvaluateExpressionAsyncResult> completionRoutine) { var name = expression.Text; GetFrameLocals(inspectionContext, workList, stackFrame, getFrameLocalsResult => { getFrameLocalsResult.EnumContext.GetItems(workList, 0, int.MaxValue, localGetItemsResult => { var vars = localGetItemsResult.Items.OfType<DkmSuccessEvaluationResult>(); // TODO: Localization: is it safe to localize [Globals] ? Appears twice in this file var globals = vars.FirstOrDefault(er => er.Name == "[Globals]"); if (globals == null) { if (!EvaluateExpressionByWalkingObjects(vars, inspectionContext, workList, expression, stackFrame, completionRoutine)) { EvaluateExpressionViaInterpreter(inspectionContext, workList, expression, stackFrame, completionRoutine); } } else { globals.GetChildren(workList, 0, inspectionContext, globalsGetChildrenResult => { globalsGetChildrenResult.EnumContext.GetItems(workList, 0, int.MaxValue, globalsGetItemsResult => { vars = vars.Concat(globalsGetItemsResult.Items.OfType<DkmSuccessEvaluationResult>()); if (!EvaluateExpressionByWalkingObjects(vars, inspectionContext, workList, expression, stackFrame, completionRoutine)) { EvaluateExpressionViaInterpreter(inspectionContext, workList, expression, stackFrame, completionRoutine); } }); }); } }); }); } /// <summary> /// Tries to evaluate the given expression by treating it as a chain of member access and indexing operations (e.g. <c>fob[0].oar.baz['abc'].blah</c>), /// and looking up the corresponding members in data model provided by <see cref="GetFrameLocals"/>. /// </summary> /// <param name="vars">List of variables, in the context of which the expression is evaluated.</param> /// <returns> /// <c>true</c> if evaluation was successful, or if it failed and no fallback is possible (e.g. expression is invalid). /// <c>false</c> if evaluation was not successful due to the limitations of this evaluator, and it may be possible to evaluate it correctly by other means. /// </returns> private bool EvaluateExpressionByWalkingObjects(IEnumerable<DkmSuccessEvaluationResult> vars, DkmInspectionContext inspectionContext, DkmWorkList workList, DkmLanguageExpression expression, DkmStackWalkFrame stackFrame, DkmCompletionRoutine<DkmEvaluateExpressionAsyncResult> completionRoutine) { var pyrtInfo = stackFrame.Thread.Process.GetPythonRuntimeInfo(); var parserOptions = new ParserOptions { ErrorSink = new StringErrorSink() }; var parser = Parser.CreateParser(new StringReader(expression.Text), pyrtInfo.LanguageVersion, parserOptions); var expr = ((ReturnStatement)parser.ParseTopExpression().Body).Expression; string errorText = parserOptions.ErrorSink.ToString(); if (!string.IsNullOrEmpty(errorText)) { completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, errorText, DkmEvaluationResultFlags.Invalid, null))); return true; } // Unroll the AST into a sequence of member access and indexing operations, if possible. var path = new Stack<string>(); var reprBuilder = new ReprBuilder(new ReprOptions(stackFrame.Thread.Process)); while (true) { var memberExpr = expr as MemberExpression; if (memberExpr != null) { path.Push(memberExpr.Name); expr = memberExpr.Target; continue; } var indexingExpr = expr as IndexExpression; if (indexingExpr != null) { var indexExpr = indexingExpr.Index as ConstantExpression; if (indexExpr != null) { reprBuilder.Clear(); reprBuilder.AppendFormat("[{0:PY}]", indexExpr.Value); path.Push(reprBuilder.ToString()); expr = indexingExpr.Target; continue; } } break; } var varExpr = expr as NameExpression; if (varExpr == null) { return false; } path.Push(varExpr.Name); // Walk the path through Locals while (true) { var name = path.Pop(); var evalResult = vars.FirstOrDefault(er => er.Name == name); if (evalResult == null) { return false; } if (path.Count == 0) { // Clone the evaluation result, but use expression text as its name. DkmDataItem dataItem = (DkmDataItem)evalResult.GetDataItem<PyObjectEvaluationResult>() ?? (DkmDataItem)evalResult.GetDataItem<GlobalsEvaluationResult>() ?? (DkmDataItem)evalResult.GetDataItem<CppViewEvaluationResult>() ?? (DkmDataItem)evalResult.GetDataItem<RawEvaluationResult>(); evalResult = DkmSuccessEvaluationResult.Create( evalResult.InspectionContext, evalResult.StackFrame, expression.Text, expression.Text, evalResult.Flags, evalResult.Value, evalResult.EditableValue, evalResult.Type, evalResult.Category, evalResult.Access, evalResult.StorageType, evalResult.TypeModifierFlags, evalResult.Address, evalResult.CustomUIVisualizers, evalResult.ExternalModules, dataItem); completionRoutine(new DkmEvaluateExpressionAsyncResult(evalResult)); return true; } var childWorkList = DkmWorkList.Create(null); evalResult.GetChildren(childWorkList, 0, inspectionContext, getChildrenResult => getChildrenResult.EnumContext.GetItems(childWorkList, 0, int.MaxValue, getItemsResult => vars = getItemsResult.Items.OfType<DkmSuccessEvaluationResult>())); childWorkList.Execute(); } } private AutoResetEvent _evalCompleteEvent, _evalAbortedEvent; private void EvaluateExpressionViaInterpreter(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmLanguageExpression expression, DkmStackWalkFrame stackFrame, DkmCompletionRoutine<DkmEvaluateExpressionAsyncResult> completionRoutine) { var thread = stackFrame.Thread; var process = thread.Process; if (_evalLoopThreadId.Read() != (ulong)thread.SystemPart.Id) { completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, Strings.DebugArbitraryExpressionOnStoppedThreadOnly, DkmEvaluationResultFlags.Invalid, null))); return; } var pythonFrame = PyFrameObject.TryCreate(stackFrame); if (pythonFrame == null) { completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, Strings.DebugNoPythonFrameForCurrentFrame, DkmEvaluationResultFlags.Invalid, null))); return; } byte[] input = Encoding.UTF8.GetBytes(expression.Text + "\0"); if (input.Length > ExpressionEvaluationBufferSize) { completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, Strings.DebugTooLongExpression, DkmEvaluationResultFlags.Invalid, null))); return; } _evalLoopFrame.Write(pythonFrame.Address); process.WriteMemory(_evalLoopInput.Address, input); bool timedOut; using (_evalCompleteEvent = new AutoResetEvent(false)) { thread.BeginFuncEvalExecution(DkmFuncEvalFlags.None); timedOut = !_evalCompleteEvent.WaitOne(ExpressionEvaluationTimeout); _evalCompleteEvent = null; } if (timedOut) { new RemoteComponent.AbortingEvalExecutionRequest().SendLower(process); // We need to stop the process before we can report end of func eval completion using (_evalAbortedEvent = new AutoResetEvent(false)) { process.AsyncBreak(false); if (!_evalAbortedEvent.WaitOne(20000)) { // This is a catastrophic error, since we can't report func eval completion unless we can stop the process, // and VS will hang until we do report completion. At this point we can only kill the debuggee so that the // VS at least gets back to a reasonable state. _evalAbortedEvent = null; process.Terminate(1); completionRoutine(DkmEvaluateExpressionAsyncResult.CreateErrorResult( new Exception(Strings.DebugCouldNotAbortFailedExpressionEvaluation))); return; } _evalAbortedEvent = null; } completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, Strings.DebugEvaluationTimedOut, DkmEvaluationResultFlags.Invalid, null))); return; } ulong objPtr = _evalLoopResult.Read(); var obj = PyObject.FromAddress(process, objPtr); var exc_type = PyObject.FromAddress(process, _evalLoopExcType.Read()); var exc_value = PyObject.FromAddress(process, _evalLoopExcValue.Read()); var exc_str = (PyObject.FromAddress(process, _evalLoopExcStr.Read()) as IPyBaseStringObject).ToStringOrNull(); var sehCode = _evalLoopSEHCode.Read(); if (obj != null) { var cppEval = new CppExpressionEvaluator(inspectionContext, stackFrame); var pyEvalResult = new PythonEvaluationResult(obj, expression.Text) { Flags = DkmEvaluationResultFlags.SideEffect }; var evalResult = CreatePyObjectEvaluationResult(inspectionContext, stackFrame, null, pyEvalResult, cppEval, null, hasCppView: true, isOwned: true); _evalLoopResult.Write(0); // don't let the eval loop decref the object - we will do it ourselves later, when eval result is closed completionRoutine(new DkmEvaluateExpressionAsyncResult(evalResult)); } else if (sehCode != 0) { completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, Enum.IsDefined(typeof(EXCEPTION_CODE), sehCode) ? Strings.DebugStructuredExceptionWhileEvaluatingExpression.FormatUI(sehCode, (EXCEPTION_CODE)sehCode) : Strings.DebugStructuredExceptionWhileEvaluatingExpressionNotAnEnumValue.FormatUI(sehCode), DkmEvaluationResultFlags.Invalid, null))); } else if (exc_type != null) { string typeName; var typeObject = exc_type as PyTypeObject; if (typeObject != null) { typeName = typeObject.tp_name.Read().ReadUnicode(); } else { typeName = Strings.DebugUnknownExceptionType; } completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, Strings.DebugErrorWhileEvaluatingExpression.FormatUI(typeName, exc_str), DkmEvaluationResultFlags.Invalid, null))); } else { completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, Strings.DebugUnknownErrorWhileEvaluatingExpression, DkmEvaluationResultFlags.Invalid, null))); } } private void OnEvalComplete(DkmThread thread, ulong frameBase, ulong vframe, ulong returnAddress) { var e = _evalCompleteEvent; if (e != null) { new RemoteComponent.EndFuncEvalExecutionRequest { ThreadId = thread.UniqueId }.SendLower(thread.Process); e.Set(); } } public void OnAsyncBreakComplete(DkmThread thread) { var e = _evalAbortedEvent; if (e != null) { new RemoteComponent.EndFuncEvalExecutionRequest { ThreadId = thread.UniqueId }.SendLower(thread.Process); e.Set(); } } public string GetUnderlyingString(DkmEvaluationResult result) { var rawResult = result.GetDataItem<RawEvaluationResult>(); if (rawResult != null && rawResult.Value is string) { return (string)rawResult.Value; } var objResult = result.GetDataItem<PyObjectEvaluationResult>(); if (objResult == null) { return null; } var str = objResult.ValueStore.Read() as IPyBaseStringObject; return str.ToStringOrNull(); } private class StringErrorSink : ErrorSink { private readonly StringBuilder _builder = new StringBuilder(); public override void Add(string message, SourceSpan span, int errorCode, Severity severity) { _builder.AppendLine(message); } public override string ToString() { return _builder.ToString(); } } public unsafe void SetValueAsString(DkmEvaluationResult result, string value, int timeout, out string errorText) { var pyEvalResult = result.GetDataItem<PyObjectEvaluationResult>(); if (pyEvalResult == null) { Debug.Fail("SetValueAsString called on a DkmEvaluationResult without an associated PyObjectEvaluationResult."); throw new NotSupportedException(); } var proxy = pyEvalResult.ValueStore as IWritableDataProxy; if (proxy == null) { Debug.Fail("SetValueAsString called on a DkmEvaluationResult that does not correspond to an IWritableDataProxy."); throw new InvalidOperationException(); } errorText = null; var process = result.StackFrame.Process; var pyrtInfo = process.GetPythonRuntimeInfo(); var parserOptions = new ParserOptions { ErrorSink = new StringErrorSink() }; var parser = Parser.CreateParser(new StringReader(value), pyrtInfo.LanguageVersion, parserOptions); var body = (ReturnStatement)parser.ParseTopExpression().Body; errorText = parserOptions.ErrorSink.ToString(); if (!string.IsNullOrEmpty(errorText)) { return; } var expr = body.Expression; while (true) { var parenExpr = expr as ParenthesisExpression; if (parenExpr == null) { break; } expr = parenExpr.Expression; } int sign; expr = ForceExplicitSign(expr, out sign); PyObject newObj = null; var constExpr = expr as ConstantExpression; if (constExpr != null) { if (constExpr.Value == null) { newObj = PyObject.None(process); } else if (constExpr.Value is bool) { // In 2.7, 'True' and 'False' are reported as identifiers, not literals, and are handled separately below. newObj = PyBoolObject33.Create(process, (bool)constExpr.Value); } else if (constExpr.Value is string) { if (pyrtInfo.LanguageVersion <= PythonLanguageVersion.V27) { newObj = PyUnicodeObject27.Create(process, (string)constExpr.Value); } else { newObj = PyUnicodeObject33.Create(process, (string)constExpr.Value); } } else if (constExpr.Value is AsciiString) { newObj = PyBytesObject.Create(process, (AsciiString)constExpr.Value); } } else { var unaryExpr = expr as UnaryExpression; if (unaryExpr != null && sign != 0) { constExpr = unaryExpr.Expression as ConstantExpression; if (constExpr != null) { if (constExpr.Value is BigInteger) { newObj = PyLongObject.Create(process, (BigInteger)constExpr.Value * sign); } else if (constExpr.Value is int) { if (pyrtInfo.LanguageVersion <= PythonLanguageVersion.V27) { newObj = PyIntObject.Create(process, (int)constExpr.Value * sign); } else { newObj = PyLongObject.Create(process, (int)constExpr.Value * sign); } } else if (constExpr.Value is double) { newObj = PyFloatObject.Create(process, (double)constExpr.Value * sign); } else if (constExpr.Value is Complex) { newObj = PyComplexObject.Create(process, (Complex)constExpr.Value * sign); } } } else { var binExpr = expr as BinaryExpression; if (binExpr != null && (binExpr.Operator == PythonOperator.Add || binExpr.Operator == PythonOperator.Subtract)) { int realSign; var realExpr = ForceExplicitSign(binExpr.Left, out realSign) as UnaryExpression; int imagSign; var imagExpr = ForceExplicitSign(binExpr.Right, out imagSign) as UnaryExpression; if (realExpr != null && realSign != 0 && imagExpr != null && imagSign != 0) { var realConst = realExpr.Expression as ConstantExpression; var imagConst = imagExpr.Expression as ConstantExpression; if (realConst != null && imagConst != null) { var realVal = (realConst.Value as int? ?? realConst.Value as double?) as IConvertible; var imagVal = imagConst.Value as Complex?; if (realVal != null && imagVal != null) { double real = realVal.ToDouble(null) * realSign; double imag = imagVal.Value.Imaginary * imagSign * (binExpr.Operator == PythonOperator.Add ? 1 : -1); newObj = PyComplexObject.Create(process, new Complex(real, imag)); } } } } else { if (pyrtInfo.LanguageVersion <= PythonLanguageVersion.V27) { // 'True' and 'False' are not literals in 2.x, but we want to treat them as such. var name = expr as NameExpression; if (name != null) { if (name.Name == "True") { newObj = PyBoolObject27.Create(process, true); } else if (name.Name == "False") { newObj = PyBoolObject27.Create(process, false); } } } } } } if (newObj != null) { var oldObj = proxy.Read() as PyObject; if (oldObj != null) { // We can't free the original value without running some code in the process, and it may be holding heap locks. // So don't decrement refcount now, but instead add it to the list of objects for TraceFunc to GC when it gets // a chance to run next time. _process.GetDataItem<PyObjectAllocator>().QueueForDecRef(oldObj); } newObj.ob_refcnt.Increment(); proxy.Write(newObj); } else { errorText = Strings.DebugOnlyBoolNumericStringAndNoneSupported; } } private static Expression ForceExplicitSign(Expression expr, out int sign) { var constExpr = expr as ConstantExpression; if (constExpr != null && (constExpr.Value is int || constExpr.Value is double || constExpr.Value is BigInteger || constExpr.Value is Complex)) { sign = 1; return new UnaryExpression(PythonOperator.Pos, constExpr); } var unaryExpr = expr as UnaryExpression; if (unaryExpr != null) { switch (unaryExpr.Op) { case PythonOperator.Pos: sign = 1; return unaryExpr; case PythonOperator.Negate: sign = -1; return unaryExpr; } } sign = 0; return expr; } } internal class PythonEvaluationResult { /// <summary> /// A store containing the evaluated value. /// </summary> public IValueStore ValueStore { get; set; } /// <summary> /// For named results, name of the result. For unnamed results, <c>null</c>. /// </summary> public string Name { get; set; } public DkmEvaluationResultCategory Category { get; set; } public DkmEvaluationResultAccessType AccessType { get; set; } public DkmEvaluationResultStorageType StorageType { get; set; } public DkmEvaluationResultTypeModifierFlags TypeModifierFlags { get; set; } public DkmEvaluationResultFlags Flags { get; set; } public PythonEvaluationResult(IValueStore valueStore, string name = null) { ValueStore = valueStore; Name = name; Category = DkmEvaluationResultCategory.Data; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Globalization; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Text; namespace Microsoft.PowerShell.Commands { /// <summary> /// Implementing type for WSManConfigurationOption. /// </summary> public class WSManConfigurationOption : PSTransportOption { private const string Token = " {0}='{1}'"; private const string QuotasToken = "<Quotas {0} />"; internal const string AttribOutputBufferingMode = "OutputBufferingMode"; internal static readonly System.Management.Automation.Runspaces.OutputBufferingMode? DefaultOutputBufferingMode = System.Management.Automation.Runspaces.OutputBufferingMode.Block; private System.Management.Automation.Runspaces.OutputBufferingMode? _outputBufferingMode = null; private const string AttribProcessIdleTimeout = "ProcessIdleTimeoutSec"; internal static readonly int? DefaultProcessIdleTimeout_ForPSRemoting = 0; // in seconds private int? _processIdleTimeoutSec = null; internal const string AttribMaxIdleTimeout = "MaxIdleTimeoutms"; internal static readonly int? DefaultMaxIdleTimeout = int.MaxValue; private int? _maxIdleTimeoutSec = null; internal const string AttribIdleTimeout = "IdleTimeoutms"; internal static readonly int? DefaultIdleTimeout = 7200; // 2 hours in seconds private int? _idleTimeoutSec = null; private const string AttribMaxConcurrentUsers = "MaxConcurrentUsers"; internal static readonly int? DefaultMaxConcurrentUsers = int.MaxValue; private int? _maxConcurrentUsers = null; private const string AttribMaxProcessesPerSession = "MaxProcessesPerShell"; internal static readonly int? DefaultMaxProcessesPerSession = int.MaxValue; private int? _maxProcessesPerSession = null; private const string AttribMaxMemoryPerSessionMB = "MaxMemoryPerShellMB"; internal static readonly int? DefaultMaxMemoryPerSessionMB = int.MaxValue; private int? _maxMemoryPerSessionMB = null; private const string AttribMaxSessions = "MaxShells"; internal static readonly int? DefaultMaxSessions = int.MaxValue; private int? _maxSessions = null; private const string AttribMaxSessionsPerUser = "MaxShellsPerUser"; internal static readonly int? DefaultMaxSessionsPerUser = int.MaxValue; private int? _maxSessionsPerUser = null; private const string AttribMaxConcurrentCommandsPerSession = "MaxConcurrentCommandsPerShell"; internal static readonly int? DefaultMaxConcurrentCommandsPerSession = int.MaxValue; private int? _maxConcurrentCommandsPerSession = null; /// <summary> /// Constructor that instantiates with default values. /// </summary> internal WSManConfigurationOption() { } /// <summary> /// Override LoadFromDefaults method. /// </summary> /// <param name="keepAssigned">Keep old values.</param> protected internal override void LoadFromDefaults(bool keepAssigned) { if (!keepAssigned || !_outputBufferingMode.HasValue) { _outputBufferingMode = DefaultOutputBufferingMode; } if (!keepAssigned || !_processIdleTimeoutSec.HasValue) { _processIdleTimeoutSec = DefaultProcessIdleTimeout_ForPSRemoting; } if (!keepAssigned || !_maxIdleTimeoutSec.HasValue) { _maxIdleTimeoutSec = DefaultMaxIdleTimeout; } if (!keepAssigned || !_idleTimeoutSec.HasValue) { _idleTimeoutSec = DefaultIdleTimeout; } if (!keepAssigned || !_maxConcurrentUsers.HasValue) { _maxConcurrentUsers = DefaultMaxConcurrentUsers; } if (!keepAssigned || !_maxProcessesPerSession.HasValue) { _maxProcessesPerSession = DefaultMaxProcessesPerSession; } if (!keepAssigned || !_maxMemoryPerSessionMB.HasValue) { _maxMemoryPerSessionMB = DefaultMaxMemoryPerSessionMB; } if (!keepAssigned || !_maxSessions.HasValue) { _maxSessions = DefaultMaxSessions; } if (!keepAssigned || !_maxSessionsPerUser.HasValue) { _maxSessionsPerUser = DefaultMaxSessionsPerUser; } if (!keepAssigned || !_maxConcurrentCommandsPerSession.HasValue) { _maxConcurrentCommandsPerSession = DefaultMaxConcurrentCommandsPerSession; } } /// <summary> /// ProcessIdleTimeout in Seconds. /// </summary> public int? ProcessIdleTimeoutSec { get { return _processIdleTimeoutSec; } internal set { _processIdleTimeoutSec = value; } } /// <summary> /// MaxIdleTimeout in Seconds. /// </summary> public int? MaxIdleTimeoutSec { get { return _maxIdleTimeoutSec; } internal set { _maxIdleTimeoutSec = value; } } /// <summary> /// MaxSessions. /// </summary> public int? MaxSessions { get { return _maxSessions; } internal set { _maxSessions = value; } } /// <summary> /// MaxConcurrentCommandsPerSession. /// </summary> public int? MaxConcurrentCommandsPerSession { get { return _maxConcurrentCommandsPerSession; } internal set { _maxConcurrentCommandsPerSession = value; } } /// <summary> /// MaxSessionsPerUser. /// </summary> public int? MaxSessionsPerUser { get { return _maxSessionsPerUser; } internal set { _maxSessionsPerUser = value; } } /// <summary> /// MaxMemoryPerSessionMB. /// </summary> public int? MaxMemoryPerSessionMB { get { return _maxMemoryPerSessionMB; } internal set { _maxMemoryPerSessionMB = value; } } /// <summary> /// MaxProcessesPerSession. /// </summary> public int? MaxProcessesPerSession { get { return _maxProcessesPerSession; } internal set { _maxProcessesPerSession = value; } } /// <summary> /// MaxConcurrentUsers. /// </summary> public int? MaxConcurrentUsers { get { return _maxConcurrentUsers; } internal set { _maxConcurrentUsers = value; } } /// <summary> /// IdleTimeout in Seconds. /// </summary> public int? IdleTimeoutSec { get { return _idleTimeoutSec; } internal set { _idleTimeoutSec = value; } } /// <summary> /// OutputBufferingMode. /// </summary> public System.Management.Automation.Runspaces.OutputBufferingMode? OutputBufferingMode { get { return _outputBufferingMode; } internal set { _outputBufferingMode = value; } } internal override Hashtable ConstructQuotasAsHashtable() { Hashtable quotas = new Hashtable(); if (_idleTimeoutSec.HasValue) { quotas[AttribIdleTimeout] = (1000 * _idleTimeoutSec.Value).ToString(CultureInfo.InvariantCulture); } if (_maxConcurrentUsers.HasValue) { quotas[AttribMaxConcurrentUsers] = _maxConcurrentUsers.Value.ToString(CultureInfo.InvariantCulture); } if (_maxProcessesPerSession.HasValue) { quotas[AttribMaxProcessesPerSession] = _maxProcessesPerSession.Value.ToString(CultureInfo.InvariantCulture); } if (_maxMemoryPerSessionMB.HasValue) { quotas[AttribMaxMemoryPerSessionMB] = _maxMemoryPerSessionMB.Value.ToString(CultureInfo.InvariantCulture); } if (_maxSessionsPerUser.HasValue) { quotas[AttribMaxSessionsPerUser] = _maxSessionsPerUser.Value.ToString(CultureInfo.InvariantCulture); } if (_maxConcurrentCommandsPerSession.HasValue) { quotas[AttribMaxConcurrentCommandsPerSession] = _maxConcurrentCommandsPerSession.Value.ToString(CultureInfo.InvariantCulture); } if (_maxSessions.HasValue) { quotas[AttribMaxSessions] = _maxSessions.Value.ToString(CultureInfo.InvariantCulture); } if (_maxIdleTimeoutSec.HasValue) { quotas[AttribMaxIdleTimeout] = (1000 * _maxIdleTimeoutSec.Value).ToString(CultureInfo.InvariantCulture); } return quotas; } /// <summary> /// ConstructQuotas. /// </summary> /// <returns></returns> internal override string ConstructQuotas() { StringBuilder sb = new StringBuilder(); if (_idleTimeoutSec.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribIdleTimeout, 1000 * _idleTimeoutSec)); } if (_maxConcurrentUsers.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxConcurrentUsers, _maxConcurrentUsers)); } if (_maxProcessesPerSession.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxProcessesPerSession, _maxProcessesPerSession)); } if (_maxMemoryPerSessionMB.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxMemoryPerSessionMB, _maxMemoryPerSessionMB)); } if (_maxSessionsPerUser.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxSessionsPerUser, _maxSessionsPerUser)); } if (_maxConcurrentCommandsPerSession.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxConcurrentCommandsPerSession, _maxConcurrentCommandsPerSession)); } if (_maxSessions.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxSessions, _maxSessions)); } if (_maxIdleTimeoutSec.HasValue) { // Special case max int value for unbounded default. sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxIdleTimeout, (_maxIdleTimeoutSec == int.MaxValue) ? _maxIdleTimeoutSec : (1000 * _maxIdleTimeoutSec))); } return sb.Length > 0 ? string.Format(CultureInfo.InvariantCulture, QuotasToken, sb.ToString()) : string.Empty; } /// <summary> /// ConstructOptionsXmlAttributes. /// </summary> /// <returns></returns> internal override string ConstructOptionsAsXmlAttributes() { StringBuilder sb = new StringBuilder(); if (_outputBufferingMode.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribOutputBufferingMode, _outputBufferingMode.ToString())); } if (_processIdleTimeoutSec.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribProcessIdleTimeout, _processIdleTimeoutSec)); } return sb.ToString(); } /// <summary> /// ConstructOptionsXmlAttributes. /// </summary> /// <returns></returns> internal override Hashtable ConstructOptionsAsHashtable() { Hashtable table = new Hashtable(); if (_outputBufferingMode.HasValue) { table[AttribOutputBufferingMode] = _outputBufferingMode.ToString(); } if (_processIdleTimeoutSec.HasValue) { table[AttribProcessIdleTimeout] = _processIdleTimeoutSec; } return table; } } /// <summary> /// Command to create an object for WSManConfigurationOption. /// </summary> [Cmdlet(VerbsCommon.New, "PSTransportOption", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=210608", RemotingCapability = RemotingCapability.None)] [OutputType(typeof(WSManConfigurationOption))] public sealed class NewPSTransportOptionCommand : PSCmdlet { private readonly WSManConfigurationOption _option = new WSManConfigurationOption(); /// <summary> /// MaxIdleTimeoutSec. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(60, 2147483)] public int? MaxIdleTimeoutSec { get { return _option.MaxIdleTimeoutSec; } set { _option.MaxIdleTimeoutSec = value; } } /// <summary> /// ProcessIdleTimeoutSec. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(0, 1209600)] public int? ProcessIdleTimeoutSec { get { return _option.ProcessIdleTimeoutSec; } set { _option.ProcessIdleTimeoutSec = value; } } /// <summary> /// MaxSessions. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(1, int.MaxValue)] public int? MaxSessions { get { return _option.MaxSessions; } set { _option.MaxSessions = value; } } /// <summary> /// MaxConcurrentCommandsPerSession. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(1, int.MaxValue)] public int? MaxConcurrentCommandsPerSession { get { return _option.MaxConcurrentCommandsPerSession; } set { _option.MaxConcurrentCommandsPerSession = value; } } /// <summary> /// MaxSessionsPerUser. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(1, int.MaxValue)] public int? MaxSessionsPerUser { get { return _option.MaxSessionsPerUser; } set { _option.MaxSessionsPerUser = value; } } /// <summary> /// MaxMemoryPerSessionMB. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(5, int.MaxValue)] public int? MaxMemoryPerSessionMB { get { return _option.MaxMemoryPerSessionMB; } set { _option.MaxMemoryPerSessionMB = value; } } /// <summary> /// MaxProcessesPerSession. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(1, int.MaxValue)] public int? MaxProcessesPerSession { get { return _option.MaxProcessesPerSession; } set { _option.MaxProcessesPerSession = value; } } /// <summary> /// MaxConcurrentUsers. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(1, 100)] public int? MaxConcurrentUsers { get { return _option.MaxConcurrentUsers; } set { _option.MaxConcurrentUsers = value; } } /// <summary> /// IdleTimeoutMs. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(60, 2147483)] public int? IdleTimeoutSec { get { return _option.IdleTimeoutSec; } set { _option.IdleTimeoutSec = value; } } /// <summary> /// OutputBufferingMode. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] public System.Management.Automation.Runspaces.OutputBufferingMode? OutputBufferingMode { get { return _option.OutputBufferingMode; } set { _option.OutputBufferingMode = value; } } /// <summary> /// Overriding the base method. /// </summary> protected override void ProcessRecord() { this.WriteObject(_option); } } }
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using Moq.Properties; namespace Moq { /// <summary> /// Defines the number of invocations allowed by a mocked method. /// </summary> public readonly struct Times : IEquatable<Times> { private readonly int from; private readonly int to; private readonly Kind kind; private Times(Kind kind, int from, int to) { this.from = from; this.to = to; this.kind = kind; } /// <summary>Deconstructs this instance.</summary> /// <param name="from">This output parameter will receive the minimum required number of calls satisfying this instance (i.e. the lower inclusive bound).</param> /// <param name="to">This output parameter will receive the maximum allowed number of calls satisfying this instance (i.e. the upper inclusive bound).</param> [EditorBrowsable(EditorBrowsableState.Advanced)] public void Deconstruct(out int from, out int to) { if (this.kind == default) { // This branch makes `default(Times)` equivalent to `Times.AtLeastOnce()`, // which is the implicit default across Moq's API for overloads that don't // accept a `Times` instance. While user code shouldn't use `default(Times)` // (but instead either specify `Times` explicitly or not at all), it is // easy enough to correct: Debug.Assert(this.kind == Kind.AtLeastOnce); from = 1; to = int.MaxValue; } else { from = this.from; to = this.to; } } /// <summary> /// Specifies that a mocked method should be invoked <paramref name="callCount"/> times /// as minimum. /// </summary> /// <param name="callCount">The minimum number of times.</param> /// <returns>An object defining the allowed number of invocations.</returns> public static Times AtLeast(int callCount) { if (callCount < 1) { throw new ArgumentOutOfRangeException(nameof(callCount)); } return new Times(Kind.AtLeast, callCount, int.MaxValue); } /// <summary> /// Specifies that a mocked method should be invoked one time as minimum. /// </summary> /// <returns>An object defining the allowed number of invocations.</returns> public static Times AtLeastOnce() { return new Times(Kind.AtLeastOnce, 1, int.MaxValue); } /// <summary> /// Specifies that a mocked method should be invoked <paramref name="callCount"/> times /// as maximum. /// </summary> /// <param name="callCount">The maximum number of times.</param> /// <returns>An object defining the allowed number of invocations.</returns> public static Times AtMost(int callCount) { if (callCount < 0) { throw new ArgumentOutOfRangeException(nameof(callCount)); } return new Times(Kind.AtMost, 0, callCount); } /// <summary> /// Specifies that a mocked method should be invoked one time as maximum. /// </summary> /// <returns>An object defining the allowed number of invocations.</returns> public static Times AtMostOnce() { return new Times(Kind.AtMostOnce, 0, 1); } /// <summary> /// Specifies that a mocked method should be invoked between /// <paramref name="callCountFrom"/> and <paramref name="callCountTo"/> times. /// </summary> /// <param name="callCountFrom">The minimum number of times.</param> /// <param name="callCountTo">The maximum number of times.</param> /// <param name="rangeKind">The kind of range. See <see cref="Range"/>.</param> /// <returns>An object defining the allowed number of invocations.</returns> public static Times Between(int callCountFrom, int callCountTo, Range rangeKind) { if (rangeKind == Range.Exclusive) { if (callCountFrom <= 0 || callCountTo <= callCountFrom) { throw new ArgumentOutOfRangeException(nameof(callCountFrom)); } if (callCountTo - callCountFrom == 1) { throw new ArgumentOutOfRangeException(nameof(callCountTo)); } return new Times(Kind.BetweenExclusive, callCountFrom + 1, callCountTo - 1); } if (callCountFrom < 0 || callCountTo < callCountFrom) { throw new ArgumentOutOfRangeException(nameof(callCountFrom)); } return new Times(Kind.BetweenInclusive, callCountFrom, callCountTo); } /// <summary> /// Specifies that a mocked method should be invoked exactly /// <paramref name="callCount"/> times. /// </summary> /// <param name="callCount">The times that a method or property can be called.</param> /// <returns>An object defining the allowed number of invocations.</returns> public static Times Exactly(int callCount) { if (callCount < 0) { throw new ArgumentOutOfRangeException(nameof(callCount)); } return new Times(Kind.Exactly, callCount, callCount); } /// <summary> /// Specifies that a mocked method should not be invoked. /// </summary> /// <returns>An object defining the allowed number of invocations.</returns> public static Times Never() { return new Times(Kind.Never, 0, 0); } /// <summary> /// Specifies that a mocked method should be invoked exactly one time. /// </summary> /// <returns>An object defining the allowed number of invocations.</returns> public static Times Once() { return new Times(Kind.Once, 1, 1); } /// <summary> /// Returns a value indicating whether this instance is equal to a specified <see cref="Times"/> value. /// </summary> /// <param name="other">A <see cref="Times"/> value to compare to this instance.</param> /// <returns> /// <see langword="true"/> if <paramref name="other"/> has the same value as this instance; /// otherwise, <see langword="false"/>. /// </returns> public bool Equals(Times other) { var (from, to) = this; var (otherFrom, otherTo) = other; return from == otherFrom && to == otherTo; } /// <summary> /// Returns a value indicating whether this instance is equal to a specified <see cref="Times"/> value. /// </summary> /// <param name="obj">An object to compare to this instance.</param> /// <returns> /// <see langword="true"/> if <paramref name="obj"/> has the same value as this instance; /// otherwise, <see langword="false"/>. /// </returns> public override bool Equals(object obj) { return obj is Times other && this.Equals(other); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms /// and data structures like a hash table. /// </returns> public override int GetHashCode() { var (from, to) = this; return from.GetHashCode() ^ to.GetHashCode(); } /// <summary> /// Determines whether two specified <see cref="Times"/> objects have the same value. /// </summary> /// <param name="left">The first <see cref="Times"/>.</param> /// <param name="right">The second <see cref="Times"/>.</param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> has the same value as <paramref name="right"/>; /// otherwise, <see langword="false"/>. /// </returns> public static bool operator ==(Times left, Times right) { return left.Equals(right); } /// <summary> /// Determines whether two specified <see cref="Times"/> objects have different values. /// </summary> /// <param name="left">The first <see cref="Times"/>.</param> /// <param name="right">The second <see cref="Times"/>.</param> /// <returns> /// <see langword="true"/> if the value of <paramref name="left"/> is different from /// <paramref name="right"/>'s; otherwise, <see langword="false"/>. /// </returns> public static bool operator !=(Times left, Times right) { return !left.Equals(right); } /// <inheritdoc/> public override string ToString() { return this.kind switch { Kind.AtLeastOnce => "AtLeastOnce", Kind.AtLeast => $"AtLeast({this.from})", Kind.AtMost => $"AtMost({this.to})", Kind.AtMostOnce => "AtMostOnce", Kind.BetweenExclusive => $"Between({this.from - 1}, {this.to + 1}, Exclusive)", Kind.BetweenInclusive => $"Between({this.from}, {this.to}, Inclusive)", Kind.Exactly => $"Exactly({this.from})", Kind.Once => "Once", Kind.Never => "Never", _ => throw new InvalidOperationException(), }; } internal string GetExceptionMessage(int callCount) { var (from, to) = this; if (this.kind == Kind.BetweenExclusive) { --from; ++to; } var message = this.kind switch { Kind.AtLeastOnce => Resources.NoMatchingCallsAtLeastOnce, Kind.AtLeast => Resources.NoMatchingCallsAtLeast, Kind.AtMost => Resources.NoMatchingCallsAtMost, Kind.AtMostOnce => Resources.NoMatchingCallsAtMostOnce, Kind.BetweenExclusive => Resources.NoMatchingCallsBetweenExclusive, Kind.BetweenInclusive => Resources.NoMatchingCallsBetweenInclusive, Kind.Exactly => Resources.NoMatchingCallsExactly, Kind.Once => Resources.NoMatchingCallsOnce, Kind.Never => Resources.NoMatchingCallsNever, _ => throw new InvalidOperationException(), }; return string.Format(CultureInfo.CurrentCulture, message, from, to, callCount); } /// <summary> /// Checks whether the specified number of invocations matches the constraint described by this instance. /// </summary> /// <param name="count">The number of invocations to check.</param> /// <returns> /// <see langword="true"/> if <paramref name="count"/> matches the constraint described by this instance; /// otherwise, <see langword="false"/>. /// </returns> public bool Validate(int count) { var (from, to) = this; return from <= count && count <= to; } private enum Kind { AtLeastOnce, AtLeast, AtMost, AtMostOnce, BetweenExclusive, BetweenInclusive, Exactly, Once, Never, } } }
/* * Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Net; using System.Reflection; using OpenMetaverse; using OpenMetaverse.StructuredData; using Aurora.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using Aurora.Framework; namespace OpenSim.Services.CapsService { /// <summary> /// CapsHandlers is a cap handler container but also takes /// care of adding and removing cap handlers to and from the /// supplied BaseHttpServer. /// </summary> public class PerRegionClientCapsService : IRegionClientCapsService { #region Declares private List<ICapsServiceConnector> m_connectors = new List<ICapsServiceConnector>(); private bool m_disabled = true; private AgentCircuitData m_circuitData; private IHttpServer m_server; public AgentCircuitData CircuitData { get { return m_circuitData; } } public IPAddress LoopbackRegionIP { get; set; } public bool Disabled { get { return m_disabled; } set { m_disabled = value; } } public ulong RegionHandle { get { return m_regionCapsService.RegionHandle; } } public int RegionX { get { return m_regionCapsService.RegionX; } } public int RegionY { get { return m_regionCapsService.RegionY; } } public GridRegion Region { get { return m_regionCapsService.Region; } } public Vector3 LastPosition { get; set; } /// <summary> /// This is the /CAPS/UUID 0000/ string /// </summary> protected String m_capsUrlBase; public UUID AgentID { get { return m_clientCapsService.AgentID; } } protected bool m_isRootAgent = false; public bool RootAgent { get { return m_isRootAgent; } set { m_isRootAgent = value; } } protected IClientCapsService m_clientCapsService; public IClientCapsService ClientCaps { get { return m_clientCapsService; } } protected IRegionCapsService m_regionCapsService; public IRegionCapsService RegionCaps { get { return m_regionCapsService; } } #endregion #region Properties public String HostUri { get { return Server.ServerURI; } } public IRegistryCore Registry { get { return m_clientCapsService.Registry; } } public IHttpServer Server { get { return m_server ?? (m_server = m_clientCapsService.Server); } set { m_server = value; } } private string m_overrideCapsURL; // ONLY FOR OPENSIM /// <summary> /// This is the full URL to the Caps SEED request /// </summary> public String CapsUrl { get { if (!string.IsNullOrEmpty(m_overrideCapsURL)) return m_overrideCapsURL; return HostUri + m_capsUrlBase; } set { m_overrideCapsURL = value; } } #endregion #region Initialize public void Initialise(IClientCapsService clientCapsService, IRegionCapsService regionCapsService, string capsBase, AgentCircuitData circuitData, uint port) { m_clientCapsService = clientCapsService; m_regionCapsService = regionCapsService; m_circuitData = circuitData; if (port != 0)//Someone requested a non standard port, probably for OpenSim { ISimulationBase simBase = Registry.RequestModuleInterface<ISimulationBase> (); Server = simBase.GetHttpServer (port); } AddSEEDCap(capsBase); AddCAPS(); } #endregion #region Add/Remove Caps from the known caps OSDMap //X cap name to path protected OSDMap registeredCAPS = new OSDMap(); public string CreateCAPS(string method, string appendedPath) { string caps = "/CAPS/" + method + "/" + UUID.Random() + appendedPath + "/"; return caps; } public void AddCAPS(string method, string caps) { if (method == null || caps == null) return; string CAPSPath = HostUri + caps; registeredCAPS[method] = CAPSPath; } public void AddCAPS(OSDMap caps) { foreach (KeyValuePair<string, OSD> kvp in caps) { if(!registeredCAPS.ContainsKey(kvp.Key)) registeredCAPS[kvp.Key] = kvp.Value; } } protected void RemoveCaps(string method) { registeredCAPS.Remove(method); } #endregion #region Overriden Http Server methods public void AddStreamHandler(string method, IRequestHandler handler) { Server.AddStreamHandler(handler); AddCAPS(method, handler.Path); } public void RemoveStreamHandler (string method, string httpMethod, string path) { Server.RemoveStreamHandler (httpMethod, path); RemoveCaps (method); } public void RemoveStreamHandler (string method, string httpMethod) { string path = registeredCAPS[method].AsString (); if (path != "")//If it doesn't exist... { if (path.StartsWith (HostUri))//Only try to remove local ones { path = path.Remove (0, HostUri.Length); Server.RemoveStreamHandler (httpMethod, path); } RemoveCaps (method); } } #endregion #region SEED cap handling public void AddSEEDCap(string CapsUrl2) { if (CapsUrl2 != "") m_capsUrlBase = CapsUrl2; Disabled = false; //Add our SEED cap AddStreamHandler("SEED", new RestStreamHandler("POST", m_capsUrlBase, CapsRequest)); } public void Close() { //Remove our SEED cap RemoveStreamHandler("SEED", "POST", m_capsUrlBase); RemoveCAPS (); } public virtual string CapsRequest(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { MainConsole.Instance.Info("[CapsHandlers]: Handling Seed Cap request at " + CapsUrl); return OSDParser.SerializeLLSDXmlString(registeredCAPS); } #endregion #region Add/Remove known caps protected void AddCAPS() { List<ICapsServiceConnector> connectors = GetServiceConnectors(); foreach (ICapsServiceConnector connector in connectors) { connector.RegisterCaps(this); } } protected void RemoveCAPS() { List<ICapsServiceConnector> connectors = GetServiceConnectors(); foreach (ICapsServiceConnector connector in connectors) { connector.DeregisterCaps(); } } public void InformModulesOfRequest() { List<ICapsServiceConnector> connectors = GetServiceConnectors(); foreach (ICapsServiceConnector connector in connectors) { connector.EnteringRegion(); } } public List<ICapsServiceConnector> GetServiceConnectors() { if (m_connectors.Count == 0) { m_connectors = AuroraModuleLoader.PickupModules<ICapsServiceConnector>(); } return m_connectors; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void AddInt16() { var test = new SimpleBinaryOpTest__AddInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AddInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int16> _fld1; public Vector128<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AddInt16 testClass) { var result = AdvSimd.Add(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddInt16 testClass) { fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector128<Int16> _clsVar1; private static Vector128<Int16> _clsVar2; private Vector128<Int16> _fld1; private Vector128<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AddInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public SimpleBinaryOpTest__AddInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Add( Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Add( AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Add( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int16>* pClsVar1 = &_clsVar1) fixed (Vector128<Int16>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Add( AdvSimd.LoadVector128((Int16*)(pClsVar1)), AdvSimd.LoadVector128((Int16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr); var result = AdvSimd.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AddInt16(); var result = AdvSimd.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AddInt16(); fixed (Vector128<Int16>* pFld1 = &test._fld1) fixed (Vector128<Int16>* pFld2 = &test._fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Add(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Add( AdvSimd.LoadVector128((Int16*)(&test._fld1)), AdvSimd.LoadVector128((Int16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((short)(left[0] + right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((short)(left[i] + right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Add)}<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Composition; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.SolutionCrawler { public class WorkCoordinatorTests { private const string SolutionCrawler = nameof(SolutionCrawler); [Fact] public void RegisterService() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var registrationService = new SolutionCrawlerRegistrationService( SpecializedCollections.EmptyEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>(), AggregateAsynchronousOperationListener.EmptyListeners); // register and unregister workspace to the service registrationService.Register(workspace); registrationService.Unregister(workspace); } } [Fact, WorkItem(747226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747226")] public async Task SolutionAdded_Simple() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solutionId = SolutionId.CreateNewId(); var projectId = ProjectId.CreateNewId(); var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), projects: new[] { ProjectInfo.Create(projectId, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1") }) }); var worker = await ExecuteOperation(workspace, w => w.OnSolutionAdded(solutionInfo)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task SolutionAdded_Complex() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); var worker = await ExecuteOperation(workspace, w => w.OnSolutionAdded(solution)); Assert.Equal(10, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task Solution_Remove() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var worker = await ExecuteOperation(workspace, w => w.OnSolutionRemoved()); Assert.Equal(10, worker.InvalidateDocumentIds.Count); } } [Fact] public async Task Solution_Clear() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var worker = await ExecuteOperation(workspace, w => w.ClearSolution()); Assert.Equal(10, worker.InvalidateDocumentIds.Count); } } [Fact] public async Task Solution_Reload() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var worker = await ExecuteOperation(workspace, w => w.OnSolutionReloaded(solution)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task Solution_Change() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solutionInfo); await WaitWaiterAsync(workspace.ExportProvider); var solution = workspace.CurrentSolution; var documentId = solution.Projects.First().DocumentIds[0]; solution = solution.RemoveDocument(documentId); var changedSolution = solution.AddProject("P3", "P3", LanguageNames.CSharp).AddDocument("D1", "").Project.Solution; var worker = await ExecuteOperation(workspace, w => w.ChangeSolution(changedSolution)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task Project_Add() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var projectId = ProjectId.CreateNewId(); var projectInfo = ProjectInfo.Create( projectId, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp, documents: new List<DocumentInfo> { DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1"), DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D2") }); var worker = await ExecuteOperation(workspace, w => w.OnProjectAdded(projectInfo)); Assert.Equal(2, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task Project_Remove() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var projectid = workspace.CurrentSolution.ProjectIds[0]; var worker = await ExecuteOperation(workspace, w => w.OnProjectRemoved(projectid)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.InvalidateDocumentIds.Count); } } [Fact] public async Task Project_Change() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solutionInfo); await WaitWaiterAsync(workspace.ExportProvider); var project = workspace.CurrentSolution.Projects.First(); var documentId = project.DocumentIds[0]; var solution = workspace.CurrentSolution.RemoveDocument(documentId); var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, solution)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); Assert.Equal(1, worker.InvalidateDocumentIds.Count); } } [Fact] public async Task Project_AssemblyName_Change() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solutionInfo); await WaitWaiterAsync(workspace.ExportProvider); var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1").WithAssemblyName("newName"); var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, project.Solution)); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); } } [Fact] public async Task Project_AnalyzerOptions_Change() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solutionInfo); await WaitWaiterAsync(workspace.ExportProvider); var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1").AddAdditionalDocument("a1", SourceText.From("")).Project; var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, project.Solution)); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); } } [Fact] public async Task Project_Reload() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var project = solution.Projects[0]; var worker = await ExecuteOperation(workspace, w => w.OnProjectReloaded(project)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task Document_Add() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var project = solution.Projects[0]; var info = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6"); var worker = await ExecuteOperation(workspace, w => w.OnDocumentAdded(info)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); Assert.Equal(6, worker.DocumentIds.Count); } } [Fact] public async Task Document_Remove() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var worker = await ExecuteOperation(workspace, w => w.OnDocumentRemoved(id)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); Assert.Equal(4, worker.DocumentIds.Count); Assert.Equal(1, worker.InvalidateDocumentIds.Count); } } [Fact] public async Task Document_Reload() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = solution.Projects[0].Documents[0]; var worker = await ExecuteOperation(workspace, w => w.OnDocumentReloaded(id)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task Document_Reanalyze() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var info = solution.Projects[0].Documents[0]; var worker = new Analyzer(); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(worker), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); // don't rely on background parser to have tree. explicitly do it here. await TouchEverything(workspace.CurrentSolution); service.Reanalyze(workspace, worker, projectIds: null, documentIds: SpecializedCollections.SingletonEnumerable<DocumentId>(info.Id), highPriority: false); await TouchEverything(workspace.CurrentSolution); await WaitAsync(service, workspace); service.Unregister(workspace); Assert.Equal(1, worker.SyntaxDocumentIds.Count); Assert.Equal(1, worker.DocumentIds.Count); } } [WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")] public async Task Document_Change() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var worker = await ExecuteOperation(workspace, w => w.ChangeDocument(id, SourceText.From("//"))); Assert.Equal(1, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task Document_AdditionalFileChange() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var project = solution.Projects[0]; var ncfile = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6"); var worker = await ExecuteOperation(workspace, w => w.OnAdditionalDocumentAdded(ncfile)); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); worker = await ExecuteOperation(workspace, w => w.ChangeAdditionalDocument(ncfile.Id, SourceText.From("//"))); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); worker = await ExecuteOperation(workspace, w => w.OnAdditionalDocumentRemoved(ncfile.Id)); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); } } [WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")] public async Task Document_Cancellation() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var analyzer = new Analyzer(waitForCancellation: true); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); workspace.ChangeDocument(id, SourceText.From("//")); analyzer.RunningEvent.Wait(); workspace.ChangeDocument(id, SourceText.From("// ")); await WaitAsync(service, workspace); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(5, analyzer.DocumentIds.Count); } } [WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")] public async Task Document_Cancellation_MultipleTimes() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var analyzer = new Analyzer(waitForCancellation: true); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); workspace.ChangeDocument(id, SourceText.From("//")); analyzer.RunningEvent.Wait(); analyzer.RunningEvent.Reset(); workspace.ChangeDocument(id, SourceText.From("// ")); analyzer.RunningEvent.Wait(); workspace.ChangeDocument(id, SourceText.From("// ")); await WaitAsync(service, workspace); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(5, analyzer.DocumentIds.Count); } } [WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")] public async Task Document_InvocationReasons() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var analyzer = new Analyzer(blockedRun: true); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); // first invocation will block worker workspace.ChangeDocument(id, SourceText.From("//")); analyzer.RunningEvent.Wait(); var openReady = new ManualResetEventSlim(initialState: false); var closeReady = new ManualResetEventSlim(initialState: false); workspace.DocumentOpened += (o, e) => openReady.Set(); workspace.DocumentClosed += (o, e) => closeReady.Set(); // cause several different request to queue up workspace.ChangeDocument(id, SourceText.From("// ")); workspace.OpenDocument(id); workspace.CloseDocument(id); openReady.Set(); closeReady.Set(); analyzer.BlockEvent.Set(); await WaitAsync(service, workspace); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(5, analyzer.DocumentIds.Count); } } [Fact] public async Task Document_TopLevelType_Whitespace() { var code = @"class C { $$ }"; var textToInsert = " "; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_TopLevelType_Character() { var code = @"class C { $$ }"; var textToInsert = "int"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_TopLevelType_NewLine() { var code = @"class C { $$ }"; var textToInsert = "\r\n"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_TopLevelType_NewLine2() { var code = @"class C { $$"; var textToInsert = "\r\n"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_EmptyFile() { var code = @"$$"; var textToInsert = "class"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_TopLevel1() { var code = @"class C { public void Test($$"; var textToInsert = "int"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_TopLevel2() { var code = @"class C { public void Test(int $$"; var textToInsert = " "; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_TopLevel3() { var code = @"class C { public void Test(int i,$$"; var textToInsert = "\r\n"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_InteriorNode1() { var code = @"class C { public void Test() {$$"; var textToInsert = "\r\n"; await InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public async Task Document_InteriorNode2() { var code = @"class C { public void Test() { $$ }"; var textToInsert = "int"; await InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public async Task Document_InteriorNode_Field() { var code = @"class C { int i = $$ }"; var textToInsert = "1"; await InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public async Task Document_InteriorNode_Field1() { var code = @"class C { int i = 1 + $$ }"; var textToInsert = "1"; await InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public async Task Document_InteriorNode_Accessor() { var code = @"class C { public int A { get { $$ } } }"; var textToInsert = "return"; await InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public async Task Document_TopLevelWhitespace() { var code = @"class C { /// $$ public int A() { } }"; var textToInsert = "return"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_TopLevelWhitespace2() { var code = @"/// $$ class C { public int A() { } }"; var textToInsert = "return"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_InteriorNode_Malformed() { var code = @"class C { public void Test() { $$"; var textToInsert = "int"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void VBPropertyTest() { var markup = @"Class C Default Public Property G(x As Integer) As Integer Get $$ End Get Set(value As Integer) End Set End Property End Class"; int position; string code; MarkupTestFile.GetPosition(markup, out code, out position); var root = Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseCompilationUnit(code); var property = root.FindToken(position).Parent.FirstAncestorOrSelf<Microsoft.CodeAnalysis.VisualBasic.Syntax.PropertyBlockSyntax>(); var memberId = (new Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxFactsService()).GetMethodLevelMemberId(root, property); Assert.Equal(0, memberId); } [Fact, WorkItem(739943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739943")] public async Task SemanticChange_Propagation_Transitive() { var solution = GetInitialSolutionInfoWithP2P(); using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { workspace.Options = workspace.Options.WithChangedOption(InternalSolutionCrawlerOptions.DirectDependencyPropagationOnly, false); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = solution.Projects[0].Id; var info = DocumentInfo.Create(DocumentId.CreateNewId(id), "D6"); var worker = await ExecuteOperation(workspace, w => w.OnDocumentAdded(info)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); Assert.Equal(4, worker.DocumentIds.Count); } } [Fact, WorkItem(739943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739943")] public async Task SemanticChange_Propagation_Direct() { var solution = GetInitialSolutionInfoWithP2P(); using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { workspace.Options = workspace.Options.WithChangedOption(InternalSolutionCrawlerOptions.DirectDependencyPropagationOnly, true); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = solution.Projects[0].Id; var info = DocumentInfo.Create(DocumentId.CreateNewId(id), "D6"); var worker = await ExecuteOperation(workspace, w => w.OnDocumentAdded(info)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); Assert.Equal(3, worker.DocumentIds.Count); } } [Fact] public async Task ProgressReporterTest() { var solution = GetInitialSolutionInfoWithP2P(); using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { await WaitWaiterAsync(workspace.ExportProvider); var service = workspace.Services.GetService<ISolutionCrawlerService>(); var reporter = service.GetProgressReporter(workspace); Assert.False(reporter.InProgress); // set up events bool started = false; reporter.Started += (o, a) => { started = true; }; bool stopped = false; reporter.Stopped += (o, a) => { stopped = true; }; var registrationService = workspace.Services.GetService<ISolutionCrawlerRegistrationService>(); registrationService.Register(workspace); // first mutation workspace.OnSolutionAdded(solution); await WaitAsync((SolutionCrawlerRegistrationService)registrationService, workspace); Assert.True(started); Assert.True(stopped); // reset started = false; stopped = false; // second mutation workspace.OnDocumentAdded(DocumentInfo.Create(DocumentId.CreateNewId(solution.Projects[0].Id), "D6")); await WaitAsync((SolutionCrawlerRegistrationService)registrationService, workspace); Assert.True(started); Assert.True(stopped); registrationService.Unregister(workspace); } } private async Task InsertText(string code, string text, bool expectDocumentAnalysis, string language = LanguageNames.CSharp) { using (var workspace = await TestWorkspace.CreateAsync( SolutionCrawler, language, compilationOptions: null, parseOptions: null, content: code)) { SetOptions(workspace); var analyzer = new Analyzer(); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); var testDocument = workspace.Documents.First(); var insertPosition = testDocument.CursorPosition; var textBuffer = testDocument.GetTextBuffer(); using (var edit = textBuffer.CreateEdit()) { edit.Insert(insertPosition.Value, text); edit.Apply(); } await WaitAsync(service, workspace); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(expectDocumentAnalysis ? 1 : 0, analyzer.DocumentIds.Count); } } private async Task<Analyzer> ExecuteOperation(TestWorkspace workspace, Action<TestWorkspace> operation) { var worker = new Analyzer(); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(worker), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); // don't rely on background parser to have tree. explicitly do it here. await TouchEverything(workspace.CurrentSolution); operation(workspace); await TouchEverything(workspace.CurrentSolution); await WaitAsync(service, workspace); service.Unregister(workspace); return worker; } private async Task TouchEverything(Solution solution) { foreach (var project in solution.Projects) { foreach (var document in project.Documents) { await document.GetTextAsync(); await document.GetSyntaxRootAsync(); await document.GetSemanticModelAsync(); } } } private async Task WaitAsync(SolutionCrawlerRegistrationService service, TestWorkspace workspace) { await WaitWaiterAsync(workspace.ExportProvider); service.WaitUntilCompletion_ForTestingPurposesOnly(workspace); } private async Task WaitWaiterAsync(ExportProvider provider) { var workspaceWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as IAsynchronousOperationWaiter; await workspaceWaiter.CreateWaitTask(); var solutionCrawlerWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as IAsynchronousOperationWaiter; await solutionCrawlerWaiter.CreateWaitTask(); } private static SolutionInfo GetInitialSolutionInfoWithP2P() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var projectId3 = ProjectId.CreateNewId(); var projectId4 = ProjectId.CreateNewId(); var projectId5 = ProjectId.CreateNewId(); var solution = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), projects: new[] { ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1") }), ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2") }, projectReferences: new[] { new ProjectReference(projectId1) }), ProjectInfo.Create(projectId3, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId3), "D3") }, projectReferences: new[] { new ProjectReference(projectId2) }), ProjectInfo.Create(projectId4, VersionStamp.Create(), "P4", "P4", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId4), "D4") }), ProjectInfo.Create(projectId5, VersionStamp.Create(), "P5", "P5", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId5), "D5") }, projectReferences: new[] { new ProjectReference(projectId4) }), }); return solution; } private static SolutionInfo GetInitialSolutionInfo(TestWorkspace workspace) { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); return SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), projects: new[] { ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D2"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D3"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D4"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D5") }), ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D1"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D3"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D4"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D5") }) }); } private static IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> GetListeners(ExportProvider provider) { return provider.GetExports<IAsynchronousOperationListener, FeatureMetadata>(); } [Shared] [Export(typeof(IAsynchronousOperationListener))] [Export(typeof(IAsynchronousOperationWaiter))] [Feature(FeatureAttribute.SolutionCrawler)] private class SolutionCrawlerWaiter : AsynchronousOperationListener { internal SolutionCrawlerWaiter() { } } [Shared] [Export(typeof(IAsynchronousOperationListener))] [Export(typeof(IAsynchronousOperationWaiter))] [Feature(FeatureAttribute.Workspace)] private class WorkspaceWaiter : AsynchronousOperationListener { internal WorkspaceWaiter() { } } private static void SetOptions(Workspace workspace) { // override default timespan to make test run faster workspace.Options = workspace.Options.WithChangedOption(InternalSolutionCrawlerOptions.ActiveFileWorkerBackOffTimeSpanInMS, 0) .WithChangedOption(InternalSolutionCrawlerOptions.AllFilesWorkerBackOffTimeSpanInMS, 0) .WithChangedOption(InternalSolutionCrawlerOptions.PreviewBackOffTimeSpanInMS, 0) .WithChangedOption(InternalSolutionCrawlerOptions.ProjectPropagationBackOffTimeSpanInMS, 0) .WithChangedOption(InternalSolutionCrawlerOptions.SemanticChangeBackOffTimeSpanInMS, 0) .WithChangedOption(InternalSolutionCrawlerOptions.EntireProjectWorkerBackOffTimeSpanInMS, 100); } private class WorkCoordinatorWorkspace : TestWorkspace { private readonly IAsynchronousOperationWaiter _workspaceWaiter; private readonly IAsynchronousOperationWaiter _solutionCrawlerWaiter; public WorkCoordinatorWorkspace(string workspaceKind = null, bool disablePartialSolutions = true) : base(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), workspaceKind, disablePartialSolutions) { _workspaceWaiter = GetListeners(ExportProvider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as IAsynchronousOperationWaiter; _solutionCrawlerWaiter = GetListeners(ExportProvider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as IAsynchronousOperationWaiter; Assert.False(_workspaceWaiter.HasPendingWork); Assert.False(_solutionCrawlerWaiter.HasPendingWork); SetOptions(this); } protected override void Dispose(bool finalize) { base.Dispose(finalize); Assert.False(_workspaceWaiter.HasPendingWork); Assert.False(_solutionCrawlerWaiter.HasPendingWork); } } private class AnalyzerProvider : IIncrementalAnalyzerProvider { private readonly Analyzer _analyzer; public AnalyzerProvider(Analyzer analyzer) { _analyzer = analyzer; } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) { return _analyzer; } } internal class Metadata : IncrementalAnalyzerProviderMetadata { public Metadata(params string[] workspaceKinds) : base(new Dictionary<string, object> { { "WorkspaceKinds", workspaceKinds }, { "HighPriorityForActiveFile", false } }) { } public static readonly Metadata Crawler = new Metadata(SolutionCrawler); } private class Analyzer : IIncrementalAnalyzer { private readonly bool _waitForCancellation; private readonly bool _blockedRun; public readonly ManualResetEventSlim BlockEvent; public readonly ManualResetEventSlim RunningEvent; public readonly HashSet<DocumentId> SyntaxDocumentIds = new HashSet<DocumentId>(); public readonly HashSet<DocumentId> DocumentIds = new HashSet<DocumentId>(); public readonly HashSet<ProjectId> ProjectIds = new HashSet<ProjectId>(); public readonly HashSet<DocumentId> InvalidateDocumentIds = new HashSet<DocumentId>(); public readonly HashSet<ProjectId> InvalidateProjectIds = new HashSet<ProjectId>(); public Analyzer(bool waitForCancellation = false, bool blockedRun = false) { _waitForCancellation = waitForCancellation; _blockedRun = blockedRun; this.BlockEvent = new ManualResetEventSlim(initialState: false); this.RunningEvent = new ManualResetEventSlim(initialState: false); } public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken) { this.ProjectIds.Add(project.Id); return SpecializedTasks.EmptyTask; } public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken) { if (bodyOpt == null) { this.DocumentIds.Add(document.Id); } return SpecializedTasks.EmptyTask; } public Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) { this.SyntaxDocumentIds.Add(document.Id); Process(document.Id, cancellationToken); return SpecializedTasks.EmptyTask; } public void RemoveDocument(DocumentId documentId) { InvalidateDocumentIds.Add(documentId); } public void RemoveProject(ProjectId projectId) { InvalidateProjectIds.Add(projectId); } private void Process(DocumentId documentId, CancellationToken cancellationToken) { if (_blockedRun && !RunningEvent.IsSet) { this.RunningEvent.Set(); // Wait until unblocked this.BlockEvent.Wait(); } if (_waitForCancellation && !RunningEvent.IsSet) { this.RunningEvent.Set(); cancellationToken.WaitHandle.WaitOne(); cancellationToken.ThrowIfCancellationRequested(); } } #region unused public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task DocumentResetAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) { return false; } #endregion } #if false private string GetListenerTrace(ExportProvider provider) { var sb = new StringBuilder(); var workspaceWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as TestAsynchronousOperationListener; sb.AppendLine("workspace"); sb.AppendLine(workspaceWaiter.Trace()); var solutionCrawlerWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as TestAsynchronousOperationListener; sb.AppendLine("solutionCrawler"); sb.AppendLine(solutionCrawlerWaiter.Trace()); return sb.ToString(); } internal abstract partial class TestAsynchronousOperationListener : IAsynchronousOperationListener, IAsynchronousOperationWaiter { private readonly object gate = new object(); private readonly HashSet<TaskCompletionSource<bool>> pendingTasks = new HashSet<TaskCompletionSource<bool>>(); private readonly StringBuilder sb = new StringBuilder(); private int counter; public TestAsynchronousOperationListener() { } public IAsyncToken BeginAsyncOperation(string name, object tag = null) { lock (gate) { return new AsyncToken(this, name); } } private void Increment(string name) { lock (gate) { sb.AppendLine("i -> " + name + ":" + counter++); } } private void Decrement(string name) { lock (gate) { counter--; if (counter == 0) { foreach (var task in pendingTasks) { task.SetResult(true); } pendingTasks.Clear(); } sb.AppendLine("d -> " + name + ":" + counter); } } public virtual Task CreateWaitTask() { lock (gate) { var source = new TaskCompletionSource<bool>(); if (counter == 0) { // There is nothing to wait for, so we are immediately done source.SetResult(true); } else { pendingTasks.Add(source); } return source.Task; } } public bool TrackActiveTokens { get; set; } public bool HasPendingWork { get { return counter != 0; } } private class AsyncToken : IAsyncToken { private readonly TestAsynchronousOperationListener listener; private readonly string name; private bool disposed; public AsyncToken(TestAsynchronousOperationListener listener, string name) { this.listener = listener; this.name = name; listener.Increment(name); } public void Dispose() { lock (listener.gate) { if (disposed) { throw new InvalidOperationException("Double disposing of an async token"); } disposed = true; listener.Decrement(this.name); } } } public string Trace() { return sb.ToString(); } } #endif } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.CodeFixes.GenerateEnumMember; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.GenerateEnumMember { public class GenerateEnumMemberTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, CodeFixProvider>(null, new GenerateEnumMemberCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestEmptyEnum() { await TestAsync( @"class Program { void Main ( ) { Color . [|Red|] ; } } enum Color { } ", @"class Program { void Main ( ) { Color . Red ; } } enum Color { Red } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestWithSingleMember() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red , Blue } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestWithExistingComma() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red , } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red , Blue , } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestWithMultipleMembers() { await TestAsync( @"class Program { void Main ( ) { Color . [|Green|] ; } } enum Color { Red , Blue } ", @"class Program { void Main ( ) { Color . Green ; } } enum Color { Red , Blue , Green } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestWithZero() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 0 } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 0 , Blue = 1 } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestWithIntegralValue() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 1 } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 1 , Blue = 2 } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestWithSingleBitIntegral() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 2 } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 2 , Blue = 4 } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestGenerateIntoGeometricSequence() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 1 , Yellow = 2 , Green = 4 }", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 1 , Yellow = 2 , Green = 4 , Blue = 8}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestWithSimpleSequence1() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 1 , Green = 2 } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 1 , Green = 2 , Blue = 3 } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestWithSimpleSequence2() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Yellow = 0, Red = 1 , Green = 2 } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Yellow = 0, Red = 1 , Green = 2 , Blue = 3 } "); } [Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestWithNonZeroInteger() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Green = 5 } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Green = 5 , Blue = 6 } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestWithLeftShift0() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Green = 1 << 0 } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Green = 1 << 0 , Blue = 1 << 1 } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestWithLeftShift5() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Green = 1 << 5 } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Green = 1 << 5 , Blue = 1 << 6 } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestWithDifferentStyles() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 2 , Green = 1 << 5 } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 2 , Green = 1 << 5 , Blue = 33 } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestHex1() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 0x1 } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 0x1 , Blue = 0x2 } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestHex9() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 0x9 } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 0x9 , Blue = 0xA } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestHexF() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 0xF } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 0xF , Blue = 0x10 } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestGenerateAfterEnumWithIntegerMaxValue() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = int.MaxValue } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = int.MaxValue , Blue = int.MinValue } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestUnsigned16BitEnums() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color : ushort { Red = 65535 } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color : ushort { Red = 65535 , Blue = 0 } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestGenerateEnumMemberOfTypeLong() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color : long { Red = long.MaxValue } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color : long { Red = long.MaxValue , Blue = long.MinValue } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestGenerateAfterEnumWithLongMaxValueInHex() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color : long { Red = 0x7FFFFFFFFFFFFFFF } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color : long { Red = 0x7FFFFFFFFFFFFFFF , Blue = 0x8000000000000000 } "); } [WorkItem(528312)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestGenerateAfterEnumWithLongMinValueInHex() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color : long { Red = 0xFFFFFFFFFFFFFFFF } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color : long { Red = 0xFFFFFFFFFFFFFFFF , Blue} "); } [WorkItem(528312)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestGenerateAfterPositiveLongInHex() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color : long { Red = 0xFFFFFFFFFFFFFFFF , Green = 0x0 } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color : long { Red = 0xFFFFFFFFFFFFFFFF , Green = 0x0 , Blue = 0x1 } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestGenerateAfterPositiveLongExprInHex() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color : long { Red = 0x414 / 2 } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color : long { Red = 0x414 / 2 , Blue = 523 } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestGenerateAfterEnumWithULongMaxValue() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color : ulong { Red = ulong.MaxValue } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color : ulong { Red = ulong.MaxValue , Blue = 0 } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestNegativeRangeIn64BitSignedEnums() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color : long { Red = -10 } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color : long { Red = -10 , Blue = -9 } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestGenerateWithImplicitValues() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red , Green , Yellow = -1 }", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red , Green , Yellow = -1 , Blue = 2 }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestGenerateWithImplicitValues2() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red , Green = 10 , Yellow }", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red , Green = 10 , Yellow , Blue }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestNoExtraneousStatementTerminatorBeforeCommentedMember() { await TestAsync( @"class Program { static void Main(string[] args) { Color . [|Blue|] ; } } enum Color { Red //Blue }", @"class Program { static void Main(string[] args) { Color . Blue ; } } enum Color { Red, Blue //Blue }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestNoExtraneousStatementTerminatorBeforeCommentedMember2() { await TestAsync( @"class Program { static void Main(string[] args) { Color . [|Blue|] ; } } enum Color { Red /*Blue*/ }", @"class Program { static void Main(string[] args) { Color . Blue ; } } enum Color { Red, Blue /*Blue*/ }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestGenerateAfterEnumWithMinValue() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = int.MinValue } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = int.MinValue , Blue = -2147483647 } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestGenerateAfterEnumWithMinValuePlusConstant() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = int.MinValue + 100 } ", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = int.MinValue + 100 , Blue = -2147483547 } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestGenerateAfterEnumWithByteMaxValue() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color : byte { Red = 255 }", @"class Program { void Main ( ) { Color . Blue ; } } enum Color : byte { Red = 255 , Blue = 0 }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestGenerateIntoBitshiftEnum1() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 1 << 1 , Green = 1 << 2 }", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 1 << 1 , Green = 1 << 2 , Blue = 1 << 3 }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestGenerateIntoBitshiftEnum2() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 2 >> 1 }", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 2 >> 1 , Blue = 2 }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestStandaloneReference() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = int.MinValue , Green = 1 }", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = int.MinValue , Green = 1 , Blue = 2 }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestCircularEnumsForErrorTolerance() { await TestAsync( @"class Program { void Main ( ) { Circular . [|C|] ; } } enum Circular { A = B , B }", @"class Program { void Main ( ) { Circular . C ; } } enum Circular { A = B , B , C }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestEnumWithIncorrectValueForErrorTolerance() { await TestAsync( @"class Program { void Main ( ) { Circular . [|B|] ; } } enum Circular : byte { A = -2 }", @"class Program { void Main ( ) { Circular . B ; } } enum Circular : byte { A = -2 , B }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestGenerateIntoNewEnum() { await TestAsync( @"class B : A { void Main ( ) { BaseColor . [|Blue|] ; } public new enum BaseColor { Yellow = 3 } } class A { public enum BaseColor { Red = 1, Green = 2 } }", @"class B : A { void Main ( ) { BaseColor . Blue ; } public new enum BaseColor { Yellow = 3 , Blue = 4 } } class A { public enum BaseColor { Red = 1, Green = 2 } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestGenerateIntoDerivedEnumMissingNewKeyword() { await TestAsync( @"class B : A { void Main ( ) { BaseColor . [|Blue|] ; } public enum BaseColor { Yellow = 3 } } class A { public enum BaseColor { Red = 1, Green = 2 } }", @"class B : A { void Main ( ) { BaseColor . Blue ; } public enum BaseColor { Yellow = 3 , Blue = 4 } } class A { public enum BaseColor { Red = 1, Green = 2 } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestGenerateIntoBaseEnum() { await TestAsync( @"class B : A { void Main ( ) { BaseColor . [|Blue|] ; } } class A { public enum BaseColor { Red = 1, Green = 2 } }", @"class B : A { void Main ( ) { BaseColor . Blue ; } } class A { public enum BaseColor { Red = 1, Green = 2 , Blue = 3 } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestGenerationWhenMembersShareValues() { await TestAsync( @"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red , Green , Yellow = Green }", @"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red , Green , Yellow = Green , Blue = 2 }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestInvokeFromAddAssignmentStatement() { await TestAsync( @"class Program { void Main ( ) { int a = 1 ; a += Color . [|Blue|] ; } } enum Color { Red , Green = 10 , Yellow }", @"class Program { void Main ( ) { int a = 1 ; a += Color . Blue ; } } enum Color { Red , Green = 10 , Yellow , Blue }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestFormatting() { await TestAsync( @"class Program { static void Main(string[] args) { Weekday.[|Tuesday|]; } } enum Weekday { Monday }", @"class Program { static void Main(string[] args) { Weekday.Tuesday; } } enum Weekday { Monday, Tuesday }", compareTokens: false); } [WorkItem(540919)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestKeyword() { await TestAsync( @"class Program { static void Main ( string [ ] args ) { Color . [|@enum|] ; } } enum Color { Red } ", @"class Program { static void Main ( string [ ] args ) { Color . @enum ; } } enum Color { Red , @enum } "); } [WorkItem(544333)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestNotAfterPointer() { await TestMissingAsync( @"struct MyStruct { public int MyField ; } class Program { static unsafe void Main ( string [ ] args ) { MyStruct s = new MyStruct ( ) ; MyStruct * ptr = & s ; var i1 = ( ( ) => & s ) -> [|M|] ; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestMissingOnHiddenEnum() { await TestMissingAsync( @"using System; enum E { #line hidden } #line default class Program { void Main() { Console.WriteLine(E.[|x|]); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestMissingOnPartiallyHiddenEnum() { await TestMissingAsync( @"using System; enum E { A, B, C, #line hidden } #line default class Program { void Main() { Console.WriteLine(E.[|x|]); } }"); } [WorkItem(545903)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestNoOctal() { await TestAsync( @"enum E { A = 007 , } class C { E x = E . [|B|] ; } ", @"enum E { A = 007 , B = 8 , } class C { E x = E . B ; } "); } [WorkItem(546654)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)] public async Task TestLastValueDoesNotHaveInitializer() { await TestAsync( @"enum E { A = 1 , B } class Program { void Main ( ) { E . [|C|] } } ", @"enum E { A = 1 , B , C } class Program { void Main ( ) { E . C } } "); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // This RegexInterpreter class is internal to the RegularExpression package. // It executes a block of regular expression codes while consuming // input. using System.Diagnostics; using System.Globalization; namespace System.Text.RegularExpressions { internal sealed class RegexInterpreter : RegexRunner { private readonly RegexCode _code; private readonly CultureInfo _culture; private int _operator; private int _codepos; private bool _rightToLeft; private bool _caseInsensitive; internal RegexInterpreter(RegexCode code, CultureInfo culture) { Debug.Assert(code != null, "code cannot be null."); Debug.Assert(culture != null, "culture cannot be null."); _code = code; _culture = culture; } protected override void InitTrackCount() { runtrackcount = _code._trackcount; } private void Advance() { Advance(0); } private void Advance(int i) { _codepos += (i + 1); SetOperator(_code._codes[_codepos]); } private void Goto(int newpos) { // when branching backward, ensure storage if (newpos < _codepos) EnsureStorage(); SetOperator(_code._codes[newpos]); _codepos = newpos; } private void Textto(int newpos) { runtextpos = newpos; } private void Trackto(int newpos) { runtrackpos = runtrack.Length - newpos; } private int Textstart() { return runtextstart; } private int Textpos() { return runtextpos; } // push onto the backtracking stack private int Trackpos() { return runtrack.Length - runtrackpos; } private void TrackPush() { runtrack[--runtrackpos] = _codepos; } private void TrackPush(int I1) { runtrack[--runtrackpos] = I1; runtrack[--runtrackpos] = _codepos; } private void TrackPush(int I1, int I2) { runtrack[--runtrackpos] = I1; runtrack[--runtrackpos] = I2; runtrack[--runtrackpos] = _codepos; } private void TrackPush(int I1, int I2, int I3) { runtrack[--runtrackpos] = I1; runtrack[--runtrackpos] = I2; runtrack[--runtrackpos] = I3; runtrack[--runtrackpos] = _codepos; } private void TrackPush2(int I1) { runtrack[--runtrackpos] = I1; runtrack[--runtrackpos] = -_codepos; } private void TrackPush2(int I1, int I2) { runtrack[--runtrackpos] = I1; runtrack[--runtrackpos] = I2; runtrack[--runtrackpos] = -_codepos; } private void Backtrack() { int newpos = runtrack[runtrackpos++]; #if DEBUG if (runmatch.Debug) { if (newpos < 0) Debug.WriteLine(" Backtracking (back2) to code position " + (-newpos)); else Debug.WriteLine(" Backtracking to code position " + newpos); } #endif if (newpos < 0) { newpos = -newpos; SetOperator(_code._codes[newpos] | RegexCode.Back2); } else { SetOperator(_code._codes[newpos] | RegexCode.Back); } // When branching backward, ensure storage if (newpos < _codepos) EnsureStorage(); _codepos = newpos; } private void SetOperator(int op) { _caseInsensitive = (0 != (op & RegexCode.Ci)); _rightToLeft = (0 != (op & RegexCode.Rtl)); _operator = op & ~(RegexCode.Rtl | RegexCode.Ci); } private void TrackPop() { runtrackpos++; } // pop framesize items from the backtracking stack private void TrackPop(int framesize) { runtrackpos += framesize; } // Technically we are actually peeking at items already popped. So if you want to // get and pop the top item from the stack, you do // TrackPop(); // TrackPeek(); private int TrackPeek() { return runtrack[runtrackpos - 1]; } // get the ith element down on the backtracking stack private int TrackPeek(int i) { return runtrack[runtrackpos - i - 1]; } // Push onto the grouping stack private void StackPush(int I1) { runstack[--runstackpos] = I1; } private void StackPush(int I1, int I2) { runstack[--runstackpos] = I1; runstack[--runstackpos] = I2; } private void StackPop() { runstackpos++; } // pop framesize items from the grouping stack private void StackPop(int framesize) { runstackpos += framesize; } // Technically we are actually peeking at items already popped. So if you want to // get and pop the top item from the stack, you do // StackPop(); // StackPeek(); private int StackPeek() { return runstack[runstackpos - 1]; } // get the ith element down on the grouping stack private int StackPeek(int i) { return runstack[runstackpos - i - 1]; } private int Operator() { return _operator; } private int Operand(int i) { return _code._codes[_codepos + i + 1]; } private int Leftchars() { return runtextpos - runtextbeg; } private int Rightchars() { return runtextend - runtextpos; } private int Bump() { return _rightToLeft ? -1 : 1; } private int Forwardchars() { return _rightToLeft ? runtextpos - runtextbeg : runtextend - runtextpos; } private char Forwardcharnext() { char ch = (_rightToLeft ? runtext[--runtextpos] : runtext[runtextpos++]); return (_caseInsensitive ? _culture.TextInfo.ToLower(ch) : ch); } private bool Stringmatch(String str) { int c; int pos; if (!_rightToLeft) { if (runtextend - runtextpos < (c = str.Length)) return false; pos = runtextpos + c; } else { if (runtextpos - runtextbeg < (c = str.Length)) return false; pos = runtextpos; } if (!_caseInsensitive) { while (c != 0) if (str[--c] != runtext[--pos]) return false; } else { while (c != 0) if (str[--c] != _culture.TextInfo.ToLower(runtext[--pos])) return false; } if (!_rightToLeft) { pos += str.Length; } runtextpos = pos; return true; } private bool Refmatch(int index, int len) { int c; int pos; int cmpos; if (!_rightToLeft) { if (runtextend - runtextpos < len) return false; pos = runtextpos + len; } else { if (runtextpos - runtextbeg < len) return false; pos = runtextpos; } cmpos = index + len; c = len; if (!_caseInsensitive) { while (c-- != 0) if (runtext[--cmpos] != runtext[--pos]) return false; } else { while (c-- != 0) if (_culture.TextInfo.ToLower(runtext[--cmpos]) != _culture.TextInfo.ToLower(runtext[--pos])) return false; } if (!_rightToLeft) { pos += len; } runtextpos = pos; return true; } private void Backwardnext() { runtextpos += _rightToLeft ? 1 : -1; } private char CharAt(int j) { return runtext[j]; } protected override bool FindFirstChar() { int i; String set; if (0 != (_code._anchors & (RegexFCD.Beginning | RegexFCD.Start | RegexFCD.EndZ | RegexFCD.End))) { if (!_code._rightToLeft) { if ((0 != (_code._anchors & RegexFCD.Beginning) && runtextpos > runtextbeg) || (0 != (_code._anchors & RegexFCD.Start) && runtextpos > runtextstart)) { runtextpos = runtextend; return false; } if (0 != (_code._anchors & RegexFCD.EndZ) && runtextpos < runtextend - 1) { runtextpos = runtextend - 1; } else if (0 != (_code._anchors & RegexFCD.End) && runtextpos < runtextend) { runtextpos = runtextend; } } else { if ((0 != (_code._anchors & RegexFCD.End) && runtextpos < runtextend) || (0 != (_code._anchors & RegexFCD.EndZ) && (runtextpos < runtextend - 1 || (runtextpos == runtextend - 1 && CharAt(runtextpos) != '\n'))) || (0 != (_code._anchors & RegexFCD.Start) && runtextpos < runtextstart)) { runtextpos = runtextbeg; return false; } if (0 != (_code._anchors & RegexFCD.Beginning) && runtextpos > runtextbeg) { runtextpos = runtextbeg; } } if (_code._bmPrefix != null) { return _code._bmPrefix.IsMatch(runtext, runtextpos, runtextbeg, runtextend); } return true; // found a valid start or end anchor } else if (_code._bmPrefix != null) { runtextpos = _code._bmPrefix.Scan(runtext, runtextpos, runtextbeg, runtextend); if (runtextpos == -1) { runtextpos = (_code._rightToLeft ? runtextbeg : runtextend); return false; } return true; } else if (_code._fcPrefix == null) { return true; } _rightToLeft = _code._rightToLeft; _caseInsensitive = _code._fcPrefix.CaseInsensitive; set = _code._fcPrefix.Prefix; if (RegexCharClass.IsSingleton(set)) { char ch = RegexCharClass.SingletonChar(set); for (i = Forwardchars(); i > 0; i--) { if (ch == Forwardcharnext()) { Backwardnext(); return true; } } } else { for (i = Forwardchars(); i > 0; i--) { if (RegexCharClass.CharInClass(Forwardcharnext(), set)) { Backwardnext(); return true; } } } return false; } protected override void Go() { Goto(0); for (; ;) { #if DEBUG if (runmatch.Debug) { DumpState(); } #endif CheckTimeout(); switch (Operator()) { case RegexCode.Stop: return; case RegexCode.Nothing: break; case RegexCode.Goto: Goto(Operand(0)); continue; case RegexCode.Testref: if (!IsMatched(Operand(0))) break; Advance(1); continue; case RegexCode.Lazybranch: TrackPush(Textpos()); Advance(1); continue; case RegexCode.Lazybranch | RegexCode.Back: TrackPop(); Textto(TrackPeek()); Goto(Operand(0)); continue; case RegexCode.Setmark: StackPush(Textpos()); TrackPush(); Advance(); continue; case RegexCode.Nullmark: StackPush(-1); TrackPush(); Advance(); continue; case RegexCode.Setmark | RegexCode.Back: case RegexCode.Nullmark | RegexCode.Back: StackPop(); break; case RegexCode.Getmark: StackPop(); TrackPush(StackPeek()); Textto(StackPeek()); Advance(); continue; case RegexCode.Getmark | RegexCode.Back: TrackPop(); StackPush(TrackPeek()); break; case RegexCode.Capturemark: if (Operand(1) != -1 && !IsMatched(Operand(1))) break; StackPop(); if (Operand(1) != -1) TransferCapture(Operand(0), Operand(1), StackPeek(), Textpos()); else Capture(Operand(0), StackPeek(), Textpos()); TrackPush(StackPeek()); Advance(2); continue; case RegexCode.Capturemark | RegexCode.Back: TrackPop(); StackPush(TrackPeek()); Uncapture(); if (Operand(0) != -1 && Operand(1) != -1) Uncapture(); break; case RegexCode.Branchmark: { int matched; StackPop(); matched = Textpos() - StackPeek(); if (matched != 0) { // Nonempty match -> loop now TrackPush(StackPeek(), Textpos()); // Save old mark, textpos StackPush(Textpos()); // Make new mark Goto(Operand(0)); // Loop } else { // Empty match -> straight now TrackPush2(StackPeek()); // Save old mark Advance(1); // Straight } continue; } case RegexCode.Branchmark | RegexCode.Back: TrackPop(2); StackPop(); Textto(TrackPeek(1)); // Recall position TrackPush2(TrackPeek()); // Save old mark Advance(1); // Straight continue; case RegexCode.Branchmark | RegexCode.Back2: TrackPop(); StackPush(TrackPeek()); // Recall old mark break; // Backtrack case RegexCode.Lazybranchmark: { // We hit this the first time through a lazy loop and after each // successful match of the inner expression. It simply continues // on and doesn't loop. StackPop(); int oldMarkPos = StackPeek(); if (Textpos() != oldMarkPos) { // Nonempty match -> try to loop again by going to 'back' state if (oldMarkPos != -1) TrackPush(oldMarkPos, Textpos()); // Save old mark, textpos else TrackPush(Textpos(), Textpos()); } else { // The inner expression found an empty match, so we'll go directly to 'back2' if we // backtrack. In this case, we need to push something on the stack, since back2 pops. // However, in the case of ()+? or similar, this empty match may be legitimate, so push the text // position associated with that empty match. StackPush(oldMarkPos); TrackPush2(StackPeek()); // Save old mark } Advance(1); continue; } case RegexCode.Lazybranchmark | RegexCode.Back: { // After the first time, Lazybranchmark | RegexCode.Back occurs // with each iteration of the loop, and therefore with every attempted // match of the inner expression. We'll try to match the inner expression, // then go back to Lazybranchmark if successful. If the inner expression // fails, we go to Lazybranchmark | RegexCode.Back2 int pos; TrackPop(2); pos = TrackPeek(1); TrackPush2(TrackPeek()); // Save old mark StackPush(pos); // Make new mark Textto(pos); // Recall position Goto(Operand(0)); // Loop continue; } case RegexCode.Lazybranchmark | RegexCode.Back2: // The lazy loop has failed. We'll do a true backtrack and // start over before the lazy loop. StackPop(); TrackPop(); StackPush(TrackPeek()); // Recall old mark break; case RegexCode.Setcount: StackPush(Textpos(), Operand(0)); TrackPush(); Advance(1); continue; case RegexCode.Nullcount: StackPush(-1, Operand(0)); TrackPush(); Advance(1); continue; case RegexCode.Setcount | RegexCode.Back: StackPop(2); break; case RegexCode.Nullcount | RegexCode.Back: StackPop(2); break; case RegexCode.Branchcount: // StackPush: // 0: Mark // 1: Count { StackPop(2); int mark = StackPeek(); int count = StackPeek(1); int matched = Textpos() - mark; if (count >= Operand(1) || (matched == 0 && count >= 0)) { // Max loops or empty match -> straight now TrackPush2(mark, count); // Save old mark, count Advance(2); // Straight } else { // Nonempty match -> count+loop now TrackPush(mark); // remember mark StackPush(Textpos(), count + 1); // Make new mark, incr count Goto(Operand(0)); // Loop } continue; } case RegexCode.Branchcount | RegexCode.Back: // TrackPush: // 0: Previous mark // StackPush: // 0: Mark (= current pos, discarded) // 1: Count TrackPop(); StackPop(2); if (StackPeek(1) > 0) { // Positive -> can go straight Textto(StackPeek()); // Zap to mark TrackPush2(TrackPeek(), StackPeek(1) - 1); // Save old mark, old count Advance(2); // Straight continue; } StackPush(TrackPeek(), StackPeek(1) - 1); // recall old mark, old count break; case RegexCode.Branchcount | RegexCode.Back2: // TrackPush: // 0: Previous mark // 1: Previous count TrackPop(2); StackPush(TrackPeek(), TrackPeek(1)); // Recall old mark, old count break; // Backtrack case RegexCode.Lazybranchcount: // StackPush: // 0: Mark // 1: Count { StackPop(2); int mark = StackPeek(); int count = StackPeek(1); if (count < 0) { // Negative count -> loop now TrackPush2(mark); // Save old mark StackPush(Textpos(), count + 1); // Make new mark, incr count Goto(Operand(0)); // Loop } else { // Nonneg count -> straight now TrackPush(mark, count, Textpos()); // Save mark, count, position Advance(2); // Straight } continue; } case RegexCode.Lazybranchcount | RegexCode.Back: // TrackPush: // 0: Mark // 1: Count // 2: Textpos { TrackPop(3); int mark = TrackPeek(); int textpos = TrackPeek(2); if (TrackPeek(1) < Operand(1) && textpos != mark) { // Under limit and not empty match -> loop Textto(textpos); // Recall position StackPush(textpos, TrackPeek(1) + 1); // Make new mark, incr count TrackPush2(mark); // Save old mark Goto(Operand(0)); // Loop continue; } else { // Max loops or empty match -> backtrack StackPush(TrackPeek(), TrackPeek(1)); // Recall old mark, count break; // backtrack } } case RegexCode.Lazybranchcount | RegexCode.Back2: // TrackPush: // 0: Previous mark // StackPush: // 0: Mark (== current pos, discarded) // 1: Count TrackPop(); StackPop(2); StackPush(TrackPeek(), StackPeek(1) - 1); // Recall old mark, count break; // Backtrack case RegexCode.Setjump: StackPush(Trackpos(), Crawlpos()); TrackPush(); Advance(); continue; case RegexCode.Setjump | RegexCode.Back: StackPop(2); break; case RegexCode.Backjump: // StackPush: // 0: Saved trackpos // 1: Crawlpos StackPop(2); Trackto(StackPeek()); while (Crawlpos() != StackPeek(1)) Uncapture(); break; case RegexCode.Forejump: // StackPush: // 0: Saved trackpos // 1: Crawlpos StackPop(2); Trackto(StackPeek()); TrackPush(StackPeek(1)); Advance(); continue; case RegexCode.Forejump | RegexCode.Back: // TrackPush: // 0: Crawlpos TrackPop(); while (Crawlpos() != TrackPeek()) Uncapture(); break; case RegexCode.Bol: if (Leftchars() > 0 && CharAt(Textpos() - 1) != '\n') break; Advance(); continue; case RegexCode.Eol: if (Rightchars() > 0 && CharAt(Textpos()) != '\n') break; Advance(); continue; case RegexCode.Boundary: if (!IsBoundary(Textpos(), runtextbeg, runtextend)) break; Advance(); continue; case RegexCode.Nonboundary: if (IsBoundary(Textpos(), runtextbeg, runtextend)) break; Advance(); continue; case RegexCode.ECMABoundary: if (!IsECMABoundary(Textpos(), runtextbeg, runtextend)) break; Advance(); continue; case RegexCode.NonECMABoundary: if (IsECMABoundary(Textpos(), runtextbeg, runtextend)) break; Advance(); continue; case RegexCode.Beginning: if (Leftchars() > 0) break; Advance(); continue; case RegexCode.Start: if (Textpos() != Textstart()) break; Advance(); continue; case RegexCode.EndZ: if (Rightchars() > 1 || Rightchars() == 1 && CharAt(Textpos()) != '\n') break; Advance(); continue; case RegexCode.End: if (Rightchars() > 0) break; Advance(); continue; case RegexCode.One: if (Forwardchars() < 1 || Forwardcharnext() != (char)Operand(0)) break; Advance(1); continue; case RegexCode.Notone: if (Forwardchars() < 1 || Forwardcharnext() == (char)Operand(0)) break; Advance(1); continue; case RegexCode.Set: if (Forwardchars() < 1 || !RegexCharClass.CharInClass(Forwardcharnext(), _code._strings[Operand(0)])) break; Advance(1); continue; case RegexCode.Multi: { if (!Stringmatch(_code._strings[Operand(0)])) break; Advance(1); continue; } case RegexCode.Ref: { int capnum = Operand(0); if (IsMatched(capnum)) { if (!Refmatch(MatchIndex(capnum), MatchLength(capnum))) break; } else { if ((runregex.roptions & RegexOptions.ECMAScript) == 0) break; } Advance(1); continue; } case RegexCode.Onerep: { int c = Operand(1); if (Forwardchars() < c) break; char ch = (char)Operand(0); while (c-- > 0) if (Forwardcharnext() != ch) goto BreakBackward; Advance(2); continue; } case RegexCode.Notonerep: { int c = Operand(1); if (Forwardchars() < c) break; char ch = (char)Operand(0); while (c-- > 0) if (Forwardcharnext() == ch) goto BreakBackward; Advance(2); continue; } case RegexCode.Setrep: { int c = Operand(1); if (Forwardchars() < c) break; String set = _code._strings[Operand(0)]; while (c-- > 0) if (!RegexCharClass.CharInClass(Forwardcharnext(), set)) goto BreakBackward; Advance(2); continue; } case RegexCode.Oneloop: { int c = Operand(1); if (c > Forwardchars()) c = Forwardchars(); char ch = (char)Operand(0); int i; for (i = c; i > 0; i--) { if (Forwardcharnext() != ch) { Backwardnext(); break; } } if (c > i) TrackPush(c - i - 1, Textpos() - Bump()); Advance(2); continue; } case RegexCode.Notoneloop: { int c = Operand(1); if (c > Forwardchars()) c = Forwardchars(); char ch = (char)Operand(0); int i; for (i = c; i > 0; i--) { if (Forwardcharnext() == ch) { Backwardnext(); break; } } if (c > i) TrackPush(c - i - 1, Textpos() - Bump()); Advance(2); continue; } case RegexCode.Setloop: { int c = Operand(1); if (c > Forwardchars()) c = Forwardchars(); String set = _code._strings[Operand(0)]; int i; for (i = c; i > 0; i--) { if (!RegexCharClass.CharInClass(Forwardcharnext(), set)) { Backwardnext(); break; } } if (c > i) TrackPush(c - i - 1, Textpos() - Bump()); Advance(2); continue; } case RegexCode.Oneloop | RegexCode.Back: case RegexCode.Notoneloop | RegexCode.Back: { TrackPop(2); int i = TrackPeek(); int pos = TrackPeek(1); Textto(pos); if (i > 0) TrackPush(i - 1, pos - Bump()); Advance(2); continue; } case RegexCode.Setloop | RegexCode.Back: { TrackPop(2); int i = TrackPeek(); int pos = TrackPeek(1); Textto(pos); if (i > 0) TrackPush(i - 1, pos - Bump()); Advance(2); continue; } case RegexCode.Onelazy: case RegexCode.Notonelazy: { int c = Operand(1); if (c > Forwardchars()) c = Forwardchars(); if (c > 0) TrackPush(c - 1, Textpos()); Advance(2); continue; } case RegexCode.Setlazy: { int c = Operand(1); if (c > Forwardchars()) c = Forwardchars(); if (c > 0) TrackPush(c - 1, Textpos()); Advance(2); continue; } case RegexCode.Onelazy | RegexCode.Back: { TrackPop(2); int pos = TrackPeek(1); Textto(pos); if (Forwardcharnext() != (char)Operand(0)) break; int i = TrackPeek(); if (i > 0) TrackPush(i - 1, pos + Bump()); Advance(2); continue; } case RegexCode.Notonelazy | RegexCode.Back: { TrackPop(2); int pos = TrackPeek(1); Textto(pos); if (Forwardcharnext() == (char)Operand(0)) break; int i = TrackPeek(); if (i > 0) TrackPush(i - 1, pos + Bump()); Advance(2); continue; } case RegexCode.Setlazy | RegexCode.Back: { TrackPop(2); int pos = TrackPeek(1); Textto(pos); if (!RegexCharClass.CharInClass(Forwardcharnext(), _code._strings[Operand(0)])) break; int i = TrackPeek(); if (i > 0) TrackPush(i - 1, pos + Bump()); Advance(2); continue; } default: throw NotImplemented.ByDesignWithMessage(SR.UnimplementedState); } BreakBackward: ; // "break Backward" comes here: Backtrack(); } } #if DEBUG internal override void DumpState() { base.DumpState(); Debug.WriteLine(" " + _code.OpcodeDescription(_codepos) + ((_operator & RegexCode.Back) != 0 ? " Back" : "") + ((_operator & RegexCode.Back2) != 0 ? " Back2" : "")); Debug.WriteLine(""); } #endif } }