context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using log4net;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.CoreModules.Agent.TextureSender
{
/// <summary>
/// A TextureSender handles the process of receiving a texture requested by the client from the
/// AssetCache, and then sending that texture back to the client.
/// </summary>
public class TextureSender : ITextureSender
{
private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Records the number of times texture send has been called.
/// </summary>
public int counter = 0;
public bool ImageLoaded = false;
/// <summary>
/// Holds the texture asset to send.
/// </summary>
private AssetBase m_asset;
//public UUID assetID { get { return m_asset.FullID; } }
// private bool m_cancel = false;
// See ITextureSender
// private bool m_sending = false;
/// <summary>
/// This is actually the number of extra packets required to send the texture data! We always assume
/// at least one is required.
/// </summary>
private int NumPackets = 0;
/// <summary>
/// Holds the packet number to send next. In this case, each packet is 1000 bytes long and starts
/// at the 600th byte (0th indexed).
/// </summary>
private int PacketCounter = 0;
private int RequestedDiscardLevel = -1;
private IClientAPI RequestUser;
private uint StartPacketNumber = 0;
public TextureSender(IClientAPI client, int discardLevel, uint packetNumber)
{
RequestUser = client;
RequestedDiscardLevel = discardLevel;
StartPacketNumber = packetNumber;
}
#region ITextureSender Members
public bool Cancel
{
get { return false; }
set
{
// m_cancel = value;
}
}
public bool Sending
{
get { return false; }
set
{
// m_sending = value;
}
}
// See ITextureSender
public void UpdateRequest(int discardLevel, uint packetNumber)
{
RequestedDiscardLevel = discardLevel;
StartPacketNumber = packetNumber;
PacketCounter = (int)StartPacketNumber;
}
// See ITextureSender
public bool SendTexturePacket()
{
//m_log.DebugFormat("[TEXTURE SENDER]: Sending packet for {0}", m_asset.FullID);
SendPacket();
counter++;
if ((NumPackets == 0) || (RequestedDiscardLevel == -1) || (PacketCounter > NumPackets) ||
((RequestedDiscardLevel > 0) && (counter > 50 + (NumPackets / (RequestedDiscardLevel + 1)))))
{
return true;
}
return false;
}
#endregion
/// <summary>
/// Load up the texture data to send.
/// </summary>
/// <param name="asset"></param>
public void TextureReceived(AssetBase asset)
{
m_asset = asset;
NumPackets = CalculateNumPackets(asset.Data.Length);
PacketCounter = (int)StartPacketNumber;
ImageLoaded = true;
}
/// <summary>
/// Sends a texture packet to the client.
/// </summary>
private void SendPacket()
{
if (PacketCounter <= NumPackets)
{
if (PacketCounter == 0)
{
if (NumPackets == 0)
{
RequestUser.SendImageFirstPart(1, m_asset.FullID, (uint)m_asset.Data.Length, m_asset.Data, 2);
PacketCounter++;
}
else
{
byte[] ImageData1 = new byte[600];
Array.Copy(m_asset.Data, 0, ImageData1, 0, 600);
RequestUser.SendImageFirstPart(
(ushort)(NumPackets), m_asset.FullID, (uint)m_asset.Data.Length, ImageData1, 2);
PacketCounter++;
}
}
else
{
int size = m_asset.Data.Length - 600 - (1000 * (PacketCounter - 1));
if (size > 1000) size = 1000;
byte[] imageData = new byte[size];
try
{
Array.Copy(m_asset.Data, 600 + (1000 * (PacketCounter - 1)), imageData, 0, size);
}
catch (ArgumentOutOfRangeException)
{
m_log.Error("[TEXTURE SENDER]: Unable to separate texture into multiple packets: Array bounds failure on asset:" +
m_asset.ID);
return;
}
RequestUser.SendImageNextPart((ushort)PacketCounter, m_asset.FullID, imageData);
PacketCounter++;
}
}
}
/// <summary>
/// Calculate the number of packets that will be required to send the texture loaded into this sender
/// This is actually the number of 1000 byte packets not including an initial 600 byte packet...
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
private int CalculateNumPackets(int length)
{
int numPackets = 0;
if (length > 600)
{
//over 600 bytes so split up file
int restData = (length - 600);
int restPackets = ((restData + 999) / 1000);
numPackets = restPackets;
}
return numPackets;
}
}
}
| |
namespace FakeItEasy.Configuration
{
using System;
using System.Linq;
using System.Linq.Expressions;
using FakeItEasy.Core;
using FakeItEasy.Expressions;
internal partial class PropertySetterConfiguration<TValue>
: IPropertySetterAnyValueConfiguration<TValue>
{
private readonly ParsedCallExpression parsedSetterExpression;
private readonly Func<ParsedCallExpression, IVoidArgumentValidationConfiguration> voidArgumentValidationConfigurationFactory;
public PropertySetterConfiguration(
ParsedCallExpression parsedCallExpression,
Func<ParsedCallExpression, IVoidArgumentValidationConfiguration> voidArgumentValidationConfigurationFactory)
{
this.parsedSetterExpression = parsedCallExpression;
this.voidArgumentValidationConfigurationFactory = voidArgumentValidationConfigurationFactory;
}
public IPropertySetterConfiguration To(TValue value) =>
this.To(() => value);
public IPropertySetterConfiguration To(Expression<Func<TValue>> valueConstraint)
{
Guard.AgainstNull(valueConstraint, nameof(valueConstraint));
var newSetterExpression = this.CreateSetterExpressionWithNewValue(valueConstraint);
var voidArgumentValidationConfiguration = this.CreateArgumentValidationConfiguration(newSetterExpression);
return AsPropertySetterConfiguration(voidArgumentValidationConfiguration);
}
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> Throws(Func<IFakeObjectCall, Exception> exceptionFactory) =>
AsPropertySetterConfiguration(this.CreateArgumentValidationConfiguration(this.parsedSetterExpression))
.Throws(exceptionFactory);
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> Throws<T>() where T : Exception, new() =>
this.Throws<IPropertySetterConfiguration, T>();
public IPropertySetterAfterCallbackConfiguredConfiguration Invokes(Action<IFakeObjectCall> action)
{
var voidConfiguration = this.CreateArgumentValidationConfiguration(this.parsedSetterExpression)
.Invokes(action);
return AsPropertySetterAfterCallbackConfiguredConfiguration(voidConfiguration);
}
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> CallsBaseMethod() =>
AsPropertySetterConfiguration(this.CreateArgumentValidationConfiguration(this.parsedSetterExpression))
.CallsBaseMethod();
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> CallsWrappedMethod() =>
AsPropertySetterConfiguration(this.CreateArgumentValidationConfiguration(this.parsedSetterExpression))
.CallsWrappedMethod();
public UnorderedCallAssertion MustHaveHappened(int numberOfTimes, Times timesOption)
{
Guard.AgainstNull(timesOption, nameof(timesOption));
return this.CreateArgumentValidationConfiguration(this.parsedSetterExpression).MustHaveHappened(numberOfTimes, timesOption);
}
public UnorderedCallAssertion MustHaveHappenedANumberOfTimesMatching(Expression<Func<int, bool>> predicate)
{
Guard.AgainstNull(predicate, nameof(predicate));
return this.CreateArgumentValidationConfiguration(this.parsedSetterExpression).MustHaveHappenedANumberOfTimesMatching(predicate);
}
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> DoesNothing() =>
AsPropertySetterConfiguration(this.CreateArgumentValidationConfiguration(this.parsedSetterExpression))
.DoesNothing();
public IPropertySetterConfiguration WhenArgumentsMatch(Func<ArgumentCollection, bool> argumentsPredicate)
{
var voidConfiguration = this.CreateArgumentValidationConfiguration(this.parsedSetterExpression)
.WhenArgumentsMatch(argumentsPredicate);
return AsPropertySetterConfiguration(voidConfiguration);
}
private static IPropertySetterConfiguration AsPropertySetterConfiguration(
IVoidConfiguration voidArgumentValidationConfiguration) =>
new PropertySetterAdapter(voidArgumentValidationConfiguration);
private static IPropertySetterAfterCallbackConfiguredConfiguration AsPropertySetterAfterCallbackConfiguredConfiguration(
IVoidAfterCallbackConfiguredConfiguration voidArgumentValidationConfiguration) =>
new PropertySetterAfterCallbackConfiguredAdapter(voidArgumentValidationConfiguration);
private ParsedCallExpression CreateSetterExpressionWithNewValue(Expression<Func<TValue>> valueExpression)
{
var originalParameterInfos = this.parsedSetterExpression.CalledMethod.GetParameters();
var parsedValueExpression = new ParsedArgumentExpression(
valueExpression.Body,
originalParameterInfos.Last());
var arguments = new ParsedArgumentExpression[originalParameterInfos.Length];
Array.Copy(this.parsedSetterExpression.ArgumentsExpressions, arguments, originalParameterInfos.Length - 1);
arguments[originalParameterInfos.Length - 1] = parsedValueExpression;
return new ParsedCallExpression(
this.parsedSetterExpression.CalledMethod,
this.parsedSetterExpression.CallTarget,
arguments);
}
private IVoidArgumentValidationConfiguration CreateArgumentValidationConfiguration(
ParsedCallExpression parsedSetter) =>
this.voidArgumentValidationConfigurationFactory(parsedSetter);
private partial class PropertySetterAdapter : IPropertySetterConfiguration
{
private IVoidConfiguration voidConfiguration;
public PropertySetterAdapter(IVoidConfiguration voidArgumentValidationConfiguration)
{
this.voidConfiguration = voidArgumentValidationConfiguration;
}
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> Throws(Func<IFakeObjectCall, Exception> exceptionFactory) =>
new PropertySetterAfterCallConfiguredAdapter(this.voidConfiguration.Throws(exceptionFactory));
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> Throws<T>() where T : Exception, new() =>
this.Throws<IPropertySetterConfiguration, T>();
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> CallsBaseMethod() =>
new PropertySetterAfterCallConfiguredAdapter(this.voidConfiguration.CallsBaseMethod());
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> CallsWrappedMethod() =>
new PropertySetterAfterCallConfiguredAdapter(this.voidConfiguration.CallsWrappedMethod());
public UnorderedCallAssertion MustHaveHappened(int numberOfTimes, Times timesOption)
{
Guard.AgainstNull(timesOption, nameof(timesOption));
return this.voidConfiguration.MustHaveHappened(numberOfTimes, timesOption);
}
public UnorderedCallAssertion MustHaveHappenedANumberOfTimesMatching(Expression<Func<int, bool>> predicate)
{
Guard.AgainstNull(predicate, nameof(predicate));
return this.voidConfiguration.MustHaveHappenedANumberOfTimesMatching(predicate);
}
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> DoesNothing() =>
new PropertySetterAfterCallConfiguredAdapter(this.voidConfiguration.DoesNothing());
public IPropertySetterAfterCallbackConfiguredConfiguration Invokes(Action<IFakeObjectCall> action) =>
AsPropertySetterAfterCallbackConfiguredConfiguration(this.voidConfiguration.Invokes(action));
}
private partial class PropertySetterAfterCallbackConfiguredAdapter : IPropertySetterAfterCallbackConfiguredConfiguration
{
private IVoidAfterCallbackConfiguredConfiguration voidConfiguration;
public PropertySetterAfterCallbackConfiguredAdapter(IVoidAfterCallbackConfiguredConfiguration voidArgumentValidationConfiguration)
{
this.voidConfiguration = voidArgumentValidationConfiguration;
}
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> Throws(Func<IFakeObjectCall, Exception> exceptionFactory) =>
new PropertySetterAfterCallConfiguredAdapter(this.voidConfiguration.Throws(exceptionFactory));
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> Throws<T>() where T : Exception, new() =>
this.Throws<IPropertySetterConfiguration, T>();
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> CallsBaseMethod() =>
new PropertySetterAfterCallConfiguredAdapter(this.voidConfiguration.CallsBaseMethod());
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> CallsWrappedMethod() =>
new PropertySetterAfterCallConfiguredAdapter(this.voidConfiguration.CallsWrappedMethod());
public IAfterCallConfiguredConfiguration<IPropertySetterConfiguration> DoesNothing() =>
new PropertySetterAfterCallConfiguredAdapter(this.voidConfiguration.DoesNothing());
public IPropertySetterAfterCallbackConfiguredConfiguration Invokes(Action<IFakeObjectCall> action)
{
this.voidConfiguration = this.voidConfiguration.Invokes(action);
return this;
}
public IThenConfiguration<IPropertySetterConfiguration> NumberOfTimes(int numberOfTimes) =>
new PropertySetterThenAdapter(this.voidConfiguration.NumberOfTimes(numberOfTimes));
}
private class PropertySetterAfterCallConfiguredAdapter : IAfterCallConfiguredConfiguration<IPropertySetterConfiguration>
{
private readonly IAfterCallConfiguredConfiguration<IVoidConfiguration> voidAfterCallConfiguration;
public PropertySetterAfterCallConfiguredAdapter(IAfterCallConfiguredConfiguration<IVoidConfiguration> voidAfterCallConfiguration)
{
this.voidAfterCallConfiguration = voidAfterCallConfiguration;
}
public IThenConfiguration<IPropertySetterConfiguration> NumberOfTimes(int numberOfTimes) =>
new PropertySetterThenAdapter(this.voidAfterCallConfiguration.NumberOfTimes(numberOfTimes));
}
private class PropertySetterThenAdapter : IThenConfiguration<IPropertySetterConfiguration>
{
private readonly IThenConfiguration<IVoidConfiguration> voidThenConfiguration;
public PropertySetterThenAdapter(IThenConfiguration<IVoidConfiguration> voidThenConfiguration)
{
this.voidThenConfiguration = voidThenConfiguration;
}
public IPropertySetterConfiguration Then => AsPropertySetterConfiguration(this.voidThenConfiguration.Then);
}
}
}
| |
using System;
using System.Collections;
/// <summary>
/// Sin(System.Double)
/// </summary>
public class MathSin
{
public static int Main(string[] args)
{
MathSin test = new MathSin();
TestLibrary.TestFramework.BeginTestCase("Testing System.Math.Sin(System.Double).");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify the result when radian is 0.");
try
{
Double d = Math.Sin(0);
if (d != 0)
{
TestLibrary.TestFramework.LogError("P01.1", "The result is error when radian is 0!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P01.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify the result is 1 when radian is Math.PI/2.");
try
{
Double d = Math.Sin(Math.PI/2);
if ( d != 1)
{
TestLibrary.TestFramework.LogError("P02.1", "The result is error when radian is Math.PI/2!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P02.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify the result is -1 when radian is -Math.PI/2.");
try
{
Double d = Math.Sin(-Math.PI / 2);
if (d != -1)
{
TestLibrary.TestFramework.LogError("P03.1", "The result is error when radian is -Math.PI/2!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P03.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify the result is 1/2 when radian is Math.PI/6.");
try
{
Double d = Math.Round(Math.Sin(Math.PI / 6), 2);
if (d != 0.5d)
{
TestLibrary.TestFramework.LogError("P04.1", "The result is error when radian is Math.PI/6!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P04.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Verify the result is -1/2 when radian is -Math.PI/6.");
try
{
Double d = Math.Round(Math.Sin(-Math.PI / 6), 2);
if (d != -0.5d)
{
TestLibrary.TestFramework.LogError("P05.1", "The result is error when radian is -Math.PI/6!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P05.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest6: Verify the result is NaN when radian is PositiveInfinity.");
try
{
Double d = Math.Sin(Double.PositiveInfinity);
if (d.CompareTo(Double.NaN) != 0)
{
TestLibrary.TestFramework.LogError("P06.1", "The result is error when radian is PositiveInfinity!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P06.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest7: Verify the result is NaN when radian is NegativeInfinity.");
try
{
Double d = Math.Sin(Double.NegativeInfinity);
if (d.CompareTo(Double.NaN) != 0)
{
TestLibrary.TestFramework.LogError("P07.1", "The result is error when radian is NegativeInfinity!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P07.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest8()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest8: Verify the result is NaN when radian is NaN.");
try
{
Double d = Math.Sin(Double.NaN);
if (d.CompareTo(Double.NaN) != 0)
{
TestLibrary.TestFramework.LogError("P08.1", "The result is error when radian is NaN!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P08.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="OrderItemEventHandler.cs" company="Sitecore Corporation">
// Copyright (c) Sitecore Corporation 1999-2015
// </copyright>
// <summary>
// Defines the OrderItemEventHandler class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
// -------------------------------------------------------------------------------------------
namespace Sitecore.Ecommerce.Orders
{
using System.Collections.Generic;
using System.Linq;
using Configuration;
using Diagnostics;
using DomainModel.Orders;
using Shell.Framework.Pipelines;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Data.Proxies;
using Sitecore.Pipelines.Save;
using Sitecore.Web.UI.Sheer;
using Sites;
using Text;
using Utils;
public class OrderItemEventHandler
{
/// <summary>
/// Order template ID.
/// </summary>
private readonly ID orderTemplateId = new ID(Settings.GetSetting("Ecommerce.Order.OrderItemTempalteId"));
/// <summary>
/// Order Line template ID.
/// </summary>
private readonly ID orderLineTemplateId = new ID(Settings.GetSetting("Ecommerce.Order.OrderLineItemTempalteId"));
/// <summary>
/// Order manager.
/// </summary>
private IOrderManager<DomainModel.Orders.Order> orderManager;
/// <summary>
/// Gets the order manager.
/// </summary>
/// <value>The order manager.</value>
protected virtual IOrderManager<DomainModel.Orders.Order> OrderManager
{
get { return this.orderManager ?? (this.orderManager = Context.Entity.Resolve<IOrderManager<DomainModel.Orders.Order>>()); }
}
/// <summary>
/// Called when the item has saved.
/// </summary>
/// <param name="args">The arguments.</param>
public void OnItemSaved([NotNull] SaveArgs args)
{
Assert.ArgumentNotNull(args, "args");
foreach (Item item in args.SavedItems)
{
this.RecalculateOrder(item);
}
}
/// <summary>
/// Called when the item has duplicated.
/// </summary>
/// <param name="args">The arguments.</param>
public void OnItemDuplicated([NotNull] ClientPipelineArgs args)
{
Assert.ArgumentNotNull(args, "args");
Item item = Sitecore.Context.Database.GetItem(args.Parameters["id"]);
if (item != null)
{
this.RecalculateOrder(item);
}
}
/// <summary>
/// Called when the item has copied.
/// </summary>
/// <param name="args">The arguments.</param>
public void OnItemCopied([NotNull] CopyItemsArgs args)
{
Assert.ArgumentNotNull(args, "args");
foreach (Item item in args.Copies)
{
this.RecalculateOrder(item);
}
}
/// <summary>
/// Called when the item has deleted.
/// </summary>
/// <param name="args">The arguments.</param>
public virtual void OnItemDeleted([NotNull] ClientPipelineArgs args)
{
Assert.ArgumentNotNull(args, "args");
foreach (Item item in this.GetItems(args))
{
if (item.TemplateID == this.orderTemplateId)
{
return;
}
if (item.TemplateID != this.orderLineTemplateId)
{
continue;
}
string site = SiteUtils.GetSiteByItem(item.Parent);
if (string.IsNullOrEmpty(site))
{
return;
}
SiteContext siteContext = SiteContextFactory.GetSiteContext(site);
using (new SiteContextSwitcher(siteContext))
{
DomainModel.Orders.Order order = this.GetOrder(item.Parent);
order.OrderLines.Remove(order.OrderLines.Where(ol => ol.Id == item.ID.ToString()).FirstOrDefault());
this.RecalculateOrder(order);
}
}
}
/// <summary>
/// Recalculates the order.
/// </summary>
/// <param name="item">The item.</param>
protected virtual void RecalculateOrder([NotNull] Item item)
{
Assert.ArgumentNotNull(item, "item");
if (item.TemplateID.ToString().ToLower() == Settings.GetSetting("Ecommerce.Order.OrderItemTempalteId").ToLower() || item.TemplateID.ToString().ToLower() == Settings.GetSetting("Ecommerce.Order.OrderLineItemTempalteId").ToLower())
{
string site = SiteUtils.GetSiteByItem(item);
SiteContext siteContext = SiteContextFactory.GetSiteContext(site);
using (new SiteContextSwitcher(siteContext))
{
DomainModel.Orders.Order order = this.GetOrder(item);
this.RecalculateOrder(order);
}
}
}
/// <summary>
/// Recalculates the order.
/// </summary>
/// <param name="order">The order.</param>
protected virtual void RecalculateOrder(DomainModel.Orders.Order order)
{
if (order == null)
{
return;
}
OrderPriceCalculator manager = Context.Entity.Resolve<OrderPriceCalculator>();
manager.Recalculate(ref order);
this.OrderManager.SaveOrder(order);
}
/// <summary>
/// Gets the order item.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>Returns Order.</returns>
protected virtual DomainModel.Orders.Order GetOrder([NotNull] Item item)
{
Assert.ArgumentNotNull(item, "item");
Item orderItem = null;
if (item.TemplateID == this.orderTemplateId || item.TemplateID == this.orderLineTemplateId)
{
orderItem = item.TemplateID == this.orderLineTemplateId ? item.Parent : item;
}
if (orderItem == null)
{
return null;
}
return OrderManager.GetOrder(orderItem["OrderNumber"]);
}
/// <summary>
/// Gets the items.
/// </summary>
/// <param name="args">The arguments.</param>
/// <returns>Retuns list of items to be deleted.</returns>
protected virtual List<Item> GetItems([NotNull] ClientPipelineArgs args)
{
Assert.ArgumentNotNull(args, "args");
Database database = GetDatabase(args);
List<Item> result = (from itemId in new ListString(args.Parameters["items"], '|')
select database.GetItem(itemId)
into item
where item != null
select MapToRealItem(item)).ToList();
return Assert.ResultNotNull(result);
}
/// <summary>
/// Gets the database.
/// </summary>
/// <param name="args">The arguments.</param>
/// <returns>Returns Items database.</returns>
protected virtual Database GetDatabase([NotNull] ClientPipelineArgs args)
{
Assert.ArgumentNotNull(args, "args");
Database database = Factory.GetDatabase(args.Parameters["database"]);
Assert.IsNotNull(database, typeof(Database), "Name: {0}", new object[] { args.Parameters["database"] });
return Assert.ResultNotNull(database);
}
/// <summary>
/// Maps to real item.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>Returns real item.</returns>
private static Item MapToRealItem([NotNull] Item item)
{
Assert.ArgumentNotNull(item, "item");
return ProxyManager.GetRealItem(item, false);
}
}
}
| |
// suppress "Missing XML comment for publicly visible type or member"
#pragma warning disable 1591
#region ReSharper warnings
// ReSharper disable PartialTypeWithSinglePart
// ReSharper disable RedundantNameQualifier
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable UnusedParameter.Local
// ReSharper disable RedundantUsingDirective
#endregion
namespace Test
{
using System.Collections.Generic;
[System.CodeDom.Compiler.GeneratedCode("gbc", "0.11.0.0")]
public enum TestEnum
{
EnumVal1,
EnumVal2,
EnumVal3,
}
[global::Bond.Schema]
[System.CodeDom.Compiler.GeneratedCode("gbc", "0.11.0.0")]
public partial class Simple
{
[global::Bond.Id(0)]
public int someInt { get; private set; }
[global::Bond.Id(1)]
public int anotherInt { get; private set; }
[global::Bond.Id(2), global::Bond.Type(typeof(global::Bond.Tag.wstring))]
public string someString { get; private set; }
public Simple(
int someInt,
int anotherInt,
string someString)
{
this.someInt = someInt;
this.anotherInt = anotherInt;
this.someString = someString;
}
public Simple()
{
someString = "";
}
}
[global::Bond.Schema]
[System.CodeDom.Compiler.GeneratedCode("gbc", "0.11.0.0")]
public partial class Foo
{
[global::Bond.Id(0), global::Bond.Type(typeof(global::Bond.Tag.wstring))]
public string someText { get; private set; }
public Foo(
string someText)
{
this.someText = someText;
}
public Foo()
{
someText = "BaseText1";
}
}
[global::Bond.Schema]
[System.CodeDom.Compiler.GeneratedCode("gbc", "0.11.0.0")]
public partial class Bar
: Foo
{
[global::Bond.Id(0)]
public TestEnum testEnum { get; private set; }
[global::Bond.Id(1), global::Bond.Type(typeof(global::Bond.Tag.wstring))]
new public string someText { get; private set; }
[global::Bond.Id(2)]
public int someInt { get; private set; }
[global::Bond.Id(3), global::Bond.Type(typeof(global::Bond.Tag.wstring))]
public string moreText { get; private set; }
[global::Bond.Id(4), global::Bond.Type(typeof(List<Simple>))]
public IList<Simple> someList { get; private set; }
[global::Bond.Id(5), global::Bond.Type(typeof(Dictionary<global::Bond.Tag.wstring, double>))]
public IDictionary<string, double> someMap { get; private set; }
[global::Bond.Id(6), global::Bond.Type(typeof(HashSet<global::Bond.Tag.wstring>))]
public ISet<string> someSet { get; private set; }
public Bar(
// Base class parameters
string someText,
// This class parameters
TestEnum testEnum,
string someText0,
int someInt,
string moreText,
IList<Simple> someList,
IDictionary<string, double> someMap,
ISet<string> someSet
) : base(
someText)
{
this.testEnum = testEnum;
this.someText = someText0;
this.someInt = someInt;
this.moreText = moreText;
this.someList = someList;
this.someMap = someMap;
this.someSet = someSet;
}
public Bar()
{
testEnum = TestEnum.Val2;
someText = "DerivedText1";
moreText = "";
someList = new List<Simple>();
someMap = new Dictionary<string, double>();
someSet = new HashSet<string>();
}
}
[global::Bond.Schema]
[System.CodeDom.Compiler.GeneratedCode("gbc", "0.11.0.0")]
public partial class Baz
: Bar
{
[global::Bond.Id(0), global::Bond.Type(typeof(global::Bond.Tag.wstring))]
new public string someText { get; private set; }
[global::Bond.Id(1), global::Bond.Type(typeof(global::Bond.Tag.wstring))]
public string evenMoreText { get; private set; }
public Baz(
// Base class parameters
string someText,
TestEnum testEnum,
string someText0,
int someInt,
string moreText,
IList<Simple> someList,
IDictionary<string, double> someMap,
ISet<string> someSet,
// This class parameters
string someText1,
string evenMoreText
) : base(
someText,
testEnum,
someText0,
someInt,
moreText,
someList,
someMap,
someSet)
{
this.someText = someText1;
this.evenMoreText = evenMoreText;
}
public Baz()
{
someText = "";
evenMoreText = "";
}
}
[global::Bond.Schema]
[System.CodeDom.Compiler.GeneratedCode("gbc", "0.11.0.0")]
public partial class DerivedEmpty
: Foo
{
public DerivedEmpty(
// Base class parameters
string someText
) : base(
someText)
{
}
public DerivedEmpty()
{
}
}
} // Test
| |
/* Copyright 2010, Object Management Group, Inc.
* Copyright 2010, PrismTech, Inc.
* Copyright 2010, Real-Time Innovations, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using DDS.ConversionUtils;
using org.omg.dds.core;
using org.omg.dds.topic;
using org.omg.dds.core.status;
using org.omg.dds.core.modifiable;
namespace org.omg.dds.sub
{
public interface IDataReader : IDomainEntity
{ }
public interface DataReader<TYPE> : IDataReader, DomainEntity<DataReader<TYPE>,
Subscriber,
DataReaderListener<TYPE>,
DataReaderQos>
{
/// <summary>
///
/// </summary>
/// <returns>The type parameter if this object's class</returns>
System.Type GetType();
/// <summary>
/// Cast this data reader to the given type, or throw an exception if
/// the Cast fails
/// </summary>
/// <typeparam name="OTHER">The type of the data subscribed to by this reader,
/// according to the caller
///</typeparam>
/// <returns>This data reader</returns>
/// <exception cref="ClassCastException">if the Cast fails</exception>
DataReader<OTHER> Cast<OTHER>();
ReadCondition<TYPE> CreateReadCondition();
ReadCondition<TYPE> CreateReadCondition(
ICollection<SampleState> sampleStates,
ICollection<ViewState> viewStates,
ICollection<InstanceState> instanceStates);
QueryCondition<TYPE> CreateQueryCondition(
string queryExpression,
List<string> queryParameters);
QueryCondition<TYPE> CreateQueryCondition(
ICollection<SampleState> sampleStates,
ICollection<ViewState> viewStates,
ICollection<InstanceState> instanceStates,
string queryExpression,
List<string> queryParameters);
void CloseContainedEntities();
TopicDescription<TYPE> GetTopicDescription();
SampleRejectedStatus<TYPE> GetSampleRejectedStatus(SampleRejectedStatus<TYPE> status);
LivelinessChangedStatus<TYPE> GetLivelinessChangedStatus(LivelinessChangedStatus<TYPE> status);
RequestedDeadlineMissedStatus<TYPE> GetRequestedDeadlineMissedStatus(RequestedDeadlineMissedStatus<TYPE> status);
RequestedIncompatibleQosStatus<TYPE> GetRequestedIncompatibleQosStatus(RequestedIncompatibleQosStatus<TYPE> status);
SubscriptionMatchedStatus<TYPE> GetSubscriptionMatchedStatus(SubscriptionMatchedStatus<TYPE> status);
SampleLostStatus<TYPE> GetSampleLostStatus(SampleLostStatus<TYPE> status);
void WaitForHistoricalData(Duration maxWait);
void WaitForHistoricalData(long maxWait, TimeUnit unit);
ICollection<InstanceHandle> GetMatchedPublications(ICollection<InstanceHandle> publicationHandles);
PublicationBuiltinTopicData GetMatchedPublicationData(PublicationBuiltinTopicData publicationData,
InstanceHandle publicationHandle);
/// <summary>
/// Create and return a new Sample of the same type as may be accessed by
/// this DataReader.
///
/// Applications may use this method, for example, to preallocate samples
/// to be overwritten by the <code>Read</code> and-or <code>Take</code>
/// methods of this interface.
///
/// @see #Read(List)
/// @see #Take(List)
/// </summary>
/// <returns></returns>
Sample<TYPE> CreateSample();
/// <summary>
///
/// </summary>
/// <returns>A non null unmodifiable iterator over loaned samples</returns>
SampleIterator<TYPE> Read();
SampleIterator<TYPE> Read(ICollection<SampleState> sampleStates,
ICollection<ViewState> viewStates,
ICollection<InstanceState> instanceStates);
/// <summary>
/// Copy samples into the provided collection, overwriting any samples that
/// might already be present
/// </summary>
/// <param name="samples"></param>
void Read(IList<Sample<TYPE>> samples);
void Read(IList<Sample<TYPE>> samples,
int maxSamples,
ICollection<SampleState> sampleStates,
ICollection<ViewState> viewStates,
ICollection<InstanceState> instanceStates);
/// <summary>
///
/// </summary>
/// <returns>A non null unmodifiable iterator over loaned samples</returns>
SampleIterator<TYPE> Take();
SampleIterator<TYPE> Take(ICollection<SampleState> sampleStates,
ICollection<ViewState> viewStates,
ICollection<InstanceState> instanceStates);
void Take(IList<Sample<TYPE>> samples);
void Take(IList<Sample<TYPE>> samples,
int maxSamples,
ICollection<SampleState> sampleStates,
ICollection<ViewState> viewStates,
ICollection<InstanceState> instanceStates);
/// <summary>
///
/// </summary>
/// <param name="condition"></param>
/// <returns>A non null unmodifiable iterator over loaned samples</returns>
SampleIterator<TYPE> Read(ReadCondition<TYPE> condition);
void Read(IList<Sample<TYPE>> samples,
ReadCondition<TYPE> condition);
void Read(IList<Sample<TYPE>> samples,
int maxSamples,
ReadCondition<TYPE> condition);
/// <summary>
///
/// </summary>
/// <param name="condition"></param>
/// <returns>A non null unmodifiable iterator over loaned samples</returns>
SampleIterator<TYPE> Take(ReadCondition<TYPE> condition);
void Take(IList<Sample<TYPE>> samples,
ReadCondition<TYPE> condition);
void Take(IList<Sample<TYPE>> samples,
int maxSamples,
ReadCondition<TYPE> condition);
/// <summary>
///
/// </summary>
/// <param name="sample"></param>
/// <returns>True if data was Read or false if no data was available</returns>
bool ReadNext(Sample<TYPE> sample);
/// <summary>
///
/// </summary>
/// <param name="sample"></param>
/// <returns>True if data was taken or false if no data was available</returns>
bool TakeNext(Sample<TYPE> sample);
/// <summary>
///
/// </summary>
/// <param name="handle"></param>
/// <returns>A non null unmodifiable iterator over loaned samples</returns>
SampleIterator<TYPE> Read(InstanceHandle handle);
SampleIterator<TYPE> Read(InstanceHandle handle,
ICollection<SampleState> sampleStates,
ICollection<ViewState> viewStates,
ICollection<InstanceState> instanceStates);
void Read(IList<Sample<TYPE>> samples,
InstanceHandle handle);
void Read(IList<Sample<TYPE>> samples,
InstanceHandle handle,
int maxSamples,
ICollection<SampleState> sampleStates,
ICollection<ViewState> viewStates,
ICollection<InstanceState> instanceStates);
/// <summary>
///
/// </summary>
/// <param name="handle"></param>
/// <returns>A non null unmodifiable iterator over loaned samples</returns>
SampleIterator<TYPE> Take(InstanceHandle handle);
SampleIterator<TYPE> Take(InstanceHandle handle,
ICollection<SampleState> sampleStates,
ICollection<ViewState> viewStates,
ICollection<InstanceState> instanceStates);
void Take(List<Sample<TYPE>> samples,
InstanceHandle handle);
void Take(List<Sample<TYPE>> samples,
InstanceHandle handle,
int maxSamples,
ICollection<SampleState> sampleStates,
ICollection<ViewState> viewStates,
ICollection<InstanceState> instanceStates);
/// <summary>
///
/// </summary>
/// <param name="previousHandle"></param>
/// <returns>A non null unmodifiable iterator over loaned samples</returns>
SampleIterator<TYPE> ReadNext(InstanceHandle previousHandle);
SampleIterator<TYPE> ReadNext(InstanceHandle previousHandle,
ICollection<SampleState> sampleStates,
ICollection<ViewState> viewStates,
ICollection<InstanceState> instanceStates);
void ReadNext(List<Sample<TYPE>> samples,
InstanceHandle previousHandle);
void ReadNext(List<Sample<TYPE>> samples,
InstanceHandle previousHandle,
int maxSamples,
ICollection<SampleState> sampleStates,
ICollection<ViewState> viewStates,
ICollection<InstanceState> instanceStates);
/// <summary>
///
/// </summary>
/// <param name="previousHandle"></param>
/// <returns>A non null unmodifiable iterator over loaned samples</returns>
SampleIterator<TYPE> TakeNext(InstanceHandle previousHandle);
SampleIterator<TYPE> TakeNext(InstanceHandle previousHandle,
ICollection<SampleState> sampleStates,
ICollection<ViewState> viewStates,
ICollection<InstanceState> instanceStates);
void TakeNext(List<Sample<TYPE>> samples,
InstanceHandle previousHandle);
void TakeNext(List<Sample<TYPE>> samples,
InstanceHandle previousHandle,
int maxSamples,
ICollection<SampleState> sampleStates,
ICollection<ViewState> viewStates,
ICollection<InstanceState> instanceStates);
/// <summary>
///
/// </summary>
/// <param name="previousHandle"></param>
/// <param name="condition"></param>
/// <returns>A non null unmodifiable iterator over loaned samples</returns>
SampleIterator<TYPE> ReadNext(InstanceHandle previousHandle,
ReadCondition<TYPE> condition);
void ReadNext(List<Sample<TYPE>> samples,
InstanceHandle previousHandle,
ReadCondition<TYPE> condition);
void ReadNext(List<Sample<TYPE>> samples,
InstanceHandle previousHandle,
int maxSamples,
ReadCondition<TYPE> condition);
/// <summary>
///
/// </summary>
/// <param name="previousHandle"></param>
/// <param name="condition"></param>
/// <returns>A non null unmodifiable iterator over loaned samples</returns>
SampleIterator<TYPE> TakeNext(InstanceHandle previousHandle,
ReadCondition<TYPE> condition);
void TakeNext(List<Sample<TYPE>> samples,
InstanceHandle previousHandle,
ReadCondition<TYPE> condition);
void TakeNext(List<Sample<TYPE>> samples,
InstanceHandle previousHandle,
int maxSamples,
ReadCondition<TYPE> condition);
TYPE GetKeyValue(TYPE keyHolder,
InstanceHandle handle);
ModifiableInstanceHandle LookupInstance(ModifiableInstanceHandle handle,
TYPE keyHolder);
}
}
| |
// 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.Globalization;
/// <summary>
/// Int64.System.IConvertible.ToType(IFormatProvider)
/// </summary>
public class Int64IConvertibleToType
{
private long c_INT64_MaxValue = 9223372036854775807;
private long c_INT64_MinValue = -9223372036854775808;
public static int Main()
{
Int64IConvertibleToType ui64IContType = new Int64IConvertibleToType();
TestLibrary.TestFramework.BeginTestCase("Int64IConvertibleToType");
if (ui64IContType.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[PosTest]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
retVal = PosTest9() && retVal;
retVal = PosTest10() && retVal;
retVal = PosTest11() && retVal;
TestLibrary.TestFramework.LogInformation("[NegTest]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region PositiveTest
public bool PosTest1()
{
bool retVal = true;
CultureInfo myculture = new CultureInfo("en-us");
IFormatProvider provider = myculture.NumberFormat;
TestLibrary.TestFramework.BeginScenario("PosTest1:The Int64 MinValue IConvertible to Type 1");
try
{
long int64A = Int64.MinValue;
IConvertible iConvert = (IConvertible)(int64A);
object objA = iConvert.ToType(typeof(Int64),provider);
if ((long)objA != c_INT64_MinValue)
{
TestLibrary.TestFramework.LogError("001", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2:The Int64 MinValue IConvertible to Type 2");
try
{
long int64A = Int64.MinValue;
IConvertible iConvert = (IConvertible)(int64A);
object objA = iConvert.ToType(typeof(double), null);
if ((Double)objA != (Double)(int64A))
{
TestLibrary.TestFramework.LogError("003", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
CultureInfo myculture = new CultureInfo("el-GR");
IFormatProvider provider = myculture.NumberFormat;
TestLibrary.TestFramework.BeginScenario("PosTest3:The Int64 MinValue IConvertible to Type 3");
try
{
long int64A = Int64.MinValue;
IConvertible iConvert = (IConvertible)(int64A);
object objA = iConvert.ToType(typeof(decimal), provider);
if ((Decimal)objA != int64A)
{
TestLibrary.TestFramework.LogError("005", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
CultureInfo myculture = new CultureInfo("en-us");
IFormatProvider provider = myculture.NumberFormat;
TestLibrary.TestFramework.BeginScenario("PosTest4:The Int64 MinValue IConvertible to Type 4");
try
{
long int64A = Int64.MinValue;
IConvertible iConvert = (IConvertible)(int64A);
object objA = iConvert.ToType(typeof(Single), provider);
if ((Single)objA != (Single)(int64A))
{
TestLibrary.TestFramework.LogError("007", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5:The Int64 MinValue IConvertible to Type 5");
try
{
long int64A = Int64.MinValue;
IConvertible iConvert = (IConvertible)(int64A);
object objA = iConvert.ToType(typeof(string), null);
if ((string)objA != int64A.ToString())
{
TestLibrary.TestFramework.LogError("009", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
CultureInfo myculture = new CultureInfo("en-us");
IFormatProvider provider = myculture.NumberFormat;
TestLibrary.TestFramework.BeginScenario("PosTest6:The Int64 MaxValue IConvertible to Type 1");
try
{
long int64A = Int64.MaxValue;
IConvertible iConvert = (IConvertible)(int64A);
object objA = iConvert.ToType(typeof(Int64), provider);
if ((long)objA != c_INT64_MaxValue)
{
TestLibrary.TestFramework.LogError("011", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest7:The Int64 MaxValue IConvertible to Type 2");
try
{
long int64A = Int64.MaxValue;
IConvertible iConvert = (IConvertible)(int64A);
object objA = iConvert.ToType(typeof(UInt64), null);
if ((ulong)objA != (ulong)int64A)
{
TestLibrary.TestFramework.LogError("013", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest8()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest8:The random Int64 IConvertible to Type 1");
try
{
long int64A = TestLibrary.Generator.GetInt64(-55);
IConvertible iConvert = (IConvertible)(int64A);
object objA = iConvert.ToType(typeof(Int64), null);
if ((long)objA != int64A)
{
TestLibrary.TestFramework.LogError("015", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest9()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest9:The random Int64 IConvertible to Type 2");
try
{
long int64A = (long)this.GetInt32(0, Int32.MaxValue);
IConvertible iConvert = (IConvertible)(int64A);
object objA = iConvert.ToType(typeof(Int32), null);
if ((Int32)objA != (Int32)int64A)
{
TestLibrary.TestFramework.LogError("017", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("018", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest10()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest10:The random Int64 IConvertible to Type 3");
try
{
long int64A = (long)this.GetInt32(0, Int16.MaxValue);
IConvertible iConvert = (IConvertible)(int64A);
object objA = iConvert.ToType(typeof(Int16), null);
if ((Int16)objA != (Int16)int64A)
{
TestLibrary.TestFramework.LogError("019", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("020", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest11()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest11:The random Int64 IConvertible to Type 4");
try
{
long int64A = TestLibrary.Generator.GetInt64(-55);
IConvertible iConvert = (IConvertible)(int64A);
object objA = iConvert.ToType(typeof(string), null);
if ((string)objA != int64A.ToString())
{
TestLibrary.TestFramework.LogError("021", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("022", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTest
public bool NegTest1()
{
bool retVal = true;
CultureInfo myculture = new CultureInfo("en-us");
IFormatProvider provider = myculture.NumberFormat;
TestLibrary.TestFramework.BeginScenario("NegTest1:The current Int64 out of the range of Type which IConverted to 1");
try
{
long int64A = Int64.MinValue;
IConvertible iConvert = (IConvertible)(int64A);
object objA = iConvert.ToType(typeof(Int32), provider);
TestLibrary.TestFramework.LogError("N001", "The current Int64 out of the range of Type which IConverted to but not throw exception");
retVal = false;
}
catch (OverflowException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2:The current Int64 out of the range of Type which IConverted to 2");
try
{
long int64A = Int64.MaxValue;
IConvertible iConvert = (IConvertible)(int64A);
object objA = iConvert.ToType(typeof(Int32), null);
TestLibrary.TestFramework.LogError("N003", "The current Int64 out of the range of Type which IConverted to but not throw exception");
retVal = false;
}
catch (OverflowException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3:The current Int64 can not IConvertibleTo the Type");
try
{
long int64A = Int64.MaxValue;
IConvertible iConvert = (IConvertible)(int64A);
object objA = iConvert.ToType(typeof(DateTime), null);
TestLibrary.TestFramework.LogError("N005", "The current Int64 can not IConvertibleTo the Type but not throw exception");
retVal = false;
}
catch (InvalidCastException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region HelpMethod
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
#endregion
}
| |
//
// Symbols.cs
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2011 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Runtime.InteropServices;
using SR = System.Reflection;
using Mono.Collections.Generic;
namespace Mono.Cecil.Cil {
[StructLayout (LayoutKind.Sequential)]
public struct ImageDebugDirectory {
public int Characteristics;
public int TimeDateStamp;
public short MajorVersion;
public short MinorVersion;
public int Type;
public int SizeOfData;
public int AddressOfRawData;
public int PointerToRawData;
}
public sealed class Scope : IVariableDefinitionProvider {
Instruction start;
Instruction end;
Collection<Scope> scopes;
Collection<VariableDefinition> variables;
public Instruction Start {
get { return start; }
set { start = value; }
}
public Instruction End {
get { return end; }
set { end = value; }
}
public bool HasScopes {
get { return !Mixin.IsNullOrEmpty (scopes); }
}
public Collection<Scope> Scopes {
get {
if (scopes == null)
scopes = new Collection<Scope> ();
return scopes;
}
}
public bool HasVariables {
get { return !Mixin.IsNullOrEmpty (variables); }
}
public Collection<VariableDefinition> Variables {
get {
if (variables == null)
variables = new Collection<VariableDefinition> ();
return variables;
}
}
}
public struct InstructionSymbol {
public readonly int Offset;
public readonly SequencePoint SequencePoint;
public InstructionSymbol (int offset, SequencePoint sequencePoint)
{
this.Offset = offset;
this.SequencePoint = sequencePoint;
}
}
public sealed class MethodSymbols {
internal int code_size;
internal string method_name;
internal MetadataToken method_token;
internal MetadataToken local_var_token;
internal Collection<VariableDefinition> variables;
public Collection<InstructionSymbol> instructions;
public bool HasVariables {
get { return !Mixin.IsNullOrEmpty (variables); }
}
public Collection<VariableDefinition> Variables {
get {
if (variables == null)
variables = new Collection<VariableDefinition> ();
return variables;
}
}
public Collection<InstructionSymbol> Instructions {
get {
if (instructions == null)
instructions = new Collection<InstructionSymbol> ();
return instructions;
}
}
public int CodeSize {
get { return code_size; }
}
public string MethodName {
get { return method_name; }
}
public MetadataToken MethodToken {
get { return method_token; }
}
public MetadataToken LocalVarToken {
get { return local_var_token; }
}
internal MethodSymbols (string methodName)
{
this.method_name = methodName;
}
public MethodSymbols (MetadataToken methodToken)
{
this.method_token = methodToken;
}
}
public delegate Instruction InstructionMapper (int offset);
public interface ISymbolReader : IDisposable {
bool ProcessDebugHeader (ImageDebugDirectory directory, byte [] header);
void Read (MethodBody body, InstructionMapper mapper);
void Read (MethodSymbols symbols);
}
public interface ISymbolReaderProvider {
ISymbolReader GetSymbolReader (ModuleDefinition module, string fileName);
ISymbolReader GetSymbolReader (ModuleDefinition module, Stream symbolStream);
}
static class SymbolProvider {
static readonly string symbol_kind = Type.GetType ("Mono.Runtime") != null ? "Mdb" : "Pdb";
static SR.AssemblyName GetPlatformSymbolAssemblyName ()
{
var cecil_name = typeof (SymbolProvider).Assembly.GetName ();
var name = new SR.AssemblyName {
Name = "Mono.Cecil." + symbol_kind,
Version = cecil_name.Version,
};
name.SetPublicKeyToken (cecil_name.GetPublicKeyToken ());
return name;
}
static Type GetPlatformType (string fullname)
{
var type = Type.GetType (fullname);
if (type != null)
return type;
var assembly_name = GetPlatformSymbolAssemblyName ();
type = Type.GetType (fullname + ", " + assembly_name.FullName);
if (type != null)
return type;
try {
var assembly = SR.Assembly.Load (assembly_name);
if (assembly != null)
return assembly.GetType (fullname);
} catch (FileNotFoundException) {
}
return null;
}
static ISymbolReaderProvider reader_provider;
public static ISymbolReaderProvider GetPlatformReaderProvider ()
{
if (reader_provider != null)
return reader_provider;
var type = GetPlatformType (GetProviderTypeName ("ReaderProvider"));
if (type == null)
return null;
return reader_provider = (ISymbolReaderProvider) Activator.CreateInstance (type);
}
static string GetProviderTypeName (string name)
{
return "Mono.Cecil." + symbol_kind + "." + symbol_kind + name;
}
}
}
| |
//
// ItunesPlayerImportSource.cs
//
// Authors:
// Scott Peterson <[email protected]>
// Alexander Kojevnikov <[email protected]>
//
// Copyright (C) 2007 Scott Peterson
// Copyright (C) 2009 Alexander Kojevnikov
//
// 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.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using Mono.Unix;
using Gtk;
using Hyena;
using Banshee.Base;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.IO;
using Banshee.Library;
using Banshee.Playlist;
using Banshee.ServiceStack;
using Banshee.Sources;
using Banshee.Widgets;
using Hyena.Data.Sqlite;
namespace Banshee.PlayerMigration
{
public sealed class ItunesPlayerImportSource : ThreadPoolImportSource
{
// This is its own class so that we don't always load this stuff into memory
private class ItunesImportData
{
public string library_uri, default_query, local_prefix, fallback_dir;
public string[] query_dirs;
public bool get_ratings, get_stats, get_playlists, user_provided_prefix, empty_library;
public int total_songs, total_processed;
public Dictionary<int, long> track_ids = new Dictionary<int, long> (); // key=itunes_id, value=banshee_id
}
private readonly object mutex = new object ();
private volatile bool ok;
public const string LibraryFilename = "iTunes Music Library.xml";
public override string Name {
get { return Catalog.GetString ("iTunes Media Player"); }
}
public override bool CanImport {
get { return true; }
}
private ItunesImportData data;
protected override bool ConfirmImport ()
{
if (data == null) {
data = new ItunesImportData ();
var dialog = new ItunesImportDialog ();
if (!HandleImportDialog (dialog, delegate { data.library_uri = dialog.LibraryUri; })) {
data = null;
return false;
}
}
return true;
}
private delegate void ImportDialogHandler (ItunesImportDialog dialog);
private bool HandleImportDialog (ItunesImportDialog dialog, ImportDialogHandler code)
{
try {
if (dialog.Run () == (int)ResponseType.Ok) {
if(code != null) {
code (dialog);
}
data.get_ratings = dialog.Ratings;
data.get_stats = dialog.Stats;
data.get_playlists = dialog.Playliststs;
} else {
return false;
}
} finally {
dialog.Destroy ();
dialog.Dispose ();
}
if (String.IsNullOrEmpty (data.library_uri)) {
return false;
}
// Make sure the library version is supported (version 1.1)
string message = null;
bool prompt = false;
using (var xml_reader = new XmlTextReader (data.library_uri))
{
xml_reader.ReadToFollowing ("key");
do {
xml_reader.Read ();
string key = xml_reader.ReadContentAsString ();
if (key == "Major Version" || key == "Minor Version") {
xml_reader.Read ();
xml_reader.Read ();
if(xml_reader.ReadContentAsString () != "1") {
message = Catalog.GetString (
"Banshee is not familiar with this version of the iTunes library format." +
" Importing may or may not work as expected, or at all. Would you like to attempt to import anyway?");
prompt = true;
break;
}
}
} while (xml_reader.ReadToNextSibling ("key"));
}
if (prompt) {
bool proceed = false;
using (var message_dialog = new MessageDialog (null, 0, MessageType.Question, ButtonsType.YesNo, message)) {
if (message_dialog.Run () == (int)ResponseType.Yes) {
proceed = true;
}
message_dialog.Destroy ();
}
if (!proceed) {
LogError (data.library_uri, "Unsupported version");
return false;
}
}
return true;
}
protected override void ImportCore ()
{
try {
CountSongs ();
data.empty_library = ServiceManager.SourceManager.MusicLibrary.TrackModel.Count == 0;
var import_manager = ServiceManager.Get<LibraryImportManager> ();
using (var xml_reader = new XmlTextReader (data.library_uri)) {
ProcessLibraryXml (import_manager, xml_reader);
}
import_manager.NotifyAllSources ();
} finally {
data = null;
}
}
private void CountSongs ()
{
using (var xml_reader = new XmlTextReader (data.library_uri)) {
xml_reader.ReadToDescendant("dict");
xml_reader.ReadToDescendant("dict");
xml_reader.ReadToDescendant("dict");
do {
data.total_songs++;
} while (xml_reader.ReadToNextSibling ("dict"));
}
}
private void ProcessLibraryXml (LibraryImportManager import_manager, XmlReader xml_reader)
{
while (xml_reader.ReadToFollowing ("key") && !CheckForCanceled ()) {
xml_reader.Read ();
string key = xml_reader.ReadContentAsString ();
xml_reader.Read ();
xml_reader.Read ();
switch (key) {
case "Music Folder":
if (!ProcessMusicFolderPath (xml_reader.ReadContentAsString ())) {
return;
}
break;
case "Tracks":
ProcessSongs (import_manager, xml_reader.ReadSubtree ());
break;
case "Playlists":
if (data.get_playlists) {
ProcessPlaylists (xml_reader.ReadSubtree ());
}
break;
}
}
}
private bool ProcessMusicFolderPath(string path)
{
string[] itunes_music_uri_parts = ConvertToLocalUriFormat (path).Split (Path.DirectorySeparatorChar);
string[] library_uri_parts = Path.GetDirectoryName (data.library_uri).Split (Path.DirectorySeparatorChar);
string itunes_dir_name = library_uri_parts[library_uri_parts.Length - 1];
int i = 0;
bool found = false;
for (i = itunes_music_uri_parts.Length - 1; i >= 0; i--) {
if (itunes_music_uri_parts[i] == itunes_dir_name) {
found = true;
break;
}
}
if (!found) {
var builder = new StringBuilder (path.Length - 17);
for (int j = 3; j < itunes_music_uri_parts.Length; j++) {
string part = itunes_music_uri_parts[j];
builder.Append (part);
if (part.Length > 0) {
builder.Append (Path.DirectorySeparatorChar);
}
}
string local_path = builder.ToString ();
System.Threading.Monitor.Enter (mutex);
ThreadAssist.ProxyToMain (delegate {
System.Threading.Monitor.Enter (mutex);
using (var dialog = new ItunesMusicDirectoryDialog (local_path)) {
if (dialog.Run () == (int)ResponseType.Ok) {
data.local_prefix = dialog.UserMusicDirectory;
data.user_provided_prefix = true;
data.default_query = local_path;
ok = true;
} else {
ok = false;
}
dialog.Destroy ();
System.Threading.Monitor.Pulse (mutex);
System.Threading.Monitor.Exit (mutex);
}
});
System.Threading.Monitor.Wait (mutex);
System.Threading.Monitor.Exit (mutex);
if (ok) {
return true;
} else {
LogError (data.library_uri, "Unable to locate iTunes directory from iTunes URI");
return false;
}
}
string[] tmp_query_dirs = new string[itunes_music_uri_parts.Length];
string upstream_uri;
string tmp_upstream_uri = null;
int step = 0;
string root = Path.GetPathRoot (data.library_uri);
bool same_root = library_uri_parts[0] == root.Split (Path.DirectorySeparatorChar)[0];
do {
upstream_uri = tmp_upstream_uri;
tmp_upstream_uri = root;
for (int j = same_root ? 1 : 0; j < library_uri_parts.Length - step - 1; j++) {
tmp_upstream_uri = Path.Combine (tmp_upstream_uri, library_uri_parts[j]);
}
tmp_upstream_uri = Path.Combine (tmp_upstream_uri, itunes_music_uri_parts[i - step]);
data.fallback_dir = tmp_query_dirs[step] = itunes_music_uri_parts[i - step];
step++;
} while (Banshee.IO.Directory.Exists (tmp_upstream_uri));
if (upstream_uri == null) {
LogError (data.library_uri, "Unable to resolve iTunes URIs to local URIs");
return false;
}
data.query_dirs = new string[step - 2];
data.default_query = string.Empty;
for (int j = step - 2; j >= 0; j--) {
if (j > 0) {
data.query_dirs[j - 1] = tmp_query_dirs[j];
}
data.default_query += tmp_query_dirs[j] + Path.DirectorySeparatorChar;
}
data.local_prefix = string.Empty;
for (int j = 0; j <= library_uri_parts.Length - step; j++) {
data.local_prefix += library_uri_parts[j] + Path.DirectorySeparatorChar;
}
return true;
}
private void ProcessSongs (LibraryImportManager import_manager, XmlReader xml_reader)
{
using (xml_reader) {
xml_reader.ReadToFollowing ("dict");
while (xml_reader.ReadToFollowing ("dict") && !CheckForCanceled ()) {
ProcessSong (import_manager, xml_reader.ReadSubtree ());
}
}
}
private void ProcessPlaylists (XmlReader xml_reader)
{
using (xml_reader) {
while(xml_reader.ReadToFollowing ("dict") && !CheckForCanceled ()) {
ProcessPlaylist (xml_reader.ReadSubtree ());
}
}
}
private void ProcessSong (LibraryImportManager import_manager, XmlReader xml_reader)
{
data.total_processed++;
var itunes_id = 0;
var title = String.Empty;
var title_sort = String.Empty;
var genre = String.Empty;
var artist = String.Empty;
var artist_sort = String.Empty;
var album_artist = String.Empty;
var album_artist_sort = String.Empty;
var composer = String.Empty;
var album = String.Empty;
var album_sort = String.Empty;
var grouping = String.Empty;
var year = 0;
var rating = 0;
var play_count = 0;
var track_number = 0;
var date_added = DateTime.Now;
var last_played = DateTime.MinValue;
SafeUri uri = null;
using (xml_reader) {
while (xml_reader.ReadToFollowing ("key")) {
xml_reader.Read();
string key = xml_reader.ReadContentAsString ();
xml_reader.Read ();
xml_reader.Read ();
try {
switch (key) {
case "Track ID":
itunes_id = Int32.Parse (xml_reader.ReadContentAsString ());
break;
case "Name":
title = xml_reader.ReadContentAsString ();
break;
case "Sort Name":
title_sort = xml_reader.ReadContentAsString ();
break;
case "Genre":
genre = xml_reader.ReadContentAsString ();
break;
case "Artist":
artist = xml_reader.ReadContentAsString ();
break;
case "Sort Artist":
artist_sort = xml_reader.ReadContentAsString ();
break;
case "Album Artist":
album_artist = xml_reader.ReadContentAsString ();
break;
case "Sort Album Artist":
album_artist_sort = xml_reader.ReadContentAsString ();
break;
case "Composer":
composer = xml_reader.ReadContentAsString ();
break;
case "Album":
album = xml_reader.ReadContentAsString ();
break;
case "Sort Album":
album_sort = xml_reader.ReadContentAsString ();
break;
case "Grouping":
grouping = xml_reader.ReadContentAsString ();
break;
case "Year":
year = Int32.Parse (xml_reader.ReadContentAsString ());
break;
case "Rating":
rating = Int32.Parse (xml_reader.ReadContentAsString ()) / 20;
break;
case "Play Count":
play_count = Int32.Parse (xml_reader.ReadContentAsString ());
break;
case "Track Number":
track_number = Int32.Parse (xml_reader.ReadContentAsString ());
break;
case "Date Added":
date_added = DateTime.Parse (xml_reader.ReadContentAsString (),
DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal);
break;
case "Play Date UTC":
last_played = DateTime.Parse (xml_reader.ReadContentAsString (),
DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal);
break;
case "Location":
uri = ConvertToLocalUri (xml_reader.ReadContentAsString ());
break;
}
} catch {
}
}
}
if (uri == null) {
return;
}
UpdateUserJob (data.total_processed, data.total_songs, artist, title);
try {
DatabaseTrackInfo track = import_manager.ImportTrack (uri);
if (track == null) {
LogError (SafeUri.UriToFilename (uri), Catalog.GetString ("Unable to import song."));
return;
}
if (!String.IsNullOrEmpty (title)) {
track.TrackTitle = title;
}
if (!String.IsNullOrEmpty (title_sort)) {
track.TrackTitleSort = title_sort;
}
if (!String.IsNullOrEmpty (artist)) {
track.ArtistName = artist;
}
if (!String.IsNullOrEmpty (artist_sort)) {
track.ArtistNameSort = artist_sort;
}
if (!String.IsNullOrEmpty (genre)) {
track.Genre = genre;
}
if (!String.IsNullOrEmpty (album_artist)) {
track.AlbumArtist = album_artist;
}
if (!String.IsNullOrEmpty (album_artist_sort)) {
track.AlbumArtistSort = album_artist_sort;
}
if (!String.IsNullOrEmpty (composer)) {
track.Composer = composer;
}
if (!String.IsNullOrEmpty (album)) {
track.AlbumTitle = album;
}
if (!String.IsNullOrEmpty (album_sort)) {
track.AlbumTitleSort = album_sort;
}
if (!String.IsNullOrEmpty (grouping)) {
track.Grouping = grouping;
}
if (year > 0) {
track.Year = year;
}
if (data.get_ratings && rating > 0 && rating <= 5) {
track.Rating = rating;
}
if (data.get_stats && play_count > 0) {
track.PlayCount = play_count;
}
if (track_number > 0) {
track.TrackNumber = track_number;
}
if (data.get_stats) {
track.DateAdded = date_added;
}
if (data.get_stats && last_played > DateTime.MinValue) {
track.LastPlayed = last_played;
}
data.track_ids.Add (itunes_id, track.TrackId);
track.Save (false);
} catch (Exception e) {
LogError (SafeUri.UriToFilename (uri), e);
}
}
private void ProcessPlaylist (XmlReader xml_reader)
{
string name = string.Empty;
bool skip = false;
bool processed = false;
using (xml_reader) {
while (xml_reader.ReadToFollowing ("key")) {
xml_reader.Read ();
string key = xml_reader.ReadContentAsString ();
xml_reader.Read ();
switch (key) {
case "Name":
xml_reader.Read ();
name = xml_reader.ReadContentAsString ();
if (name == "Library" ||
name == "Music Videos" ||
name == "Audiobooks" ||
name == "Music" ||
name == "Movies" ||
name == "Party Shuffle" ||
name == "Podcasts" ||
name == "Party Shuffle" ||
name == "Purchased Music" ||
name == "Genius" ||
name == "TV Shows") {
skip = true;
}
break;
case "Smart Info":
skip = true;
break;
case "Smart Criteria":
skip = true;
break;
case "Playlist Items":
xml_reader.Read ();
if(!skip) {
ProcessPlaylist (name, xml_reader.ReadSubtree ());
processed = true;
}
break;
}
}
}
// Empty playlist
if (!processed && !skip) {
ProcessPlaylist (name, null);
}
}
private void ProcessPlaylist (string name, XmlReader xml_reader)
{
UpdateUserJob (1, 1, Catalog.GetString("Playlists"), name);
ProcessRegularPlaylist (name, xml_reader);
if (xml_reader != null) {
xml_reader.Close ();
}
}
private void ProcessRegularPlaylist (string name, XmlReader xml_reader)
{
var playlist_source = new PlaylistSource (name, ServiceManager.SourceManager.MusicLibrary);
playlist_source.Save ();
ServiceManager.SourceManager.MusicLibrary.AddChildSource (playlist_source);
// Get the songs in the playlists
if (xml_reader != null) {
while (xml_reader.ReadToFollowing ("integer") && !CheckForCanceled ()) {
xml_reader.Read ();
int itunes_id = Int32.Parse (xml_reader.ReadContentAsString ());
long track_id;
if (data.track_ids.TryGetValue (itunes_id, out track_id)) {
try {
ServiceManager.DbConnection.Execute (
"INSERT INTO CorePlaylistEntries (PlaylistID, TrackID) VALUES (?, ?)",
playlist_source.DbId, track_id);
} catch {
}
}
}
playlist_source.Reload ();
playlist_source.NotifyUser ();
}
}
private SafeUri ConvertToLocalUri (string raw_uri)
{
if (raw_uri == null) {
return null;
}
string uri = ConvertToLocalUriFormat (raw_uri);
int index = uri.IndexOf (data.default_query);
if (data.user_provided_prefix && index != -1) {
index += data.default_query.Length;
} else if (index == -1 && data.query_dirs.Length > 0) {
int count = 0;
string path = data.query_dirs[data.query_dirs.Length - 1];
do {
for (int k = data.query_dirs.Length - 2; k >= count; k--) {
path = Path.Combine (path, data.query_dirs[k]);
}
index = uri.IndexOf (path);
count++;
} while(index == -1 && count < data.query_dirs.Length);
if (index == -1) {
index = uri.IndexOf(data.fallback_dir);
if (index != -1) {
index += data.fallback_dir.Length + 1;
}
}
}
if (index == -1) {
if (data.empty_library) {
LogError (uri, "Unable to map iTunes URI to local URI");
}
return null;
}
SafeUri safe_uri = CreateSafeUri (Path.Combine(
data.local_prefix, uri.Substring (index, uri.Length - index)), data.empty_library);
if (safe_uri == null && !data.empty_library) {
string local_uri = string.Empty;
string lower_uri = raw_uri.ToLower (CultureInfo.InvariantCulture);
int i = lower_uri.Length;
while (true) {
i = lower_uri.LastIndexOf (Path.DirectorySeparatorChar, i - 1);
if (i == -1) {
break;
}
try {
using (var reader = ServiceManager.DbConnection.Query (String.Format (
@"SELECT Uri FROM CoreTracks WHERE lower(Uri) LIKE ""%{0}""", lower_uri.Substring (i + 1)))) {
bool found = false;
local_uri = string.Empty;
while (reader.Read ()) {
if (found) {
local_uri = string.Empty;
break;
}
found = true;
local_uri = (string)reader[0];
}
if (!found || local_uri.Length > 0) {
break;
}
}
} catch {
break;
}
}
if (local_uri.Length > 0) {
safe_uri = CreateSafeUri (local_uri, true);
} else {
LogError (uri, "Unable to map iTunes URI to local URI");
}
}
return safe_uri;
}
private SafeUri CreateSafeUri (string uri, bool complain)
{
SafeUri safe_uri;
try {
safe_uri = new SafeUri (uri);
} catch {
if (complain) {
LogError (uri, "URI is not a local file path");
}
return null;
}
safe_uri = FindFile (safe_uri);
if (safe_uri == null) {
if (complain) {
LogError (uri, "File does not exist");
}
return null;
}
return safe_uri;
}
// URIs are UTF-8 percent-encoded. Deconding with System.Web.HttpServerUtility
// involves too much overhead, so we do it cheap here.
private static string ConvertToLocalUriFormat (string input)
{
var builder = new StringBuilder (input.Length);
byte[] buffer = new byte[2];
bool using_buffer = false;
for (int i = 0; i < input.Length; i++) {
// If it's a '%', treat the two subsiquent characters as a UTF-8 byte in hex.
if (input[i] == '%') {
byte code = Byte.Parse (input.Substring(i + 1, 2),
System.Globalization.NumberStyles.HexNumber);
// If it's a non-ascii character, or there are already some non-ascii
// characters in the buffer, then queue it for UTF-8 decoding.
if (using_buffer || (code & 0x80) != 0) {
if (using_buffer) {
if (buffer[1] == 0) {
buffer[1] = code;
} else {
byte[] new_buffer = new byte[buffer.Length + 1];
for (int j = 0; j < buffer.Length; j++) {
new_buffer[j] = buffer[j];
}
buffer = new_buffer;
buffer[buffer.Length - 1] = code;
}
} else {
buffer[0] = code;
using_buffer = true;
}
}
// If it's a lone ascii character, there's no need for fancy UTF-8 decoding.
else {
builder.Append ((char)code);
}
i += 2;
} else {
// If we have something in the buffer, decode it.
if (using_buffer) {
builder.Append (Encoding.UTF8.GetString (buffer));
if (buffer.Length > 2) {
buffer = new byte[2];
} else {
buffer[1] = 0;
}
using_buffer = false;
}
// And add our regular characters and convert to local directory separator char.
if (input[i] == '/') {
builder.Append (Path.DirectorySeparatorChar);
} else {
builder.Append (input[i]);
}
}
}
return builder.ToString ();
}
private static SafeUri FindFile (SafeUri uri)
{
// URIs kept by iTunes often contain characters in a case different from the actual
// files and directories. This method tries to find the real file URI.
if (Banshee.IO.File.Exists (uri)) {
return uri;
}
string path = uri.AbsolutePath;
string file = Path.GetFileName (path);
string directory = Path.GetDirectoryName (path);
directory = FindDirectory (directory);
if (directory == null) {
return null;
}
uri = new SafeUri (Path.Combine (directory, file), false);
if (Banshee.IO.File.Exists (uri)) {
return uri;
}
foreach (string item in Banshee.IO.Directory.GetFiles (directory)) {
string name = Path.GetFileName (item);
if (0 != String.Compare (file, name, true)) {
continue;
}
return new SafeUri (Path.Combine (directory, name), false);
}
return null;
}
private static string FindDirectory (string directory)
{
if (Banshee.IO.Directory.Exists (directory)) {
return directory;
}
string current = Path.GetFileName (directory);
directory = Path.GetDirectoryName (directory);
if (String.IsNullOrEmpty (directory)) {
return null;
}
directory = FindDirectory (directory);
if (String.IsNullOrEmpty (directory)) {
return null;
}
foreach (string item in Banshee.IO.Directory.GetDirectories (directory)) {
string name = Path.GetFileName (item);
if (0 != String.Compare (current, name, true)) {
continue;
}
return Path.Combine (directory, name);
}
return null;
}
public override string [] IconNames {
get { return new string [] { "itunes", "system-search" }; }
}
public override int SortOrder {
get { return 40; }
}
}
}
| |
// 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.Collections.Generic;
using System.Reflection;
using Gallio.Common.Collections;
using Gallio.Common;
namespace Gallio.Common.Reflection.Impl
{
/// <summary>
/// A <see cref="StaticReflectionPolicy"/> method wrapper.
/// </summary>
public sealed class StaticMethodWrapper : StaticFunctionWrapper, IMethodInfo
{
private Memoizer<IList<ITypeInfo>> genericArgumentsMemoizer = new Memoizer<IList<ITypeInfo>>();
private Memoizer<IList<StaticGenericParameterWrapper>> genericParametersMemoizer = new Memoizer<IList<StaticGenericParameterWrapper>>();
private Memoizer<IParameterInfo> returnParameterMemoizer = new Memoizer<IParameterInfo>();
private Memoizer<StaticMethodWrapper> genericMethodDefinitionMemoizer = new Memoizer<StaticMethodWrapper>();
private Memoizer<MethodInfo> resolveMemoizer = new Memoizer<MethodInfo>();
private readonly StaticTypeSubstitution substitution;
/// <summary>
/// Creates a wrapper.
/// </summary>
/// <param name="policy">The reflection policy.</param>
/// <param name="handle">The underlying reflection object.</param>
/// <param name="declaringType">The declaring type.</param>
/// <param name="reflectedType">The reflected type.</param>
/// <param name="substitution">The type substitution for generic parameters.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="policy"/>, <paramref name="handle"/>,
/// or <paramref name="declaringType"/> or <paramref name="reflectedType"/> is null.</exception>
public StaticMethodWrapper(StaticReflectionPolicy policy, object handle, StaticDeclaredTypeWrapper declaringType,
StaticDeclaredTypeWrapper reflectedType, StaticTypeSubstitution substitution)
: base(policy, handle, declaringType, reflectedType)
{
this.substitution = substitution;
}
/// <inheritdoc />
public override StaticTypeSubstitution Substitution
{
get { return substitution; }
}
/// <inheritdoc />
public override CodeElementKind Kind
{
get { return CodeElementKind.Method; }
}
/// <inheritdoc />
public bool IsGenericMethod
{
get { return GenericParameters.Count != 0; }
}
/// <inheritdoc />
public bool IsGenericMethodDefinition
{
get
{
IList<StaticGenericParameterWrapper> genericParameters = GenericParameters;
return genericParameters.Count != 0 && Substitution.DoesNotContainAny(genericParameters);
}
}
/// <inheritdoc />
public bool ContainsGenericParameters
{
get
{
foreach (ITypeInfo type in GenericArguments)
if (type.ContainsGenericParameters)
return true;
return DeclaringType.ContainsGenericParameters;
}
}
/// <inheritdoc />
public IList<ITypeInfo> GenericArguments
{
get
{
return genericArgumentsMemoizer.Memoize(delegate
{
return Substitution.ApplyAll(GenericParameters);
});
}
}
/// <inheritdoc cref="IMethodInfo.GenericMethodDefinition" />
public StaticMethodWrapper GenericMethodDefinition
{
get
{
return genericMethodDefinitionMemoizer.Memoize(() =>
{
if (!IsGenericMethod)
return null;
if (IsGenericMethodDefinition)
return this;
return new StaticMethodWrapper(ReflectionPolicy, Handle, DeclaringType, ReflectedType,
DeclaringType.Substitution);
});
}
}
IMethodInfo IMethodInfo.GenericMethodDefinition
{
get { return GenericMethodDefinition; }
}
/// <inheritdoc />
public ITypeInfo ReturnType
{
get { return ReturnParameter.ValueType; }
}
/// <inheritdoc />
public IParameterInfo ReturnParameter
{
get
{
return returnParameterMemoizer.Memoize(delegate
{
return ReflectionPolicy.GetMethodReturnParameter(this);
});
}
}
/// <summary>
/// Returns true if this method overrides another.
/// </summary>
public bool IsOverride
{
get { return (MethodAttributes & (MethodAttributes.Virtual | MethodAttributes.NewSlot)) == MethodAttributes.Virtual; }
}
/// <summary>
/// Gets the methods that this one overrides or hides.
/// Only includes overrides that appear on class types, not interfaces.
/// </summary>
/// <param name="overridesOnly">If true, only returns overrides.</param>
public IEnumerable<StaticMethodWrapper> GetOverridenOrHiddenMethods(bool overridesOnly)
{
if (overridesOnly && !IsOverride)
yield break;
foreach (StaticDeclaredTypeWrapper baseType in DeclaringType.GetAllBaseTypes())
{
foreach (StaticMethodWrapper other in ReflectionPolicy.GetTypeMethods(baseType, ReflectedType))
{
if (HidesMethod(other))
{
yield return other;
if (overridesOnly && !other.IsOverride)
yield break;
break;
}
}
}
}
/// <summary>
/// Returns true if this method hides the specified method.
/// </summary>
/// <remarks>
/// <para>
/// This method assumes that <paramref name="other"/> is defined by
/// a base type of this method's declaring type. It determines whether
/// method hiding has taken place based on the method's name and its signature
/// (when IsHideBySig is true).
/// </para>
/// </remarks>
/// <param name="other">The other method.</param>
/// <returns>True if this method hides the other method.</returns>
public bool HidesMethod(StaticMethodWrapper other)
{
if (Name != other.Name)
return false;
if (! IsHideBySig)
return true;
if (GenericArguments.Count != other.GenericArguments.Count)
return false;
if (IsGenericMethod)
{
IList<StaticGenericParameterWrapper> genericParameters = GenericParameters;
IList<StaticGenericParameterWrapper> otherGenericParameters = other.GenericParameters;
if (genericParameters.Count != otherGenericParameters.Count)
return false;
// Note: We perform a substitution on the method parameters to ensure that the
// same generic parameter references are used for both. Any generic method
// parameter references that appear in the signature should thus be directly comparable.
return CompareSignatures(GenericMethodDefinition,
other.GenericMethodDefinition.MakeGenericMethod(
new CovariantList<StaticGenericParameterWrapper, ITypeInfo>(genericParameters)));
}
if (other.IsGenericMethod)
return false;
return CompareSignatures(this, other);
}
private static bool CompareSignatures(IMethodInfo a, IMethodInfo b)
{
IList<IParameterInfo> aParameters = a.Parameters;
IList<IParameterInfo> bParameters = b.Parameters;
int parameterCount = aParameters.Count;
if (parameterCount != bParameters.Count)
return false;
for (int i = 0; i < parameterCount; i++)
{
if (!aParameters[i].ValueType.Equals(bParameters[i].ValueType))
return false;
}
return true;
}
/// <inheritdoc cref="IMethodInfo.MakeGenericMethod" />
public StaticMethodWrapper MakeGenericMethod(IList<ITypeInfo> genericArguments)
{
if (!IsGenericMethodDefinition)
throw new InvalidOperationException("The method is not a generic method definition.");
return new StaticMethodWrapper(ReflectionPolicy, Handle, DeclaringType, ReflectedType, Substitution.Extend(GenericParameters, genericArguments));
}
IMethodInfo IMethodInfo.MakeGenericMethod(IList<ITypeInfo> genericArguments)
{
return MakeGenericMethod(genericArguments);
}
/// <inheritdoc />
public MethodInfo Resolve(bool throwOnError)
{
return resolveMemoizer.Memoize(() => ReflectorResolveUtils.ResolveMethod(this, throwOnError));
}
/// <inheritdoc />
protected override MethodBase ResolveMethodBase(bool throwOnError)
{
return Resolve(throwOnError);
}
/// <inheritdoc />
public override string ToString()
{
return ToString(ReturnType, GenericArguments);
}
/// <excludedoc />
protected override IEnumerable<ICodeElementInfo> GetInheritedElements()
{
foreach (StaticMethodWrapper element in GetOverridenOrHiddenMethods(true))
yield return element;
}
/// <excludedoc />
protected override IEnumerable<Attribute> GetPseudoCustomAttributes()
{
// TODO: Handle DllImport, PreserveSig and code access security.
return EmptyArray<Attribute>.Instance;
}
private IList<StaticGenericParameterWrapper> GenericParameters
{
get
{
return genericParametersMemoizer.Memoize(delegate
{
return ReflectionPolicy.GetMethodGenericParameters(this);
});
}
}
}
}
| |
// RemoteZipFile.cs
// Copyright (C) 2003 Emanuele Ruffaldi
//
// ZipEntry parsing code taken from ZipFile.cs in SharpLibZip
// Copyright (C) 2001 Mike Krueger
//
// The original SharpLibZip code was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using System.Net;
using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.BZip2;
using System.Collections;
using System.IO;
using System.Text;
namespace RemoteZip
{
/// <summary>
/// Summary description for ZipDownloader.
/// </summary>
public class RemoteZipFile : IEnumerable
{
ZipEntry [] entries;
string baseUrl;
int MaxFileOffset;
public RemoteZipFile()
{
}
/*
end of central dir signature 4 bytes (0x06054b50)
number of this disk 2 bytes
number of the disk with the start of the central directory 2 bytes
total number of entries in the central directory on this disk 2 bytes
total number of entries in the central directory 2 bytes
size of the central directory 4 bytes
offset of start of central directory
with respect to the starting disk number 4 bytes
.ZIP file comment length 2 bytes
.ZIP file comment (variable size)
*/
/// <summary>
/// TODO: case when the whole file is smaller than 64K
/// TODO: handle non HTTP case
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public bool Load(string url)
{
int CentralOffset, CentralSize;
int TotalEntries;
if(!FindCentralDirectory(url, out CentralOffset, out CentralSize, out TotalEntries))
return false;
MaxFileOffset = CentralOffset;
// now retrieve the Central Directory
baseUrl = url;
entries = new ZipEntry[TotalEntries];
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.AddRange(CentralOffset, CentralOffset+CentralSize);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
Stream s = res.GetResponseStream();
try
{
// code taken from SharpZipLib with modification for not seekable stream
// and adjustement for Central Directory entry
for (int i = 0; i < TotalEntries; i++)
{
if (ReadLeInt(s) != ZipConstants.CentralHeaderSignature)
{
throw new ZipException("Wrong Central Directory signature");
}
// skip 6 bytes: version made (W), version ext (W), flags (W)
ReadLeInt(s);
ReadLeShort(s);
int method = ReadLeShort(s);
int dostime = ReadLeInt(s);
int crc = ReadLeInt(s);
int csize = ReadLeInt(s);
int size = ReadLeInt(s);
int nameLen = ReadLeShort(s);
int extraLen = ReadLeShort(s);
int commentLen = ReadLeShort(s);
// skip 8 bytes: disk number start, internal file attribs, external file attribs (DW)
ReadLeInt(s);
ReadLeInt(s);
int offset = ReadLeInt(s);
byte[] buffer = new byte[Math.Max(nameLen, commentLen)];
ReadAll(buffer, 0, nameLen, s);
string name = ZipConstants.ConvertToString(buffer);
ZipEntry entry = new ZipEntry(name);
entry.CompressionMethod = (CompressionMethod)method;
entry.Crc = crc & 0xffffffffL;
entry.Size = size & 0xffffffffL;
entry.CompressedSize = csize & 0xffffffffL;
entry.DosTime = (uint)dostime;
if (extraLen > 0)
{
byte[] extra = new byte[extraLen];
ReadAll(extra, 0, extraLen, s);
entry.ExtraData = extra;
}
if (commentLen > 0)
{
ReadAll(buffer, 0, commentLen, s);
entry.Comment = ZipConstants.ConvertToString(buffer);
}
entry.ZipFileIndex = i;
entry.Offset = offset;
entries[i] = entry;
OnProgress((i*100)/TotalEntries);
}
}
finally
{
s.Close();
res.Close();
}
OnProgress(100);
return true;
}
/// <summary>
/// OnProgress during Central Header loading
/// </summary>
/// <param name="pct"></param>
public virtual void OnProgress(int pct)
{
}
/// <summary>
/// Checks if there is a local header at the current position in the stream and skips it
/// </summary>
/// <param name="baseStream"></param>
/// <param name="entry"></param>
void SkipLocalHeader(Stream baseStream, ZipEntry entry)
{
lock(baseStream)
{
if (ReadLeInt(baseStream) != ZipConstants.LocalHeaderSignature)
{
throw new ZipException("Wrong Local header signature");
}
Skip(baseStream, 10+12);
int namelen = ReadLeShort(baseStream);
int extralen = ReadLeShort(baseStream);
Skip(baseStream, namelen+extralen);
}
}
/// <summary>
/// Finds the Central Header in the Zip file. We can minimize the number of requests and
/// the bytes taken
///
/// Actually we do: 256, 1024, 65536
/// </summary>
/// <param name="baseurl"></param>
/// <returns></returns>
bool FindCentralDirectory(string url, out int Offset, out int Size, out int Entries)
{
int currentLength = 256;
Entries = 0;
Size = 0;
Offset = -1;
while(true)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.AddRange(-(currentLength + 22));
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
// copy the buffer because we need a back seekable buffer
byte [] bb = new byte[res.ContentLength];
int endSize = ReadAll(bb, 0, (int)res.ContentLength, res.GetResponseStream());
res.Close();
// scan for the central block. The position of the central block
// is end-comment-22
//<
// 50 4B 05 06
int pos = endSize-22;
// int state = 0;
while(pos >= 0)
{
if(bb[pos] == 0x50)
{
if(bb[pos+1] == 0x4b && bb[pos+2] == 0x05 && bb[pos+3] == 0x06)
break; // found!!
pos -= 4;
}
else
pos --;
}
if(pos < 0)
{
if(currentLength == 65536)
break;
if(currentLength == 1024)
currentLength = 65536;
else if(currentLength == 256)
currentLength = 1024;
else
break;
}
else
{
// found it!! so at offset pos+3*4 there is Size, and pos+4*4
// BinaryReader is so elegant but now it's too much
Size = MakeInt(bb, pos+12);
Offset = MakeInt(bb, pos+16);
Entries = MakeShort(bb, pos+10);
return true;
}
}
return false;
}
/// <summary>
/// Get a Stream for reading the specified entry
/// </summary>
/// <param name="entry"></param>
/// <returns></returns>
public Stream GetInputStream(ZipEntry entry)
{
if(entry.Size == 0)
return null;
if (entries == null)
{
throw new InvalidOperationException("ZipFile has closed");
}
int index = (int)entry.ZipFileIndex;
if (index < 0 || index >= entries.Length || entries[index].Name != entry.Name)
{
throw new IndexOutOfRangeException();
}
// WARNING
// should parse the Local Header to get the data address
// Maximum Size of the Local Header is ... 16+64K*2
//
// So the HTTP request should ask for the big local header, but actually the
// additional data is not downloaded.
// Optionally use an additional Request to be really precise
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(baseUrl);
int limit = (int)(entry.Offset+entry.CompressedSize+16+65536*2);
if (limit >= MaxFileOffset)
limit = MaxFileOffset-1;
req.AddRange((int)entry.Offset, limit);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
Stream baseStream = res.GetResponseStream();
// skips all the header
SkipLocalHeader(baseStream, entries[index]);
CompressionMethod method = entries[index].CompressionMethod;
Stream istr = new PartialInputStream(baseStream, res, entries[index].CompressedSize);
switch (method)
{
case CompressionMethod.Stored:
return istr;
case CompressionMethod.Deflated:
return new InflaterInputStream(istr, new Inflater(true));
case (CompressionMethod)12:
return new BZip2InputStream(istr);
default:
throw new ZipException("Unknown compression method " + method);
}
}
/// <summary>
/// Read an unsigned short in little endian byte order.
/// </summary>
/// <exception name="System.IO.IOException">
/// if a i/o error occured.
/// </exception>
/// <exception name="System.IO.EndOfStreamException">
/// if the file ends prematurely
/// </exception>
int ReadLeShort(Stream s)
{
return s.ReadByte() | s.ReadByte() << 8;
}
/// <summary>
/// Read an int in little endian byte order.
/// </summary>
/// <exception name="System.IO.IOException">
/// if a i/o error occured.
/// </exception>
/// <exception name="System.IO.EndOfStreamException">
/// if the file ends prematurely
/// </exception>
int ReadLeInt(Stream s)
{
return ReadLeShort(s) | ReadLeShort(s) << 16;
}
static void Skip(Stream s, int n)
{
for(int i = 0; i < n; i++)
s.ReadByte();
}
static int ReadAll(byte [] bb, int p, int sst, Stream s)
{
int ss = 0;
while(ss < sst)
{
int r = s.Read(bb, p, sst-ss);
if(r <= 0)
return ss;
ss += r;
p += r;
}
return ss;
}
public static int MakeInt(byte [] bb, int pos)
{
return bb[pos+0]|(bb[pos+1]<<8)|(bb[pos+2]<<16)|(bb[pos+3]<<24);
}
public static int MakeShort(byte [] bb, int pos)
{
return bb[pos+0]|(bb[pos+1]<<8);
}
public int Size
{
get { return entries == null ? 0 : entries.Length; }
}
/// <summary>
/// Returns an IEnumerator of all Zip entries in this Zip file.
/// </summary>
public IEnumerator GetEnumerator()
{
if (entries == null)
{
throw new InvalidOperationException("ZipFile has closed");
}
return new ZipEntryEnumeration(entries);
}
public ZipEntry this[int index]
{
get { return entries[index]; }
}
class ZipEntryEnumeration : IEnumerator
{
ZipEntry[] array;
int ptr = -1;
public ZipEntryEnumeration(ZipEntry[] arr)
{
array = arr;
}
public object Current
{
get
{
return array[ptr];
}
}
public void Reset()
{
ptr = -1;
}
public bool MoveNext()
{
return (++ptr < array.Length);
}
}
class PartialInputStream : InflaterInputStream
{
Stream baseStream;
long filepos;
long end;
HttpWebResponse request;
public PartialInputStream(Stream baseStream, HttpWebResponse request, long len) : base(baseStream)
{
this.baseStream = baseStream;
filepos = 0;
end = len;
this.request = request;
}
public override int Available
{
get
{
long amount = end - filepos;
if (amount > Int32.MaxValue)
{
return Int32.MaxValue;
}
return (int) amount;
}
}
public override int ReadByte()
{
if (filepos == end)
{
return -1;
}
lock(baseStream)
{
filepos++;
return baseStream.ReadByte();
}
}
public override int Read(byte[] b, int off, int len)
{
if (len > end - filepos)
{
len = (int) (end - filepos);
if (len == 0)
{
return 0;
}
}
lock(baseStream)
{
int count = ReadAll(b, off, len, baseStream);
if (count > 0)
{
filepos += len;
}
return count;
}
}
public long SkipBytes(long amount)
{
if (amount < 0)
{
throw new ArgumentOutOfRangeException();
}
if (amount > end - filepos)
{
amount = end - filepos;
}
filepos += amount;
for(int i = 0; i < amount; i++)
baseStream.ReadByte();
return amount;
}
public override void Close()
{
request.Close();
baseStream.Close();
}
}
}
/// <summary>
/// This is a FilterOutputStream that writes the files into a zip
/// archive one after another. It has a special method to start a new
/// zip entry. The zip entries contains information about the file name
/// size, compressed size, CRC, etc.
///
/// It includes support for STORED and DEFLATED and BZIP2 entries.
/// This class is not thread safe.
///
/// author of the original java version : Jochen Hoenicke
/// </summary>
/// <example> This sample shows how to create a zip file
/// <code>
/// using System;
/// using System.IO;
///
/// using NZlib.Zip;
///
/// class MainClass
/// {
/// public static void Main(string[] args)
/// {
/// string[] filenames = Directory.GetFiles(args[0]);
///
/// ZipOutputStream s = new ZipOutputStream(File.Create(args[1]));
///
/// s.SetLevel(5); // 0 - store only to 9 - means best compression
///
/// foreach (string file in filenames) {
/// FileStream fs = File.OpenRead(file);
///
/// byte[] buffer = new byte[fs.Length];
/// fs.Read(buffer, 0, buffer.Length);
///
/// ZipEntry entry = new ZipEntry(file);
///
/// s.PutNextEntry(entry);
///
/// s.Write(buffer, 0, buffer.Length);
///
/// }
///
/// s.Finish();
/// s.Close();
/// }
/// }
/// </code>
/// </example>
public class ZipOutputStream : DeflaterOutputStream
{
private ArrayList entries = new ArrayList();
private Crc32 crc = new Crc32();
private ZipEntry curEntry = null;
private long startPosition = 0;
private Stream additionalStream = null;
private CompressionMethod curMethod;
private int size;
private int offset = 0;
private byte[] zipComment = new byte[0];
private int defaultMethod = DEFLATED;
/// <summary>
/// Our Zip version is hard coded to 1.0 resp. 2.0
/// </summary>
private const int ZIP_STORED_VERSION = 10;
private const int ZIP_DEFLATED_VERSION = 20;
/// <summary>
/// Compression method. This method doesn't compress at all.
/// </summary>
public const int STORED = 0;
/// <summary>
/// Compression method. This method uses the Deflater.
/// </summary>
public const int DEFLATED = 8;
public const int BZIP2 = 12;
/// <summary>
/// Creates a new Zip output stream, writing a zip archive.
/// </summary>
/// <param name="baseOutputStream">
/// the output stream to which the zip archive is written.
/// </param>
public ZipOutputStream(Stream baseOutputStream) : base(baseOutputStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true))
{
}
/// <summary>
/// Set the zip file comment.
/// </summary>
/// <param name="comment">
/// the comment.
/// </param>
/// <exception name ="ArgumentException">
/// if UTF8 encoding of comment is longer than 0xffff bytes.
/// </exception>
public void SetComment(string comment)
{
byte[] commentBytes = ZipConstants.ConvertToArray(comment);
if (commentBytes.Length > 0xffff)
{
throw new ArgumentException("Comment too long.");
}
zipComment = commentBytes;
}
/// <summary>
/// Sets default compression method. If the Zip entry specifies
/// another method its method takes precedence.
/// </summary>
/// <param name = "method">
/// the method.
/// </param>
/// <exception name = "ArgumentException">
/// if method is not supported.
/// </exception>
public void SetMethod(int method)
{
if (method != STORED && method != DEFLATED && method != BZIP2)
{
throw new ArgumentException("Method not supported.");
}
defaultMethod = method;
}
/// <summary>
/// Sets default compression level. The new level will be activated
/// immediately.
/// </summary>
/// <exception cref="System.ArgumentOutOfRangeException">
/// if level is not supported.
/// </exception>
/// <see cref="Deflater"/>
public void SetLevel(int level)
{
deflater_.SetLevel(level);
}
/// <summary>
/// Write an unsigned short in little endian byte order.
/// </summary>
private void WriteLeShort(int value)
{
baseOutputStream_.WriteByte((byte)value);
baseOutputStream_.WriteByte((byte)(value >> 8));
}
/// <summary>
/// Write an int in little endian byte order.
/// </summary>
private void WriteLeInt(int value)
{
WriteLeShort(value);
WriteLeShort(value >> 16);
}
/// <summary>
/// Write an int in little endian byte order.
/// </summary>
private void WriteLeLong(long value)
{
WriteLeInt((int)value);
WriteLeInt((int)(value >> 32));
}
bool shouldWriteBack = false;
long seekPos = -1;
/// <summary>
/// Starts a new Zip entry. It automatically closes the previous
/// entry if present. If the compression method is stored, the entry
/// must have a valid size and crc, otherwise all elements (except
/// name) are optional, but must be correct if present. If the time
/// is not set in the entry, the current time is used.
/// </summary>
/// <param name="entry">
/// the entry.
/// </param>
/// <exception cref="System.IO.IOException">
/// if an I/O error occured.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// if stream was finished
/// </exception>
public void PutNextEntry(ZipEntry entry)
{
if (entries == null)
{
throw new InvalidOperationException("ZipOutputStream was finished");
}
if (curEntry != null)
{
CloseEntry();
}
CompressionMethod method = entry.CompressionMethod;
int flags = 0;
switch (method)
{
case CompressionMethod.Stored:
if (entry.CompressedSize >= 0)
{
if (entry.Size < 0)
{
entry.Size = entry.CompressedSize;
}
else if (entry.Size != entry.CompressedSize)
{
throw new ZipException("Method STORED, but compressed size != size");
}
}
else
{
entry.CompressedSize = entry.Size;
}
if (entry.Size < 0)
{
throw new ZipException("Method STORED, but size not set");
}
else if (entry.Crc < 0)
{
throw new ZipException("Method STORED, but crc not set");
}
break;
case (CompressionMethod)12:
startPosition = baseOutputStream_.Position;
additionalStream = new BZip2OutputStream(new NoCloseSubStream(baseOutputStream_));
if (entry.CompressedSize < 0 || entry.Size < 0 || entry.Crc < 0)
{
flags |= 8;
}
break;
case CompressionMethod.Deflated:
if (entry.CompressedSize < 0 || entry.Size < 0 || entry.Crc < 0)
{
flags |= 8;
}
break;
}
// if (entry.DosTime < 0) {
// entry.Time = System.Environment.TickCount;
// }
entry.Flags = flags;
entry.Offset = offset;
entry.CompressionMethod = (CompressionMethod)method;
curMethod = method;
// Write the local file header
WriteLeInt(ZipConstants.LocalHeaderSignature);
// write ZIP version
WriteLeShort(method == CompressionMethod.Stored ? ZIP_STORED_VERSION : ZIP_DEFLATED_VERSION);
if ((flags & 8) == 0)
{
WriteLeShort(flags);
WriteLeShort((byte)method);
WriteLeInt((int)entry.DosTime);
WriteLeInt((int)entry.Crc);
WriteLeInt((int)entry.CompressedSize);
WriteLeInt((int)entry.Size);
}
else
{
if (baseOutputStream_.CanSeek)
{
shouldWriteBack = true;
WriteLeShort((short)(flags & ~8));
}
else
{
shouldWriteBack = false;
WriteLeShort(flags);
}
WriteLeShort((byte)method);
WriteLeInt((int)entry.DosTime);
seekPos = baseOutputStream_.Position;
WriteLeInt(0);
WriteLeInt(0);
WriteLeInt(0);
}
byte[] name = ZipConstants.ConvertToArray(entry.Name);
if (name.Length > 0xFFFF)
{
throw new ZipException("Name too long.");
}
byte[] extra = entry.ExtraData;
if (extra == null)
{
extra = new byte[0];
}
if (extra.Length > 0xFFFF)
{
throw new ZipException("Extra data too long.");
}
WriteLeShort(name.Length);
WriteLeShort(extra.Length);
baseOutputStream_.Write(name, 0, name.Length);
baseOutputStream_.Write(extra, 0, extra.Length);
offset += ZipConstants.LocalHeaderBaseSize + name.Length + extra.Length;
/* Activate the entry. */
curEntry = entry;
crc.Reset();
if (method == CompressionMethod.Deflated)
{
deflater_.Reset();
}
size = 0;
}
/// <summary>
/// Closes the current entry.
/// </summary>
/// <exception cref="System.IO.IOException">
/// if an I/O error occured.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// if no entry is active.
/// </exception>
public void CloseEntry()
{
if (curEntry == null)
{
throw new InvalidOperationException("No open entry");
}
/* First finish the deflater, if appropriate */
int csize = 0;
if (curMethod == CompressionMethod.Deflated)
{
base.Finish();
csize = (int)deflater_.TotalOut;
}
else if(curMethod == (CompressionMethod)12)
{
// close the sub stream, no problem because the substream has a fake
// close
additionalStream.Close();
additionalStream = null;
csize = (int)(baseOutputStream_.Position-startPosition);
}
else
csize = size;
if (curEntry.Size < 0)
{
curEntry.Size = size;
}
else if (curEntry.Size != size)
{
throw new ZipException("size was " + size + ", but I expected " + curEntry.Size);
}
if (curEntry.CompressedSize < 0)
{
curEntry.CompressedSize = csize;
}
else if (curEntry.CompressedSize != csize)
{
throw new ZipException("compressed size was " + csize + ", but I expected " + curEntry.CompressedSize);
}
if (curEntry.Crc < 0)
{
curEntry.Crc = crc.Value;
}
else if (curEntry.Crc != crc.Value)
{
throw new ZipException("crc was " + crc.Value +
", but I expected " +
curEntry.Crc);
}
offset += csize;
/* Now write the data descriptor entry if needed. */
if (curMethod != CompressionMethod.Stored && (curEntry.Flags & 8) != 0)
{
if (shouldWriteBack)
{
curEntry.Flags &= ~8;
long curPos = baseOutputStream_.Position;
baseOutputStream_.Seek(seekPos, SeekOrigin.Begin);
WriteLeInt((int)curEntry.Crc);
WriteLeInt((int)curEntry.CompressedSize);
WriteLeInt((int)curEntry.Size);
baseOutputStream_.Seek(curPos, SeekOrigin.Begin);
shouldWriteBack = false;
}
else
{
WriteLeInt(ZipConstants.DataDescriptorSignature);
WriteLeInt((int)curEntry.Crc);
WriteLeInt((int)curEntry.CompressedSize);
WriteLeInt((int)curEntry.Size);
offset += ZipConstants.DataDescriptorSize;
}
}
entries.Add(curEntry);
curEntry = null;
}
/// <summary>
/// Writes the given buffer to the current entry.
/// </summary>
/// <exception cref="System.IO.IOException">
/// if an I/O error occured.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// if no entry is active.
/// </exception>
public override void Write(byte[] b, int off, int len)
{
if (curEntry == null)
{
throw new InvalidOperationException("No open entry.");
}
switch (curMethod)
{
case (CompressionMethod)12:
additionalStream.Write(b, off, len);
break;
case CompressionMethod.Deflated:
base.Write(b, off, len);
break;
case CompressionMethod.Stored:
baseOutputStream_.Write(b, off, len);
break;
}
crc.Update(b, off, len);
size += len;
}
/// <summary>
/// Finishes the stream. This will write the central directory at the
/// end of the zip file and flush the stream.
/// </summary>
/// <exception cref="System.IO.IOException">
/// if an I/O error occured.
/// </exception>
public override void Finish()
{
if (entries == null)
{
return;
}
if (curEntry != null)
{
CloseEntry();
}
int numEntries = 0;
int sizeEntries = 0;
foreach (ZipEntry entry in entries)
{
// TODO : check the appnote file for compilance with the central directory standard
CompressionMethod method = entry.CompressionMethod;
WriteLeInt(ZipConstants.CentralHeaderSignature);
WriteLeShort(method == CompressionMethod.Stored ? ZIP_STORED_VERSION : ZIP_DEFLATED_VERSION);
WriteLeShort(method == CompressionMethod.Stored ? ZIP_STORED_VERSION : ZIP_DEFLATED_VERSION);
if (entry.IsCrypted)
{
entry.Flags |= 1;
}
WriteLeShort(entry.Flags);
WriteLeShort((short)method);
WriteLeInt((int)entry.DosTime);
WriteLeInt((int)entry.Crc);
WriteLeInt((int)entry.CompressedSize);
WriteLeInt((int)entry.Size);
byte[] name = ZipConstants.ConvertToArray(entry.Name);
if (name.Length > 0xffff)
{
throw new ZipException("Name too long.");
}
byte[] extra = entry.ExtraData;
if (extra == null)
{
extra = new byte[0];
}
string strComment = entry.Comment;
byte[] comment = strComment != null ? ZipConstants.ConvertToArray(strComment) : new byte[0];
if (comment.Length > 0xffff)
{
throw new ZipException("Comment too long.");
}
WriteLeShort(name.Length);
WriteLeShort(extra.Length);
WriteLeShort(comment.Length);
WriteLeShort(0); // disk number
WriteLeShort(0); // internal file attr
WriteLeInt(0); // external file attr
WriteLeInt((int)entry.Offset);
baseOutputStream_.Write(name, 0, name.Length);
baseOutputStream_.Write(extra, 0, extra.Length);
baseOutputStream_.Write(comment, 0, comment.Length);
++numEntries;
sizeEntries += ZipConstants.CentralHeaderBaseSize + name.Length + extra.Length + comment.Length;
}
WriteLeInt(ZipConstants.EndOfCentralDirectorySignature);
WriteLeShort(0); // disk number
WriteLeShort(0); // disk with start of central dir
WriteLeShort(numEntries);
WriteLeShort(numEntries);
WriteLeInt(sizeEntries);
WriteLeInt(offset);
WriteLeShort(zipComment.Length);
baseOutputStream_.Write(zipComment, 0, zipComment.Length);
baseOutputStream_.Flush();
entries = null;
}
}
/// <summary>
/// Stream without
/// </summary>
public class NoCloseSubStream : Stream
{
Stream baseStream;
public NoCloseSubStream(Stream b)
{
baseStream = b;
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override bool CanRead
{
get
{
return baseStream.CanRead;
}
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override bool CanSeek
{
get
{
return baseStream.CanSeek;
}
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override bool CanWrite
{
get
{
return baseStream.CanWrite;
}
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override long Length
{
get
{
return baseStream.Length;
}
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override long Position
{
get
{
return baseStream.Position;
}
set
{
baseStream.Position = value;
}
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override long Seek(long offset, SeekOrigin origin)
{
return baseStream.Seek(offset, origin);
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override void SetLength(long val)
{
baseStream.SetLength(val);
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override int ReadByte()
{
return baseStream.ReadByte();
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override int Read(byte[] b, int off, int len)
{
return baseStream.Read(b, off, len);
}
public override void Write(byte[] buf, int off, int len)
{
baseStream.Write(buf, off, len);
}
public override void WriteByte(byte bv)
{
baseStream.WriteByte(bv);
}
public override void Close()
{
baseStream = null;
}
public override void Flush()
{
baseStream.Flush();
}
}
}
| |
// 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.Diagnostics;
using System.Text;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
// Implementation for "displaying type name as string" aspect of default (C#) Formatter component
internal abstract partial class Formatter
{
/// <returns>The qualified name (i.e. including containing types and namespaces) of a named,
/// pointer, or array type.</returns>
internal string GetTypeName(TypeAndCustomInfo typeAndInfo, bool escapeKeywordIdentifiers = false)
{
var type = typeAndInfo.Type;
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
var dynamicFlags = DynamicFlagsCustomTypeInfo.Create(typeAndInfo.Info);
var index = 0;
var pooled = PooledStringBuilder.GetInstance();
AppendQualifiedTypeName(pooled.Builder, type, dynamicFlags, ref index, escapeKeywordIdentifiers);
return pooled.ToStringAndFree();
}
/// <summary>
/// Append the qualified name (i.e. including containing types and namespaces) of a named,
/// pointer, or array type to <paramref name="builder"/>.
/// </summary>
/// <remarks>
/// Keyword strings are appended for primitive types (e.g. "int" for "System.Int32").
/// Question mark syntax is used for <see cref="Nullable{T}"/>.
/// No special handling is required for anonymous types - they are expected to be
/// emitted with <see cref="DebuggerDisplayAttribute.Type"/> set to "<Anonymous Type>.
/// This is fortunate, since we don't have a good way to recognize them in metadata.
/// Does not call itself (directly).
/// </remarks>
protected void AppendQualifiedTypeName(StringBuilder builder, Type type, DynamicFlagsCustomTypeInfo dynamicFlags, ref int index, bool escapeKeywordIdentifiers)
{
Type originalType = type;
// Can have an array of pointers, but not a pointer to an array, so consume these first.
// We'll reconstruct this information later from originalType.
while (type.IsArray)
{
index++;
type = type.GetElementType();
}
int pointerCount = 0;
while (type.IsPointer)
{
index++;
pointerCount++;
type = type.GetElementType();
}
int nullableCount = 0;
Type typeArg;
while ((typeArg = type.GetNullableTypeArgument()) != null)
{
index++;
nullableCount++;
type = typeArg;
}
Debug.Assert(nullableCount < 2, "Benign: someone is nesting nullables.");
Debug.Assert(pointerCount == 0 || nullableCount == 0, "Benign: pointer to nullable?");
int oldLength = builder.Length;
AppendQualifiedTypeNameInternal(builder, type, dynamicFlags, ref index, escapeKeywordIdentifiers);
string name = builder.ToString(oldLength, builder.Length - oldLength);
builder.Append('?', nullableCount);
builder.Append('*', pointerCount);
type = originalType;
while (type.IsArray)
{
AppendRankSpecifier(builder, type.GetArrayRank());
type = type.GetElementType();
}
}
/// <summary>
/// Append the qualified name (i.e. including containing types and namespaces) of a named type
/// (i.e. not a pointer or array type) to <paramref name="builder"/>.
/// </summary>
/// <remarks>
/// Keyword strings are appended for primitive types (e.g. "int" for "System.Int32").
/// </remarks>
/// <remarks>
/// Does not call itself or <see cref="AppendQualifiedTypeName"/> (directly).
/// </remarks>
private void AppendQualifiedTypeNameInternal(StringBuilder builder, Type type, DynamicFlagsCustomTypeInfo dynamicFlags, ref int index, bool escapeKeywordIdentifiers)
{
var isDynamic = dynamicFlags[index++] && type.IsObject();
if (AppendSpecialTypeName(builder, type, isDynamic, escapeKeywordIdentifiers))
{
return;
}
Debug.Assert(!isDynamic, $"Dynamic should have been handled by {nameof(AppendSpecialTypeName)}");
Debug.Assert(!IsPredefinedType(type));
// Note: in the Reflection/LMR object model, all type arguments are on the most nested type.
var hasTypeArguments = type.IsGenericType;
var typeArguments = type.IsGenericType
? type.GetGenericArguments()
: null;
Debug.Assert(hasTypeArguments == (typeArguments != null));
var numTypeArguments = hasTypeArguments ? typeArguments.Length : 0;
if (type.IsNested)
{
// Push from inside, out.
var stack = ArrayBuilder<Type>.GetInstance();
{
var containingType = type.DeclaringType;
while (containingType != null)
{
stack.Add(containingType);
containingType = containingType.DeclaringType;
}
}
var lastContainingTypeIndex = stack.Count - 1;
AppendNamespacePrefix(builder, stack[lastContainingTypeIndex], escapeKeywordIdentifiers);
var typeArgumentOffset = 0;
// Pop from outside, in.
for (int i = lastContainingTypeIndex; i >= 0; i--)
{
var containingType = stack[i];
// ACASEY: I explored the type in the debugger and couldn't find the arity stored/exposed separately.
int arity = hasTypeArguments ? containingType.GetGenericArguments().Length - typeArgumentOffset : 0;
AppendUnqualifiedTypeName(builder, containingType, dynamicFlags, ref index, escapeKeywordIdentifiers, typeArguments, typeArgumentOffset, arity);
builder.Append('.');
typeArgumentOffset += arity;
}
stack.Free();
AppendUnqualifiedTypeName(builder, type, dynamicFlags, ref index, escapeKeywordIdentifiers, typeArguments, typeArgumentOffset, numTypeArguments - typeArgumentOffset);
}
else
{
AppendNamespacePrefix(builder, type, escapeKeywordIdentifiers);
AppendUnqualifiedTypeName(builder, type, dynamicFlags, ref index, escapeKeywordIdentifiers, typeArguments, 0, numTypeArguments);
}
}
/// <summary>
/// Helper for appending the qualified name of the containing namespace of a type.
/// NOTE: Unless the qualified name is empty, there will always be a trailing dot.
/// </summary>
private void AppendNamespacePrefix(StringBuilder builder, Type type, bool escapeKeywordIdentifiers)
{
var @namespace = type.Namespace;
if (!string.IsNullOrEmpty(@namespace))
{
if (escapeKeywordIdentifiers && @namespace.Contains("."))
{
var pooled = PooledStringBuilder.GetInstance();
var identifierBuilder = pooled.Builder;
foreach (var ch in @namespace)
{
if (ch == '.')
{
AppendIdentifier(builder, escapeKeywordIdentifiers, identifierBuilder.ToString());
builder.Append(ch);
identifierBuilder.Clear();
}
else
{
identifierBuilder.Append(ch);
}
}
AppendIdentifier(builder, escapeKeywordIdentifiers, identifierBuilder.ToString());
pooled.Free();
}
else
{
AppendIdentifier(builder, escapeKeywordIdentifiers, @namespace);
}
builder.Append('.');
}
}
/// <summary>
/// Append the name of the type and its type arguments. Do not append the type's containing type or namespace.
/// </summary>
/// <param name="builder">Builder to which the name will be appended.</param>
/// <param name="type">Type, the name of which will be appended.</param>
/// <param name="dynamicFlags">Flags indicating which occurrences of "object" need to be replaced by "dynamic".</param>
/// <param name="index">Current index into <paramref name="dynamicFlags"/>.</param>
/// <param name="escapeKeywordIdentifiers">True if identifiers that are also keywords should be prefixed with '@'.</param>
/// <param name="typeArguments">
/// The type arguments of the type passed to <see cref="AppendQualifiedTypeNameInternal"/>, which might be nested
/// within <paramref name="type"/>. In the Reflection/LMR object model, all type arguments are passed to the
/// most nested type. To get back to the C# model, we have to propagate them out to containing types.
/// </param>
/// <param name="typeArgumentOffset">
/// The first position in <paramref name="typeArguments"/> that is a type argument to <paramref name="type"/>,
/// from a C# perspective.
/// </param>
/// <param name="arity">
/// The number of type parameters of <paramref name="type"/>, from a C# perspective.
/// </param>
/// <remarks>
/// We're passing the full array plus bounds, rather than a tailored array, to avoid creating a lot of short-lived
/// temporary arrays.
/// </remarks>
private void AppendUnqualifiedTypeName(StringBuilder builder, Type type, DynamicFlagsCustomTypeInfo dynamicFlags, ref int index, bool escapeKeywordIdentifiers, Type[] typeArguments, int typeArgumentOffset, int arity)
{
if (typeArguments == null || arity == 0)
{
AppendIdentifier(builder, escapeKeywordIdentifiers, type.Name);
return;
}
var mangledName = type.Name;
var separatorIndex = mangledName.IndexOf('`');
AppendIdentifier(builder, escapeKeywordIdentifiers, mangledName, separatorIndex);
AppendGenericTypeArgumentList(builder, typeArguments, typeArgumentOffset, dynamicFlags, ref index, arity, escapeKeywordIdentifiers);
}
protected void AppendIdentifier(StringBuilder builder, bool escapeKeywordIdentifiers, string identifier, int length = -1)
{
Debug.Assert(length < 0 || (0 <= length && length <= identifier.Length));
if (escapeKeywordIdentifiers)
{
if (length >= 0)
{
identifier = identifier.Substring(0, length);
}
AppendIdentifierEscapingPotentialKeywords(builder, identifier);
}
else if (length < 0)
{
builder.Append(identifier);
}
else
{
builder.Append(identifier, 0, length);
}
}
internal string GetIdentifierEscapingPotentialKeywords(string identifier)
{
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
AppendIdentifierEscapingPotentialKeywords(builder, identifier);
return pooled.ToStringAndFree();
}
#region Language-specific type name formatting behavior
protected abstract void AppendIdentifierEscapingPotentialKeywords(StringBuilder builder, string identifier);
protected abstract void AppendGenericTypeArgumentList(
StringBuilder builder,
Type[] typeArguments,
int typeArgumentOffset,
DynamicFlagsCustomTypeInfo dynamicFlags,
ref int index,
int arity,
bool escapeKeywordIdentifiers);
protected abstract void AppendRankSpecifier(StringBuilder builder, int rank);
protected abstract bool AppendSpecialTypeName(StringBuilder builder, Type type, bool isDynamic, bool escapeKeywordIdentifiers);
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Xml;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;
using SharpVectors.Dom.Css;
namespace SharpVectors.Dom.Stylesheets
{
/// <summary>
/// The StyleSheet interface is the abstract base interface for any type of style sheet. It represents a single style sheet associated with a structured document. In HTML, the StyleSheet interface represents either an external style sheet, included via the HTML LINK element, or an inline STYLE element. In XML, this interface represents an external style sheet, included via a style sheet processing instruction.
/// </summary>
/// <developer>[email protected]</developer>
/// <completed>75</completed>
public class StyleSheet : IStyleSheet
{
#region Constructors
internal StyleSheet()
{
}
internal StyleSheet(XmlProcessingInstruction pi)
{
Regex re = new Regex(@"(?<name>[a-z]+)=[""'](?<value>[^""']*)[""']");
Match match = re.Match(pi.Data);
while(match.Success)
{
string name = match.Groups["name"].Value;
string val = match.Groups["value"].Value;
switch(name)
{
case "href":
_Href = val;
break;
case "type":
_Type = val;
break;
case "title":
_Title = val;
break;
case "media":
_Media = new MediaList(val);
break;
}
match = match.NextMatch();
}
ownerNode = (XmlNode)pi;
}
internal StyleSheet(XmlElement styleElement)
{
if(styleElement.HasAttribute("href")) _Href = styleElement.Attributes["href"].Value;
if(styleElement.HasAttribute("type")) _Type = styleElement.Attributes["type"].Value;
if(styleElement.HasAttribute("title")) _Title = styleElement.Attributes["title"].Value;
if(styleElement.HasAttribute("media")) _Media = new MediaList(styleElement.Attributes["media"].Value);
ownerNode = (XmlNode)styleElement;
}
internal StyleSheet(XmlNode ownerNode, string href, string type, string title, string media)
{
this.ownerNode = ownerNode;
_Href = href;
_Type = type;
_Title = title;
_Media = new MediaList(media);
}
#endregion
#region Internal methods
/// <summary>
/// Used to find matching style rules in the cascading order
/// </summary>
/// <param name="elt">The element to find styles for</param>
/// <param name="pseudoElt">The pseudo-element to find styles for</param>
/// <param name="ml">The medialist that the document is using</param>
/// <param name="csd">A CssStyleDeclaration that holds the collected styles</param>
protected internal virtual void GetStylesForElement(XmlElement elt, string pseudoElt, MediaList ml, CssCollectedStyleDeclaration csd)
{
}
#endregion
#region Public methods
internal XmlNode ResolveOwnerNode()
{
if(OwnerNode != null) return OwnerNode;
else
{
return ((StyleSheet)ParentStyleSheet).ResolveOwnerNode();
}
}
#endregion
#region Protected methods
internal void LoadSheet()
{
WebRequest request = (WebRequest)WebRequest.Create(AbsoluteHref);
TriedDownload = true;
try
{
WebResponse response = (WebResponse)request.GetResponse();
SucceededDownload = true;
System.IO.StreamReader str = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default, true);
sheetContent = str.ReadToEnd();
str.Close();
}
catch
{
SucceededDownload = false;
sheetContent = String.Empty;
}
}
#endregion
#region Private fields
private bool TriedDownload = false;
private bool SucceededDownload = false;
#endregion
#region Protected properties
private string sheetContent = null;
internal string SheetContent
{
get
{
if(OwnerNode is XmlElement)
{
return OwnerNode.InnerText;
}
else
{
// a PI
if(!TriedDownload)
{
LoadSheet();
}
if(SucceededDownload) return sheetContent;
else return String.Empty;
}
}
}
#endregion
#region Implementation of IStyleSheet
private MediaList _Media = new MediaList();
/// <summary>
/// The intended destination media for style information. The media is often specified in the ownerNode. If no media has been specified, the MediaList will be empty. See the media attribute definition for the LINK element in HTML 4.0, and the media pseudo-attribute for the XML style sheet processing instruction . Modifying the media list may cause a change to the attribute disabled.
/// </summary>
public IMediaList Media
{
get
{
return _Media;
}
}
private string _Title = String.Empty;
/// <summary>
/// The advisory title. The title is often specified in the ownerNode. See the title attribute definition for the LINK element in HTML 4.0, and the title pseudo-attribute for the XML style sheet processing instruction.
/// </summary>
public string Title
{
get
{
return _Title;
}
}
private string _Href = String.Empty;
/// <summary>
/// If the style sheet is a linked style sheet, the value of its attribute is its location. For inline style sheets, the value of this attribute is null. See the href attribute definition for the LINK element in HTML 4.0, and the href pseudo-attribute for the XML style sheet processing instruction.
/// </summary>
public string Href
{
get
{
return _Href;
}
}
/// <summary>
/// The resolved absolute URL to the stylesheet
/// </summary>
public Uri AbsoluteHref
{
get
{
Uri u;
try{
if (OwnerNode != null && OwnerNode.BaseURI != null)
u = new Uri(new Uri(OwnerNode.BaseURI), Href);
else
u = new Uri(ApplicationContext.DocumentDirectoryUri, Href);
}
catch
{
u = new Uri(ApplicationContext.DocumentDirectoryUri, Href);
}
return u;
}
}
private IStyleSheet _ParentStyleSheet = null;
/// <summary>
/// For style sheet languages that support the concept of style sheet inclusion, this attribute represents the including style sheet, if one exists. If the style sheet is a top-level style sheet, or the style sheet language does not support inclusion, the value of this attribute is null.
/// </summary>
public IStyleSheet ParentStyleSheet
{
get
{
return _ParentStyleSheet;
}
}
private XmlNode ownerNode = null;
/// <summary>
/// The node that associates this style sheet with the document. For HTML, this may be the corresponding LINK or STYLE element. For XML, it may be the linking processing instruction. For style sheets that are included by other style sheets, the value of this attribute is null.
/// </summary>
public XmlNode OwnerNode
{
get
{
return ownerNode;
}
}
private bool _Disabled = false;
/// <summary>
/// false if the style sheet is applied to the document. true if it is not. Modifying this attribute may cause a new resolution of style for the document. A stylesheet only applies if both an appropriate medium definition is present and the disabled attribute is false. So, if the media doesn't apply to the current user agent, the disabled attribute is ignored.
/// </summary>
public bool Disabled
{
get
{
return _Disabled;
}
set
{
_Disabled = value;
}
}
private string _Type = String.Empty;
/// <summary>
/// This specifies the style sheet language for this style sheet. The style sheet language is specified as a content type (e.g. "text/css"). The content type is often specified in the ownerNode. Also see the type attribute definition for the LINK element in HTML 4.0, and the type pseudo-attribute for the XML style sheet processing instruction.
/// </summary>
public string Type
{
get
{
return _Type;
}
}
#endregion
}
}
| |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2009 Oracle. All rights reserved.
*
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using BerkeleyDB.Internal;
namespace BerkeleyDB {
/// <summary>
/// A class representing database cursors over secondary indexes, which
/// allow for traversal of database records.
/// </summary>
public class SecondaryCursor
: BaseCursor, IEnumerable<KeyValuePair<DatabaseEntry,
KeyValuePair<DatabaseEntry, DatabaseEntry>>> {
private KeyValuePair<DatabaseEntry,
KeyValuePair<DatabaseEntry, DatabaseEntry>> cur;
/// <summary>
/// The secondary key and primary key/data pair at which the cursor
/// currently points.
/// </summary>
public KeyValuePair<DatabaseEntry,
KeyValuePair<DatabaseEntry, DatabaseEntry>> Current {
get { return cur; }
private set { cur = value; }
}
internal SecondaryCursor(DBC dbc) : base(dbc) { }
/// <summary>
/// Protected method wrapping DBC->pget()
/// </summary>
/// <param name="key">The secondary key</param>
/// <param name="pkey">The primary key</param>
/// <param name="data">The primary data</param>
/// <param name="flags">Flags to pass to DBC->pget</param>
/// <param name="info">Locking parameters</param>
/// <returns></returns>
protected bool PGet(
DatabaseEntry key, DatabaseEntry pkey,
DatabaseEntry data, uint flags, LockingInfo info) {
flags |= (info == null) ? 0 : info.flags;
try {
dbc.pget(key, pkey, data, flags);
Current = new KeyValuePair<DatabaseEntry,
KeyValuePair<DatabaseEntry, DatabaseEntry>>(key,
new KeyValuePair<DatabaseEntry, DatabaseEntry>(pkey, data));
return true;
} catch (NotFoundException) {
Current = new KeyValuePair<DatabaseEntry,
KeyValuePair<DatabaseEntry, DatabaseEntry>>(
null, new KeyValuePair<DatabaseEntry, DatabaseEntry>());
return false;
}
}
/// <summary>
/// Delete the key/data pair to which the cursor refers from the primary
/// database and all secondary indices.
/// </summary>
/// <remarks>
/// <para>
/// The cursor position is unchanged after a delete, and subsequent
/// calls to cursor functions expecting the cursor to refer to an
/// existing key will fail.
/// </para>
/// </remarks>
/// <exception cref="KeyEmptyException">
/// The element has already been deleted.
/// </exception>
public new void Delete() {
base.Delete();
Current =
new KeyValuePair<DatabaseEntry,
KeyValuePair<DatabaseEntry, DatabaseEntry>>(
null, new KeyValuePair<DatabaseEntry, DatabaseEntry>());
}
/// <summary>
/// Create a new cursor that uses the same transaction and locker ID as
/// the original cursor.
/// </summary>
/// <remarks>
/// This is useful when an application is using locking and requires two
/// or more cursors in the same thread of control.
/// </remarks>
/// <param name="keepPosition">
/// If true, the newly created cursor is initialized to refer to the
/// same position in the database as the original cursor (if any) and
/// hold the same locks (if any). If false, or the original cursor does
/// not hold a database position and locks, the created cursor is
/// uninitialized and will behave like a cursor newly created by
/// <see cref="BaseDatabase.Cursor"/>.</param>
/// <returns>A newly created cursor</returns>
public SecondaryCursor Duplicate(bool keepPosition) {
return new SecondaryCursor(
dbc.dup(keepPosition ? DbConstants.DB_POSITION : 0));
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the
/// <see cref="SecondaryCursor"/>.
/// </summary>
/// <remarks>
/// The enumerator will begin at the cursor's current position (or the
/// first record if the cursor has not yet been positioned) and iterate
/// forwards (i.e. in the direction of <see cref="MoveNext"/>) over the
/// remaining records.
/// </remarks>
/// <returns>An enumerator for the SecondaryCursor.</returns>
public new IEnumerator<KeyValuePair<DatabaseEntry,
KeyValuePair<DatabaseEntry, DatabaseEntry>>> GetEnumerator() {
while (MoveNext())
yield return Current;
}
/// <summary>
/// Set the cursor to refer to the first key/data pair of the database,
/// and store the secondary key along with the corresponding primary
/// key/data pair in <see cref="Current"/>. If the first key has
/// duplicate values, the first data item in the set of duplicates is
/// stored in <see cref="Current"/>.
/// </summary>
/// <remarks>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </remarks>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MoveFirst() { return MoveFirst(null); }
/// <summary>
/// Set the cursor to refer to the first key/data pair of the database,
/// and store the secondary key along with the corresponding primary
/// key/data pair in <see cref="Current"/>. If the first key has
/// duplicate values, the first data item in the set of duplicates is
/// stored in <see cref="Current"/>.
/// </summary>
/// <remarks>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </remarks>
/// <param name="info">The locking behavior to use.</param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MoveFirst(LockingInfo info) {
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry pkey = new DatabaseEntry();
DatabaseEntry data = new DatabaseEntry();
return PGet(key, pkey, data, DbConstants.DB_FIRST, info);
}
/// <summary>
/// Set the cursor to refer to <paramref name="key"/>, and store the
/// primary key/data pair associated with the given secondary key in
/// <see cref="Current"/>. In the presence of duplicate key values, the
/// first data item in the set of duplicates is stored in
/// <see cref="Current"/>.
/// </summary>
/// <remarks>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </remarks>
/// <param name="key">The key at which to position the cursor</param>
/// <param name="exact">
/// If true, require the given key to match the key in the database
/// exactly. If false, position the cursor at the smallest key greater
/// than or equal to the specified key, permitting partial key matches
/// and range searches.
/// </param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool Move(DatabaseEntry key, bool exact) {
return Move(key, exact, null);
}
/// <summary>
/// Set the cursor to refer to <paramref name="key"/>, and store the
/// primary key/data pair associated with the given secondary key in
/// <see cref="Current"/>. In the presence of duplicate key values, the
/// first data item in the set of duplicates is stored in
/// <see cref="Current"/>.
/// </summary>
/// <remarks>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </remarks>
/// <param name="key">The key at which to position the cursor</param>
/// <param name="exact">
/// If true, require the given key to match the key in the database
/// exactly. If false, position the cursor at the smallest key greater
/// than or equal to the specified key, permitting partial key matches
/// and range searches.
/// </param>
/// <param name="info">The locking behavior to use.</param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool Move(DatabaseEntry key, bool exact, LockingInfo info) {
DatabaseEntry pkey = new DatabaseEntry();
DatabaseEntry data = new DatabaseEntry();
return PGet(key, pkey, data,
exact ? DbConstants.DB_SET : DbConstants.DB_SET_RANGE, info);
}
/// <summary>
/// Move the cursor to the specified key/data pair of the database. The
/// cursor is positioned to a key/data pair if both the key and data
/// match the values provided on the key and data parameters.
/// </summary>
/// <remarks>
/// <para>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </para>
/// <para>
/// If this flag is specified on a database configured without sorted
/// duplicate support, the value of <paramref name="exact"/> is ignored.
/// </para>
/// </remarks>
/// <param name="pair">
/// The key/data pair at which to position the cursor.
/// </param>
/// <param name="exact">
/// If true, require the given key and data to match the key and data
/// in the database exactly. If false, position the cursor at the
/// smallest data value which is greater than or equal to the value
/// provided by <paramref name="pair.Value"/> (as determined by the
/// comparison function).
/// </param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool Move(KeyValuePair<DatabaseEntry,
KeyValuePair<DatabaseEntry, DatabaseEntry>> pair, bool exact) {
return Move(pair, exact, null);
}
/// <summary>
/// Move the cursor to the specified key/data pair of the database. The
/// cursor is positioned to a key/data pair if both the key and data
/// match the values provided on the key and data parameters.
/// </summary>
/// <remarks>
/// <para>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </para>
/// <para>
/// If this flag is specified on a database configured without sorted
/// duplicate support, the value of <paramref name="exact"/> is ignored.
/// </para>
/// </remarks>
/// <param name="pair">
/// The key/data pair at which to position the cursor.
/// </param>
/// <param name="exact">
/// If true, require the given key and data to match the key and data
/// in the database exactly. If false, position the cursor at the
/// smallest data value which is greater than or equal to the value
/// provided by <paramref name="pair.Value"/> (as determined by the
/// comparison function).
/// </param>
/// <param name="info">The locking behavior to use.</param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool Move(KeyValuePair<DatabaseEntry,
KeyValuePair<DatabaseEntry, DatabaseEntry>> pair,
bool exact, LockingInfo info) {
return PGet(pair.Key, pair.Value.Key, pair.Value.Value, exact ?
DbConstants.DB_GET_BOTH : DbConstants.DB_GET_BOTH_RANGE, info);
}
/// <summary>
/// Set the cursor to refer to the last key/data pair of the database,
/// and store the secondary key and primary key/data pair in
/// <see cref="Current"/>. If the last key has duplicate values, the
/// last data item in the set of duplicates is stored in
/// <see cref="Current"/>.
/// </summary>
/// <remarks>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </remarks>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MoveLast() { return MoveLast(null); }
/// <summary>
/// Set the cursor to refer to the last key/data pair of the database,
/// and store the secondary key and primary key/data pair in
/// <see cref="Current"/>. If the last key has duplicate values, the
/// last data item in the set of duplicates is stored in
/// <see cref="Current"/>.
/// </summary>
/// <remarks>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </remarks>
/// <param name="info">The locking behavior to use.</param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MoveLast(LockingInfo info) {
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry pkey = new DatabaseEntry();
DatabaseEntry data = new DatabaseEntry();
return PGet(key, pkey, data, DbConstants.DB_LAST, info);
}
/// <summary>
/// If the cursor is not yet initialized, MoveNext is identical to
/// <see cref="MoveFirst()"/>. Otherwise, move the cursor to the next
/// key/data pair of the database, and store the secondary key and
/// primary key/data pair in <see cref="Current"/>. In the presence of
/// duplicate key values, the value of <see cref="Current">Current.Key
/// </see> may not change.
/// </summary>
/// <remarks>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </remarks>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MoveNext() { return MoveNext(null); }
/// <summary>
/// If the cursor is not yet initialized, MoveNext is identical to
/// <see cref="MoveFirst()"/>. Otherwise, move the cursor to the next
/// key/data pair of the database, and store the secondary key and
/// primary key/data pair in <see cref="Current"/>. In the presence of
/// duplicate key values, the value of <see cref="Current">Current.Key
/// </see> may not change.
/// </summary>
/// <remarks>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </remarks>
/// <param name="info">The locking behavior to use.</param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MoveNext(LockingInfo info) {
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry pkey = new DatabaseEntry();
DatabaseEntry data = new DatabaseEntry();
return PGet(key, pkey, data, DbConstants.DB_NEXT, info);
}
/// <summary>
/// If the next key/data pair of the database is a duplicate data record
/// for the current key/data pair, move the cursor to the next key/data
/// pair in the database, and store the secondary key and primary
/// key/data pair in <see cref="Current"/>. MoveNextDuplicate will
/// return false if the next key/data pair of the database is not a
/// duplicate data record for the current key/data pair.
/// </summary>
/// <remarks>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </remarks>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MoveNextDuplicate() { return MoveNextDuplicate(null); }
/// <summary>
/// If the next key/data pair of the database is a duplicate data record
/// for the current key/data pair, move the cursor to the next key/data
/// pair in the database, and store the secondary key and primary
/// key/data pair in <see cref="Current"/>. MoveNextDuplicate will
/// return false if the next key/data pair of the database is not a
/// duplicate data record for the current key/data pair.
/// </summary>
/// <remarks>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </remarks>
/// <param name="info">The locking behavior to use.</param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MoveNextDuplicate(LockingInfo info) {
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry pkey = new DatabaseEntry();
DatabaseEntry data = new DatabaseEntry();
return PGet(key, pkey, data, DbConstants.DB_NEXT_DUP, info);
}
/// <summary>
/// If the cursor is not yet initialized, MoveNextUnique is identical to
/// <see cref="MoveFirst()"/>. Otherwise, move the cursor to the next
/// non-duplicate key in the database, and store the secondary key and
/// primary key/data pair in <see cref="Current"/>. MoveNextUnique will
/// return false if no non-duplicate key/data pairs exist after the
/// cursor position in the database.
/// </summary>
/// <remarks>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </remarks>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MoveNextUnique() { return MoveNextUnique(null); }
/// <summary>
/// If the cursor is not yet initialized, MoveNextUnique is identical to
/// <see cref="MoveFirst()"/>. Otherwise, move the cursor to the next
/// non-duplicate key in the database, and store the secondary key and
/// primary key/data pair in <see cref="Current"/>. MoveNextUnique will
/// return false if no non-duplicate key/data pairs exist after the
/// cursor position in the database.
/// </summary>
/// <remarks>
/// <para>
/// If the database is a Queue or Recno database, MoveNextUnique will
/// ignore any keys that exist but were never explicitly created by the
/// application, or those that were created and later deleted.
/// </para>
/// <para>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </para>
/// </remarks>
/// <param name="info">The locking behavior to use.</param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MoveNextUnique(LockingInfo info) {
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry pkey = new DatabaseEntry();
DatabaseEntry data = new DatabaseEntry();
return PGet(key, pkey, data, DbConstants.DB_NEXT_NODUP, info);
}
/// <summary>
/// If the cursor is not yet initialized, MovePrev is identical to
/// <see cref="MoveLast()"/>. Otherwise, move the cursor to the previous
/// key/data pair of the database, and store the secondary key and
/// primary key/data pair in <see cref="Current"/>. In the presence of
/// duplicate key values, the value of <see cref="Current">Current.Key
/// </see> may not change.
/// </summary>
/// <remarks>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </remarks>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MovePrev() { return MovePrev(null); }
/// <summary>
/// If the cursor is not yet initialized, MovePrev is identical to
/// <see cref="MoveLast(LockingInfo)"/>. Otherwise, move the cursor to
/// the previous key/data pair of the database, and store the secondary
/// key and primary key/data pair in <see cref="Current"/>. In the
/// presence of duplicate key values, the value of <see cref="Current">
/// Current.Key</see> may not change.
/// </summary>
/// <remarks>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </remarks>
/// <param name="info">The locking behavior to use.</param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MovePrev(LockingInfo info) {
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry pkey = new DatabaseEntry();
DatabaseEntry data = new DatabaseEntry();
return PGet(key, pkey, data, DbConstants.DB_PREV, info);
}
/// <summary>
/// If the previous key/data pair of the database is a duplicate data
/// record for the current key/data pair, the cursor is moved to the
/// previous key/data pair of the database, and the secondary key and
/// primary key/data pair in <see cref="Current"/>. MovePrevDuplicate
/// will return false if the previous key/data pair of the database is
/// not a duplicate data record for the current key/data pair.
/// </summary>
/// <remarks>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </remarks>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MovePrevDuplicate() { return MovePrevDuplicate(null); }
/// <summary>
/// If the previous key/data pair of the database is a duplicate data
/// record for the current key/data pair, the cursor is moved to the
/// previous key/data pair of the database, and the secondary key and
/// primary key/data pair in <see cref="Current"/>. MovePrevDuplicate
/// will return false if the previous key/data pair of the database is
/// not a duplicate data record for the current key/data pair.
/// </summary>
/// <remarks>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </remarks>
/// <param name="info">The locking behavior to use.</param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MovePrevDuplicate(LockingInfo info) {
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry pkey = new DatabaseEntry();
DatabaseEntry data = new DatabaseEntry();
return PGet(key, pkey, data, DbConstants.DB_PREV_DUP, info);
}
/// <summary>
/// If the cursor is not yet initialized, MovePrevUnique is identical to
/// <see cref="MoveLast()"/>. Otherwise, move the cursor to the previous
/// non-duplicate key in the database, and store the secondary key and
/// primary key/data pair in <see cref="Current"/>. MovePrevUnique will
/// return false if no non-duplicate key/data pairs exist after the
/// cursor position in the database.
/// </summary>
/// <remarks>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </remarks>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MovePrevUnique() { return MovePrevUnique(null); }
/// <summary>
/// If the cursor is not yet initialized, MovePrevUnique is identical to
/// <see cref="MoveLast(LockingInfo)"/>. Otherwise, move the cursor to
/// the previous non-duplicate key in the database, and store the
/// secondary key and primary key/data pair in <see cref="Current"/>.
/// MovePrevUnique will return false if no non-duplicate key/data pairs
/// exist after the cursor position in the database.
/// </summary>
/// <remarks>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </remarks>
/// <param name="info">The locking behavior to use.</param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MovePrevUnique(LockingInfo info) {
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry pkey = new DatabaseEntry();
DatabaseEntry data = new DatabaseEntry();
return PGet(key, pkey, data, DbConstants.DB_PREV_NODUP, info);
}
/// <summary>
/// Store the secondary key and primary key/data pair to which the
/// cursor refers in <see cref="Current"/>.
/// </summary>
/// <remarks>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </remarks>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool Refresh() { return Refresh(null); }
/// <summary>
/// Store the secondary key and primary key/data pair to which the
/// cursor refers in <see cref="Current"/>.
/// </summary>
/// <remarks>
/// If positioning the cursor fails, <see cref="Current"/> will contain
/// an empty <see cref="KeyValuePair{T,T}"/>.
/// </remarks>
/// <param name="info">The locking behavior to use.</param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool Refresh(LockingInfo info) {
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry pkey = new DatabaseEntry();
DatabaseEntry data = new DatabaseEntry();
return PGet(key, pkey, data, DbConstants.DB_CURRENT, info);
}
}
}
| |
namespace dotless.Test.Specs
{
using NUnit.Framework;
public class StringsFixture : SpecFixtureBase
{
[Test]
public void Strings()
{
AssertExpressionUnchanged(@"""http://son-of-a-banana.com""");
AssertExpressionUnchanged(@"""~"" ""~""");
AssertExpressionUnchanged(@"""#*%:&^,)!.(~*})""");
AssertExpressionUnchanged(@"""""");
}
[Test]
public void Comments()
{
AssertExpressionUnchanged(@"""/* hello */ // not-so-secret""");
}
[Test]
public void SingleQuotes()
{
AssertExpressionUnchanged(@"""'"" ""'""");
AssertExpressionUnchanged(@"'""""#!&""""'");
AssertExpressionUnchanged(@"''");
}
[Test]
public void EscapingQuotes()
{
AssertExpressionUnchanged(@"""\""""");
AssertExpressionUnchanged(@"'\''");
AssertExpressionUnchanged(@"'\'\""'");
}
[Test]
public void EscapingQuotesUnescaped()
{
AssertExpression(@"""", @"~""\""""");
AssertExpression(@"'", @"~""\'""");
}
[Test]
public void EscapedWithTilde()
{
AssertExpression(@"DX.Transform.MS.BS.filter(opacity=50)", @"~""DX.Transform.MS.BS.filter(opacity=50)""");
}
[Test]
public void StringInterpolation1()
{
var input = @"
#interpolation {
@var: '/dev';
url: ""http://lesscss.org@{var}/image.jpg"";
}
";
var expected = @"
#interpolation {
url: ""http://lesscss.org/dev/image.jpg"";
}";
AssertLess(input, expected);
}
[Test]
public void StringInterpolation2()
{
var input = @"
#interpolation {
@var2: 256;
url2: ""http://lesscss.org/image-@{var2}.jpg"";
}
";
var expected = @"
#interpolation {
url2: ""http://lesscss.org/image-256.jpg"";
}";
AssertLess(input, expected);
}
[Test]
public void StringInterpolation3()
{
var input = @"
#interpolation {
@var3: #456;
url3: ""http://lesscss.org@{var3}"";
}
";
var expected = @"
#interpolation {
url3: ""http://lesscss.org#445566"";
}";
AssertLess(input, expected);
}
[Test]
public void StringInterpolation4()
{
var input = @"
#interpolation {
@var4: hello;
url4: ""http://lesscss.org/@{var4}"";
}
";
var expected = @"
#interpolation {
url4: ""http://lesscss.org/hello"";
}";
AssertLess(input, expected);
}
[Test]
public void StringInterpolation5()
{
var input = @"
#interpolation {
@var5: 54.4px;
url5: ""http://lesscss.org/@{var5}"";
}
";
var expected = @"
#interpolation {
url5: ""http://lesscss.org/54.4px"";
}";
AssertLess(input, expected);
}
[Test]
public void StringInterpolationMultipleCalls()
{
var input = @"
.mix-mul (@a: green) {
color: ~""@{a}"";
}
.mix-mul-class {
.mix-mul(blue);
.mix-mul(red);
.mix-mul(orange);
}";
var expected = @"
.mix-mul-class {
color: blue;
color: red;
color: orange;
}";
AssertLess(input, expected);
}
[Test]
public void StringInterpolationInUrl()
{
var input = @"
#interpolation {
@var: '/dev';
url: url(""http://lesscss.org@{var}/image.jpg"");
}
";
var expected = @"
#interpolation {
url: url(""http://lesscss.org/dev/image.jpg"");
}";
AssertLess(input, expected);
}
[Test]
public void BracesInQuotes()
{
AssertExpressionUnchanged(@"""{"" ""}""");
}
[Test]
public void BracesInQuotesUneven()
{
AssertExpressionUnchanged(@"""{"" """"");
}
[Test]
public void SemiColonInQuotes()
{
AssertExpressionUnchanged(@"';'");
}
[Test]
public void CloseBraceInsideStringAfterQuoteInsideString()
{
var input = @"
#test {
prop: ""'test'"";
prop: ""}"";
}
";
AssertLessUnchanged(input);
}
[Test]
public void NewLineInStringNotSupported1()
{
// this was never supported in the parser but is now not supported in the tokenizer either
var input = @"""
""";
AssertExpressionError("Missing closing quote (\")", 0, input);
}
[Test]
public void NewLineInStringNotSupported2()
{
// this was never supported in the parser but is now not supported in the tokenizer either
var input = @"""\
""";
AssertExpressionError("Missing closing quote (\")", 0, input);
}
[Test]
public void NoEndDoubleQuote()
{
var input = @"
.cla { background-image: ""my-image.jpg; }
.clb { background-image: ""my-second-image.jpg""; }";
AssertError(
"Missing closing quote (\")",
".cla { background-image: \"my-image.jpg; }",
1,
25,
input);
}
[Test]
public void NoEndDoubleQuote2()
{
var input =
@"
.cla { background-image: ""my-image.jpg; }
.clb { background-position: 12px 3px; }";
AssertError(
"Missing closing quote (\")",
".cla { background-image: \"my-image.jpg; }",
1,
25,
input);
}
[Test]
public void NoEndSingleQuote()
{
var input = @"
.cla { background-image: 'my-image.jpg; }
.clb { background-image: 'my-second-image.jpg'; }";
AssertError(
"Missing closing quote (')",
".cla { background-image: 'my-image.jpg; }",
1,
25,
input);
}
[Test]
public void NoEndSingleQuote2()
{
var input = @"
.cla { background-image: 'my-image.jpg; }
.clb { background-position: 12px 3px; }";
AssertError(
"Missing closing quote (')",
".cla { background-image: 'my-image.jpg; }",
1,
25,
input);
}
[Test]
public void NoEndSingleQuote3()
{
var input = @"
.cla { background-image: 'my-image.jpg; } /* comment
.clb { background-position: 12px 3px; }*/";
AssertError(
"Missing closing quote (')",
".cla { background-image: 'my-image.jpg; } /* comment",
1,
25,
input);
}
[Test]
public void NoEndSingleQuote4()
{
var input = @".cla { background-image: 'my-image.jpg; }";
AssertError(
"Missing closing quote (')",
".cla { background-image: 'my-image.jpg; }",
1,
25,
input);
}
[Test]
public void EscapeCopesWithIE8Hack1()
{
var input = @"~""\9""";
var expected = @"\9";
AssertExpression(expected, input);
}
[Test]
public void EscapeCopesWithIE8Hack2()
{
var input = @"""\9""";
var expected = @"""\9""";
AssertExpression(expected, input);
}
[Test]
public void EscapeSlash()
{
// from less.js
var input = @"""\"" \\""";
var expected = @"""\"" \\""";
AssertExpression(expected, input);
}
[Test]
public void NoEndComment()
{
var input = @"
.cla { background-image: 'my-image.jpg'; } /* My comment starts here but isn't closed
.clb { background-image: 'my-second-image.jpg'; }";
AssertError(
"Missing closing comment",
".cla { background-image: 'my-image.jpg'; } /* My comment starts here but isn't closed",
1,
43,
input);
}
}
}
| |
// Copyright (c) rubicon IT GmbH, www.rubicon.eu
//
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership. rubicon licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
using System;
#if NET_3_5
using System.Diagnostics;
#endif
using System.Linq.Expressions;
using Remotion.Linq.Clauses.Expressions;
using Remotion.Linq.Utilities;
using Remotion.Utilities;
namespace Remotion.Linq.Clauses
{
/// <summary>
/// Represents the join part of a query, adding new data items and joining them with data items from previous clauses. This can either
/// be part of <see cref="QueryModel.BodyClauses"/> or of <see cref="GroupJoinClause"/>. The semantics of the <see cref="JoinClause"/>
/// is that of an inner join, i.e. only combinations where both an input item and a joined item exist are returned.
/// </summary>
/// <example>
/// In C#, the "join" clause in the following sample corresponds to a <see cref="JoinClause"/>. The <see cref="JoinClause"/> adds a new
/// query source to the query, selecting addresses (called "a") from the source "Addresses". It associates addresses and students by
/// comparing the students' "AddressID" properties with the addresses' "ID" properties. "a" corresponds to <see cref="ItemName"/> and
/// <see cref="ItemType"/>, "Addresses" is <see cref="InnerSequence"/> and the left and right side of the "equals" operator are held by
/// <see cref="OuterKeySelector"/> and <see cref="InnerKeySelector"/>, respectively:
/// <code>
/// var query = from s in Students
/// join a in Addresses on s.AdressID equals a.ID
/// select new { s, a };
/// </code>
/// </example>
public sealed class JoinClause : IBodyClause, IQuerySource
{
private Type _itemType;
private string _itemName;
private Expression _innerSequence;
private Expression _outerKeySelector;
private Expression _innerKeySelector;
/// <summary>
/// Initializes a new instance of the <see cref="JoinClause"/> class.
/// </summary>
/// <param name="itemName">A name describing the items generated by this <see cref="JoinClause"/>.</param>
/// <param name="itemType">The type of the items generated by this <see cref="JoinClause"/>.</param>
/// <param name="innerSequence">The expression that generates the inner sequence, i.e. the items of this <see cref="JoinClause"/>.</param>
/// <param name="outerKeySelector">An expression that selects the left side of the comparison by which source items and inner items are joined.</param>
/// <param name="innerKeySelector">An expression that selects the right side of the comparison by which source items and inner items are joined.</param>
public JoinClause (string itemName, Type itemType, Expression innerSequence, Expression outerKeySelector, Expression innerKeySelector)
{
ArgumentUtility.CheckNotNull ("itemName", itemName);
ArgumentUtility.CheckNotNull ("itemType", itemType);
ArgumentUtility.CheckNotNull ("innerSequence", innerSequence);
ArgumentUtility.CheckNotNull ("outerKeySelector", outerKeySelector);
ArgumentUtility.CheckNotNull ("innerKeySelector", innerKeySelector);
_itemName = itemName;
_itemType = itemType;
_innerSequence = innerSequence;
_outerKeySelector = outerKeySelector;
_innerKeySelector = innerKeySelector;
}
/// <summary>
/// Gets or sets the type of the items generated by this <see cref="JoinClause"/>.
/// </summary>
/// <note type="warning">
/// Changing the <see cref="ItemType"/> of a <see cref="IQuerySource"/> can make all <see cref="QuerySourceReferenceExpression"/> objects that
/// point to that <see cref="IQuerySource"/> invalid, so the property setter should be used with care.
/// </note>
public Type ItemType
{
get { return _itemType; }
set { _itemType = ArgumentUtility.CheckNotNull ("value", value); }
}
/// <summary>
/// Gets or sets a name describing the items generated by this <see cref="JoinClause"/>.
/// </summary>
/// <remarks>
/// Item names are inferred when a query expression is parsed, and they usually correspond to the variable names present in that expression.
/// However, note that names are not necessarily unique within a <see cref="QueryModel"/>. Use names only for readability and debugging, not for
/// uniquely identifying <see cref="IQuerySource"/> objects. To match an <see cref="IQuerySource"/> with its references, use the
/// <see cref="QuerySourceReferenceExpression.ReferencedQuerySource"/> property rather than the <see cref="ItemName"/>.
/// </remarks>
public string ItemName
{
get { return _itemName; }
set { _itemName = ArgumentUtility.CheckNotNullOrEmpty ("value", value); }
}
/// <summary>
/// Gets or sets the inner sequence, the expression that generates the inner sequence, i.e. the items of this <see cref="JoinClause"/>.
/// </summary>
/// <value>The inner sequence.</value>
#if NET_3_5
[DebuggerDisplay ("{Remotion.Linq.Clauses.ExpressionVisitors.FormattingExpressionVisitor.Format (InnerSequence),nq}")]
#endif
public Expression InnerSequence
{
get { return _innerSequence; }
set { _innerSequence = ArgumentUtility.CheckNotNull ("value", value); }
}
/// <summary>
/// Gets or sets the outer key selector, an expression that selects the right side of the comparison by which source items and inner items are joined.
/// </summary>
/// <value>The outer key selector.</value>
#if NET_3_5
[DebuggerDisplay ("{Remotion.Linq.Clauses.ExpressionVisitors.FormattingExpressionVisitor.Format (OuterKeySelector),nq}")]
#endif
public Expression OuterKeySelector
{
get { return _outerKeySelector; }
set { _outerKeySelector = ArgumentUtility.CheckNotNull ("value", value); }
}
/// <summary>
/// Gets or sets the inner key selector, an expression that selects the left side of the comparison by which source items and inner items are joined.
/// </summary>
/// <value>The inner key selector.</value>
#if NET_3_5
[DebuggerDisplay ("{Remotion.Linq.Clauses.ExpressionVisitors.FormattingExpressionVisitor.Format (InnerKeySelector),nq}")]
#endif
public Expression InnerKeySelector
{
get { return _innerKeySelector; }
set { _innerKeySelector = ArgumentUtility.CheckNotNull ("value", value); }
}
/// <summary>
/// Accepts the specified visitor by calling its <see cref="IQueryModelVisitor.VisitJoinClause(Remotion.Linq.Clauses.JoinClause,Remotion.Linq.QueryModel,int)"/>
/// method.
/// </summary>
/// <param name="visitor">The visitor to accept.</param>
/// <param name="queryModel">The query model in whose context this clause is visited.</param>
/// <param name="index">The index of this clause in the <paramref name="queryModel"/>'s <see cref="QueryModel.BodyClauses"/> collection.</param>
public void Accept (IQueryModelVisitor visitor, QueryModel queryModel, int index)
{
ArgumentUtility.CheckNotNull ("visitor", visitor);
ArgumentUtility.CheckNotNull ("queryModel", queryModel);
visitor.VisitJoinClause (this, queryModel, index);
}
/// <summary>
/// Accepts the specified visitor by calling its <see cref="IQueryModelVisitor.VisitJoinClause(Remotion.Linq.Clauses.JoinClause,Remotion.Linq.QueryModel,Remotion.Linq.Clauses.GroupJoinClause)"/>
/// method. This overload is used when visiting a <see cref="JoinClause"/> that is held by a <see cref="GroupJoinClause"/>.
/// </summary>
/// <param name="visitor">The visitor to accept.</param>
/// <param name="queryModel">The query model in whose context this clause is visited.</param>
/// <param name="groupJoinClause">The <see cref="GroupJoinClause"/> holding this <see cref="JoinClause"/> instance.</param>
public void Accept (IQueryModelVisitor visitor, QueryModel queryModel, GroupJoinClause groupJoinClause)
{
ArgumentUtility.CheckNotNull ("visitor", visitor);
ArgumentUtility.CheckNotNull ("queryModel", queryModel);
ArgumentUtility.CheckNotNull ("groupJoinClause", groupJoinClause);
visitor.VisitJoinClause (this, queryModel, groupJoinClause);
}
/// <summary>
/// Clones this clause, registering its clone with the <paramref name="cloneContext"/>.
/// </summary>
/// <param name="cloneContext">The clones of all query source clauses are registered with this <see cref="CloneContext"/>.</param>
/// <returns>A clone of this clause.</returns>
public JoinClause Clone (CloneContext cloneContext)
{
ArgumentUtility.CheckNotNull ("cloneContext", cloneContext);
var clone = new JoinClause (ItemName, ItemType, InnerSequence, OuterKeySelector, InnerKeySelector);
cloneContext.QuerySourceMapping.AddMapping (this, new QuerySourceReferenceExpression (clone));
return clone;
}
IBodyClause IBodyClause.Clone (CloneContext cloneContext)
{
return Clone (cloneContext);
}
/// <summary>
/// Transforms all the expressions in this clause and its child objects via the given <paramref name="transformation"/> delegate.
/// </summary>
/// <param name="transformation">The transformation object. This delegate is called for each <see cref="Expression"/> within this
/// clause, and those expressions will be replaced with what the delegate returns.</param>
public void TransformExpressions (Func<Expression, Expression> transformation)
{
ArgumentUtility.CheckNotNull ("transformation", transformation);
InnerSequence = transformation (InnerSequence);
OuterKeySelector = transformation (OuterKeySelector);
InnerKeySelector = transformation (InnerKeySelector);
}
public override string ToString ()
{
return string.Format (
"join {0} {1} in {2} on {3} equals {4}",
ItemType.Name,
ItemName,
InnerSequence.BuildString(),
OuterKeySelector.BuildString(),
InnerKeySelector.BuildString());
}
}
}
| |
// -----
// GNU General Public License
// The Forex Professional Analyzer is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
// The Forex Professional Analyzer is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
// See the GNU Lesser General Public License for more details.
// -----
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace fxpa
{
public class LineObject : DynamicCustomObject
{
public enum ModeEnum
{
LineSegment,
Line,
HorizontalLine,
VerticalLine
}
ModeEnum _mode;
public ModeEnum Mode
{
get { return _mode; }
}
Pen _pen = Pens.White;
public Pen Pen
{
get { return _pen; }
set { _pen = value; }
}
public override bool IsBuilding
{
get
{
if (_mode == ModeEnum.Line || _mode == ModeEnum.LineSegment)
{
return _controlPoints.Count < 2;
}
else
{
return _controlPoints.Count < 1;
}
}
}
/// <summary>
///
/// </summary>
public LineObject(string name, ModeEnum mode)
: base(name)
{
_mode = mode;
}
public override RectangleF GetContainingRectangle(RectangleF drawingSpace)
{
if (_controlPoints.Count < 2)
{
return RectangleF.Empty;
}
if (_mode == ModeEnum.LineSegment)
{// Base method relies on control points and is good in this scenario.
return base.GetContainingRectangle(drawingSpace);
}
else if (_mode == ModeEnum.Line)
{
PointF point1 = _controlPoints[0];
PointF point2 = _controlPoints[1];
StretchSegmentToDrawingSpace(ref point1, ref point2, drawingSpace);
return new RectangleF(point1.X, point1.Y, point2.X - point1.X, point2.Y - point1.Y);
}
return RectangleF.Empty;
}
public override bool TrySelect(Matrix transformationMatrix, PointF drawingSpaceSelectionPoint, float absoluteSelectionMargin, bool canLoseSelection)
{
if (IsBuilding)
{
return false;
}
PointF point1 = _controlPoints[0];
PointF point2;
if (_mode == ModeEnum.Line || _mode == ModeEnum.LineSegment)
{
point2 = _controlPoints[1];
}
else if (_mode == ModeEnum.HorizontalLine)
{
point2 = new PointF(point1.X + 1, point1.Y);
}
else if (_mode == ModeEnum.VerticalLine)
{
point2 = new PointF(point1.X, point1.Y + 1);
}
else
{
// SystemMonitor.Throw("Unhandled case.");
return false;
}
if (TrySelectControlPoints(transformationMatrix, drawingSpaceSelectionPoint, absoluteSelectionMargin) > 0
|| TrySelectLine(transformationMatrix, _mode == ModeEnum.LineSegment, point1, point2, drawingSpaceSelectionPoint, absoluteSelectionMargin))
{
Selected = true;
return true;
}
if (canLoseSelection)
{
Selected = false;
}
return false;
}
public override bool AddBuildingPoint(PointF point)
{
_controlPoints.Add(point);
return !IsBuilding;
}
public override void Draw(GraphicsWrapper g, PointF? mousePosition, RectangleF clippingRectangle, RectangleF drawingSpace)
{
if (Visible == false)
{
return;
}
if (_controlPoints.Count < 1)
{
return;
}
if (_mode == ModeEnum.HorizontalLine || _mode == ModeEnum.VerticalLine)
{
PointF point1 = _controlPoints[0];
PointF point2 = new PointF(drawingSpace.X + drawingSpace.Width, _controlPoints[0].Y);
if (_mode == ModeEnum.VerticalLine)
{
point2 = new PointF(_controlPoints[0].X, drawingSpace.Y + drawingSpace.Height);
}
StretchSegmentToDrawingSpace(ref point1, ref point2, drawingSpace);
g.DrawLine(_pen, point1, point2);
if (Selected)
{
DrawControlPoints(g);
}
}
else
if (_controlPoints.Count == 1 && mousePosition.HasValue)
{
PointF point1 = _controlPoints[0];
PointF point2 = mousePosition.Value;
if (_mode == ModeEnum.Line)
{
StretchSegmentToDrawingSpace(ref point1, ref point2, drawingSpace);
}
g.DrawLine(_pen, point1, point2);
}
else if (_controlPoints.Count == 2)
{
PointF point1 = _controlPoints[0];
PointF point2 = _controlPoints[1];
if (_mode == ModeEnum.Line)
{
StretchSegmentToDrawingSpace(ref point1, ref point2, drawingSpace);
}
// Clipping opitmization.
RectangleF rectangle = new RectangleF(
Math.Min(point1.X, point2.X), Math.Min(point1.Y, point2.Y),
Math.Abs(point2.X - point1.X), Math.Abs(point2.Y - point1.Y));
if (rectangle.IntersectsWith(clippingRectangle) == false)
{
return;
}
//if (_isSegment == false)
//{// Draw the central line piece separately.
//g.DrawLine(_pen, _controlPoints[0], _controlPoints[1]);
//}
g.DrawLine(_pen, point1, point2);
if (Selected)
{
DrawControlPoints(g);
}
}
}
}
}
| |
#region Copyright (c) 2006-2008, Nate Zobrist
/*
* Copyright (c) 2006-2008, Nate Zobrist
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with
* the distribution.
* Neither the name of "Nate Zobrist" 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 Copyright (c) 2006-2008, Nate Zobrist
using System;
using System.Collections.Generic;
using System.Xml;
namespace Delicious
{
public class Bundle
{
private string _Name;
private string _Tags;
public Bundle ()
{
}
public Bundle (string name, string tags)
{
this.Name = name;
this.Tags = tags;
}
public string Name
{
get { return this._Name; }
set { this._Name = value; }
}
public string Tags
{
get { return this._Tags; }
set { this._Tags = value; }
}
public string[] GetTagsAsArray ()
{
if (this.Tags == null || this.Tags.Length == 0)
return null;
return this.Tags.Split (' ');
}
public override string ToString ()
{
return this.Name + " : " + this.Tags;
}
public override bool Equals (object obj)
{
if (!(obj is Bundle))
return false;
return (this == (Bundle)obj);
}
public override int GetHashCode ()
{
return this.Name.GetHashCode();
}
/// <summary>
/// Determines whether the specified object instances are the same instance
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public bool ReferenceEquals (object obj)
{
return Object.ReferenceEquals (this, obj);
}
#region Static Methods
public static bool operator == (Bundle bundle1, Bundle bundle2)
{
if ((object)bundle1 == null)
return ((object)bundle2 == null);
else if ((object)bundle2 == null)
return false;
return (bundle1.Name == bundle2.Name &&
bundle1.Tags == bundle2.Tags);
}
public static bool operator != (Bundle bundle1, Bundle bundle2)
{
return !(bundle1 == bundle2);
}
/// <summary>
/// Add a new Bundle of Tags. If either <c>bundleName</c> or <c>tags</c> is null or String.Empty,
/// we immediately return false.
/// </summary>
/// <param name="bundleName">Name of the bundle</param>
/// <param name="tags">Space-seperated list of tags</param>
/// <returns><c>true</c> if the Bundle was created, <c>false</c> otherwise</returns>
public static bool Add (string bundleName, string tags)
{
if (bundleName == null || bundleName.Length == 0 ||
tags == null || tags.Length == 0)
{
return false;
}
string relativeUrl = Constants.RelativeUrl.BundlesSet;
relativeUrl = Utilities.AddParameter (relativeUrl, Constants.UrlParameter.Bundle, bundleName);
relativeUrl = Utilities.AddParameter (relativeUrl, Constants.UrlParameter.Tags, tags);
XmlDocument xmlDoc = Connection.Connect (relativeUrl);
string resultCode = Utilities.ParseForResultCode (xmlDoc.DocumentElement);
return (resultCode == Constants.ReturnCode.Ok);
}
/// <summary>
/// Delete the specified Bundle. If the <c>bundleName</c> is null or String.Empty,
/// we immediately return false.
/// </summary>
/// <param name="bundleName">Name of the bundle to delete</param>
/// <returns><c>true</c> if the Bundle was deleted, <c>false</c> otherwise</returns>
public static bool Delete (string bundleName)
{
if (bundleName == null || bundleName.Length == 0)
return false;
string relativeUrl = Constants.RelativeUrl.BundlesDelete;
relativeUrl = Utilities.AddParameter (relativeUrl, Constants.UrlParameter.Bundle, bundleName);
XmlDocument xmlDoc = Connection.Connect (relativeUrl);
string resultCode = Utilities.ParseForResultCode (xmlDoc.DocumentElement);
return (resultCode == Constants.ReturnCode.Ok);
}
/// <summary>
/// Return a list of <c>Bundle</c> objects
/// </summary>
/// <returns>List of <c>Bundle</c> objects</returns>
public static List<Bundle> Get ()
{
XmlDocument xmlDoc = Connection.Connect (Constants.RelativeUrl.BundlesAll);
XmlNodeList nodeList = xmlDoc.DocumentElement.GetElementsByTagName (Constants.XmlTag.Bundle);
List<Bundle> bundles = new List<Bundle> (nodeList.Count);
foreach (XmlNode node in nodeList)
{
string name = node.Attributes[ Constants.XmlAttribute.Name ].Value;
string tags = node.Attributes[ Constants.XmlAttribute.Tags ].Value;
Bundle bundle = new Bundle (name, tags);
bundles.Add (bundle);
}
return bundles;
}
#endregion Static Methods
}
}
| |
//
// Copyright 2013 Matthew Ducker
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.IO;
namespace Obscur.Core
{
/// <summary>
/// Extension methods for writing and reading to/from streams.
/// </summary>
public static class StreamExtensions
{
/// <summary>
/// Writes a boolean value to a stream as a byte (0 or 1).
/// </summary>
/// <param name="stream">Stream to write to.</param>
/// <param name="value">Boolean value to write.</param>
public static void WriteBoolean(this Stream stream, bool value)
{
stream.WriteByte(value ? (byte) 1 : (byte) 0);
}
/// <summary>
/// Reads a boolean value from a stream as a byte (0 or 1).
/// </summary>
/// <param name="stream">Stream to read from.</param>
public static bool ReadBoolean(this Stream stream)
{
int b = stream.ReadByte();
return b != 0;
}
/// <summary>
/// Encode an unsigned integer as a variable-length
/// integer and write it to a stream.
/// </summary>
/// <param name="stream">Stream to write to.</param>
/// <param name="value">Integer to encode and write.</param>
public static void WriteUInt16(this Stream stream, UInt16 value)
{
WriteVarint32(stream, value);
}
/// <summary>
/// Reads an unsigned integer that was encoded as a
/// variable-length integer from a stream.
/// </summary>
/// <param name="stream">Stream to read from.</param>
public static UInt16 ReadUInt16(this Stream stream)
{
return (UInt16)ReadVarint32(stream);
}
/// <summary>
/// Encodes a signed integer as a 'zig-zag' variable-length
/// integer and writes it to a stream.
/// </summary>
/// <param name="stream">Stream to write to.</param>
/// <param name="value">Integer to encode and write.</param>
public static void WriteInt16(this Stream stream, Int16 value)
{
WriteVarint32(stream, EncodeZigZag32(value));
}
/// <summary>
/// Reads a signed integer that was encoded as a
/// 'zig-zag' variable-length integer from a stream.
/// </summary>
/// <param name="stream">Stream to read from.</param>
public static Int16 ReadInt16(this Stream stream)
{
return (Int16)DecodeZigZag32(ReadVarint32(stream));
}
/// <summary>
/// Encodes an unsigned integer as a variable-length
/// integer and writes it to a stream.
/// </summary>
/// <param name="stream">Stream to write to.</param>
/// <param name="value">Integer to encode and write.</param>
public static void WriteUInt32(this Stream stream, uint value)
{
WriteVarint32(stream, value);
}
/// <summary>
/// Reads an unsigned integer that was encoded as a
/// variable-length integer from a stream.
/// </summary>
/// <param name="stream">Stream to read from.</param>
public static UInt32 ReadUInt32(this Stream stream)
{
return ReadVarint32(stream);
}
/// <summary>
/// Encodes a signed integer as a 'zig-zag' variable-length
/// integer and writes it to a stream.
/// </summary>
/// <param name="stream">Stream to write to.</param>
/// <param name="value">Integer to encode and write.</param>
public static void WriteInt32(this Stream stream, Int32 value)
{
WriteVarint32(stream, EncodeZigZag32(value));
}
/// <summary>
/// Reads a signed integer that was encoded as a
/// 'zig-zag' variable-length integer from a stream.
/// </summary>
/// <param name="stream">Stream to read from.</param>
public static Int32 ReadInt32(this Stream stream)
{
return DecodeZigZag32(ReadVarint32(stream));
}
/// <summary>
/// Encodes an unsigned integer as a variable-length
/// integer and writes it to a stream.
/// </summary>
/// <param name="stream">Stream to write to.</param>
/// <param name="value">Integer to encode and write.</param>
public static void WriteUInt64(this Stream stream, UInt64 value)
{
WriteVarint64(stream, value);
}
/// <summary>
/// Reads an unsigned integer that was encoded as a
/// variable-length integer from a stream.
/// </summary>
/// <param name="stream">Stream to read from.</param>
public static UInt64 ReadUInt64(this Stream stream)
{
return ReadVarint64(stream);
}
/// <summary>
/// Encodes a signed integer as a 'zig-zag' variable-length
/// integer and writes it to a stream.
/// </summary>
/// <param name="stream">Stream to write to.</param>
/// <param name="value">Integer to encode and write.</param>
public static void WriteInt64(this Stream stream, Int64 value)
{
WriteVarint64(stream, EncodeZigZag64(value));
}
/// <summary>
/// Reads a signed integer that was encoded as a
/// 'zig-zag' variable-length integer from a stream.
/// </summary>
/// <param name="stream">Stream to read from.</param>
public static Int64 ReadInt64(this Stream stream)
{
return DecodeZigZag64(ReadVarint64(stream));
}
#if INCLUDE_UNSAFE
/// <summary>
/// Encodes a single-precision (32-bit) floating-point number as
/// a variable-length integer and writes it to a stream.
/// </summary>
/// <param name="stream">Stream to write to.</param>
/// <param name="value">Integer to encode and write.</param>
public static unsafe void WriteSingle(this Stream stream, Single value)
{
UInt32 v = *(UInt32*)(&value);
WriteVarint32(stream, v);
}
/// <summary>
/// Reads a single-precision (32-bit) floating-point number
/// that was encoded as a variable-length integer from a stream.
/// </summary>
/// <param name="stream">Stream to read from.</param>
public static unsafe Single ReadSingle(this Stream stream)
{
UInt32 v = ReadVarint32(stream);
return *(Single*)(&v);
}
/// <summary>
/// Encodes a double-precision (64-bit) floating-point number as
/// a variable-length integer and writes it to a stream.
/// </summary>
/// <param name="stream">Stream to write to.</param>
/// <param name="value">Integer to encode and write.</param>
public static unsafe void WriteDouble(this Stream stream, Double value)
{
UInt64 v = *(UInt64*)(&value);
WriteVarint64(stream, v);
}
/// <summary>
/// Reads a double-precision (32-bit) floating-point number
/// that was encoded as a variable-length integer from a stream.
/// </summary>
/// <param name="stream">Stream to read from.</param>
public static unsafe Double ReadDouble(this Stream stream)
{
UInt64 v = ReadVarint64(stream);
return *(Double*)(&v);
}
#endif
private static UInt32 EncodeZigZag32(Int32 n)
{
return (UInt32)((n << 1) ^ (n >> 31));
}
private static UInt64 EncodeZigZag64(Int64 n)
{
return (UInt64)((n << 1) ^ (n >> 63));
}
private static Int32 DecodeZigZag32(UInt32 n)
{
return (Int32)(n >> 1) ^ -(Int32)(n & 1);
}
private static Int64 DecodeZigZag64(UInt64 n)
{
return (Int64)(n >> 1) ^ -(Int64)(n & 1);
}
private static UInt32 ReadVarint32(Stream stream)
{
int result = 0;
int offset = 0;
for (; offset < 32; offset += 7) {
int b = stream.ReadByte();
if (b == -1) {
throw new EndOfStreamException();
}
result |= (b & 0x7f) << offset;
if ((b & 0x80) == 0) {
return (UInt32)result;
}
}
throw new InvalidDataException();
}
private static void WriteVarint32(Stream stream, UInt32 value)
{
for (; value >= 0x80u; value >>= 7) {
stream.WriteByte((byte) (value | 0x80u));
}
stream.WriteByte((byte) value);
}
private static UInt64 ReadVarint64(Stream stream)
{
long result = 0;
int offset = 0;
for (; offset < 64; offset += 7) {
int b = stream.ReadByte();
if (b == -1) {
throw new EndOfStreamException();
}
result |= ((long) (b & 0x7f)) << offset;
if ((b & 0x80) == 0) {
return (UInt64)result;
}
}
throw new InvalidDataException();
}
private static void WriteVarint64(Stream stream, UInt64 value)
{
for (; value >= 0x80u; value >>= 7) {
stream.WriteByte((byte) (value | 0x80u));
}
stream.WriteByte((byte) value);
}
}
}
| |
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
#if DLAB_UNROOT_NAMESPACE || DLAB_XRM
namespace DLaB.Xrm
#else
namespace Source.DLaB.Xrm
#endif
{
public static partial class Extensions
{
#region IOrganizationService
#region GetEntityOrDefault
/// <summary>
/// Gets the entity by id. Null is returned if it isn't found.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="logicalName">Logical name of the entity.</param>
/// <param name="id">Id of the entity to search for.</param>
/// <returns></returns>
public static Entity GetEntityOrDefault(this IOrganizationService service, string logicalName, Guid id)
{
return service.GetFirstOrDefault(logicalName, EntityHelper.GetIdAttributeName(logicalName), id);
}
/// <summary>
/// Gets the entity by id. Null is returned if it isn't found.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="logicalName">Logical name of the entity.</param>
/// <param name="id">Id of the entity to search for.</param>
/// <param name="columnSet">Columns to retrieve.</param>
/// <returns></returns>
public static Entity GetEntityOrDefault(this IOrganizationService service, string logicalName, Guid id, ColumnSet columnSet)
{
return service.GetFirstOrDefault(logicalName, EntityHelper.GetIdAttributeName(logicalName), id);
}
/// <summary>
/// Gets the first entity that matches the query expression. Null is returned if none are found.
/// </summary>
/// <typeparam name="T">The Entity Type.</typeparam>
/// <param name="service">The service.</param>
/// <param name="id">Id of the entity to search for.</param>
/// <returns></returns>
public static T GetEntityOrDefault<T>(this IOrganizationService service, Guid id) where T : Entity
{
return service.GetFirstOrDefault<T>(EntityHelper.GetIdAttributeName<T>(), id);
}
/// <summary>
/// Gets the first entity that matches the query expression. Null is returned if none are found.
/// </summary>
/// <typeparam name="T">The Entity Type.</typeparam>
/// <param name="service">The service.</param>
/// <param name="id">Id of the entity to search for.</param>
/// <param name="anonymousTypeInitializer">An Anonymous Type Initializer where the properties of the anonymous
/// type are the column names to add.</param>
/// <returns></returns>
public static T GetEntityOrDefault<T>(this IOrganizationService service, Guid id, Expression<Func<T, object>> anonymousTypeInitializer) where T : Entity
{
return service.GetFirstOrDefault(anonymousTypeInitializer, EntityHelper.GetIdAttributeName<T>(), id);
}
#endregion GetEntityOrDefault
#region GetEntitiesById
/// <summary>
/// Gets the first 5000 active entities with the given ids.
/// </summary>
/// <param name="service">The IOrganizationService.</param>
/// <param name="logicalName">Logical name of the entity.</param>
/// <param name="ids">Ids of the entity to search for.</param>
/// <returns></returns>
public static List<Entity> GetEntitiesById(this IOrganizationService service,
string logicalName, IEnumerable<Guid> ids)
{
return service.GetEntitiesIn(logicalName, EntityHelper.GetIdAttributeName(logicalName), ids);
}
/// <summary>
/// Gets the first 5000 active entities with the given ids.
/// </summary>
/// <param name="service">The IOrganizationService.</param>
/// <param name="logicalName">Logical name of the entity.</param>
/// <param name="ids">Ids of the entity to search for.</param>
/// <returns></returns>
public static List<Entity> GetEntitiesById(this IOrganizationService service,
string logicalName, params Guid[] ids)
{
return service.GetEntitiesIn(logicalName, EntityHelper.GetIdAttributeName(logicalName), ids);
}
/// <summary>
/// Gets the first 5000 active entities (with the given subset of columns only) with the given ids.
/// </summary>
/// <param name="service">The IOrganizationService.</param>
/// <param name="columnSet">Columns to retrieve.</param>
/// <param name="logicalName">Logical name of the entity.</param>
/// <param name="ids">Ids of the entity to search for.</param>
/// <returns></returns>
public static List<Entity> GetEntitiesById(this IOrganizationService service, string logicalName,
ColumnSet columnSet, IEnumerable<Guid> ids)
{
return service.GetEntitiesIn(logicalName, columnSet, EntityHelper.GetIdAttributeName(logicalName), ids);
}
/// <summary>
/// Gets the first 5000 active entities (with the given subset of columns only) with the given ids.
/// </summary>
/// <param name="service">The IOrganizationService.</param>
/// <param name="columnSet">Columns to retrieve.</param>
/// <param name="logicalName">Logical name of the entity.</param>
/// <param name="ids">Ids of the entity to search for.</param>
/// <returns></returns>
public static List<Entity> GetEntitiesById(this IOrganizationService service, string logicalName,
ColumnSet columnSet, params Guid[] ids)
{
return service.GetEntitiesIn(logicalName, columnSet, EntityHelper.GetIdAttributeName(logicalName), ids);
}
#endregion GetEntitiesById
#region GetEntitiesById<T>
/// <summary>
/// Gets the first 5000 active entities with the given ids.
/// </summary>
/// <typeparam name="T">Type of Entity List to return</typeparam>
/// <param name="service">The IOrganizationService.</param>
/// <param name="ids">Ids of the entity to search for.</param>
/// <returns></returns>
public static List<T> GetEntitiesById<T>(this IOrganizationService service, IEnumerable<Guid> ids) where T : Entity
{
return service.GetEntitiesIn<T>(EntityHelper.GetIdAttributeName<T>(), ids);
}
/// <summary>
/// Gets the first 5000 active entities with the given ids.
/// </summary>
/// <typeparam name="T">Type of Entity List to return.</typeparam>
/// <param name="service">The IOrganizationService.</param>
/// <param name="ids">Ids of the entity to search for.</param>
/// <returns></returns>
public static List<T> GetEntitiesById<T>(this IOrganizationService service, params Guid[] ids) where T : Entity
{
return service.GetEntitiesIn<T>(EntityHelper.GetIdAttributeName<T>(), ids);
}
/// <summary>
/// Gets the first 5000 active entities (with the given subset of columns only) with the given ids.
/// </summary>
/// <typeparam name="T">Type of Entity List to return.</typeparam>
/// <param name="service">The IOrganizationService.</param>
/// <param name="anonymousTypeInitializer">An Anonymous Type Initializer where the properties of the anonymous
/// type are the column names to add.</param>
/// <param name="ids">Ids of the entity to search for.</param>
/// <returns></returns>
public static List<T> GetEntitiesById<T>(this IOrganizationService service, Expression<Func<T, object>> anonymousTypeInitializer,
IEnumerable<Guid> ids) where T : Entity
{
return service.GetEntitiesIn(anonymousTypeInitializer, EntityHelper.GetIdAttributeName<T>(), ids);
}
/// <summary>
/// Gets the first 5000 active entities (with the given subset of columns only) with the given ids.
/// </summary>
/// <typeparam name="T">Type of Entity List to return.</typeparam>
/// <param name="service">The IOrganizationService.</param>
/// <param name="anonymousTypeInitializer">An Anonymous Type Initializer where the properties of the anonymous
/// type are the column names to add.</param>
/// <param name="ids">Ids of the entity to search for.</param>
/// <returns></returns>
public static List<T> GetEntitiesById<T>(this IOrganizationService service, Expression<Func<T, object>> anonymousTypeInitializer,
params Guid[] ids) where T : Entity
{
return service.GetEntitiesIn(anonymousTypeInitializer, EntityHelper.GetIdAttributeName<T>(), ids);
}
/// <summary>
/// Gets the first 5000 active entities (with the given subset of columns only) with the given ids.
/// </summary>
/// <typeparam name="T">Type of Entity List to return.</typeparam>
/// <param name="service">The IOrganizationService.</param>
/// <param name="columnSet">Columns to retrieve</param>
/// <param name="ids">Ids of the entity to search for.</param>
/// <returns></returns>
public static List<T> GetEntitiesById<T>(this IOrganizationService service, ColumnSet columnSet, IEnumerable<Guid> ids) where T : Entity
{
return service.GetEntitiesIn<T>(columnSet, EntityHelper.GetIdAttributeName<T>(), ids);
}
/// <summary>
/// Gets first 5000 Active Entities (with the given subset of columns only)
/// where the columnNameAndValue Pairs match.
/// </summary>
/// <typeparam name="T">Type of Entity List to return.</typeparam>
/// <param name="service">The IOrganizationService.</param>
/// <param name="columnSet">Columns to retrieve.</param>
/// <param name="ids">Ids of the entity to search for.</param>
/// <returns></returns>
public static List<T> GetEntitiesById<T>(this IOrganizationService service, ColumnSet columnSet, params Guid[] ids) where T : Entity
{
return service.GetEntitiesIn<T>(columnSet, EntityHelper.GetIdAttributeName<T>(), ids);
}
#endregion GetEntitiesById<T>
#endregion IOrganizationServic
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Host;
using System.Reflection;
using System.Globalization;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// This class implements get-member command.
/// </summary>
[Cmdlet(VerbsCommon.Add, "Member", DefaultParameterSetName = "TypeNameSet",
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113280", RemotingCapability = RemotingCapability.None)]
public class AddMemberCommand : PSCmdlet
{
private static object s_notSpecified = new object();
private static bool HasBeenSpecified(object obj)
{
return !System.Object.ReferenceEquals(obj, s_notSpecified);
}
private PSObject _inputObject;
/// <summary>
/// The object to add a member to.
/// </summary>
[Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = "MemberSet")]
[Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = "TypeNameSet")]
[Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = NotePropertySingleMemberSet)]
[Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = NotePropertyMultiMemberSet)]
public PSObject InputObject
{
set { _inputObject = value; }
get { return _inputObject; }
}
private PSMemberTypes _memberType;
/// <summary>
/// The member type of to be added.
/// </summary>
[Parameter(Mandatory = true, Position = 0, ParameterSetName = "MemberSet")]
[Alias("Type")]
public PSMemberTypes MemberType
{
set { _memberType = value; }
get { return _memberType; }
}
private string _memberName;
/// <summary>
/// The name of the new member.
/// </summary>
[Parameter(Mandatory = true, Position = 1, ParameterSetName = "MemberSet")]
public string Name
{
set { _memberName = value; }
get { return _memberName; }
}
private object _value1 = s_notSpecified;
/// <summary>
/// First value of the new member. The meaning of this value changes according to the member type.
/// </summary>
[Parameter(Position = 2, ParameterSetName = "MemberSet")]
public object Value
{
set { _value1 = value; }
get { return _value1; }
}
private object _value2 = s_notSpecified;
/// <summary>
/// Second value of the new member. The meaning of this value changes according to the member type.
/// </summary>
[Parameter(Position = 3, ParameterSetName = "MemberSet")]
public object SecondValue
{
set { _value2 = value; }
get { return _value2; }
}
private string _typeName;
/// <summary>
/// Add new type name to the specified object for TypeNameSet.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = "TypeNameSet")]
[Parameter(ParameterSetName = "MemberSet")]
[Parameter(ParameterSetName = NotePropertySingleMemberSet)]
[Parameter(ParameterSetName = NotePropertyMultiMemberSet)]
[ValidateNotNullOrEmpty]
public string TypeName
{
set { _typeName = value; }
get { return _typeName; }
}
private bool _force;
/// <summary>
/// True if we should overwrite a possibly existing member.
/// </summary>
[Parameter(ParameterSetName = "MemberSet")]
[Parameter(ParameterSetName = NotePropertySingleMemberSet)]
[Parameter(ParameterSetName = NotePropertyMultiMemberSet)]
public SwitchParameter Force
{
set { _force = value; }
get { return _force; }
}
private bool _passThru /* = false */;
/// <summary>
/// Gets or sets the parameter -passThru which states output from the command should be placed in the pipeline.
/// </summary>
[Parameter(ParameterSetName = "MemberSet")]
[Parameter(ParameterSetName = "TypeNameSet")]
[Parameter(ParameterSetName = NotePropertySingleMemberSet)]
[Parameter(ParameterSetName = NotePropertyMultiMemberSet)]
public SwitchParameter PassThru
{
set { _passThru = value; }
get { return _passThru; }
}
#region Simplifying NoteProperty Declaration
private const string NotePropertySingleMemberSet = "NotePropertySingleMemberSet";
private const string NotePropertyMultiMemberSet = "NotePropertyMultiMemberSet";
private string _notePropertyName;
/// <summary>
/// The name of the new NoteProperty member.
/// </summary>
[Parameter(Mandatory = true, Position = 0, ParameterSetName = NotePropertySingleMemberSet)]
[ValidateNotePropertyNameAttribute()]
[NotePropertyTransformationAttribute()]
[ValidateNotNullOrEmpty]
public string NotePropertyName
{
set { _notePropertyName = value; }
get { return _notePropertyName; }
}
private object _notePropertyValue;
/// <summary>
/// The value of the new NoteProperty member.
/// </summary>
[Parameter(Mandatory = true, Position = 1, ParameterSetName = NotePropertySingleMemberSet)]
[AllowNull]
public object NotePropertyValue
{
set { _notePropertyValue = value; }
get { return _notePropertyValue; }
}
// Use IDictionary to support both Hashtable and OrderedHashtable
private IDictionary _property;
/// <summary>
/// The NoteProperty members to be set.
/// </summary>
[Parameter(Mandatory = true, Position = 0, ParameterSetName = NotePropertyMultiMemberSet)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public IDictionary NotePropertyMembers
{
get { return _property; }
set { _property = value; }
}
#endregion Simplifying NoteProperty Declaration
private static object GetParameterType(object sourceValue, Type destinationType)
{
return LanguagePrimitives.ConvertTo(sourceValue, destinationType, CultureInfo.InvariantCulture);
}
private void EnsureValue1AndValue2AreNotBothNull()
{
if (_value1 == null &&
(_value2 == null || !HasBeenSpecified(_value2)))
{
ThrowTerminatingError(NewError("Value1AndValue2AreNotBothNull", "Value1AndValue2AreNotBothNull", null, _memberType));
}
}
private void EnsureValue1IsNotNull()
{
if (_value1 == null)
{
ThrowTerminatingError(NewError("Value1ShouldNotBeNull", "Value1ShouldNotBeNull", null, _memberType));
}
}
private void EnsureValue2IsNotNull()
{
if (_value2 == null)
{
ThrowTerminatingError(NewError("Value2ShouldNotBeNull", "Value2ShouldNotBeNull", null, _memberType));
}
}
private void EnsureValue1HasBeenSpecified()
{
if (!HasBeenSpecified(_value1))
{
Collection<FieldDescription> fdc = new Collection<FieldDescription>();
fdc.Add(new FieldDescription("Value"));
string prompt = StringUtil.Format(AddMember.Value1Prompt, _memberType);
Dictionary<string, PSObject> result = this.Host.UI.Prompt(prompt, null, fdc);
if (result != null)
{
_value1 = result["Value"].BaseObject;
}
}
}
private void EnsureValue2HasNotBeenSpecified()
{
if (HasBeenSpecified(_value2))
{
ThrowTerminatingError(NewError("Value2ShouldNotBeSpecified", "Value2ShouldNotBeSpecified", null, _memberType));
}
}
private PSMemberInfo GetAliasProperty()
{
EnsureValue1HasBeenSpecified();
EnsureValue1IsNotNull();
string value1Str = (string)GetParameterType(_value1, typeof(string));
if (HasBeenSpecified(_value2))
{
EnsureValue2IsNotNull();
Type value2Type = (Type)GetParameterType(_value2, typeof(Type));
return new PSAliasProperty(_memberName, value1Str, value2Type);
}
return new PSAliasProperty(_memberName, value1Str);
}
private PSMemberInfo GetCodeMethod()
{
EnsureValue1HasBeenSpecified();
EnsureValue1IsNotNull();
EnsureValue2HasNotBeenSpecified();
MethodInfo value1MethodInfo = (MethodInfo)GetParameterType(_value1, typeof(MethodInfo));
return new PSCodeMethod(_memberName, value1MethodInfo);
}
private PSMemberInfo GetCodeProperty()
{
EnsureValue1HasBeenSpecified();
EnsureValue1AndValue2AreNotBothNull();
MethodInfo value1MethodInfo = null;
if (HasBeenSpecified(_value1))
{
value1MethodInfo = (MethodInfo)GetParameterType(_value1, typeof(MethodInfo));
}
MethodInfo value2MethodInfo = null;
if (HasBeenSpecified(_value2))
{
value2MethodInfo = (MethodInfo)GetParameterType(_value2, typeof(MethodInfo));
}
return new PSCodeProperty(_memberName, value1MethodInfo, value2MethodInfo);
}
private PSMemberInfo GetMemberSet()
{
EnsureValue2HasNotBeenSpecified();
if (_value1 == null || !HasBeenSpecified(_value1))
{
return new PSMemberSet(_memberName);
}
Collection<PSMemberInfo> value1Collection =
(Collection<PSMemberInfo>)GetParameterType(_value1, typeof(Collection<PSMemberInfo>));
return new PSMemberSet(_memberName, value1Collection);
}
private PSMemberInfo GetNoteProperty()
{
EnsureValue1HasBeenSpecified();
EnsureValue2HasNotBeenSpecified();
return new PSNoteProperty(_memberName, _value1);
}
private PSMemberInfo GetPropertySet()
{
EnsureValue2HasNotBeenSpecified();
EnsureValue1HasBeenSpecified();
EnsureValue1IsNotNull();
Collection<string> value1Collection =
(Collection<string>)GetParameterType(_value1, typeof(Collection<string>));
return new PSPropertySet(_memberName, value1Collection);
}
private PSMemberInfo GetScriptMethod()
{
EnsureValue2HasNotBeenSpecified();
EnsureValue1HasBeenSpecified();
EnsureValue1IsNotNull();
ScriptBlock value1ScriptBlock = (ScriptBlock)GetParameterType(_value1, typeof(ScriptBlock));
return new PSScriptMethod(_memberName, value1ScriptBlock);
}
private PSMemberInfo GetScriptProperty()
{
EnsureValue1HasBeenSpecified();
EnsureValue1AndValue2AreNotBothNull();
ScriptBlock value1ScriptBlock = null;
if (HasBeenSpecified(_value1))
{
value1ScriptBlock = (ScriptBlock)GetParameterType(_value1, typeof(ScriptBlock));
}
ScriptBlock value2ScriptBlock = null;
if (HasBeenSpecified(_value2))
{
value2ScriptBlock = (ScriptBlock)GetParameterType(_value2, typeof(ScriptBlock));
}
return new PSScriptProperty(_memberName, value1ScriptBlock, value2ScriptBlock);
}
/// <summary>
/// This method implements the ProcessRecord method for add-member command.
/// </summary>
protected override void ProcessRecord()
{
if (_typeName != null && string.IsNullOrWhiteSpace(_typeName))
{
ThrowTerminatingError(NewError("TypeNameShouldNotBeEmpty", "TypeNameShouldNotBeEmpty", _typeName));
}
if (ParameterSetName == "TypeNameSet")
{
UpdateTypeNames();
if (_passThru)
{
WriteObject(_inputObject);
}
return;
}
if (ParameterSetName == NotePropertyMultiMemberSet)
{
ProcessNotePropertyMultiMemberSet();
return;
}
PSMemberInfo member = null;
if (ParameterSetName == NotePropertySingleMemberSet)
{
member = new PSNoteProperty(_notePropertyName, _notePropertyValue);
}
else
{
int memberCountHelper = (int)_memberType;
int memberCount = 0;
while (memberCountHelper != 0)
{
if ((memberCountHelper & 1) != 0)
{
memberCount++;
}
memberCountHelper = memberCountHelper >> 1;
}
if (memberCount != 1)
{
ThrowTerminatingError(NewError("WrongMemberCount", "WrongMemberCount", null, _memberType.ToString()));
return;
}
switch (_memberType)
{
case PSMemberTypes.AliasProperty:
member = GetAliasProperty();
break;
case PSMemberTypes.CodeMethod:
member = GetCodeMethod();
break;
case PSMemberTypes.CodeProperty:
member = GetCodeProperty();
break;
case PSMemberTypes.MemberSet:
member = GetMemberSet();
break;
case PSMemberTypes.NoteProperty:
member = GetNoteProperty();
break;
case PSMemberTypes.PropertySet:
member = GetPropertySet();
break;
case PSMemberTypes.ScriptMethod:
member = GetScriptMethod();
break;
case PSMemberTypes.ScriptProperty:
member = GetScriptProperty();
break;
default:
ThrowTerminatingError(NewError("CannotAddMemberType", "CannotAddMemberType", null, _memberType.ToString()));
break;
}
}
if (member == null)
{
return;
}
if (!AddMemberToTarget(member))
return;
if (_typeName != null)
{
UpdateTypeNames();
}
if (_passThru)
{
WriteObject(_inputObject);
}
}
/// <summary>
/// Add the member to the target object.
/// </summary>
/// <param name="member"></param>
/// <returns></returns>
private bool AddMemberToTarget(PSMemberInfo member)
{
PSMemberInfo previousMember = _inputObject.Members[member.Name];
if (previousMember != null)
{
if (!_force)
{
WriteError(NewError("MemberAlreadyExists",
"MemberAlreadyExists",
_inputObject, member.Name));
return false;
}
else
{
if (previousMember.IsInstance)
{
_inputObject.Members.Remove(member.Name);
}
else
{
WriteError(NewError("CannotRemoveTypeDataMember",
"CannotRemoveTypeDataMember",
_inputObject, member.Name, previousMember.MemberType));
return false;
}
}
}
_inputObject.Members.Add(member);
return true;
}
/// <summary>
/// Process the 'NotePropertyMultiMemberSet' parameter set.
/// </summary>
private void ProcessNotePropertyMultiMemberSet()
{
bool result = false;
foreach (DictionaryEntry prop in _property)
{
string noteName = PSObject.ToStringParser(this.Context, prop.Key);
object noteValue = prop.Value;
if (string.IsNullOrEmpty(noteName))
{
WriteError(NewError("NotePropertyNameShouldNotBeNull",
"NotePropertyNameShouldNotBeNull", noteName));
continue;
}
PSMemberInfo member = new PSNoteProperty(noteName, noteValue);
if (AddMemberToTarget(member) && !result)
result = true;
}
if (result && _typeName != null)
{
UpdateTypeNames();
}
if (result && _passThru)
{
WriteObject(_inputObject);
}
}
private void UpdateTypeNames()
{
// Respect the type shortcut
Type type;
string typeNameInUse = _typeName;
if (LanguagePrimitives.TryConvertTo(_typeName, out type)) { typeNameInUse = type.FullName; }
_inputObject.TypeNames.Insert(0, typeNameInUse);
}
private ErrorRecord NewError(string errorId, string resourceId, object targetObject, params object[] args)
{
ErrorDetails details = new ErrorDetails(this.GetType().GetTypeInfo().Assembly,
"Microsoft.PowerShell.Commands.Utility.resources.AddMember", resourceId, args);
ErrorRecord errorRecord = new ErrorRecord(
new InvalidOperationException(details.Message),
errorId,
ErrorCategory.InvalidOperation,
targetObject);
return errorRecord;
}
/// <summary>
/// This ValidateArgumentsAttribute is used to guarantee the argument to be bound to
/// -NotePropertyName parameter cannot be converted to the enum type PSMemberTypes.
/// So when given a string or a number that can be converted, we make sure it gets
/// bound to -MemberType, instead of -NotePropertyName.
/// </summary>
/// <remarks>
/// This exception will be hidden in the positional binding phase. So we make sure
/// if the argument can be converted to PSMemberTypes, it gets bound to the -MemberType
/// parameter. We are sure that when this exception is thrown, the current positional
/// argument can be successfully bound to.
/// </remarks>
private sealed class ValidateNotePropertyNameAttribute : ValidateArgumentsAttribute
{
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics)
{
string notePropertyName = arguments as string;
PSMemberTypes memberType;
if (notePropertyName != null && LanguagePrimitives.TryConvertTo<PSMemberTypes>(notePropertyName, out memberType))
{
switch (memberType)
{
case PSMemberTypes.AliasProperty:
case PSMemberTypes.CodeMethod:
case PSMemberTypes.CodeProperty:
case PSMemberTypes.MemberSet:
case PSMemberTypes.NoteProperty:
case PSMemberTypes.PropertySet:
case PSMemberTypes.ScriptMethod:
case PSMemberTypes.ScriptProperty:
string errMsg = StringUtil.Format(AddMember.InvalidValueForNotePropertyName, typeof(PSMemberTypes).FullName);
throw new ValidationMetadataException(errMsg, true);
default:
break;
}
}
}
}
/// <summary>
/// Transform the integer arguments to strings for the parameter NotePropertyName.
/// </summary>
internal sealed class NotePropertyTransformationAttribute : ArgumentTransformationAttribute
{
public override object Transform(EngineIntrinsics engineIntrinsics, object inputData)
{
object target = PSObject.Base(inputData);
if (target != null && target.GetType().IsNumeric())
{
var result = LanguagePrimitives.ConvertTo<string>(target);
return result;
}
return inputData;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Microsoft.CSharp.RuntimeBinder.Errors;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal sealed partial class ExpressionBinder
{
// ----------------------------------------------------------------------------
// BindImplicitConversion
// ----------------------------------------------------------------------------
private sealed class ImplicitConversion
{
public ImplicitConversion(ExpressionBinder binder, EXPR exprSrc, CType typeSrc, EXPRTYPEORNAMESPACE typeDest, bool needsExprDest, CONVERTTYPE flags)
{
_binder = binder;
_exprSrc = exprSrc;
_typeSrc = typeSrc;
_typeDest = typeDest.TypeOrNamespace.AsType();
_exprTypeDest = typeDest;
_needsExprDest = needsExprDest;
_flags = flags;
_exprDest = null;
}
public EXPR ExprDest { get { return _exprDest; } }
private EXPR _exprDest;
private readonly ExpressionBinder _binder;
private readonly EXPR _exprSrc;
private readonly CType _typeSrc;
private readonly CType _typeDest;
private readonly EXPRTYPEORNAMESPACE _exprTypeDest;
private readonly bool _needsExprDest;
private CONVERTTYPE _flags;
/*
* BindImplicitConversion
*
* This is a complex routine with complex parameters. Generally, this should
* be called through one of the helper methods that insulates you
* from the complexity of the interface. This routine handles all the logic
* associated with implicit conversions.
*
* exprSrc - the expression being converted. Can be null if only type conversion
* info is being supplied.
* typeSrc - type of the source
* typeDest - type of the destination
* exprDest - returns an expression of the src converted to the dest. If null, we
* only care about whether the conversion can be attempted, not the
* expression tree.
* flags - flags possibly customizing the conversions allowed. E.g., can suppress
* user-defined conversions.
*
* returns true if the conversion can be made, false if not.
*/
public bool Bind()
{
// 13.1 Implicit conversions
//
// The following conversions are classified as implicit conversions:
//
// * Identity conversions
// * Implicit numeric conversions
// * Implicit enumeration conversions
// * Implicit reference conversions
// * Boxing conversions
// * Implicit type parameter conversions
// * Implicit constant expression conversions
// * User-defined implicit conversions
// * Implicit conversions from an anonymous method expression to a compatible delegate type
// * Implicit conversion from a method group to a compatible delegate type
// * Conversions from the null type (11.2.7) to any nullable type
// * Implicit nullable conversions
// * Lifted user-defined implicit conversions
//
// Implicit conversions can occur in a variety of situations, including function member invocations
// (14.4.3), cast expressions (14.6.6), and assignments (14.14).
// Can't convert to or from the error type.
if (_typeSrc == null || _typeDest == null || _typeDest.IsNeverSameType())
{
return false;
}
Debug.Assert(_typeSrc != null && _typeDest != null); // types must be supplied.
Debug.Assert(_exprSrc == null || _typeSrc == _exprSrc.type); // type of source should be correct if source supplied
Debug.Assert(!_needsExprDest || _exprSrc != null); // need source expr to create dest expr
switch (_typeDest.GetTypeKind())
{
case TypeKind.TK_ErrorType:
Debug.Assert(_typeDest.AsErrorType().HasTypeParent() || _typeDest.AsErrorType().HasNSParent());
if (_typeSrc != _typeDest)
{
return false;
}
if (_needsExprDest)
{
_exprDest = _exprSrc;
}
return true;
case TypeKind.TK_NullType:
// Can only convert to the null type if src is null.
if (!_typeSrc.IsNullType())
{
return false;
}
if (_needsExprDest)
{
_exprDest = _exprSrc;
}
return true;
case TypeKind.TK_MethodGroupType:
VSFAIL("Something is wrong with Type.IsNeverSameType()");
return false;
case TypeKind.TK_NaturalIntegerType:
case TypeKind.TK_ArgumentListType:
return _typeSrc == _typeDest;
case TypeKind.TK_VoidType:
return false;
default:
break;
}
if (_typeSrc.IsErrorType())
{
Debug.Assert(!_typeDest.IsErrorType());
return false;
}
// 13.1.1 Identity conversion
//
// An identity conversion converts from any type to the same type. This conversion exists only
// such that an entity that already has a required type can be said to be convertible to that type.
if (_typeSrc == _typeDest &&
((_flags & CONVERTTYPE.ISEXPLICIT) == 0 || (!_typeSrc.isPredefType(PredefinedType.PT_FLOAT) && !_typeSrc.isPredefType(PredefinedType.PT_DOUBLE))))
{
if (_needsExprDest)
{
_exprDest = _exprSrc;
}
return true;
}
if (_typeDest.IsNullableType())
{
return BindNubConversion(_typeDest.AsNullableType());
}
if (_typeSrc.IsNullableType())
{
return bindImplicitConversionFromNullable(_typeSrc.AsNullableType());
}
if ((_flags & CONVERTTYPE.ISEXPLICIT) != 0)
{
_flags |= CONVERTTYPE.NOUDC;
}
// Get the fundamental types of destination.
FUNDTYPE ftDest = _typeDest.fundType();
Debug.Assert(ftDest != FUNDTYPE.FT_NONE || _typeDest.IsParameterModifierType());
switch (_typeSrc.GetTypeKind())
{
default:
VSFAIL("Bad type symbol kind");
break;
case TypeKind.TK_MethodGroupType:
if (_exprSrc.isMEMGRP())
{
EXPRCALL outExpr;
bool retVal = _binder.BindGrpConversion(_exprSrc.asMEMGRP(), _typeDest, _needsExprDest, out outExpr, false);
_exprDest = outExpr;
return retVal;
}
return false;
case TypeKind.TK_VoidType:
case TypeKind.TK_ErrorType:
case TypeKind.TK_ParameterModifierType:
case TypeKind.TK_ArgumentListType:
return false;
case TypeKind.TK_NullType:
if (bindImplicitConversionFromNull())
{
return true;
}
// If not, try user defined implicit conversions.
break;
case TypeKind.TK_ArrayType:
if (bindImplicitConversionFromArray())
{
return true;
}
// If not, try user defined implicit conversions.
break;
case TypeKind.TK_PointerType:
if (bindImplicitConversionFromPointer())
{
return true;
}
// If not, try user defined implicit conversions.
break;
case TypeKind.TK_TypeParameterType:
if (bindImplicitConversionFromTypeVar(_typeSrc.AsTypeParameterType()))
{
return true;
}
// If not, try user defined implicit conversions.
break;
case TypeKind.TK_AggregateType:
// TypeReference and ArgIterator can't be boxed (or converted to anything else)
if (_typeSrc.isSpecialByRefType())
{
return false;
}
if (bindImplicitConversionFromAgg(_typeSrc.AsAggregateType()))
{
return true;
}
// If not, try user defined implicit conversions.
break;
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// RUNTIME BINDER ONLY CHANGE
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// Every incoming dynamic operand should be implicitly convertible
// to any type that it is an instance of.
object srcRuntimeObject = _exprSrc?.RuntimeObject;
if (srcRuntimeObject != null
&& _typeDest.AssociatedSystemType.IsInstanceOfType(srcRuntimeObject)
&& _binder.GetSemanticChecker().CheckTypeAccess(_typeDest, _binder.Context.ContextForMemberLookup()))
{
if (_needsExprDest)
{
_binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, _exprSrc.flags & EXPRFLAG.EXF_CANTBENULL);
}
return true;
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// END RUNTIME BINDER ONLY CHANGE
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// 13.1.8 User-defined implicit conversions
//
// A user-defined implicit conversion consists of an optional standard implicit conversion,
// followed by execution of a user-defined implicit conversion operator, followed by another
// optional standard implicit conversion. The exact rules for evaluating user-defined
// conversions are described in 13.4.3.
if (0 == (_flags & CONVERTTYPE.NOUDC))
{
return _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, _typeDest, _needsExprDest, out _exprDest, true);
}
// No conversion was found.
return false;
}
/***************************************************************************************************
Called by BindImplicitConversion when the destination type is Nullable<T>. The following
conversions are handled by this method:
* For S in { object, ValueType, interfaces implemented by underlying type} there is an explicit
unboxing conversion S => T?
* System.Enum => T? there is an unboxing conversion if T is an enum type
* null => T? implemented as default(T?)
* Implicit T?* => T?+ implemented by either wrapping or calling GetValueOrDefault the
appropriate number of times.
* If imp/exp S => T then imp/exp S => T?+ implemented by converting to T then wrapping the
appropriate number of times.
* If imp/exp S => T then imp/exp S?+ => T?+ implemented by calling GetValueOrDefault (m-1) times
then calling HasValue, producing a null if it returns false, otherwise calling Value,
converting to T then wrapping the appropriate number of times.
The 3 rules above can be summarized with the following recursive rules:
* If imp/exp S => T? then imp/exp S? => T? implemented as
qs.HasValue ? (T?)(qs.Value) : default(T?)
* If imp/exp S => T then imp/exp S => T? implemented as new T?((T)s)
This method also handles calling bindUserDefinedConverion. This method does NOT handle
the following conversions:
* Implicit boxing conversion from S? to { object, ValueType, Enum, ifaces implemented by S }. (Handled by BindImplicitConversion.)
* If imp/exp S => T then explicit S?+ => T implemented by calling Value the appropriate number
of times. (Handled by BindExplicitConversion.)
The recursive equivalent is:
* If imp/exp S => T and T is not nullable then explicit S? => T implemented as qs.Value
Some nullable conversion are NOT standard conversions. In particular, if S => T is implicit
then S? => T is not standard. Similarly if S => T is not implicit then S => T? is not standard.
***************************************************************************************************/
private bool BindNubConversion(NullableType nubDst)
{
// This code assumes that STANDARD and ISEXPLICIT are never both set.
// bindUserDefinedConversion should ensure this!
Debug.Assert(0 != (~_flags & (CONVERTTYPE.STANDARD | CONVERTTYPE.ISEXPLICIT)));
Debug.Assert(_exprSrc == null || _exprSrc.type == _typeSrc);
Debug.Assert(!_needsExprDest || _exprSrc != null);
Debug.Assert(_typeSrc != nubDst); // BindImplicitConversion should have taken care of this already.
AggregateType atsDst = nubDst.GetAts(GetErrorContext());
if (atsDst == null)
return false;
// Check for the unboxing conversion. This takes precedence over the wrapping conversions.
if (GetSymbolLoader().HasBaseConversion(nubDst.GetUnderlyingType(), _typeSrc) && !CConversions.FWrappingConv(_typeSrc, nubDst))
{
// These should be different! Fix the caller if typeSrc is an AggregateType of Nullable.
Debug.Assert(atsDst != _typeSrc);
// typeSrc is a base type of the destination nullable type so there is an explicit
// unboxing conversion.
if (0 == (_flags & CONVERTTYPE.ISEXPLICIT))
{
return false;
}
if (_needsExprDest)
{
_binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_UNBOX);
}
return true;
}
int cnubDst;
int cnubSrc;
CType typeDstBase = nubDst.StripNubs(out cnubDst);
EXPRCLASS exprTypeDstBase = GetExprFactory().MakeClass(typeDstBase);
CType typeSrcBase = _typeSrc.StripNubs(out cnubSrc);
ConversionFunc pfn = (_flags & CONVERTTYPE.ISEXPLICIT) != 0 ?
(ConversionFunc)_binder.BindExplicitConversion :
(ConversionFunc)_binder.BindImplicitConversion;
if (cnubSrc == 0)
{
Debug.Assert(_typeSrc == typeSrcBase);
// The null type can be implicitly converted to T? as the default value.
if (_typeSrc.IsNullType())
{
// If we have the constant null, generate it as a default value of T?. If we have
// some crazy expression which has been determined to be always null, like (null??null)
// keep it in its expression form and transform it in the nullable rewrite pass.
if (_needsExprDest)
{
if (_exprSrc.isCONSTANT_OK())
{
_exprDest = GetExprFactory().CreateZeroInit(nubDst);
}
else
{
_exprDest = GetExprFactory().CreateCast(0x00, _typeDest, _exprSrc);
}
}
return true;
}
EXPR exprTmp = _exprSrc;
// If there is an implicit/explicit S => T then there is an implicit/explicit S => T?
if (_typeSrc == typeDstBase || pfn(_exprSrc, _typeSrc, exprTypeDstBase, nubDst, _needsExprDest, out exprTmp, _flags | CONVERTTYPE.NOUDC))
{
if (_needsExprDest)
{
EXPRUSERDEFINEDCONVERSION exprUDC = exprTmp.kind == ExpressionKind.EK_USERDEFINEDCONVERSION ? exprTmp.asUSERDEFINEDCONVERSION() : null;
if (exprUDC != null)
{
exprTmp = exprUDC.UserDefinedCall;
}
// This logic is left over from the days when T?? was legal. However there are error/LAF cases that necessitates the loop.
// typeSrc is not nullable so just wrap the required number of times. For legal code (cnubDst <= 0).
for (int i = 0; i < cnubDst; i++)
{
exprTmp = _binder.BindNubNew(exprTmp);
exprTmp.asCALL().nubLiftKind = NullableCallLiftKind.NullableConversionConstructor;
}
if (exprUDC != null)
{
exprUDC.UserDefinedCall = exprTmp;
exprUDC.setType((CType)exprTmp.type);
exprTmp = exprUDC;
}
Debug.Assert(exprTmp.type == nubDst);
_exprDest = exprTmp;
}
return true;
}
// No builtin conversion. Maybe there is a user defined conversion....
return 0 == (_flags & CONVERTTYPE.NOUDC) && _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, nubDst, _needsExprDest, out _exprDest, 0 == (_flags & CONVERTTYPE.ISEXPLICIT));
}
// Both are Nullable so there is only a conversion if there is a conversion between the base types.
// That is, if there is an implicit/explicit S => T then there is an implicit/explicit S?+ => T?+.
if (typeSrcBase != typeDstBase && !pfn(null, typeSrcBase, exprTypeDstBase, nubDst, false, out _exprDest, _flags | CONVERTTYPE.NOUDC))
{
// No builtin conversion. Maybe there is a user defined conversion....
return 0 == (_flags & CONVERTTYPE.NOUDC) && _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, nubDst, _needsExprDest, out _exprDest, 0 == (_flags & CONVERTTYPE.ISEXPLICIT));
}
if (_needsExprDest)
{
MethWithInst mwi = new MethWithInst(null, null);
EXPRMEMGRP pMemGroup = GetExprFactory().CreateMemGroup(null, mwi);
EXPRCALL exprDst = GetExprFactory().CreateCall(0, nubDst, _exprSrc, pMemGroup, null);
// Here we want to first check whether or not the conversions work on the base types.
EXPR arg1 = _binder.mustCast(_exprSrc, typeSrcBase);
EXPRCLASS arg2 = GetExprFactory().MakeClass(typeDstBase);
bool convertible;
if (0 != (_flags & CONVERTTYPE.ISEXPLICIT))
{
convertible = _binder.BindExplicitConversion(arg1, arg1.type, arg2, typeDstBase, out arg1, _flags | CONVERTTYPE.NOUDC);
}
else
{
convertible = _binder.BindImplicitConversion(arg1, arg1.type, arg2, typeDstBase, out arg1, _flags | CONVERTTYPE.NOUDC);
}
if (!convertible)
{
VSFAIL("bind(Im|Ex)plicitConversion failed unexpectedly");
return false;
}
exprDst.castOfNonLiftedResultToLiftedType = _binder.mustCast(arg1, nubDst, 0);
exprDst.nubLiftKind = NullableCallLiftKind.NullableConversion;
exprDst.pConversions = exprDst.castOfNonLiftedResultToLiftedType;
_exprDest = exprDst;
}
return true;
}
private bool bindImplicitConversionFromNull()
{
// null type can be implicitly converted to any reference type or pointer type or type
// variable with reference-type constraint.
FUNDTYPE ftDest = _typeDest.fundType();
if (ftDest != FUNDTYPE.FT_REF && ftDest != FUNDTYPE.FT_PTR &&
(ftDest != FUNDTYPE.FT_VAR || !_typeDest.AsTypeParameterType().IsReferenceType()) &&
// null is convertible to System.Nullable<T>.
!_typeDest.isPredefType(PredefinedType.PT_G_OPTIONAL))
{
return false;
}
if (_needsExprDest)
{
// If the conversion argument is a constant null then return a ZEROINIT.
// Otherwise, bind this as a cast to the destination type. In a later
// rewrite pass we will rewrite the cast as SEQ(side effects, ZEROINIT).
if (_exprSrc.isCONSTANT_OK())
{
_exprDest = GetExprFactory().CreateZeroInit(_typeDest);
}
else
{
_exprDest = GetExprFactory().CreateCast(0x00, _typeDest, _exprSrc);
}
}
return true;
}
private bool bindImplicitConversionFromNullable(NullableType nubSrc)
{
// We can convert T? using a boxing conversion, we can convert it to ValueType, and
// we can convert it to any interface implemented by T.
//
// 13.1.5 Boxing Conversions
//
// A nullable-type has a boxing conversion to the same set of types to which the nullable-type's
// underlying type has boxing conversions. A boxing conversion applied to a value of a nullable-type
// proceeds as follows:
//
// * If the HasValue property of the nullable value evaluates to false, then the result of the
// boxing conversion is the null reference of the appropriate type.
//
// Otherwise, the result is obtained by boxing the result of evaluating the Value property on
// the nullable value.
AggregateType atsNub = nubSrc.GetAts(GetErrorContext());
if (atsNub == null)
{
return false;
}
if (atsNub == _typeDest)
{
if (_needsExprDest)
{
_exprDest = _exprSrc;
}
return true;
}
if (GetSymbolLoader().HasBaseConversion(nubSrc.GetUnderlyingType(), _typeDest) && !CConversions.FUnwrappingConv(nubSrc, _typeDest))
{
if (_needsExprDest)
{
_binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_BOX);
if (!_typeDest.isPredefType(PredefinedType.PT_OBJECT))
{
// The base type of a nullable is always a non-nullable value type,
// therefore so is typeDest unless typeDest is PT_OBJECT. In this case the conversion
// needs to be unboxed. We only need this if we actually will use the result.
_binder.bindSimpleCast(_exprDest, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_FORCE_UNBOX);
}
}
return true;
}
return 0 == (_flags & CONVERTTYPE.NOUDC) && _binder.bindUserDefinedConversion(_exprSrc, nubSrc, _typeDest, _needsExprDest, out _exprDest, true);
}
private bool bindImplicitConversionFromArray()
{
// 13.1.4
//
// The implicit reference conversions are:
//
// * From an array-type S with an element type SE to an array-type T with an element
// type TE, provided all of the following are true:
// * S and T differ only in element type. In other words, S and T have the same number of dimensions.
// * An implicit reference conversion exists from SE to TE.
// * From a one-dimensional array-type S[] to System.Collections.Generic.IList<S>,
// System.Collections.Generic.IReadOnlyList<S> and their base interfaces
// * From a one-dimensional array-type S[] to System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T>
// and their base interfaces, provided there is an implicit reference conversion from S to T.
// * From any array-type to System.Array.
// * From any array-type to any interface implemented by System.Array.
if (!GetSymbolLoader().HasBaseConversion(_typeSrc, _typeDest))
{
return false;
}
EXPRFLAG grfex = 0;
// The above if checks for dest==Array, object or an interface the array implements,
// including IList<T>, ICollection<T>, IEnumerable<T>, IReadOnlyList<T>, IReadOnlyCollection<T>
// and the non-generic versions.
if ((_typeDest.IsArrayType() ||
(_typeDest.isInterfaceType() &&
_typeDest.AsAggregateType().GetTypeArgsAll().Count == 1 &&
((_typeDest.AsAggregateType().GetTypeArgsAll()[0] != _typeSrc.AsArrayType().GetElementType()) ||
0 != (_flags & CONVERTTYPE.FORCECAST))))
&&
(0 != (_flags & CONVERTTYPE.FORCECAST) ||
TypeManager.TypeContainsTyVars(_typeSrc, null) ||
TypeManager.TypeContainsTyVars(_typeDest, null)))
{
grfex = EXPRFLAG.EXF_REFCHECK;
}
if (_needsExprDest)
{
_binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, grfex);
}
return true;
}
private bool bindImplicitConversionFromPointer()
{
// 27.4 Pointer conversions
//
// In an unsafe context, the set of available implicit conversions (13.1) is extended to include
// the following implicit pointer conversions:
//
// * From any pointer-type to the type void*.
if (_typeDest.IsPointerType() && _typeDest.AsPointerType().GetReferentType() == _binder.getVoidType())
{
if (_needsExprDest)
_binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest);
return true;
}
return false;
}
private bool bindImplicitConversionFromAgg(AggregateType aggTypeSrc)
{
// GENERICS: The case for constructed types is very similar to types with
// no parameters. The parameters are irrelevant for most of the conversions
// below. They could be relevant if we had user-defined conversions on
// generic types.
AggregateSymbol aggSrc = aggTypeSrc.getAggregate();
if (aggSrc.IsEnum())
{
return bindImplicitConversionFromEnum(aggTypeSrc);
}
if (_typeDest.isEnumType())
{
if (bindImplicitConversionToEnum(aggTypeSrc))
{
return true;
}
// Even though enum is sealed, a class can derive from enum in LAF scenarios --
// continue testing for derived to base conversions below.
}
else if (aggSrc.getThisType().isSimpleType() && _typeDest.isSimpleType())
{
if (bindImplicitConversionBetweenSimpleTypes(aggTypeSrc))
{
return true;
}
// No simple conversion -- continue testing for derived to base conversions below.
}
return bindImplicitConversionToBase(aggTypeSrc);
}
private bool bindImplicitConversionToBase(AggregateType pSource)
{
// 13.1.4 Implicit reference conversions
//
// * From any reference-type to object.
// * From any class-type S to any class-type T, provided S is derived from T.
// * From any class-type S to any interface-type T, provided S implements T.
// * From any interface-type S to any interface-type T, provided S is derived from T.
// * From any delegate-type to System.Delegate.
// * From any delegate-type to System.ICloneable.
if (!_typeDest.IsAggregateType() || !GetSymbolLoader().HasBaseConversion(pSource, _typeDest))
{
return false;
}
EXPRFLAG flags = 0x00;
if (pSource.getAggregate().IsStruct() && _typeDest.fundType() == FUNDTYPE.FT_REF)
{
flags = EXPRFLAG.EXF_BOX | EXPRFLAG.EXF_CANTBENULL;
}
else if (_exprSrc != null)
{
flags = _exprSrc.flags & EXPRFLAG.EXF_CANTBENULL;
}
if (_needsExprDest)
_binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, flags);
return true;
}
private bool bindImplicitConversionFromEnum(AggregateType aggTypeSrc)
{
// 13.1.5 Boxing conversions
//
// A boxing conversion permits any non-nullable-value-type to be implicitly converted to the type
// object or System.ValueType or to any interface-type implemented by the value-type, and any enum
// type to be implicitly converted to System.Enum as well. Boxing a value of a
// non-nullable-value-type consists of allocating an object instance and copying the value-type
// value into that instance. An enum can be boxed to the type System.Enum, since that is the direct
// base class for all enums (21.4). A struct or enum can be boxed to the type System.ValueType,
// since that is the direct base class for all structs (18.3.2) and a base class for all enums.
if (_typeDest.IsAggregateType() && GetSymbolLoader().HasBaseConversion(aggTypeSrc, _typeDest.AsAggregateType()))
{
if (_needsExprDest)
_binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_BOX | EXPRFLAG.EXF_CANTBENULL);
return true;
}
return false;
}
private bool bindImplicitConversionToEnum(AggregateType aggTypeSrc)
{
// The spec states:
// *****************
// 13.1.3 Implicit enumeration conversions
//
// An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any
// enum-type.
// *****************
// However, we actually allow any constant zero, not just the integer literal zero, to be converted
// to enum. The reason for this is for backwards compatibility with a premature optimization
// that used to be in the binding layer. We would optimize away expressions such as 0 | blah to be
// just 0, but not erase the "is literal" bit. This meant that expression such as 0 | 0 | E.X
// would succeed rather than correctly producing an error pointing out that 0 | 0 is not a literal
// zero and therefore does not convert to any enum.
//
// We have removed the premature optimization but want old code to continue to compile. Rather than
// try to emulate the somewhat complex behaviour of the previous optimizer, it is easier to simply
// say that any compile time constant zero is convertible to any enum. This means unfortunately
// expressions such as (7-7) * 12 are convertible to enum, but frankly, that's better than having
// some terribly complex rule about what constitutes a legal zero and what doesn't.
// Note: Don't use GetConst here since the conversion only applies to bona-fide compile time constants.
if (
aggTypeSrc.getAggregate().GetPredefType() != PredefinedType.PT_BOOL &&
_exprSrc != null &&
_exprSrc.isZero() &&
_exprSrc.type.isNumericType() &&
/*(exprSrc.flags & EXF_LITERALCONST) &&*/
0 == (_flags & CONVERTTYPE.STANDARD))
{
// NOTE: This allows conversions from uint, long, ulong, float, double, and hexadecimal int
// NOTE: This is for backwards compatibility with Everett
// This is another place where we lose EXPR fidelity. We shouldn't fold this
// into a constant here - we should move this to a later pass.
if (_needsExprDest)
{
_exprDest = GetExprFactory().CreateConstant(_typeDest, ConstVal.GetDefaultValue(_typeDest.constValKind()));
}
return true;
}
return false;
}
private bool bindImplicitConversionBetweenSimpleTypes(AggregateType aggTypeSrc)
{
AggregateSymbol aggSrc = aggTypeSrc.getAggregate();
Debug.Assert(aggSrc.getThisType().isSimpleType());
Debug.Assert(_typeDest.isSimpleType());
Debug.Assert(aggSrc.IsPredefined() && _typeDest.isPredefined());
PredefinedType ptSrc = aggSrc.GetPredefType();
PredefinedType ptDest = _typeDest.getPredefType();
ConvKind convertKind;
bool fConstShrinkCast = false;
Debug.Assert((int)ptSrc < NUM_SIMPLE_TYPES && (int)ptDest < NUM_SIMPLE_TYPES);
// 13.1.7 Implicit constant expression conversions
//
// An implicit constant expression conversion permits the following conversions:
// * A constant-expression (14.16) of type int can be converted to type sbyte, byte, short,
// ushort, uint, or ulong, provided the value of the constant-expression is within the range
// of the destination type.
// * A constant-expression of type long can be converted to type ulong, provided the value of
// the constant-expression is not negative.
// Note: Don't use GetConst here since the conversion only applies to bona-fide compile time constants.
if (_exprSrc != null && _exprSrc.isCONSTANT_OK() &&
((ptSrc == PredefinedType.PT_INT && ptDest != PredefinedType.PT_BOOL && ptDest != PredefinedType.PT_CHAR) ||
(ptSrc == PredefinedType.PT_LONG && ptDest == PredefinedType.PT_ULONG)) &&
isConstantInRange(_exprSrc.asCONSTANT(), _typeDest))
{
// Special case (CLR 6.1.6): if integral constant is in range, the conversion is a legal implicit conversion.
convertKind = ConvKind.Implicit;
fConstShrinkCast = _needsExprDest && (GetConvKind(ptSrc, ptDest) != ConvKind.Implicit);
}
else if (ptSrc == ptDest)
{
// Special case: precision limiting casts to float or double
Debug.Assert(ptSrc == PredefinedType.PT_FLOAT || ptSrc == PredefinedType.PT_DOUBLE);
Debug.Assert(0 != (_flags & CONVERTTYPE.ISEXPLICIT));
convertKind = ConvKind.Implicit;
}
else
{
convertKind = GetConvKind(ptSrc, ptDest);
Debug.Assert(convertKind != ConvKind.Identity);
// identity conversion should have been handled at first.
}
if (convertKind != ConvKind.Implicit)
{
return false;
}
// An implicit conversion exists. Do the conversion.
if (_exprSrc.GetConst() != null)
{
// Fold the constant cast if possible.
ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, false);
if (result == ConstCastResult.Success)
{
return true; // else, don't fold and use a regular cast, below.
}
}
if (isUserDefinedConversion(ptSrc, ptDest))
{
if (!_needsExprDest)
{
return true;
}
// According the language, this is a standard conversion, but it is implemented
// through a user-defined conversion. Because it's a standard conversion, we don't
// test the NOUDC flag here.
return _binder.bindUserDefinedConversion(_exprSrc, aggTypeSrc, _typeDest, _needsExprDest, out _exprDest, true);
}
if (_needsExprDest)
_binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest);
return true;
}
private bool bindImplicitConversionFromTypeVar(TypeParameterType tyVarSrc)
{
// 13.1.4
//
// For a type-parameter T that is known to be a reference type (25.7), the following implicit
// reference conversions exist:
//
// * From T to its effective base class C, from T to any base class of C, and from T to any
// interface implemented by C.
// * From T to an interface-type I in T's effective interface set and from T to any base
// interface of I.
// * From T to a type parameter U provided that T depends on U (25.7). [Note: Since T is known
// to be a reference type, within the scope of T, the run-time type of U will always be a
// reference type, even if U is not known to be a reference type at compile-time.]
// * From the null type (11.2.7) to T.
//
// 13.1.5
//
// For a type-parameter T that is not known to be a reference type (25.7), the following conversions
// involving T are considered to be boxing conversions at compile-time. At run-time, if T is a value
// type, the conversion is executed as a boxing conversion. At run-time, if T is a reference type,
// the conversion is executed as an implicit reference conversion or identity conversion.
//
// * From T to its effective base class C, from T to any base class of C, and from T to any
// interface implemented by C. [Note: C will be one of the types System.Object, System.ValueType,
// or System.Enum (otherwise T would be known to be a reference type and 13.1.4 would apply
// instead of this clause).]
// * From T to an interface-type I in T's effective interface set and from T to any base
// interface of I.
//
// 13.1.6 Implicit type parameter conversions
//
// This clause details implicit conversions involving type parameters that are not classified as
// implicit reference conversions or implicit boxing conversions.
//
// For a type-parameter T that is not known to be a reference type, there is an implicit conversion
// from T to a type parameter U provided T depends on U. At run-time, if T is a value type and U is
// a reference type, the conversion is executed as a boxing conversion. At run-time, if both T and U
// are value types, then T and U are necessarily the same type and no conversion is performed. At
// run-time, if T is a reference type, then U is necessarily also a reference type and the conversion
// is executed as an implicit reference conversion or identity conversion (25.7).
CType typeTmp = tyVarSrc.GetEffectiveBaseClass();
TypeArray bnds = tyVarSrc.GetBounds();
int itype = -1;
for (; ;)
{
if (_binder.canConvert(typeTmp, _typeDest, _flags | CONVERTTYPE.NOUDC))
{
if (!_needsExprDest)
{
return true;
}
if (_typeDest.IsTypeParameterType())
{
// For a type var destination we need to cast to object then to the other type var.
EXPR exprT;
EXPRCLASS exprObj = GetExprFactory().MakeClass(_binder.GetReqPDT(PredefinedType.PT_OBJECT));
_binder.bindSimpleCast(_exprSrc, exprObj, out exprT, EXPRFLAG.EXF_FORCE_BOX);
_binder.bindSimpleCast(exprT, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_FORCE_UNBOX);
}
else
{
_binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_FORCE_BOX);
}
return true;
}
do
{
if (++itype >= bnds.Count)
{
return false;
}
typeTmp = bnds[itype];
}
while (!typeTmp.isInterfaceType() && !typeTmp.IsTypeParameterType());
}
}
private SymbolLoader GetSymbolLoader()
{
return _binder.GetSymbolLoader();
}
private ExprFactory GetExprFactory()
{
return _binder.GetExprFactory();
}
private ErrorHandling GetErrorContext()
{
return _binder.GetErrorContext();
}
}
}
}
| |
/**
* @brief Same throttleing mechanism as the baseline global_round_robin scheme. However
* this controller puts high apps into a cluster with batching. The number of clusters is
* no longer static. Each cluster is batched with an average MPKI value. Therefore the number
* of clusters depends on the number of high apps and their average MPKI value.
*
* TODO: can go into throttle mode with only 2 nodes, and none of them has high enough MPKI to throttle.
*
* Trigger metric: netutil.
* High app metric: MPKI.
* Batch metric: MPKI.
**/
//#define DEBUG_NETUTIL
//#define DEBUG
//#define DEBUG_CLUSTER
//#define DEBUG_CLUSTER_RATE
//#define DEBUG_AD
using System;
using System.Collections.Generic;
namespace ICSimulator
{
public class Controller_Adaptive_Cluster_dist: Controller_Global_Batch
{
public Controller_Adaptive_Cluster_dist()
{
isThrottling = false;
for (int i = 0; i < Config.N; i++)
{
MPKI[i]=0.0;
num_ins_last_epoch[i]=0;
m_isThrottled[i]=false;
L1misses[i]=0;
lastNetUtil = 0;
}
cluster_pool=new BatchClusterPool_distance(Config.cluster_MPKI_threshold);
}
public override void setThrottling()
{
#if DEBUG_NETUTIL
Console.Write("\n:: cycle {0} ::",
Simulator.CurrentRound);
#endif
//get the MPKI value
for (int i = 0; i < Config.N; i++)
{
prev_MPKI[i]=MPKI[i];
if(num_ins_last_epoch[i]==0)
MPKI[i]=((double)(L1misses[i]*1000))/(Simulator.stats.insns_persrc[i].Count);
else
{
if(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]>0)
MPKI[i]=((double)(L1misses[i]*1000))/(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]);
else if(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]==0)
MPKI[i]=0;
else
throw new Exception("MPKI error!");
}
}
recordStats();
if(isThrottling)
{
double netutil=((double)(Simulator.stats.netutil.Total-lastNetUtil)/(double)Config.throttle_sampling_period);
#if DEBUG_NETUTIL
Console.WriteLine("In throttle mode: avg netUtil = {0} thres at {1}",
netutil,Config.netutil_throttling_threshold);
#endif
/* TODO:
* 1.If the netutil remains high, lower the threshold value for each cluster
* to reduce the netutil further more and create a new pool/schedule for
* all the clusters. How to raise it back?
* Worst case: 1 app per cluster.
*
* 2.Find the difference b/w the current netutil and the threshold.
* Then increase the throttle rate for each cluster based on that difference.
*
* 3.maybe add stalling clusters?
* */
isThrottling=false;
//un-throttle the network
for(int i=0;i<Config.N;i++)
setThrottleRate(i,false);
cluster_pool.removeAllClusters();
double diff=netutil-Config.netutil_throttling_threshold;
//Option1: adjust the mpki thresh for each cluster
//if netutil within range of 10% increase MPKI boundary for each cluster
if(Config.adaptive_cluster_mpki)
{
double new_MPKI_thresh=cluster_pool.clusterThreshold();
if(diff<0.10)
new_MPKI_thresh*=1.05;
else if(diff>0.2)
new_MPKI_thresh*=0.95;
cluster_pool.changeThresh(new_MPKI_thresh);
}
//Option2: adjust the throttle rate
//
//
//Use alpha*total_MPKI+base to find the optimal netutil for performance
//0.5 is the baseline netutil threshold
//0.03 is calculated empricically using some base cases to find this number b/w total_mpki and target netutil
double total_mpki=0.0;
for(int i=0;i<Config.N;i++)
total_mpki+=MPKI[i];
double target_netutil=(0.03*total_mpki+50)/100;
//50% baseline
if(Config.alpha)
{
//within 2% range
if(netutil<(0.98*target_netutil))
Config.RR_throttle_rate-=0.02;
else if(netutil>(1.02*target_netutil))
if(Config.RR_throttle_rate<0.95)//max is 95%
Config.RR_throttle_rate+=0.01;
//if target is too high, only throttle max to 95% inj rate
if(target_netutil>0.9)
Config.RR_throttle_rate=0.95;
}
//Trying to force 60-70% netutil
if(Config.adaptive_rate)
{
if(diff<0.1)
Config.RR_throttle_rate-=0.02;
else if(diff>0.2)
if(Config.RR_throttle_rate<0.95)
Config.RR_throttle_rate+=0.01;
}
#if DEBUG_CLUSTER_RATE
Console.WriteLine("Netutil diff: {2}-{3}={1} New th rate:{0} New MPKI thresh: {6} Target netutil:{4} Total MPKI:{5}",
Config.RR_throttle_rate,diff,
netutil,Config.netutil_throttling_threshold,target_netutil,total_mpki,cluster_pool.clusterThreshold());
#endif
Simulator.stats.total_th_rate.Add(Config.RR_throttle_rate);
}
if (thresholdTrigger()) // an abstract fn() that trigger whether to start throttling or not
{
List<int> sortedList = new List<int>();
double total_mpki=0.0;
double small_mpki=0.0;
double current_allow=0.0;
int total_high=0;
for(int i=0;i<Config.N;i++)
{
sortedList.Add(i);
total_mpki+=MPKI[i];
//stats recording-see what's the total mpki composed by low/med apps
if(MPKI[i]<=30)
small_mpki+=MPKI[i];
}
//sort by mpki
sortedList.Sort(CompareByMpki);
#if DEBUG_AD
for(int i=0;i<Config.N;i++)
Console.WriteLine("ID:{0} MPKI:{1}",sortedList[i],MPKI[sortedList[i]]);
Console.WriteLine("*****total MPKI: {0}",total_mpki);
Console.WriteLine("*****small MPKI: {0}\n",small_mpki);
#endif
//find the first few apps that will be allowed to run freely without being throttled
for(int i=0;i<Config.N;i++)
{
int node_id=sortedList[i];
if(withInRange(current_allow+MPKI[node_id],Config.free_total_MPKI))
{
current_allow+=MPKI[node_id];
continue;
}
else
{
#if DEBUG_AD
Console.WriteLine("high node: {0}",node_id);
#endif
cluster_pool.addNewNode(node_id,MPKI[node_id]);
total_high++;
}
}
#if DEBUG_AD
Console.WriteLine("total high: {0}\n",total_high);
#endif
//STATS
Simulator.stats.allowed_sum_mpki.Add(current_allow);
Simulator.stats.total_sum_mpki.Add(total_mpki);
sortedList.Clear();
isThrottling = (total_high>0)?true:false;
}
}
//within 10% of range
private bool withInRange(double mpki,double target)
{
if(mpki<=(target*1.1))
return true;
return false;
}
private int CompareByMpki(int x,int y)
{
if(MPKI[x]-MPKI[y]>0.0) return 1;
else if(MPKI[x]-MPKI[y]<0.0) return -1;
return 0;
}
}
}
| |
using System;
using System.Text.RegularExpressions;
using System.Xml.Linq;
// JSON.NET
using Newtonsoft.Json;
namespace IvionWebSoft
{
static class BooruTools
{
internal static int ExtractPostNo(Regex urlRegexp, string url)
{
var groups = urlRegexp.Match(url).Groups;
if (groups[1].Success)
return int.Parse(groups[1].Value);
else
return -1;
}
}
public static class DanboTools
{
static readonly Regex danboUrlRegexp = new Regex(@"(?i)donmai\.us/posts/(\d+)");
/// <summary>
/// Get info of a Danbooru post.
/// </summary>
/// <returns><see cref="DanboPost">DanboPost</see> detailing a post.</returns>
///
/// <exception cref="ArgumentNullException">Thrown if url is null.</exception>
/// <exception cref="ArgumentException">Thrown if url is empty or whitespace.</exception>
///
/// <param name="url">URL pointing to a post.</param>
public static DanboPost GetPostInfo(string url)
{
url.ThrowIfNullOrWhiteSpace("url");
int postNo = BooruTools.ExtractPostNo(danboUrlRegexp, url);
if (postNo > 0)
return GetPostInfo(postNo);
else
{
var ex = new FormatException("Unable to extract (valid) Post No. from URL.");
return new DanboPost(null, ex);
}
}
/// <summary>
/// Get info of a Danbooru post.
/// </summary>
/// <returns><see cref="DanboPost">DanboPost</see> detailing a post.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown if postNo is <= 0.</exception>
/// <param name="postNo">Post number.</param>
public static DanboPost GetPostInfo(int postNo)
{
if (postNo < 1)
throw new ArgumentOutOfRangeException(nameof(postNo), "Can't be 0 or negative.");
var jsonReq = string.Format("https://danbooru.donmai.us/posts/{0}.json", postNo);
var json = WebString.Download(jsonReq);
if (!json.Success)
return new DanboPost(json);
dynamic postJson = JsonConvert.DeserializeObject(json.Document);
string copyrights = postJson.tag_string_copyright;
string characters = postJson.tag_string_character;
string artists = postJson.tag_string_artist;
string general = postJson.tag_string_general;
string meta = postJson.tag_string_meta;
string all = postJson.tag_string;
string rating = postJson.rating;
return new DanboPost(json.Location, postNo,
copyrights, characters, artists, general, meta, all, rating);
}
/// <summary>
/// Cleans up the character tags. Removes the "_(source)" part of the tags.
/// Modifies charTags in place.
/// </summary>
///
/// <exception cref="ArgumentNullException">Thrown if charTags or copyrightTags is null.</exception>
///
/// <param name="charTags">A tag array of character tags.</param>
/// <param name="copyrightTags">A tag array of copyright tags.</param>
public static void CleanupCharacterTags(string[] charTags, string[] copyrightTags)
{
if (charTags == null)
throw new ArgumentNullException(nameof(charTags));
if (copyrightTags == null)
throw new ArgumentNullException(nameof(copyrightTags));
// Return early if there's nothing to be done.
if (charTags.Length == 0 || copyrightTags.Length == 0)
return;
for (int i = 0; i < charTags.Length; i++)
{
string charTag = charTags[i];
int sourceOpenIdx, sourceCloseIdx;
if ( TryFindSourceIndices(charTag, out sourceOpenIdx, out sourceCloseIdx) )
{
string source = ExtractSource(charTag, sourceOpenIdx, sourceCloseIdx);
if (RemoveSource(source, copyrightTags))
{
int len = (sourceCloseIdx - sourceOpenIdx) + 1;
charTags[i] = charTag.Remove(sourceOpenIdx, len);
}
}
} // for
}
static bool TryFindSourceIndices(string charTag, out int start, out int end)
{
start = FindSourceStart(charTag);
if (start < 0)
{
end = -1;
return false;
}
else
{
end = FindSourceEnd(charTag, start);
return true;
}
}
static int FindSourceStart(string charTag)
{
const string sourceStart = "_(";
return charTag.IndexOf(sourceStart, StringComparison.Ordinal);
}
static int FindSourceEnd(string charTag, int sourceStart)
{
const string sourceEnd= ")";
int end = charTag.IndexOf(sourceEnd, sourceStart, StringComparison.Ordinal);
if (end > sourceStart)
return end;
else
return charTag.Length - 1;
}
static string ExtractSource(string charTag, int sourceStart, int sourceEnd)
{
// Plus 2 to skip past the "_(" part of the source.
int start = sourceStart + 2;
int len = sourceEnd - start;
return charTag.Substring(start, len);
}
static bool RemoveSource(string source, string[] copyrightTags)
{
foreach (string copyTag in copyrightTags)
{
if (RemoveSource(source, copyTag))
return true;
}
return false;
}
static bool RemoveSource(string source, string copyrightTag)
{
// Slice off the source if a copyright tag contains it. Examples:
// _(kantai_collection) is in kantai_collection
// _(jojo) is in jojo_no_kimyou_na_bouken
// But also check if the source starts with a copyright tag, this is less common. Examples:
// _(gundam_bf) starts with gundam
if (copyrightTag.Contains(source, StringComparison.Ordinal))
return true;
if (source.StartsWith(copyrightTag, StringComparison.Ordinal))
return true;
return false;
}
}
public static class GelboTools
{
static readonly Regex gelboUrlRegexp = new Regex(@"(?i)gelbooru\.com/index\.php\?page=post&s=view&id=(\d+)");
/// <summary>
/// Get info of a Gelbooru post.
/// </summary>
/// <returns><see cref="BooruPost">BooruPost</see> detailing a post.</returns>
///
/// <exception cref="ArgumentNullException">Thrown if url is null.</exception>
/// <exception cref="ArgumentException">Thrown if url is empty or whitespace.</exception>
///
/// <param name="url">URL pointing to a post.</param>
public static BooruPost GetPostInfo(string url)
{
url.ThrowIfNullOrWhiteSpace("url");
int postNo = BooruTools.ExtractPostNo(gelboUrlRegexp, url);
if (postNo > 0)
return GetPostInfo(postNo);
else
{
var ex = new FormatException("Unable to extract (valid) Post No. from URL.");
return new BooruPost(null, ex);
}
}
/// <summary>
/// Get info of a Gelbooru post.
/// </summary>
/// <returns><see cref="BooruPost">BooruPost</see> detailing a post.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown if postNo is <= 0.</exception>
/// <param name="postNo">Post number.</param>
public static BooruPost GetPostInfo(int postNo)
{
if (postNo < 1)
throw new ArgumentOutOfRangeException(nameof(postNo), "Can't be 0 or negative.");
var xmlReq = string.Format("https://gelbooru.com/index.php?page=dapi&s=post&q=index&id={0}", postNo);
var xml = WebString.Download(xmlReq);
if (!xml.Success)
return new BooruPost(xml);
var postXml = XElement.Parse(xml.Document).Element("post");
string tags = postXml.Attribute("tags").Value;
string rated = postXml.Attribute("rating").Value;
return new BooruPost(xml.Location, postNo, tags, rated);
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Xml
{
using System.Runtime;
using System.Runtime.Serialization; // for SR
using System.Security;
public class UniqueId
{
Int64 idLow;
Int64 idHigh;
[Fx.Tag.SecurityNote(Critical = "Some SecurityCritical unsafe code assumes that this field has been validated.")]
[SecurityCritical]
string s;
const int guidLength = 16;
const int uuidLength = 45;
static short[] char2val = new short[256]
{
/* 0-15 */ 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 16-31 */ 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 32-47 */ 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 48-63 */ 0x000, 0x010, 0x020, 0x030, 0x040, 0x050, 0x060, 0x070, 0x080, 0x090, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 64-79 */ 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 80-95 */ 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 96-111 */ 0x100, 0x0A0, 0x0B0, 0x0C0, 0x0D0, 0x0E0, 0x0F0, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 112-127 */ 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 0-15 */ 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 16-31 */ 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 32-47 */ 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 48-63 */ 0x000, 0x001, 0x002, 0x003, 0x004, 0x005, 0x006, 0x007, 0x008, 0x009, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 64-79 */ 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 80-95 */ 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 96-111 */ 0x100, 0x00A, 0x00B, 0x00C, 0x00D, 0x00E, 0x00F, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 112-127 */ 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
};
const string val2char = "0123456789abcdef";
public UniqueId() : this(Guid.NewGuid())
{
}
public UniqueId(Guid guid) : this(guid.ToByteArray())
{
}
public UniqueId(byte[] guid) : this(guid, 0)
{
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code.",
Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")]
[SecuritySafeCritical]
unsafe public UniqueId(byte[] guid, int offset)
{
if (guid == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("guid"));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.ValueMustBeNonNegative)));
if (offset > guid.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.OffsetExceedsBufferSize, guid.Length)));
if (guidLength > guid.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.XmlArrayTooSmallInput, guidLength), "guid"));
fixed (byte* pb = &guid[offset])
{
this.idLow = UnsafeGetInt64(pb);
this.idHigh = UnsafeGetInt64(&pb[8]);
}
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code.",
Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")]
[SecuritySafeCritical]
unsafe public UniqueId(string value)
{
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
if (value.Length == 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.XmlInvalidUniqueId)));
fixed (char* pch = value)
{
UnsafeParse(pch, value.Length);
}
this.s = value;
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code.",
Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")]
[SecuritySafeCritical]
unsafe public UniqueId(char[] chars, int offset, int count)
{
if (chars == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars"));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.ValueMustBeNonNegative)));
if (offset > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.OffsetExceedsBufferSize, chars.Length)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.ValueMustBeNonNegative)));
if (count > chars.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.SizeExceedsRemainingBufferSpace, chars.Length - offset)));
if (count == 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.XmlInvalidUniqueId)));
fixed (char* pch = &chars[offset])
{
UnsafeParse(pch, count);
}
if (!IsGuid)
{
this.s = new string(chars, offset, count);
}
}
public int CharArrayLength
{
[Fx.Tag.SecurityNote(Critical = "Accesses critical field 's'.",
Safe = "Doesn't leak any control or data.")]
[SecuritySafeCritical]
get
{
if (s != null)
return s.Length;
return uuidLength;
}
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code. Caller needs to validate arguments.")]
[SecurityCritical]
unsafe int UnsafeDecode(short* char2val, char ch1, char ch2)
{
if ((ch1 | ch2) >= 0x80)
return 0x100;
return char2val[ch1] | char2val[0x80 + ch2];
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code. Caller needs to validate arguments.")]
[SecurityCritical]
unsafe void UnsafeEncode(char* val2char, byte b, char* pch)
{
pch[0] = val2char[b >> 4];
pch[1] = val2char[b & 0x0F];
}
public bool IsGuid
{
get
{
return ((idLow | idHigh) != 0);
}
}
// It must be the case that comparing UniqueId's as strings yields the same result as comparing UniqueId's as
// their binary equivalent. This means that there must be a 1-1 relationship between a string and its binary
// equivalent. Therefore, for example, we cannot accept both upper and lower case hex chars since there would
// then be more than 1 string that mapped to a binary equivalent.
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code. Caller needs to validate arguments.")]
[SecurityCritical]
unsafe void UnsafeParse(char* chars, int charCount)
{
// 1 2 3 4
// 012345678901234567890123456789012345678901234
// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
if (charCount != uuidLength ||
chars[0] != 'u' || chars[1] != 'r' || chars[2] != 'n' || chars[3] != ':' ||
chars[4] != 'u' || chars[5] != 'u' || chars[6] != 'i' || chars[7] != 'd' || chars[8] != ':' ||
chars[17] != '-' || chars[22] != '-' || chars[27] != '-' || chars[32] != '-')
{
return;
}
byte* bytes = stackalloc byte[guidLength];
int i = 0;
int j = 0;
fixed (short* ps = char2val)
{
short* _char2val = ps;
// 0 1 2 3 4
// 012345678901234567890123456789012345678901234
// urn:uuid:aabbccdd-eeff-gghh-0011-223344556677
//
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
// ddccbbaaffeehhgg0011223344556677
i = UnsafeDecode(_char2val, chars[15], chars[16]); bytes[0] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[13], chars[14]); bytes[1] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[11], chars[12]); bytes[2] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[9], chars[10]); bytes[3] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[20], chars[21]); bytes[4] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[18], chars[19]); bytes[5] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[25], chars[26]); bytes[6] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[23], chars[24]); bytes[7] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[28], chars[29]); bytes[8] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[30], chars[31]); bytes[9] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[33], chars[34]); bytes[10] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[35], chars[36]); bytes[11] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[37], chars[38]); bytes[12] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[39], chars[40]); bytes[13] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[41], chars[42]); bytes[14] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[43], chars[44]); bytes[15] = (byte)i; j |= i;
if (j >= 0x100)
return;
this.idLow = UnsafeGetInt64(bytes);
this.idHigh = UnsafeGetInt64(&bytes[8]);
}
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code.",
Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")]
[SecuritySafeCritical]
unsafe public int ToCharArray(char[] chars, int offset)
{
int count = CharArrayLength;
if (chars == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars"));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.ValueMustBeNonNegative)));
if (offset > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.OffsetExceedsBufferSize, chars.Length)));
if (count > chars.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("chars", SR.GetString(SR.XmlArrayTooSmallOutput, count)));
if (s != null)
{
s.CopyTo(0, chars, offset, count);
}
else
{
byte* bytes = stackalloc byte[guidLength];
UnsafeSetInt64(this.idLow, bytes);
UnsafeSetInt64(this.idHigh, &bytes[8]);
fixed (char* _pch = &chars[offset])
{
char* pch = _pch;
pch[0] = 'u';
pch[1] = 'r';
pch[2] = 'n';
pch[3] = ':';
pch[4] = 'u';
pch[5] = 'u';
pch[6] = 'i';
pch[7] = 'd';
pch[8] = ':';
pch[17] = '-';
pch[22] = '-';
pch[27] = '-';
pch[32] = '-';
fixed (char* ps = val2char)
{
char* _val2char = ps;
UnsafeEncode(_val2char, bytes[0], &pch[15]);
UnsafeEncode(_val2char, bytes[1], &pch[13]);
UnsafeEncode(_val2char, bytes[2], &pch[11]);
UnsafeEncode(_val2char, bytes[3], &pch[9]);
UnsafeEncode(_val2char, bytes[4], &pch[20]);
UnsafeEncode(_val2char, bytes[5], &pch[18]);
UnsafeEncode(_val2char, bytes[6], &pch[25]);
UnsafeEncode(_val2char, bytes[7], &pch[23]);
UnsafeEncode(_val2char, bytes[8], &pch[28]);
UnsafeEncode(_val2char, bytes[9], &pch[30]);
UnsafeEncode(_val2char, bytes[10], &pch[33]);
UnsafeEncode(_val2char, bytes[11], &pch[35]);
UnsafeEncode(_val2char, bytes[12], &pch[37]);
UnsafeEncode(_val2char, bytes[13], &pch[39]);
UnsafeEncode(_val2char, bytes[14], &pch[41]);
UnsafeEncode(_val2char, bytes[15], &pch[43]);
}
}
}
return count;
}
public bool TryGetGuid(out Guid guid)
{
byte[] buffer = new byte[guidLength];
if (!TryGetGuid(buffer, 0))
{
guid = Guid.Empty;
return false;
}
guid = new Guid(buffer);
return true;
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code.",
Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")]
[SecuritySafeCritical]
unsafe public bool TryGetGuid(byte[] buffer, int offset)
{
if (!IsGuid)
return false;
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("buffer"));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.ValueMustBeNonNegative)));
if (offset > buffer.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.OffsetExceedsBufferSize, buffer.Length)));
if (guidLength > buffer.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("buffer", SR.GetString(SR.XmlArrayTooSmallOutput, guidLength)));
fixed (byte* pb = &buffer[offset])
{
UnsafeSetInt64(this.idLow, pb);
UnsafeSetInt64(this.idHigh, &pb[8]);
}
return true;
}
[Fx.Tag.SecurityNote(Critical = "Accesses critical field 's'.",
Safe = "Doesn't allow unchecked write access to the field.")]
[SecuritySafeCritical]
unsafe public override string ToString()
{
if (s == null)
{
int length = CharArrayLength;
char[] chars = new char[length];
ToCharArray(chars, 0);
s = new string(chars, 0, length);
}
return s;
}
static public bool operator ==(UniqueId id1, UniqueId id2)
{
if (object.ReferenceEquals(id1, null) && object.ReferenceEquals(id2, null))
return true;
if (object.ReferenceEquals(id1, null) || object.ReferenceEquals(id2, null))
return false;
#pragma warning suppress 56506 // [....], checks for whether id1 and id2 are null done above.
if (id1.IsGuid && id2.IsGuid)
{
return id1.idLow == id2.idLow && id1.idHigh == id2.idHigh;
}
return id1.ToString() == id2.ToString();
}
static public bool operator !=(UniqueId id1, UniqueId id2)
{
return !(id1 == id2);
}
public override bool Equals(object obj)
{
return this == (obj as UniqueId);
}
public override int GetHashCode()
{
if (IsGuid)
{
Int64 hash = (idLow ^ idHigh);
return ((int)(hash >> 32)) ^ ((int)hash);
}
else
{
return ToString().GetHashCode();
}
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code. Caller needs to validate arguments.")]
[SecurityCritical]
unsafe Int64 UnsafeGetInt64(byte* pb)
{
Int32 idLow = UnsafeGetInt32(pb);
Int32 idHigh = UnsafeGetInt32(&pb[4]);
return (((Int64)idHigh) << 32) | ((UInt32)idLow);
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code. Caller needs to validate arguments.")]
[SecurityCritical]
unsafe Int32 UnsafeGetInt32(byte* pb)
{
int value = pb[3];
value <<= 8;
value |= pb[2];
value <<= 8;
value |= pb[1];
value <<= 8;
value |= pb[0];
return value;
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code. Caller needs to validate arguments.")]
[SecurityCritical]
unsafe void UnsafeSetInt64(Int64 value, byte* pb)
{
UnsafeSetInt32((int)value, pb);
UnsafeSetInt32((int)(value >> 32), &pb[4]);
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code. Caller needs to validate arguments.")]
[SecurityCritical]
unsafe void UnsafeSetInt32(Int32 value, byte* pb)
{
pb[0] = (byte)value;
value >>= 8;
pb[1] = (byte)value;
value >>= 8;
pb[2] = (byte)value;
value >>= 8;
pb[3] = (byte)value;
}
}
}
| |
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Orleans.Hosting;
using Orleans.Runtime.Configuration;
using Orleans.TestingHost.Tests.Grains;
using TestExtensions;
using Xunit;
using Xunit.Abstractions;
namespace Orleans.TestingHost.Tests
{
public class T0
{
[Fact, TestCategory("Functional")]
public async Task CanInitialize()
{
var builder = new TestClusterBuilder(2);
builder.Options.ServiceId = Guid.NewGuid().ToString();
builder.ConfigureHostConfiguration(TestDefaultConfiguration.ConfigureHostConfiguration);
var testCluster = builder.Build();
await testCluster.DeployAsync();
}
}
public class T1
{
[Fact, TestCategory("Functional")]
public async Task CanInitialize()
{
var builder = new TestClusterBuilder(2);
builder.Options.ServiceId = Guid.NewGuid().ToString();
builder.ConfigureHostConfiguration(TestDefaultConfiguration.ConfigureHostConfiguration);
var testCluster = builder.Build();
await testCluster.DeployAsync();
}
}
public class T2
{
[Fact, TestCategory("Functional")]
public async Task CanInitialize()
{
var builder = new TestClusterBuilder(2);
builder.Options.ServiceId = Guid.NewGuid().ToString();
builder.ConfigureHostConfiguration(TestDefaultConfiguration.ConfigureHostConfiguration);
var testCluster = builder.Build();
await testCluster.DeployAsync();
}
}
public class T3
{
[Fact, TestCategory("Functional")]
public async Task CanInitialize()
{
var builder = new TestClusterBuilder(2);
builder.Options.ServiceId = Guid.NewGuid().ToString();
builder.ConfigureHostConfiguration(TestDefaultConfiguration.ConfigureHostConfiguration);
var testCluster = builder.Build();
await testCluster.DeployAsync();
}
}
public class T4
{
[Fact, TestCategory("Functional")]
public async Task CanInitialize()
{
var builder = new TestClusterBuilder(2);
builder.Options.ServiceId = Guid.NewGuid().ToString();
builder.ConfigureHostConfiguration(TestDefaultConfiguration.ConfigureHostConfiguration);
var testCluster = builder.Build();
await testCluster.DeployAsync();
}
}
public class T5
{
[Fact, TestCategory("Functional")]
public async Task CanInitialize()
{
var builder = new TestClusterBuilder(2);
builder.Options.ServiceId = Guid.NewGuid().ToString();
builder.ConfigureHostConfiguration(TestDefaultConfiguration.ConfigureHostConfiguration);
var testCluster = builder.Build();
await testCluster.DeployAsync();
}
}
public class T6
{
[Fact, TestCategory("Functional")]
public async Task CanInitialize()
{
var builder = new TestClusterBuilder(2);
builder.Options.ServiceId = Guid.NewGuid().ToString();
builder.ConfigureHostConfiguration(TestDefaultConfiguration.ConfigureHostConfiguration);
var testCluster = builder.Build();
await testCluster.DeployAsync();
}
}
public class T7
{
[Fact, TestCategory("Functional")]
public async Task CanInitialize()
{
var builder = new TestClusterBuilder(2);
builder.Options.ServiceId = Guid.NewGuid().ToString();
builder.ConfigureHostConfiguration(TestDefaultConfiguration.ConfigureHostConfiguration);
var testCluster = builder.Build();
await testCluster.DeployAsync();
}
}
public class T8
{
[Fact, TestCategory("Functional")]
public async Task CanInitialize()
{
var builder = new TestClusterBuilder(2);
builder.Options.ServiceId = Guid.NewGuid().ToString();
builder.ConfigureHostConfiguration(TestDefaultConfiguration.ConfigureHostConfiguration);
var testCluster = builder.Build();
await testCluster.DeployAsync();
}
}
public class T9
{
[Fact, TestCategory("Functional")]
public async Task CanInitialize()
{
var builder = new TestClusterBuilder(2);
builder.Options.ServiceId = Guid.NewGuid().ToString();
builder.ConfigureHostConfiguration(TestDefaultConfiguration.ConfigureHostConfiguration);
var testCluster = builder.Build();
await testCluster.DeployAsync();
}
}
public class TestClusterTests : IDisposable
{
private readonly ITestOutputHelper output;
private TestCluster testCluster;
public TestClusterTests(ITestOutputHelper output)
{
this.output = output;
}
[Fact, TestCategory("Functional")]
public async Task CanInitialize()
{
var builder = new TestClusterBuilder(2);
builder.Options.ServiceId = Guid.NewGuid().ToString();
builder.ConfigureHostConfiguration(TestDefaultConfiguration.ConfigureHostConfiguration);
this.testCluster = builder.Build();
await this.testCluster.DeployAsync();
var grain = this.testCluster.Client.GetGrain<ISimpleGrain>(1);
await grain.SetA(2);
Assert.Equal(2, await grain.GetA());
}
[Fact, TestCategory("Functional")]
public async Task CanInitializeWithLegacyConfiguration()
{
var builder = new TestClusterBuilder(2);
builder.ConfigureHostConfiguration(TestDefaultConfiguration.ConfigureHostConfiguration);
builder.AddSiloBuilderConfigurator<SiloConfigurator>();
this.testCluster = builder.Build();
await this.testCluster.DeployAsync();
var grain = this.testCluster.Client.GetGrain<ISimpleGrain>(1);
await grain.SetA(2);
Assert.Equal(2, await grain.GetA());
}
public class SiloConfigurator : ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder.AddMemoryGrainStorageAsDefault();
}
}
public void Dispose()
{
this.testCluster?.StopAllSilos();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*============================================================
**
** Class: EqualityComparer<T>
**
===========================================================*/
using System;
using System.Collections;
namespace System.Collections.Generic
{
public abstract class EqualityComparer<T> : IEqualityComparer, IEqualityComparer<T>
{
protected EqualityComparer()
{
}
public static EqualityComparer<T> Default
{
get
{
if (_default == null)
{
object comparer;
// NUTC compiler is able to static evalulate the conditions and only put the necessary branches in finally binary code,
// even casting to EqualityComparer<T> can be removed.
// For example: for Byte, the code generated is
// if (_default == null) _default = new EqualityComparerForByte(); return _default;
// For classes, due to generic sharing, the code generated is:
// if (_default == null) { if (handle == typeof(string).RuntimeTypeHandle) comparer = new EqualityComparerForString(); else comparer = new LastResortEqalityComparer<T>; ...
if (typeof(T) == typeof(SByte))
comparer = new EqualityComparerForSByte();
else if (typeof(T) == typeof(Byte))
comparer = new EqualityComparerForByte();
else if (typeof(T) == typeof(Int16))
comparer = new EqualityComparerForInt16();
else if (typeof(T) == typeof(UInt16))
comparer = new EqualityComparerForUInt16();
else if (typeof(T) == typeof(Int32))
comparer = new EqualityComparerForInt32();
else if (typeof(T) == typeof(UInt32))
comparer = new EqualityComparerForUInt32();
else if (typeof(T) == typeof(Int64))
comparer = new EqualityComparerForInt64();
else if (typeof(T) == typeof(UInt64))
comparer = new EqualityComparerForUInt64();
else if (typeof(T) == typeof(IntPtr))
comparer = new EqualityComparerForIntPtr();
else if (typeof(T) == typeof(UIntPtr))
comparer = new EqualityComparerForUIntPtr();
else if (typeof(T) == typeof(Single))
comparer = new EqualityComparerForSingle();
else if (typeof(T) == typeof(Double))
comparer = new EqualityComparerForDouble();
else if (typeof(T) == typeof(Decimal))
comparer = new EqualityComparerForDecimal();
else if (typeof(T) == typeof(String))
comparer = new EqualityComparerForString();
else
comparer = new LastResortEqualityComparer<T>();
_default = (EqualityComparer<T>)comparer;
}
return _default;
}
}
private static volatile EqualityComparer<T> _default;
public abstract bool Equals(T x, T y);
public abstract int GetHashCode(T obj);
int IEqualityComparer.GetHashCode(object obj)
{
if (obj == null)
return 0;
if (obj is T)
return GetHashCode((T)obj);
throw new ArgumentException(SR.Argument_InvalidArgumentForComparison);
}
bool IEqualityComparer.Equals(object x, object y)
{
if (x == y)
return true;
if (x == null || y == null)
return false;
if ((x is T) && (y is T))
return Equals((T)x, (T)y);
throw new ArgumentException(SR.Argument_InvalidArgumentForComparison);
}
}
//
// ProjectN compatiblity notes:
//
// Unlike the full desktop, we make no attempt to use the IEquatable<T> interface on T. Because we can't generate
// code at runtime, we derive no performance benefit from using the type-specific Equals(). We can't even
// perform the check for IEquatable<> at the time the type-specific constructor is created (due to the removable of Type.IsAssignableFrom).
// We would thus be incurring an interface cast check on each call to Equals() for no performance gain.
//
// This should not cause a compat problem unless some type implements an IEquatable.Equals() that is semantically
// incompatible with Object.Equals(). That goes specifically against the documented guidelines (and would in any case,
// break any hashcode-dependent collection.)
//
internal sealed class LastResortEqualityComparer<T> : EqualityComparer<T>
{
public LastResortEqualityComparer()
{
}
public sealed override bool Equals(T x, T y)
{
if (x == null)
return y == null;
if (y == null)
return false;
return x.Equals(y);
}
public sealed override int GetHashCode(T obj)
{
if (obj == null)
return 0;
return obj.GetHashCode();
}
}
internal sealed class EqualityComparerForSByte : EqualityComparer<SByte>
{
public override bool Equals(SByte x, SByte y)
{
return x == y;
}
public override int GetHashCode(SByte x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForByte : EqualityComparer<Byte>
{
public override bool Equals(Byte x, Byte y)
{
return x == y;
}
public override int GetHashCode(Byte x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForInt16 : EqualityComparer<Int16>
{
public override bool Equals(Int16 x, Int16 y)
{
return x == y;
}
public override int GetHashCode(Int16 x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForUInt16 : EqualityComparer<UInt16>
{
public override bool Equals(UInt16 x, UInt16 y)
{
return x == y;
}
public override int GetHashCode(UInt16 x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForInt32 : EqualityComparer<Int32>
{
public override bool Equals(Int32 x, Int32 y)
{
return x == y;
}
public override int GetHashCode(Int32 x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForUInt32 : EqualityComparer<UInt32>
{
public override bool Equals(UInt32 x, UInt32 y)
{
return x == y;
}
public override int GetHashCode(UInt32 x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForInt64 : EqualityComparer<Int64>
{
public override bool Equals(Int64 x, Int64 y)
{
return x == y;
}
public override int GetHashCode(Int64 x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForUInt64 : EqualityComparer<UInt64>
{
public override bool Equals(UInt64 x, UInt64 y)
{
return x == y;
}
public override int GetHashCode(UInt64 x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForIntPtr : EqualityComparer<IntPtr>
{
public override bool Equals(IntPtr x, IntPtr y)
{
return x == y;
}
public override int GetHashCode(IntPtr x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForUIntPtr : EqualityComparer<UIntPtr>
{
public override bool Equals(UIntPtr x, UIntPtr y)
{
return x == y;
}
public override int GetHashCode(UIntPtr x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForSingle : EqualityComparer<Single>
{
public override bool Equals(Single x, Single y)
{
return x == y;
}
public override int GetHashCode(Single x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForDouble : EqualityComparer<Double>
{
public override bool Equals(Double x, Double y)
{
return x == y;
}
public override int GetHashCode(Double x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForDecimal : EqualityComparer<Decimal>
{
public override bool Equals(Decimal x, Decimal y)
{
return x == y;
}
public override int GetHashCode(Decimal x)
{
return x.GetHashCode();
}
}
internal sealed class EqualityComparerForString : EqualityComparer<String>
{
public override bool Equals(String x, String y)
{
return x == y;
}
public override int GetHashCode(String x)
{
if (x == null)
return 0;
return x.GetHashCode();
}
}
}
| |
// 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;
/// <summary>
/// System.Collections.Generic.ICollection.Remove(T)
/// </summary>
public class ICollectionRemove
{
private int c_MINI_STRING_LENGTH = 8;
private int c_MAX_STRING_LENGTH = 256;
public static int Main(string[] args)
{
ICollectionRemove testObj = new ICollectionRemove();
TestLibrary.TestFramework.BeginTestCase("Testing for Methord: System.Collections.Generic.ICollection.Remove(T)");
if (testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Netativ]");
retVal = NegTest1() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Using List<T> which implemented the Remove method in ICollection<T> and Type is int...";
const string c_TEST_ID = "P001";
List<int> list = new List<int>();
int item1 = TestLibrary.Generator.GetInt32(-55);
list.Add(item1);
for (int i = 1; i < 10; i++)
{
list.Add(TestLibrary.Generator.GetInt32(-55));
}
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
if (!((ICollection<int>)list).Remove(item1))
{
string errorDesc = "result is not true as expected: Actual is false";
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
if (list.Count != 9)
{
string errorDesc = "List<T>.Count is not 9 as expected: Actual is "+list.Count;
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2: Using List<T> which implemented the Remove method in ICollection<T> and Type is a reference type...";
const string c_TEST_ID = "P002";
List<String> list = new List<String>();
String item1 = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
list.Add(item1);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
if (!((ICollection<String>)list).Remove(item1))
{
string errorDesc = "result is not true as expected: Actual is false";
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
if (list.Count != 0)
{
string errorDesc = "List<T>.Count is not 0 as expected: Actual is " + list.Count;
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest3: Using List<T> which implemented the Remove method in ICollection<T> and the List<T> doesn't contain this item...";
const string c_TEST_ID = "P003";
List<int> list = new List<int>();
Random rand = new Random(-55);
for (int i = 0; i < 10; i++)
{
list.Add(rand.Next(10, 20));
}
int item1 = 1;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
if (((ICollection<int>)list).Remove(item1))
{
string errorDesc = "result is not true as expected: Actual is false";
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
if (list.Count != 10)
{
string errorDesc = "List<T>.Count is not 10 as expected: Actual is " + list.Count;
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("009", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest4: Using custome class which implemented the Remove method in ICollection<T>...";
const string c_TEST_ID = "P004";
MyCollection<int> myC = new MyCollection<int>();
int item1 = TestLibrary.Generator.GetInt32(-55);
myC.Add(item1);
for (int i = 1;i<10; i++)
{
myC.Add(TestLibrary.Generator.GetInt32(-55));
}
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
if (!((ICollection<int>)myC).Remove(item1))
{
string errorDesc = "result is not true as expected: Actual is false";
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
if (myC.Count != 9)
{
string errorDesc = "MyCollection<int>.Count is not 9 as expected: Actual is " + myC.Count;
TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: Using custome class which implemented the Remove method in ICollection<T> and is readonly");
MyCollection<int> myC = new MyCollection<int>();
int item1 = TestLibrary.Generator.GetInt32(-55);
myC.Add(item1);
myC.isReadOnly = true;
try
{
((ICollection<int>)myC).Remove(item1);
TestLibrary.TestFramework.LogError("013", "The NotSupportedException was not thrown as expected");
retVal = false;
}
catch (NotSupportedException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Help Class
public class MyCollection<T> : ICollection<T>
{
public T[] _items;
protected int length;
public bool isReadOnly = false;
public MyCollection()
{
_items = new T[10];
length = 0;
}
#region ICollection<T> Members
public void Add(T item)
{
if (isReadOnly)
{
throw new NotSupportedException();
}
else
{
_items[length] = item;
length++;
}
}
public void Clear()
{
throw new Exception("The method or operation is not implemented.");
}
public bool Contains(T item)
{
throw new Exception("The method or operation is not implemented.");
}
public void CopyTo(T[] array, int arrayIndex)
{
throw new Exception("The method or operation is not implemented.");
}
public int Count
{
get { return length; }
}
public bool IsReadOnly
{
get { return isReadOnly; }
}
public bool Remove(T item)
{
if (isReadOnly)
{
throw new NotSupportedException();
}
int index = Array.IndexOf(_items, item, 0, length);
if (index < 0)
{
return false;
}
else
{
if ((uint)index >= (uint)length)
{
throw new ArgumentOutOfRangeException(); ;
}
length--;
if (index < length)
{
Array.Copy(_items, index + 1, _items, index, length - index);
}
_items[length] = default(T);
return true;
}
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace System.Text
{
[Serializable]
internal sealed class OSEncoding : Encoding
{
private readonly int _codePage;
private string _encodingName;
internal OSEncoding(int codePage) : base(codePage)
{
_codePage = codePage;
}
public override unsafe int GetByteCount(char[] chars, int index, int count)
{
if (chars == null)
throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer);
if (count == 0)
return 0;
fixed (char* pChar = chars)
{
return WideCharToMultiByte(_codePage, pChar+index, count, null, 0);
}
}
public override unsafe int GetByteCount(String s)
{
// Validate input
if (s == null)
throw new ArgumentNullException(nameof(s));
if (s.Length == 0)
return 0;
fixed (char* pChars = s)
{
return WideCharToMultiByte(_codePage, pChars, s.Length, null, 0);
}
}
public override unsafe int GetBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
if (s == null || bytes == null)
throw new ArgumentNullException(s == null ? nameof(s) : nameof(bytes), SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum);
if (s.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(s), SR.ArgumentOutOfRange_IndexCount);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index);
if (charCount == 0)
return 0;
if (bytes.Length == 0)
{
throw new ArgumentOutOfRangeException(SR.Argument_EncodingConversionOverflowBytes);
}
fixed (char* pChars = s)
fixed (byte *pBytes = &bytes[0])
{
return WideCharToMultiByte(_codePage, pChars+charIndex, charCount, pBytes+byteIndex, bytes.Length - byteIndex);
}
}
public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
if (chars == null || bytes == null)
throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index);
if (charCount == 0)
return 0;
if (bytes.Length == 0)
{
throw new ArgumentOutOfRangeException(SR.Argument_EncodingConversionOverflowBytes);
}
fixed (char* pChars = chars)
fixed (byte *pBytes = &bytes[0])
{
return WideCharToMultiByte(_codePage, pChars+charIndex, charCount, pBytes+byteIndex, bytes.Length - byteIndex);
}
}
public override unsafe int GetCharCount(byte[] bytes, int index, int count)
{
if (bytes == null)
throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer);
if (count == 0)
return 0;
fixed (byte* pBytes = bytes)
{
return MultiByteToWideChar(_codePage, pBytes+index, count, null, 0);
}
}
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer);
if (charIndex < 0 || charIndex > chars.Length)
throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_Index);
if (byteCount == 0)
return 0;
if (chars.Length == 0)
throw new ArgumentOutOfRangeException(SR.Argument_EncodingConversionOverflowChars);
fixed (byte* pBytes = bytes)
fixed (char* pChars = &chars[0])
{
return MultiByteToWideChar(_codePage, pBytes+byteIndex, byteCount, pChars+charIndex, chars.Length - charIndex);
}
}
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum);
long byteCount = (long)charCount * 14; // Max possible value for all encodings
if (byteCount > 0x7fffffff)
throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow);
return (int)byteCount;
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum);
long charCount = byteCount * 4; // Max possible value for all encodings
if (charCount > 0x7fffffff)
throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_GetCharCountOverflow);
return (int)charCount;
}
public override String EncodingName
{
get
{
if (_encodingName == null)
{
_encodingName = "Codepage - " + _codePage.ToString();
}
return _encodingName;
}
}
public override String WebName
{
get
{
return EncodingName;
}
}
public override Encoder GetEncoder()
{
return new OSEncoder(this);
}
public override Decoder GetDecoder()
{
switch (CodePage)
{
case 932: // Japanese (Shift-JIS)
case 936: // Chinese Simplified (GB2312)
case 949: // Korean
case 950: // Chinese Traditional (Big5)
case 1361: // Korean (Johab)
case 10001: // Japanese (Mac)
case 10002: // Chinese Traditional (Mac)
case 10003: // Korean (Mac)
case 10008: // Chinese Simplified (Mac)
case 20000: // Chinese Traditional (CNS)
case 20001: // TCA Taiwan
case 20002: // Chinese Traditional (Eten)
case 20003: // IBM5550 Taiwan
case 20004: // TeleText Taiwan
case 20005: // Wang Taiwan
case 20261: // T.61
case 20932: // Japanese (JIS 0208-1990 and 0212-1990)
case 20936: // Chinese Simplified (GB2312-80)
case 51949: // Korean (EUC)
return new DecoderDBCS(this);
default:
return base.GetDecoder();
}
}
internal static unsafe int WideCharToMultiByte(int codePage, char* pChars, int count, byte* pBytes, int byteCount)
{
int result = Interop.Kernel32.WideCharToMultiByte((uint)codePage, 0, pChars, count, pBytes, byteCount, IntPtr.Zero, IntPtr.Zero);
if (result <= 0)
throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
return result;
}
internal static unsafe int MultiByteToWideChar(int codePage, byte* pBytes, int byteCount, char* pChars, int count)
{
int result = Interop.Kernel32.MultiByteToWideChar((uint)codePage, 0, pBytes, byteCount, pChars, count);
if (result <= 0)
throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
return result;
}
}
}
| |
//
// BookmarkUI.cs
//
// Authors:
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2008-2010 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Gtk;
using Mono.Unix;
using Hyena;
using Hyena.Data.Sqlite;
using Banshee.Base;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.MediaEngine;
using Banshee.ServiceStack;
namespace Banshee.Gui
{
public class BookmarkUI
{
private Menu bookmark_menu;
private Menu remove_menu;
private ImageMenuItem bookmark_item;
private ImageMenuItem new_item;
private ImageMenuItem remove_item;
private SeparatorMenuItem separator;
private List<Bookmark> bookmarks = new List<Bookmark> ();
private Dictionary<Bookmark, MenuItem> select_items = new Dictionary<Bookmark, MenuItem> ();
private Dictionary<Bookmark, MenuItem> remove_items = new Dictionary<Bookmark, MenuItem> ();
private Dictionary<MenuItem, Bookmark> bookmark_map = new Dictionary<MenuItem, Bookmark> ();
private InterfaceActionService action_service;
private BansheeActionGroup actions;
private bool loaded;
private static BookmarkUI instance = null;
public static BookmarkUI Instance {
get {
if (instance == null) {
instance = new BookmarkUI ();
}
return instance;
}
}
public static bool Instantiated {
get { return instance != null; }
}
private BookmarkUI ()
{
action_service = ServiceManager.Get<InterfaceActionService> ();
actions = new BansheeActionGroup ("Bookmarks");
actions.Add (new ActionEntry [] {
new ActionEntry ("BookmarksAction", null,
Catalog.GetString ("_Bookmarks"), null,
null, null),
new ActionEntry ("BookmarksAddAction", Stock.Add,
Catalog.GetString ("_Add Bookmark"), "<control>D",
Catalog.GetString ("Bookmark the Position in the Current Track"),
HandleNewBookmark)
});
actions.AddUiFromFile ("BookmarksMenu.xml");
actions.Register ();
bookmark_item = action_service.UIManager.GetWidget ("/MainMenu/ToolsMenu/Bookmarks") as ImageMenuItem;
new_item = action_service.UIManager.GetWidget ("/MainMenu/ToolsMenu/Bookmarks/Add") as ImageMenuItem;
bookmark_menu = bookmark_item.Submenu as Menu;
bookmark_item.Selected += HandleMenuShown;
remove_item = new ImageMenuItem (Catalog.GetString ("_Remove Bookmark"));
remove_item.Sensitive = false;
remove_item.Image = new Image (Stock.Remove, IconSize.Menu);
remove_item.Submenu = remove_menu = new Menu ();
bookmark_menu.Append (remove_item);
actions["BookmarksAction"].Activated += (o, a) => {
if (!loaded) {
LoadBookmarks ();
loaded = true;
}
};
}
private void HandleMenuShown (object sender, EventArgs args)
{
new_item.Sensitive = (ServiceManager.PlayerEngine.CurrentTrack != null);
}
private void HandleNewBookmark (object sender, EventArgs args)
{
var track = ServiceManager.PlayerEngine.CurrentTrack as DatabaseTrackInfo;
if (track != null) {
try {
var bookmark = new Bookmark (track, (int)ServiceManager.PlayerEngine.Position);
if (loaded) {
AddBookmark (bookmark);
}
} catch (Exception e) {
Log.Exception ("Unable to Add New Bookmark", e);
}
}
}
private void LoadBookmarks ()
{
separator = new SeparatorMenuItem ();
foreach (var bookmark in Bookmark.Provider.FetchAllMatching ("Type IS NULL")) {
if (bookmark.Track != null) {
AddBookmark (bookmark);
} else {
Hyena.Log.DebugFormat ("Removing bookmark that points to missing track ({0})", bookmark.Position);
bookmark.Remove ();
}
}
bookmark_item.ShowAll ();
}
public void AddBookmark (Bookmark bookmark)
{
if (select_items.ContainsKey (bookmark))
return;
bookmarks.Add (bookmark);
if (bookmarks.Count == 1) {
bookmark_menu.Append (separator);
remove_item.Sensitive = true;
}
// Add menu item to jump to this bookmark
ImageMenuItem select_item = new ImageMenuItem (bookmark.Name.Replace ("_", "__"));
select_item.Image = new Image (Stock.JumpTo, IconSize.Menu);
select_item.Activated += delegate {
bookmark.JumpTo ();
};
bookmark_menu.Append (select_item);
select_items[bookmark] = select_item;
// Add menu item to remove this bookmark
ImageMenuItem rem = new ImageMenuItem (bookmark.Name.Replace ("_", "__"));
rem.Image = new Image (Stock.Remove, IconSize.Menu);
rem.Activated += delegate {
bookmark.Remove ();
RemoveBookmark (bookmark);
};
remove_menu.Append (rem);
remove_items[bookmark] = rem;
bookmark_map[rem] = bookmark;
bookmark_menu.ShowAll ();
}
private void RemoveBookmark (Bookmark bookmark)
{
if (!remove_items.ContainsKey (bookmark))
return;
bookmark_menu.Remove (select_items[bookmark]);
remove_menu.Remove (remove_items[bookmark]);
bookmarks.Remove (bookmark);
select_items.Remove (bookmark);
bookmark_map.Remove (remove_items[bookmark]);
remove_items.Remove (bookmark);
if (bookmarks.Count == 0) {
bookmark_menu.Remove (separator);
remove_item.Sensitive = false;
}
}
public void Dispose ()
{
actions.Dispose ();
actions = null;
instance = null;
}
}
}
| |
/*
Copyright 2018 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ArcGIS.Core;
using ArcGIS.Core.Data;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Editing;
using ArcGIS.Desktop.Framework.Threading.Tasks;
namespace SDKExamples
{
/// <summary>
/// Illustrates how to validate updated rows in a FeatureClass.
/// </summary>
///
/// <remarks>
/// <para>
/// While it is true classes that are derived from the <see cref="ArcGIS.Core.CoreObjectsBase"/> super class
/// consumes native resources (e.g., <see cref="ArcGIS.Core.Data.Geodatabase"/> or <see cref="ArcGIS.Core.Data.FeatureClass"/>),
/// you can rest assured that the garbage collector will properly dispose of the unmanaged resources during
/// finalization. However, there are certain workflows that require a <b>deterministic</b> finalization of the
/// <see cref="ArcGIS.Core.Data.Geodatabase"/>. Consider the case of a file geodatabase that needs to be deleted
/// on the fly at a particular moment. Because of the <b>indeterministic</b> nature of garbage collection, we can't
/// count on the garbage collector to dispose of the Geodatabase object, thereby removing the <b>lock(s)</b> at the
/// moment we want. To ensure a deterministic finalization of important native resources such as a
/// <see cref="ArcGIS.Core.Data.Geodatabase"/> or <see cref="ArcGIS.Core.Data.FeatureClass"/>, you should declare
/// and instantiate said objects in a <b>using</b> statement. Alternatively, you can achieve the same result by
/// putting the object inside a try block and then calling Dispose() in a finally block.
/// </para>
/// <para>
/// In general, you should always call Dispose() on the following types of objects:
/// </para>
/// <para>
/// - Those that are derived from <see cref="ArcGIS.Core.Data.Datastore"/> (e.g., <see cref="ArcGIS.Core.Data.Geodatabase"/>).
/// </para>
/// <para>
/// - Those that are derived from <see cref="ArcGIS.Core.Data.Dataset"/> (e.g., <see cref="ArcGIS.Core.Data.Table"/>).
/// </para>
/// <para>
/// - <see cref="ArcGIS.Core.Data.RowCursor"/> and <see cref="ArcGIS.Core.Data.RowBuffer"/>.
/// </para>
/// <para>
/// - <see cref="ArcGIS.Core.Data.Row"/> and <see cref="ArcGIS.Core.Data.Feature"/>.
/// </para>
/// <para>
/// - <see cref="ArcGIS.Core.Data.Selection"/>.
/// </para>
/// <para>
/// - <see cref="ArcGIS.Core.Data.VersionManager"/> and <see cref="ArcGIS.Core.Data.Version"/>.
/// </para>
/// </remarks>
public class FeatureClassValidate
{
/// <summary>
/// In order to illustrate that Geodatabase calls have to be made on the MCT
/// </summary>
/// <returns></returns>
public async Task FeatureClassValidateAsync()
{
await QueuedTask.Run(() => MainMethodCode());
}
public void MainMethodCode()
{
using (Geodatabase fileGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb"))))
using (FeatureClass featureClass = fileGeodatabase.OpenDataset<FeatureClass>("PollingPlace"))
{
QueryFilter queryFilter = new QueryFilter { WhereClause = "CITY = 'Plainfield'" };
Selection selection = featureClass.Select(queryFilter, SelectionType.ObjectID, SelectionOption.Normal);
// The result is a mapping between those object ids which failed validation and the reason why the validation failed (a string message).
IReadOnlyDictionary<long, string> validationResult = featureClass.Validate(selection);
RowCursor rowCursor = featureClass.Search(queryFilter, false);
List<Feature> features = new List<Feature>();
try
{
while (rowCursor.MoveNext())
{
features.Add(rowCursor.Current as Feature);
}
// This is equivalent to the validation performed using the selection.
IReadOnlyDictionary<long, string> equivalentValidationResult = featureClass.Validate(features);
// Again this is equivalent to both the above results.
IReadOnlyDictionary<long, string> anotherEquivalentResult = featureClass.Validate(queryFilter);
SpatialQueryFilter spatialQueryFilter = new SpatialQueryFilter
{
FilterGeometry = new EnvelopeBuilder(
new MapPointBuilder(1052803, 1812751).ToGeometry(),
new MapPointBuilder(1034600, 1821320).ToGeometry()).ToGeometry(),
SpatialRelationship = SpatialRelationship.Within
};
IReadOnlyDictionary<long, string> spatialFilterBasedValidationResult = featureClass.Validate(spatialQueryFilter);
}
finally
{
rowCursor.Dispose();
Dispose(features);
}
}
// Opening a Non-Versioned SQL Server instance.
DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer)
{
AuthenticationMode = AuthenticationMode.DBMS,
// Where testMachine is the machine where the instance is running and testInstance is the name of the SqlServer instance.
Instance = @"testMachine\testInstance",
// Provided that a database called LocalGovernment has been created on the testInstance and geodatabase has been enabled on the database.
Database = "LocalGovernment",
// Provided that a login called gdb has been created and corresponding schema has been created with the required permissions.
User = "gdb",
Password = "password",
Version = "dbo.DEFAULT"
};
using (Geodatabase geodatabase = new Geodatabase(connectionProperties))
using (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.FacilitySite"))
{
QueryFilter parkFilter = new QueryFilter { WhereClause = "FCODE = 'Park'" };
Selection parkSelection = enterpriseFeatureClass.Select(parkFilter, SelectionType.ObjectID, SelectionOption.Normal);
// Remember that validation cost is directly proprtional to the number of Features validated. So, select the set of features to be
// validated judiciously. This will be empty because all the Park Features are valid.
IReadOnlyDictionary<long, string> emptyDictionary = enterpriseFeatureClass.Validate(parkSelection);
// We are adding an invalid feature to illustrate a case where the validation result is not empty.
long invalidFeatureObjectID = -1;
EditOperation editOperation = new EditOperation();
editOperation.Callback(context =>
{
RowBuffer rowBuffer = null;
Feature feature = null;
try
{
FeatureClassDefinition facilitySiteDefinition = enterpriseFeatureClass.GetDefinition();
rowBuffer = enterpriseFeatureClass.CreateRowBuffer();
rowBuffer["FACILITYID"] = "FAC-400";
rowBuffer["NAME"] = "Griffith Park";
rowBuffer["OWNTYPE"] = "Municipal";
rowBuffer["FCODE"] = "Park";
// Note that this is an invalid subtype value.
rowBuffer[facilitySiteDefinition.GetSubtypeField()] = 890;
rowBuffer[facilitySiteDefinition.GetShapeField()] = new PolygonBuilder(new List<Coordinate2D>
{
new Coordinate2D(1021570, 1880583),
new Coordinate2D(1028730, 1880994),
new Coordinate2D(1029718, 1875644),
new Coordinate2D(1021405, 1875397)
}).ToGeometry();
feature = enterpriseFeatureClass.CreateRow(rowBuffer);
invalidFeatureObjectID = feature.GetObjectID();
}
catch (GeodatabaseException exObj)
{
Console.WriteLine(exObj);
}
finally
{
if (rowBuffer != null)
rowBuffer.Dispose();
if (feature != null)
feature.Dispose();
}
}, enterpriseFeatureClass);
editOperation.Execute();
// This will have one keypair value for the invalid row that was added.
IReadOnlyDictionary<long, string> result = enterpriseFeatureClass.Validate(parkFilter);
// This will say "invalid subtype code".
string errorMessage = result[invalidFeatureObjectID];
}
}
private static void Dispose<T>(IEnumerable<T> iterator) where T : CoreObjectsBase
{
if (iterator != null)
{
foreach (T coreObject in iterator)
{
if (coreObject != null)
coreObject.Dispose();
}
}
}
}
}
| |
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.IO;
using System.Linq;
using System;
namespace Agens.StickersEditor.UnityEditor.iOS.Xcode.PBX
{
enum TokenType
{
EOF,
Invalid,
String,
QuotedString,
Comment,
Semicolon, // ;
Comma, // ,
Eq, // =
LParen, // (
RParen, // )
LBrace, // {
RBrace, // }
}
class Token
{
public TokenType type;
// the line of the input stream the token starts in (0-based)
public int line;
// start and past-the-end positions of the token in the input stream
public int begin, end;
}
class TokenList : List<Token>
{
}
class Lexer
{
string text;
int pos;
int length;
int line;
public static TokenList Tokenize(string text)
{
var lexer = new Lexer();
lexer.SetText(text);
return lexer.ScanAll();
}
public void SetText(string text)
{
this.text = text + " "; // to prevent out-of-bounds access during look ahead
pos = 0;
length = text.Length;
line = 0;
}
public TokenList ScanAll()
{
var tokens = new TokenList();
while (true)
{
var tok = new Token();
ScanOne(tok);
tokens.Add(tok);
if (tok.type == TokenType.EOF)
break;
}
return tokens;
}
void UpdateNewlineStats(char ch)
{
if (ch == '\n')
line++;
}
// tokens list is modified in the case when we add BrokenLine token and need to remove already
// added tokens for the current line
void ScanOne(Token tok)
{
while (true)
{
while (pos < length && Char.IsWhiteSpace(text[pos]))
{
UpdateNewlineStats(text[pos]);
pos++;
}
if (pos >= length)
{
tok.type = TokenType.EOF;
break;
}
char ch = text[pos];
char ch2 = text[pos+1];
if (ch == '\"')
ScanQuotedString(tok);
else if (ch == '/' && ch2 == '*')
ScanMultilineComment(tok);
else if (ch == '/' && ch2 == '/')
ScanComment(tok);
else if (IsOperator(ch))
ScanOperator(tok);
else
ScanString(tok); // be more robust and accept whatever is left
return;
}
}
void ScanString(Token tok)
{
tok.type = TokenType.String;
tok.begin = pos;
while (pos < length)
{
char ch = text[pos];
char ch2 = text[pos+1];
if (Char.IsWhiteSpace(ch))
break;
else if (ch == '\"')
break;
else if (ch == '/' && ch2 == '*')
break;
else if (ch == '/' && ch2 == '/')
break;
else if (IsOperator(ch))
break;
pos++;
}
tok.end = pos;
tok.line = line;
}
void ScanQuotedString(Token tok)
{
tok.type = TokenType.QuotedString;
tok.begin = pos;
pos++;
while (pos < length)
{
// ignore escaped quotes
if (text[pos] == '\\' && text[pos+1] == '\"')
{
pos += 2;
continue;
}
// note that we close unclosed quotes
if (text[pos] == '\"')
break;
UpdateNewlineStats(text[pos]);
pos++;
}
pos++;
tok.end = pos;
tok.line = line;
}
void ScanMultilineComment(Token tok)
{
tok.type = TokenType.Comment;
tok.begin = pos;
pos += 2;
while (pos < length)
{
if (text[pos] == '*' && text[pos+1] == '/')
break;
// we support multiline comments
UpdateNewlineStats(text[pos]);
pos++;
}
pos += 2;
tok.end = pos;
tok.line = line;
}
void ScanComment(Token tok)
{
tok.type = TokenType.Comment;
tok.begin = pos;
pos += 2;
while (pos < length)
{
if (text[pos] == '\n')
break;
pos++;
}
UpdateNewlineStats(text[pos]);
pos++;
tok.end = pos;
tok.line = line;
}
bool IsOperator(char ch)
{
if (ch == ';' || ch == ',' || ch == '=' || ch == '(' || ch == ')' || ch == '{' || ch == '}')
return true;
return false;
}
void ScanOperator(Token tok)
{
switch (text[pos])
{
case ';': ScanOperatorSpecific(tok, TokenType.Semicolon); return;
case ',': ScanOperatorSpecific(tok, TokenType.Comma); return;
case '=': ScanOperatorSpecific(tok, TokenType.Eq); return;
case '(': ScanOperatorSpecific(tok, TokenType.LParen); return;
case ')': ScanOperatorSpecific(tok, TokenType.RParen); return;
case '{': ScanOperatorSpecific(tok, TokenType.LBrace); return;
case '}': ScanOperatorSpecific(tok, TokenType.RBrace); return;
default: return;
}
}
void ScanOperatorSpecific(Token tok, TokenType type)
{
tok.type = type;
tok.begin = pos;
pos++;
tok.end = pos;
tok.line = line;
}
}
} // namespace UnityEditor.iOS.Xcode
| |
/*
Copyright (c) 2004-2006 Ladislav Prosek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger 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 from this software.
*/
using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using PHP.Core;
using PHP.Core.Reflection;
using System.Diagnostics;
namespace PHP.Library
{
/// <summary>
/// Contains object-related class library functions.
/// </summary>
/// <threadsafety static="true"/>
public static class PhpObjects
{
/// <summary>
/// Calls the method referred by <paramref name="methodName"/> from the user defined
/// object <paramref name="classNameOrObject"/> with parameters <paramref name="args"/>.
/// </summary>
/// <param name="caller">DTypeDesc of the caller's class context. Can be UnknownTypeDesc.</param>
/// <param name="methodName">The name of the method.</param>
/// <param name="classNameOrObject">An instance to invoke the method on or a class name.</param>
/// <param name="args">Parameters to invoke the method with.</param>
/// <returns>The method's return value (always dereferenced).</returns>
internal static object CallUserMethodInternal(DTypeDesc caller, string methodName, object classNameOrObject, ICollection args)
{
PhpException.Throw(PhpError.Notice, LibResources.GetString("call_user_method_deprecated"));
object ret_val = false;
DObject obj;
string class_name;
ScriptContext context = ScriptContext.CurrentContext;
//DTypeDesc classContext = PhpStackTrace.GetClassContext(); // TODO: GetClassContext only if needed by context.ResolveType
if (caller != null && caller.IsUnknown) caller = PhpStackTrace.GetClassContext();
if ((obj = classNameOrObject as DObject) != null)
{
// push arguments on stack
context.Stack.AddFrame(args);
ret_val = obj.InvokeMethod(methodName, caller, context);
}
else if ((class_name = PhpVariable.AsString(classNameOrObject)) != null)
{
// push arguments on stack
context.Stack.AddFrame(args);
ResolveTypeFlags flags = ResolveTypeFlags.UseAutoload | ResolveTypeFlags.ThrowErrors;
DTypeDesc type = PHP.Core.Convert.ObjectToTypeDesc(class_name, flags, caller, context, null, null);
ret_val = Operators.InvokeStaticMethod(type, methodName, null, caller, context);
}
else
{
PhpException.InvalidArgument("classNameOrObject", LibResources.GetString("arg:not_object_or_class_name"));
}
return PhpVariable.Dereference(ret_val);
}
/// <summary>
/// Calls the method referred by <paramref name="methodName"/> from the user defined
/// object <paramref name="classNameOrObject"/> with parameters <paramref name="args"/>.
/// </summary>
/// <param name="caller">DTypeDesc of the caller's class context. Can be UnknownTypeDesc.</param>
/// <param name="methodName">The name of the method.</param>
/// <param name="classNameOrObject">An instance to invoke the method on or a class name.</param>
/// <param name="args">Parameters to invoke the method with.</param>
/// <returns>The method's return value (always dereferenced).</returns>
[ImplementsFunction("call_user_method", FunctionImplOptions.NeedsClassContext)]
public static object CallUserMethod(DTypeDesc caller, string methodName, object classNameOrObject, params object[] args)
{
return CallUserMethodInternal(caller, methodName, classNameOrObject, args);
}
/// <summary>
/// Calls the method referred by <paramref name="methodName"/> from the user defined
/// object <paramref name="classNameOrObject"/> with parameters <paramref name="args"/>.
/// </summary>
/// <param name="caller">DTypeDesc of the caller's class context. Can be UnknownTypeDesc.</param>
/// <param name="methodName">The name of the method.</param>
/// <param name="classNameOrObject">An instance to invoke the method on or a class name.</param>
/// <param name="args">Parameters to invoke the method with.</param>
/// <returns>The method's return value.</returns>
[ImplementsFunction("call_user_method_array", FunctionImplOptions.NeedsClassContext)]
public static object CallUserMethodArray(DTypeDesc caller, string methodName, object classNameOrObject, PhpArray args)
{
return CallUserMethodInternal(caller, methodName, classNameOrObject, ((IDictionary)args).Values);
}
/// <summary>
/// Returns a <see cref="PhpArray"/> of default fields of a class.
/// </summary>
/// <param name="caller">The caller of the method to resolve visible properties properly. Can be UnknownTypeDesc.</param>
/// <param name="className">The name of the class.</param>
/// <param name="parentsFirst">Whether to list vars in PHP order (child vars then parent vars) or logical (parent vars then child).</param>
/// <param name="includeStatic">Specifies whether static variables should be listed as well</param>
/// <returns>Array of <paramref name="className"/>'s default fields.</returns>
/// <remarks>
/// <para>
/// The resulting array elements are in the form of <c>varname => value</c>, where <c>value</c>
/// is the default value of the field.
/// </para>
/// <para>
/// This method returns fields declared in <paramref name="className"/> and all its parent classes.
/// </para>
/// </remarks>
[ImplementsFunction("get_class_vars", FunctionImplOptions.NeedsClassContext)]
[return: PhpDeepCopy]
[return: CastToFalse]
public static PhpArray GetClassVars(DTypeDesc caller, string className, bool parentsFirst, bool includeStatic)
{
ScriptContext script_context = ScriptContext.CurrentContext;
DTypeDesc type = script_context.ResolveType(className);
if (type == null) return null;
// determine the calling type
//DTypeDesc caller = PhpStackTrace.GetClassContext();
if (caller != null && caller.IsUnknown) caller = PhpStackTrace.GetClassContext();
PhpArray result = new PhpArray();
// add instance properties
bool have_instance_props = false;
if (!type.IsAbstract)
{
// the class has to be instantiated in order to discover default instance property values
// (the constructor will initialize default properties, user defined constructor will not be called)
DObject obj = type.New(script_context) as DObject;
if (obj == null) return null;
// populate the resulting array taking into account current caller
IDictionaryEnumerator enumerator = obj.GetEnumerator(caller);
while (enumerator.MoveNext())
{
result.Add(enumerator.Key, enumerator.Value);
}
have_instance_props = true;
}
// add static fields (static and instance fields if the type is abstract)
if (includeStatic)
{
foreach (KeyValuePair<VariableName, DPropertyDesc> pair in type.EnumerateProperties(caller))
{
if (pair.Value.IsStatic)
{
result.Add(pair.Key.ToString(), pair.Value.Get(null));
}
else if (!have_instance_props)
{
result.Add(pair.Key.ToString(), null);
}
}
}
result.InplaceCopyOnReturn = true;
return result;
}
[ImplementsFunction("get_class_vars", FunctionImplOptions.NeedsClassContext)]
[return: PhpDeepCopy]
[return: CastToFalse]
public static PhpArray GetClassVars(DTypeDesc caller, string className)
{
return GetClassVars(caller, className, false, true);
}
/// <summary>
/// Returns a <see cref="PhpArray"/> of defined fields for the specified object <paramref name="obj"/>.
/// </summary>
/// <param name="caller">The caller of the method to resolve visible properties properly. Can be UnknownTypeDesc.</param>
/// <param name="obj">The object whose fields are requested.</param>
/// <returns>Array of <paramref name="obj"/>'s fields (name => value pairs).</returns>
/// <remarks>
/// This method returns default fields (those declared in the class using "var") declared in the
/// class and all its parent classes) as well as fields added at runtime.
/// </remarks>
[ImplementsFunction("get_object_vars", FunctionImplOptions.NeedsClassContext)]
//[return: PhpDeepCopy]
public static PhpArray GetObjectVars(DTypeDesc caller, DObject obj)
{
return GetObjectVars(caller,obj,false);
}
/// <summary>
/// Returns a <see cref="PhpArray"/> of defined fields for the specified object <paramref name="obj"/>.
/// </summary>
/// <param name="caller">The caller of the method to resolve visible properties properly. Can be UnknownTypeDesc.</param>
/// <param name="obj">The object whose fields are requested.</param>
/// <param name="IgnoreReferences">References will be omited from the result</param>
/// <returns>Array of <paramref name="obj"/>'s fields (name => value pairs).</returns>
/// <remarks>
/// This method returns default fields (those declared in the class using "var") declared in the
/// class and all its parent classes) as well as fields added at runtime.
/// </remarks>
[ImplementsFunction("get_object_vars", FunctionImplOptions.NeedsClassContext)]
//[return: PhpDeepCopy] // already deep copied
public static PhpArray GetObjectVars(DTypeDesc caller, DObject obj, bool IgnoreReferences)
{
if (obj == null) return null;
Converter<object, object> copy = null;
///////////////////////////////////////
// This is hot fix for a reference counting problem when reference aren't released in same way as in PHP.
// Hence, we need to perform deep copy ignoring references
if (IgnoreReferences)
copy = (value) =>
{
PhpReference refValue = value as PhpReference;
if (refValue != null)
return copy(refValue.Value);
PhpArray array = value as PhpArray;
if (array != null)
{
PhpArray dst = new PhpArray(array.IntegerCount, array.StringCount);
foreach (KeyValuePair<IntStringKey, object> entry in array)
{
// checks whether a value is a reference pointing to the instance itself:
refValue = entry.Value as PhpReference;
if (refValue != null && refValue.Value == array)
{
// copies the value so that it will self-reference the new instance (not the old one):
dst.Add(entry.Key, new PhpReference(dst));
}
else
{
dst.Add(entry.Key, copy(entry.Value));
}
}
return dst;
}
return value;
};
else
copy = (value) => { return PhpVariable.DeepCopy(value); }; // perform InplaceDeepCopy() here to save one more iteration through the array
///////////////////////////////////////
PhpArray result = new PhpArray(0, obj.Count);
var foreachEnumerator = obj.GetEnumerator((caller != null && caller.IsUnknown) ? PhpStackTrace.GetClassContext() : caller);
while (foreachEnumerator.MoveNext())
//foreach (DictionaryEntry pair in obj)
{
DictionaryEntry pair = (DictionaryEntry)foreachEnumerator.Current;
result.Add((string)pair.Key, copy(pair.Value));
}
//result.InplaceCopyOnReturn = true; // already deep copied
return result;
}
/// <summary>
/// Verifies whether the method given by <paramref name="methodName"/> has been defined for the given
/// object <paramref name="obj"/>.
/// </summary>
/// <param name="caller">Current class context.</param>
/// <param name="obj">The object to test.</param>
/// <param name="methodName">The name of the method.</param>
/// <returns><B>True</B> if the method given by <paramref name="methodName"/> has been defined for the given
/// object <paramref name="obj"/>, <B>false</B> otherwise.</returns>
[ImplementsFunction("method_exists", FunctionImplOptions.NeedsClassContext)]
public static bool MethodExists(DTypeDesc caller, object obj, string methodName)
{
if (obj == null || string.IsNullOrEmpty(methodName)) return false;
DTypeDesc dtype;
DObject dobj;
string str;
if ((dobj = (obj as DObject)) != null)
{
dtype = dobj.TypeDesc;
if (dtype == null)
{
Debug.Fail("DObject.TypeDesc should not be null");
return false;
}
}
else if ((str = PhpVariable.AsString(obj)) != null)
{
ScriptContext script_context = ScriptContext.CurrentContext;
dtype = script_context.ResolveType(str, null, caller, null, ResolveTypeFlags.UseAutoload);
if (dtype == null)
return false;
}
else
{
// other type names are not handled
return false;
}
DRoutineDesc method;
return (dtype.GetMethod(new Name(methodName), dtype, out method) != GetMemberResult.NotFound);
}
/// <summary>
/// Converts a class name or class instance to <see cref="DTypeDesc"/> object.
/// </summary>
/// <param name="scriptContext">Current <see cref="ScriptContext"/>.</param>
/// <param name="namingContext">Current <see cref="NamingContext"/>.</param>
/// <param name="caller">The caller of the method to resolve visible properties properly. Can be UnknownTypeDesc.</param>
/// <param name="classNameOrObject">The class name or class instance (<see cref="DObject"/>).</param>
/// <param name="useAutoload"><B>True</B> iff the <c>__autoload</c> magic function should be used.</param>
/// <returns>The type desc that corresponds to <paramref name="classNameOrObject"/> or <B>null</B>
/// if the type could not be found or <paramref name="classNameOrObject"/> is neither a string
/// nor <see cref="DObject"/>.</returns>
internal static DTypeDesc ClassNameOrObjectToType(ScriptContext/*!*/ scriptContext, NamingContext namingContext,
DTypeDesc caller, object classNameOrObject, bool useAutoload)
{
string class_name = PhpVariable.AsString(classNameOrObject);
if (class_name != null)
{
// lookup the Type
return scriptContext.ResolveType(class_name, namingContext, caller, null,
(useAutoload ? ResolveTypeFlags.UseAutoload : ResolveTypeFlags.None));
}
else
{
DObject obj = classNameOrObject as DObject;
if (obj != null) return obj.TypeDesc;
}
return null;
}
/// <summary>
/// Verifies whether the property given by <paramref name="propertyName"/> has been defined for the given
/// object object or class.
/// </summary>
/// <param name="caller">The caller of the method to resolve visible properties properly. Can be UnknownTypeDesc.</param>
/// <param name="classNameOrObject">The object (<see cref="DObject"/>) or the name of a class
/// (<see cref="String"/>).</param>
/// <param name="propertyName">The name of the property.</param>
/// <returns><B>True</B> if the property given by <paramref name="propertyName"/> has been defined for the
/// given class or object and is accessible from current class context.</returns>
/// <remarks>
/// This function has different semantics than <see cref="MethodExists"/>, which ignores visibility.
/// If an object is passed in the first parameter, the property is searched among runtime fields as well.
/// </remarks>
[ImplementsFunction("property_exists", FunctionImplOptions.NeedsClassContext)]
public static bool PropertyExists(DTypeDesc caller, object classNameOrObject, string propertyName)
{
ScriptContext context = ScriptContext.CurrentContext;
DTypeDesc type = ClassNameOrObjectToType(context, null, caller, classNameOrObject, true);
if (type == null) return false;
// determine the calling class context
//DTypeDesc caller = PhpStackTrace.GetClassContext();
if (caller != null && caller.IsUnknown) caller = PhpStackTrace.GetClassContext();
DPropertyDesc property;
if (type.GetProperty(new VariableName(propertyName), caller, out property) == GetMemberResult.OK)
{
// CT property was found
return true;
}
else
{
// search RT fields, if possible
DObject obj = classNameOrObject as DObject;
return (obj != null && obj.RuntimeFields != null && obj.RuntimeFields.ContainsKey(propertyName));
}
}
/// <summary>
/// Returns all methods defined in the specified class or class of specified object, and its predecessors.
/// </summary>
/// <param name="caller">The caller of the method to resolve visible properties properly. Can be UnknownTypeDesc.</param>
/// <param name="classNameOrObject">The object (<see cref="DObject"/>) or the name of a class
/// (<see cref="String"/>).</param>
/// <returns>Array of all methods defined in <paramref name="classNameOrObject"/>.</returns>
[ImplementsFunction("get_class_methods", FunctionImplOptions.NeedsClassContext)]
public static PhpArray GetClassMethods(DTypeDesc caller, object classNameOrObject)
{
ScriptContext context = ScriptContext.CurrentContext;
DTypeDesc type = ClassNameOrObjectToType(context, null, caller, classNameOrObject, true);
if (type == null) return null;
// determine the calling type
//DTypeDesc caller = PhpStackTrace.GetClassContext();
if (caller != null && caller.IsUnknown) caller = PhpStackTrace.GetClassContext();
PhpArray result = new PhpArray();
foreach (KeyValuePair<Name, DRoutineDesc> pair in type.EnumerateMethods(caller))
{
result.Add(pair.Key.ToString());
}
return result;
}
/// <summary>
/// Returns a <see cref="PhpArray"/> with names of all defined classes (system and user).
/// </summary>
/// <returns><see cref="PhpArray"/> of class names.</returns>
[ImplementsFunction("get_declared_classes")]
public static PhpArray GetDeclaredClasses()
{
return (PhpArray)ScriptContext.CurrentContext.GetDeclaredClasses(new PhpArray());
}
/// <summary>
/// Returns a <see cref="PhpArray"/> with names of all defined interfaces (system and user).
/// </summary>
/// <returns><see cref="PhpArray"/> of interface names.</returns>
[ImplementsFunction("get_declared_interfaces")]
public static PhpArray GetDeclaredInterfaces()
{
return (PhpArray)ScriptContext.CurrentContext.GetDeclaredInterfaces(new PhpArray());
}
/// <summary>
/// Tests whether the class given by <paramref name="classNameOrObject"/> is derived from a class given
/// by <paramref name="baseClassName"/>.
/// </summary>
/// <param name="caller">The caller of the method to resolve visible properties properly. Can be UnknownTypeDesc.</param>
/// <param name="classNameOrObject">The object (<see cref="DObject"/>) or the name of a class
/// (<see cref="String"/>).</param>
/// <param name="baseClassName">The name of the (base) class.</param>
/// <returns><B>true</B> if <paramref name="classNameOrObject"/> implements or extends <paramref name="baseClassName"/>,
/// <B>false</B> otherwise.</returns>
[ImplementsFunction("is_subclass_of", FunctionImplOptions.NeedsClassContext)]
public static bool IsSubclassOf(DTypeDesc caller, object classNameOrObject, string baseClassName)
{
ScriptContext context = ScriptContext.CurrentContext;
DTypeDesc type = ClassNameOrObjectToType(context, null, caller, classNameOrObject, true);
if (type == null) return false;
// look for the class, do not use autoload (since PHP 5.1):
DTypeDesc base_type = context.ResolveType(baseClassName, null, caller, null, ResolveTypeFlags.None); // do not call autoload [workitem:26664]
if (base_type == null) return false;
return (base_type.RealType.IsAssignableFrom(type.RealType) && base_type != type);
}
/// <summary>
/// Tests whether a given class is defined.
/// </summary>
/// <param name="caller">The caller class context to resolve visibility.</param>
/// <param name="className">The name of the class.</param>
/// <returns><B>true</B> if the class given by <paramref name="className"/> has been defined,
/// <B>false</B> otherwise.</returns>
[ImplementsFunction("class_exists", FunctionImplOptions.NeedsClassContext)]
[PureFunction(typeof(PhpObjects), "ClassExists_Analyze_1")]
public static bool ClassExists(DTypeDesc caller, string className)
{
return ClassExists(caller, className, true);
}
/// <summary>
/// Tests whether a given class is defined.
/// </summary>
/// <param name="caller">The caller class context to resolve visibility.</param>
/// <param name="className">The name of the class.</param>
/// <param name="autoload">Whether to attempt to call <c>__autoload</c>.</param>
/// <returns><B>true</B> if the class given by <paramref name="className"/> has been defined,
/// <B>false</B> otherwise.</returns>
[ImplementsFunction("class_exists", FunctionImplOptions.NeedsClassContext)]
[PureFunction(typeof(PhpObjects), "ClassExists_Analyze_2")]
public static bool ClassExists(DTypeDesc caller, string className, bool autoload)
{
DTypeDesc type = ScriptContext.CurrentContext.ResolveType(className, null, caller, null, autoload ? ResolveTypeFlags.UseAutoload : ResolveTypeFlags.None);
return type != null;
}
#region analyzer of class_exists
public static PHP.Core.Compiler.AST.FunctionCallEvaluateInfo ClassExists_Analyze_2(Analyzer analyzer, string name, bool autoload)
{
// ignore autoload at the compile time
return ClassExists_Analyze_1(analyzer, name);
}
public static PHP.Core.Compiler.AST.FunctionCallEvaluateInfo ClassExists_Analyze_1(Analyzer analyzer, string name)
{
QualifiedName? alias;
DType type = analyzer.SourceUnit.ResolveTypeName(
new QualifiedName(new Name(name)),
analyzer.CurrentScope,
out alias,
null,
PHP.Core.Text.Span.Invalid,
false);
if (type == null || type.IsUnknown)
return null; // type is not known at the compilation time. However it can be defined at the runtime (dynamic include, script library, etc).
return new PHP.Core.Compiler.AST.FunctionCallEvaluateInfo()
{
value = true // type is definitely known the the compilation time
};
}
#endregion
/// <summary>
/// Tests whether a given interface is defined.
/// </summary>
/// <param name="caller">The class context of the caller.</param>
/// <param name="ifaceName">The name of the interface.</param>
/// <returns><B>true</B> if the interface given by <paramref name="ifaceName"/> has been defined,
/// <B>false</B> otherwise.</returns>
[ImplementsFunction("interface_exists", FunctionImplOptions.NeedsClassContext)]
public static bool InterfaceExists(DTypeDesc caller, string ifaceName)
{
return InterfaceExists(caller, ifaceName, true);
}
/// <summary>
/// Tests whether a given interface is defined.
/// </summary>
/// <param name="caller">The class context of the caller.</param>
/// <param name="ifaceName">The name of the interface.</param>
/// <param name="autoload">Whether to attempt to call <c>__autoload</c>.</param>
/// <returns><B>true</B> if the interface given by <paramref name="ifaceName"/> has been defined,
/// <B>false</B> otherwise.</returns>
[ImplementsFunction("interface_exists", FunctionImplOptions.NeedsClassContext)]
public static bool InterfaceExists(DTypeDesc caller, string ifaceName, bool autoload)
{
DTypeDesc type = ScriptContext.CurrentContext.ResolveType(ifaceName, null, caller, null, autoload ? ResolveTypeFlags.UseAutoload : ResolveTypeFlags.None);
return type != null && type.IsInterface;
}
/// <summary>
/// Returns the name of the current class.
/// </summary>
/// <param name="caller">Current class context.</param>
/// <returns>Current class name.</returns>
[ImplementsFunction("get_class", FunctionImplOptions.NeedsClassContext)]
[return: CastToFalse]
public static string GetClass(DTypeDesc caller)
{
if (caller == null || caller.IsUnknown)
return null;
return caller.MakeFullName();
}
/// <summary>
/// Returns the name of the class of which the object <paramref name="var"/> is an instance.
/// </summary>
/// <param name="caller">Current class context.</param>
/// <param name="var">The object whose class is requested.</param>
/// <returns><paramref name="var"/>'s class name or current class name if <paramref name="var"/> is
/// <B>null</B>.</returns>
[ImplementsFunction("get_class", FunctionImplOptions.NeedsClassContext)]
[return: CastToFalse]
public static string GetClass(DTypeDesc caller, object var)
{
if (var == null)
return GetClass(caller);
DObject obj = var as DObject;
return (obj != null) ? obj.TypeName : null;
}
[ImplementsFunction("get_called_class", FunctionImplOptions.NeedsLateStaticBind)]
[return: CastToFalse]
public static string GetCalledClass(DTypeDesc caller)
{
if (caller == null || caller.IsUnknown)
return null;
return caller.MakeFullName();
}
/// <summary>
/// Gets the name of the class from which class given by <paramref name="classNameOrObject"/>
/// inherits.
/// </summary>
/// <param name="caller">The caller of the method to resolve visible properties properly. Can be UnknownTypeDesc.</param>
/// <param name="classNameOrObject">The object (<see cref="DObject"/>) or the name of a class
/// (<see cref="String"/>).</param>
/// <returns>If <paramref name="classNameOrObject"/> is an <see cref="DObject"/>, returns the name
/// of the parent class of the class of which <paramref name="classNameOrObject"/> is an instance.
/// If <paramref name="classNameOrObject"/> is a <see cref="String"/>, returns the name of the parent
/// class of the class with that name.</returns>
/// <remarks>
/// If the class given by <paramref name="classNameOrObject"/> has no parent in PHP class hierarchy,
/// this method returns <B>null</B>.
/// </remarks>
[ImplementsFunction("get_parent_class", FunctionImplOptions.NeedsClassContext)]
[return: CastToFalse]
[PureFunction(typeof(PhpObjects), "GetParentClass_Analyze")]
public static string GetParentClass(DTypeDesc caller, object classNameOrObject)
{
ScriptContext context = ScriptContext.CurrentContext;
DTypeDesc type = ClassNameOrObjectToType(context, null, caller, classNameOrObject, true);
if (type == null || type.IsInterface) return null;
DTypeDesc parent_type = type.Base;
return (parent_type == null ? null : parent_type.MakeFullName());
}
#region analyzer of get_parent_class
[return: CastToFalse]
public static PHP.Core.Compiler.AST.FunctionCallEvaluateInfo GetParentClass_Analyze(Analyzer analyzer, string name)
{
QualifiedName? alias;
DType type = analyzer.SourceUnit.ResolveTypeName(
new QualifiedName(new Name(name)),
analyzer.CurrentScope,
out alias,
null,
PHP.Core.Text.Span.Invalid,
false);
if (type == null || type.IsUnknown)
return null; // type is not known at the compilation time. However it can be defined at the runtime (dynamic include, script library, etc).
// type is definitely known the the compilation time
var parent_type = type.Base;
return new PHP.Core.Compiler.AST.FunctionCallEvaluateInfo()
{
value = (parent_type == null ? null : parent_type.FullName)
};
}
#endregion
/// <summary>
/// Tests whether <paramref name="obj"/>'s class is derived from a class given by <paramref name="className"/>.
/// </summary>
/// <param name="caller">The caller of the method to resolve visible properties properly. Can be UnknownTypeDesc.</param>
/// <param name="obj">The object to test.</param>
/// <param name="className">The name of the class.</param>
/// <returns><B>true</B> if the object <paramref name="obj"/> belongs to <paramref name="className"/> class or
/// a class which is a subclass of <paramref name="className"/>, <B>false</B> otherwise.</returns>
[ImplementsFunction("is_a", FunctionImplOptions.NeedsClassContext)]
public static bool IsA(DTypeDesc caller, object obj, string className)
{
if (obj == null || !(obj is DObject)) return false;
DObject dobj = (DObject)obj;
DTypeDesc type = ScriptContext.CurrentContext.ResolveType(className, null, caller, null, ResolveTypeFlags.None); // do not call autoload [workitem:26664]
if (type == null) return false;
return type.IsAssignableFrom(dobj.TypeDesc);
}
/// <summary>
/// Returns a <see cref="PhpArray"/> with keys and values being names of a given class's
/// base classes.
/// </summary>
/// <param name="caller">The caller of the method to resolve visible properties properly. Can be UnknownTypeDesc.</param>
/// <param name="classNameOrObject">The <see cref="DObject"/> or class name to get base classes of.</param>
/// <param name="useAutoload"><B>True</B> if the magic <c>__autoload</c> function should be used.</param>
/// <returns>The <see cref="PhpArray"/> with base class names.</returns>
[ImplementsFunction("class_parents", FunctionImplOptions.NeedsClassContext)]
[return: CastToFalse]
public static PhpArray GetClassParents(DTypeDesc caller, object classNameOrObject, bool useAutoload)
{
ScriptContext context = ScriptContext.CurrentContext;
DTypeDesc type = ClassNameOrObjectToType(context, null, caller, classNameOrObject, useAutoload);
if (type == null || type.IsInterface) return null;
PhpArray result = new PhpArray();
while ((type = type.Base) != null)
{
string class_name = type.MakeFullName();
result.Add(class_name, class_name);
}
return result;
}
/// <summary>
/// Returns a <see cref="PhpArray"/> with keys and values being names of a given class's
/// base classes.
/// </summary>
/// <param name="caller">The caller of the method to resolve visible properties properly. Can be UnknownTypeDesc.</param>
/// <param name="classNameOrObject">The <see cref="DObject"/> or class name to get base classes of.</param>
/// <returns>The <see cref="PhpArray"/> with base class names.</returns>
[ImplementsFunction("class_parents", FunctionImplOptions.NeedsClassContext)]
[return: CastToFalse]
public static PhpArray GetClassParents(DTypeDesc caller, object classNameOrObject)
{
return GetClassParents(caller, classNameOrObject, true);
}
/// <summary>
/// Returns a <see cref="PhpArray"/> with keys and values being names of interfaces implemented by a given
/// class.
/// </summary>
/// <param name="caller">The caller of the method to resolve visible properties properly. Can be UnknownTypeDesc.</param>
/// <param name="classNameOrObject">The <see cref="DObject"/> or class name to get implemented interfaces of.
/// <param name="useAutoload"><B>True</B> if the magic <c>__autoload</c> function should be used.</param>
/// </param>
/// <returns>The <see cref="PhpArray"/> with interface names.</returns>
[ImplementsFunction("class_implements", FunctionImplOptions.NeedsClassContext)]
[return: CastToFalse]
public static PhpArray GetClassInterfaces(DTypeDesc caller, object classNameOrObject, bool useAutoload)
{
ScriptContext context = ScriptContext.CurrentContext;
DTypeDesc type = ClassNameOrObjectToType(context, null, caller, classNameOrObject, useAutoload);
if (type == null) return null;
PhpArray result = new PhpArray();
DTypeDesc[] interfaces = type.GetImplementedInterfaces();
for (int i = 0; i < interfaces.Length; i++)
{
string iface_name = interfaces[i].MakeFullName();
result[iface_name] = iface_name;
}
return result;
}
/// <summary>
/// Returns a <see cref="PhpArray"/> with keys and values being names of interfaces implemented by a given
/// class.
/// </summary>
/// <param name="caller">The caller of the method to resolve visible properties properly. Can be UnknownTypeDesc.</param>
/// <param name="classNameOrObject">The <see cref="DObject"/> or class name to get implemented interfaces of.
/// </param>
/// <returns>The <see cref="PhpArray"/> with interface names.</returns>
[ImplementsFunction("class_implements", FunctionImplOptions.NeedsClassContext)]
[return: CastToFalse]
public static PhpArray GetClassInterfaces(DTypeDesc caller, object classNameOrObject)
{
return GetClassInterfaces(caller, classNameOrObject, true);
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// 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.IO;
using DiscUtils.Streams;
namespace DiscUtils.Fat
{
internal class Directory : IDisposable
{
private readonly Stream _dirStream;
private readonly Directory _parent;
private readonly long _parentId;
private long _endOfEntries;
private Dictionary<long, DirectoryEntry> _entries;
private List<long> _freeEntries;
private DirectoryEntry _parentEntry;
private long _parentEntryLocation;
private DirectoryEntry _selfEntry;
private long _selfEntryLocation;
/// <summary>
/// Initializes a new instance of the Directory class. Use this constructor to represent non-root directories.
/// </summary>
/// <param name="parent">The parent directory.</param>
/// <param name="parentId">The identity of the entry representing this directory in the parent.</param>
internal Directory(Directory parent, long parentId)
{
FileSystem = parent.FileSystem;
_parent = parent;
_parentId = parentId;
DirectoryEntry dirEntry = ParentsChildEntry;
_dirStream = new ClusterStream(FileSystem, FileAccess.ReadWrite, dirEntry.FirstCluster, uint.MaxValue);
LoadEntries();
}
/// <summary>
/// Initializes a new instance of the Directory class. Use this constructor to represent the root directory.
/// </summary>
/// <param name="fileSystem">The file system.</param>
/// <param name="dirStream">The stream containing the directory info.</param>
internal Directory(FatFileSystem fileSystem, Stream dirStream)
{
FileSystem = fileSystem;
_dirStream = dirStream;
LoadEntries();
}
public DirectoryEntry[] Entries
{
get { return new List<DirectoryEntry>(_entries.Values).ToArray(); }
}
public FatFileSystem FileSystem { get; }
public bool IsEmpty
{
get { return _entries.Count == 0; }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public DirectoryEntry[] GetDirectories()
{
List<DirectoryEntry> dirs = new List<DirectoryEntry>(_entries.Count);
foreach (DirectoryEntry dirEntry in _entries.Values)
{
if ((dirEntry.Attributes & FatAttributes.Directory) != 0)
{
dirs.Add(dirEntry);
}
}
return dirs.ToArray();
}
public DirectoryEntry[] GetFiles()
{
List<DirectoryEntry> files = new List<DirectoryEntry>(_entries.Count);
foreach (DirectoryEntry dirEntry in _entries.Values)
{
if ((dirEntry.Attributes & (FatAttributes.Directory | FatAttributes.VolumeId)) == 0)
{
files.Add(dirEntry);
}
}
return files.ToArray();
}
public DirectoryEntry GetEntry(long id)
{
return id < 0 ? null : _entries[id];
}
public Directory GetChildDirectory(FileName name)
{
long id = FindEntry(name);
if (id < 0)
{
return null;
}
if ((_entries[id].Attributes & FatAttributes.Directory) == 0)
{
return null;
}
return FileSystem.GetDirectory(this, id);
}
internal Directory CreateChildDirectory(FileName name)
{
long id = FindEntry(name);
if (id >= 0)
{
if ((_entries[id].Attributes & FatAttributes.Directory) == 0)
{
throw new IOException("A file exists with the same name");
}
return FileSystem.GetDirectory(this, id);
}
try
{
uint firstCluster;
if (!FileSystem.Fat.TryGetFreeCluster(out firstCluster))
{
throw new IOException("Failed to allocate first cluster for new directory");
}
FileSystem.Fat.SetEndOfChain(firstCluster);
DirectoryEntry newEntry = new DirectoryEntry(FileSystem.FatOptions, name, FatAttributes.Directory,
FileSystem.FatVariant);
newEntry.FirstCluster = firstCluster;
newEntry.CreationTime = FileSystem.ConvertFromUtc(DateTime.UtcNow);
newEntry.LastWriteTime = newEntry.CreationTime;
id = AddEntry(newEntry);
PopulateNewChildDirectory(newEntry);
// Rather than just creating a new instance, pull it through the fileSystem cache
// to ensure the cache model is preserved.
return FileSystem.GetDirectory(this, id);
}
finally
{
FileSystem.Fat.Flush();
}
}
internal void AttachChildDirectory(FileName name, Directory newChild)
{
long id = FindEntry(name);
if (id >= 0)
{
throw new IOException("Directory entry already exists");
}
DirectoryEntry newEntry = new DirectoryEntry(newChild.ParentsChildEntry);
newEntry.Name = name;
AddEntry(newEntry);
DirectoryEntry newParentEntry = new DirectoryEntry(SelfEntry);
newParentEntry.Name = FileName.ParentEntryName;
newChild.ParentEntry = newParentEntry;
}
internal long FindVolumeId()
{
foreach (long id in _entries.Keys)
{
DirectoryEntry focus = _entries[id];
if ((focus.Attributes & FatAttributes.VolumeId) != 0)
{
return id;
}
}
return -1;
}
internal long FindEntry(FileName name)
{
foreach (long id in _entries.Keys)
{
DirectoryEntry focus = _entries[id];
if (focus.Name == name && (focus.Attributes & FatAttributes.VolumeId) == 0)
{
return id;
}
}
return -1;
}
internal SparseStream OpenFile(FileName name, FileMode mode, FileAccess fileAccess)
{
if (mode == FileMode.Append || mode == FileMode.Truncate)
{
throw new NotImplementedException();
}
long fileId = FindEntry(name);
bool exists = fileId != -1;
if (mode == FileMode.CreateNew && exists)
{
throw new IOException("File already exists");
}
if (mode == FileMode.Open && !exists)
{
throw new FileNotFoundException("File not found",
name.GetDisplayName(FileSystem.FatOptions.FileNameEncoding));
}
if ((mode == FileMode.Open || mode == FileMode.OpenOrCreate || mode == FileMode.Create) && exists)
{
SparseStream stream = new FatFileStream(FileSystem, this, fileId, fileAccess);
if (mode == FileMode.Create)
{
stream.SetLength(0);
}
HandleAccessed(false);
return stream;
}
if ((mode == FileMode.OpenOrCreate || mode == FileMode.CreateNew || mode == FileMode.Create) && !exists)
{
// Create new file
DirectoryEntry newEntry = new DirectoryEntry(FileSystem.FatOptions, name, FatAttributes.Archive,
FileSystem.FatVariant);
newEntry.FirstCluster = 0; // i.e. Zero-length
newEntry.CreationTime = FileSystem.ConvertFromUtc(DateTime.UtcNow);
newEntry.LastWriteTime = newEntry.CreationTime;
fileId = AddEntry(newEntry);
return new FatFileStream(FileSystem, this, fileId, fileAccess);
}
// Should never get here...
throw new NotImplementedException();
}
internal long AddEntry(DirectoryEntry newEntry)
{
// Unlink an entry from the free list (or add to the end of the existing directory)
long pos;
if (_freeEntries.Count > 0)
{
pos = _freeEntries[0];
_freeEntries.RemoveAt(0);
}
else
{
pos = _endOfEntries;
_endOfEntries += 32;
}
// Put the new entry into it's slot
_dirStream.Position = pos;
newEntry.WriteTo(_dirStream);
// Update internal structures to reflect new entry (as if read from disk)
_entries.Add(pos, newEntry);
HandleAccessed(true);
return pos;
}
internal void DeleteEntry(long id, bool releaseContents)
{
if (id < 0)
{
throw new IOException("Attempt to delete unknown directory entry");
}
try
{
DirectoryEntry entry = _entries[id];
DirectoryEntry copy = new DirectoryEntry(entry);
copy.Name = entry.Name.Deleted();
_dirStream.Position = id;
copy.WriteTo(_dirStream);
if (releaseContents)
{
FileSystem.Fat.FreeChain(entry.FirstCluster);
}
_entries.Remove(id);
_freeEntries.Add(id);
HandleAccessed(true);
}
finally
{
FileSystem.Fat.Flush();
}
}
internal void UpdateEntry(long id, DirectoryEntry entry)
{
if (id < 0)
{
throw new IOException("Attempt to update unknown directory entry");
}
_dirStream.Position = id;
entry.WriteTo(_dirStream);
_entries[id] = entry;
}
private void LoadEntries()
{
_entries = new Dictionary<long, DirectoryEntry>();
_freeEntries = new List<long>();
_selfEntryLocation = -1;
_parentEntryLocation = -1;
while (_dirStream.Position < _dirStream.Length)
{
long streamPos = _dirStream.Position;
DirectoryEntry entry = new DirectoryEntry(FileSystem.FatOptions, _dirStream, FileSystem.FatVariant);
if (entry.Attributes ==
(FatAttributes.ReadOnly | FatAttributes.Hidden | FatAttributes.System | FatAttributes.VolumeId))
{
// Long File Name entry
}
else if (entry.Name.IsDeleted())
{
// E5 = Free Entry
_freeEntries.Add(streamPos);
}
else if (entry.Name == FileName.SelfEntryName)
{
_selfEntry = entry;
_selfEntryLocation = streamPos;
}
else if (entry.Name == FileName.ParentEntryName)
{
_parentEntry = entry;
_parentEntryLocation = streamPos;
}
else if (entry.Name.IsEndMarker())
{
// Free Entry, no more entries available
_endOfEntries = streamPos;
break;
}
else
{
_entries.Add(streamPos, entry);
}
}
}
private void HandleAccessed(bool forWrite)
{
if (FileSystem.CanWrite && _parent != null)
{
DateTime now = DateTime.Now;
DirectoryEntry entry = SelfEntry;
DateTime oldAccessTime = entry.LastAccessTime;
DateTime oldWriteTime = entry.LastWriteTime;
entry.LastAccessTime = now;
if (forWrite)
{
entry.LastWriteTime = now;
}
if (entry.LastAccessTime != oldAccessTime || entry.LastWriteTime != oldWriteTime)
{
SelfEntry = entry;
DirectoryEntry parentEntry = ParentsChildEntry;
parentEntry.LastAccessTime = entry.LastAccessTime;
parentEntry.LastWriteTime = entry.LastWriteTime;
ParentsChildEntry = parentEntry;
}
}
}
private void PopulateNewChildDirectory(DirectoryEntry newEntry)
{
// Populate new directory with initial (special) entries. First one is easy, just change the name!
using (
ClusterStream stream = new ClusterStream(FileSystem, FileAccess.Write, newEntry.FirstCluster,
uint.MaxValue))
{
// First is the self-referencing entry...
DirectoryEntry selfEntry = new DirectoryEntry(newEntry);
selfEntry.Name = FileName.SelfEntryName;
selfEntry.WriteTo(stream);
// Second is a clone of our self entry (i.e. parent) - though dates are odd...
DirectoryEntry parentEntry = new DirectoryEntry(SelfEntry);
parentEntry.Name = FileName.ParentEntryName;
parentEntry.CreationTime = newEntry.CreationTime;
parentEntry.LastWriteTime = newEntry.LastWriteTime;
parentEntry.WriteTo(stream);
}
}
private void Dispose(bool disposing)
{
if (disposing)
{
_dirStream.Dispose();
}
}
#region Convenient accessors for special entries
internal DirectoryEntry ParentsChildEntry
{
get
{
if (_parent == null)
{
return new DirectoryEntry(FileSystem.FatOptions, FileName.ParentEntryName, FatAttributes.Directory,
FileSystem.FatVariant);
}
return _parent.GetEntry(_parentId);
}
set
{
if (_parent != null)
{
_parent.UpdateEntry(_parentId, value);
}
}
}
internal DirectoryEntry SelfEntry
{
get
{
if (_parent == null)
{
// If we're the root directory, simulate the parent entry with a dummy record
return new DirectoryEntry(FileSystem.FatOptions, FileName.Null, FatAttributes.Directory,
FileSystem.FatVariant);
}
return _selfEntry;
}
set
{
if (_selfEntryLocation >= 0)
{
_dirStream.Position = _selfEntryLocation;
value.WriteTo(_dirStream);
_selfEntry = value;
}
}
}
internal DirectoryEntry ParentEntry
{
get { return _parentEntry; }
set
{
if (_parentEntryLocation < 0)
{
throw new IOException("No parent entry on disk to update");
}
_dirStream.Position = _parentEntryLocation;
value.WriteTo(_dirStream);
_parentEntry = value;
}
}
#endregion
}
}
| |
//
// ListViewBackend.cs
//
// Author:
// Lluis Sanchez <[email protected]>
// Jan Strnadek <[email protected]>
// - GetAtRowPosition
// - NSTableView for mouse events
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
#if MONOMAC
using nint = System.Int32;
using nfloat = System.Single;
using CGRect = System.Drawing.RectangleF;
using CGPoint = System.Drawing.PointF;
using CGSize = System.Drawing.SizeF;
using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.CoreGraphics;
#else
using Foundation;
using AppKit;
using CoreGraphics;
#endif
namespace Xwt.Mac
{
public class ListViewBackend: TableViewBackend<NSTableView, IListViewEventSink>, IListViewBackend
{
IListDataSource source;
ListSource tsource;
protected override NSTableView CreateView ()
{
return new NSTableViewBackend (EventSink, ApplicationContext);
}
protected override string SelectionChangeEventName {
get { return "NSTableViewSelectionDidChangeNotification"; }
}
public override void EnableEvent (object eventId)
{
base.EnableEvent (eventId);
if (eventId is ListViewEvent) {
switch ((ListViewEvent)eventId) {
case ListViewEvent.RowActivated:
Table.DoubleClick += HandleDoubleClick;
break;
}
}
}
public override void DisableEvent (object eventId)
{
base.DisableEvent (eventId);
if (eventId is ListViewEvent) {
switch ((ListViewEvent)eventId) {
case ListViewEvent.RowActivated:
Table.DoubleClick -= HandleDoubleClick;
Table.DoubleAction = null;
break;
}
}
}
void HandleDoubleClick (object sender, EventArgs e)
{
var cr = Table.ClickedRow;
if (cr >= 0) {
ApplicationContext.InvokeUserCode (delegate {
((IListViewEventSink)EventSink).OnRowActivated ((int)cr);
});
}
}
public virtual void SetSource (IListDataSource source, IBackend sourceBackend)
{
this.source = source;
tsource = new ListSource (source);
Table.DataSource = tsource;
//TODO: Reloading single rows would be slightly more efficient.
// According to NSTableView.ReloadData() documentation,
// only the visible rows are reloaded.
source.RowInserted += (sender, e) => Table.ReloadData();
source.RowDeleted += (sender, e) => Table.ReloadData();
source.RowChanged += (sender, e) => Table.ReloadData();
source.RowsReordered += (sender, e) => Table.ReloadData();
}
public int[] SelectedRows {
get {
int[] sel = new int [Table.SelectedRowCount];
if (sel.Length > 0) {
int i = 0;
foreach (int r in Table.SelectedRows)
sel [i++] = r;
}
return sel;
}
}
public int FocusedRow {
get {
if (Table.SelectedRowCount > 0)
return (int)Table.SelectedRows.FirstIndex;
return -1;
}
set {
SelectRow (value);
}
}
public void SelectRow (int pos)
{
Table.SelectRow (pos, Table.AllowsMultipleSelection);
}
public void UnselectRow (int pos)
{
Table.DeselectRow (pos);
}
public override object GetValue (object pos, int nField)
{
return source.GetValue ((int)pos, nField);
}
public override void SetValue (object pos, int nField, object value)
{
source.SetValue ((int)pos, nField, value);
}
public int CurrentEventRow { get; internal set; }
public override void SetCurrentEventRow (object pos)
{
CurrentEventRow = (int)pos;
}
// TODO
// public bool BorderVisible { get; set; }
public int GetRowAtPosition (Point p)
{
return (int) Table.GetRow (new CGPoint ((nfloat)p.X, (nfloat)p.Y));
}
}
class TableRow: NSObject, ITablePosition
{
public int Row;
public object Position {
get { return Row; }
}
}
class ListSource: NSTableViewDataSource
{
IListDataSource source;
public ListSource (IListDataSource source)
{
this.source = source;
}
public override bool AcceptDrop (NSTableView tableView, NSDraggingInfo info, nint row, NSTableViewDropOperation dropOperation)
{
return false;
}
public override string[] FilesDropped (NSTableView tableView, NSUrl dropDestination, NSIndexSet indexSet)
{
return new string [0];
}
public override NSObject GetObjectValue (NSTableView tableView, NSTableColumn tableColumn, nint row)
{
return NSNumber.FromInt32 ((int)row);
}
public override nint GetRowCount (NSTableView tableView)
{
return source.RowCount;
}
public override void SetObjectValue (NSTableView tableView, NSObject theObject, NSTableColumn tableColumn, nint row)
{
}
public override void SortDescriptorsChanged (NSTableView tableView, NSSortDescriptor[] oldDescriptors)
{
}
public override NSDragOperation ValidateDrop (NSTableView tableView, NSDraggingInfo info, nint row, NSTableViewDropOperation dropOperation)
{
return NSDragOperation.None;
}
public override bool WriteRows (NSTableView tableView, NSIndexSet rowIndexes, NSPasteboard pboard)
{
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
using Microsoft.Diagnostics.Tracing.Session;
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace BasicEventSourceTests
{
/// <summary>
/// A listener can represent an out of process ETW listener (real time or not) or an EventListener
/// </summary>
public abstract class Listener : IDisposable
{
public Action<Event> OnEvent; // Called when you get events.
public abstract void Dispose();
/// <summary>
/// Send a command to an eventSource. Be careful this is async. You may wish to do a WaitForEnable
/// </summary>
public abstract void EventSourceCommand(string eventSourceName, EventCommand command, FilteringOptions options = null);
public void EventSourceSynchronousEnable(EventSource eventSource, FilteringOptions options = null)
{
EventSourceCommand(eventSource.Name, EventCommand.Enable, options);
WaitForEnable(eventSource);
}
public void WaitForEnable(EventSource logger)
{
if (!SpinWait.SpinUntil(() => logger.IsEnabled(), TimeSpan.FromSeconds(10)))
{
throw new InvalidOperationException("EventSource not enabled after 5 seconds");
}
}
internal void EnableTimer(EventSource eventSource, double pollingTime)
{
FilteringOptions options = new FilteringOptions();
options.Args = new Dictionary<string, string>();
options.Args.Add("EventCounterIntervalSec", pollingTime.ToString());
EventSourceCommand(eventSource.Name, EventCommand.Enable, options);
}
}
/// <summary>
/// Used to control what options the harness sends to the EventSource when turning it on. If not given
/// it turns on all keywords, Verbose level, and no args.
/// </summary>
public class FilteringOptions
{
public FilteringOptions() { Keywords = EventKeywords.All; Level = EventLevel.Verbose; }
public EventKeywords Keywords;
public EventLevel Level;
public IDictionary<string, string> Args;
public override string ToString()
{
return string.Format("<Options Keywords='{0}' Level'{1}' ArgsCount='{2}'",
((ulong)Keywords).ToString("x"), Level, Args.Count);
}
}
/// <summary>
/// Because events can be written to a EventListener as well as to ETW, we abstract what the result
/// of an event coming out of the pipe. Basically there are properties that fetch the name
/// and the payload values, and we subclass this for the ETW case and for the EventListener case.
/// </summary>
public abstract class Event
{
public virtual bool IsEtw { get { return false; } }
public virtual bool IsEventListener { get { return false; } }
public abstract string ProviderName { get; }
public abstract string EventName { get; }
public abstract object PayloadValue(int propertyIndex, string propertyName);
public abstract int PayloadCount { get; }
public virtual string PayloadString(int propertyIndex, string propertyName)
{
var obj = PayloadValue(propertyIndex, propertyName);
var asDict = obj as IDictionary<string, object>;
if (asDict != null)
{
StringBuilder sb = new StringBuilder();
sb.Append("{");
bool first = true;
foreach (var key in asDict.Keys)
{
if (!first)
sb.Append(",");
first = false;
var value = asDict[key];
sb.Append(key).Append(":").Append(value != null ? value.ToString() : "NULL");
}
sb.Append("}");
return sb.ToString();
}
if (obj != null)
return obj.ToString();
return "";
}
public abstract IList<string> PayloadNames { get; }
#if DEBUG
/// <summary>
/// This is a convenience function for the debugger. It is not used typically
/// </summary>
public List<object> PayloadValues
{
get
{
var ret = new List<object>();
for (int i = 0; i < PayloadCount; i++)
ret.Add(PayloadValue(i, null));
return ret;
}
}
#endif
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append(ProviderName).Append('/').Append(EventName).Append('(');
for (int i = 0; i < PayloadCount; i++)
{
if (i != 0)
sb.Append(',');
sb.Append(PayloadString(i, null));
}
sb.Append(')');
return sb.ToString();
}
}
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
/**************************************************************************/
/* Concrete implementation of the Listener abstraction */
/// <summary>
/// Implementation of the Listener abstraction for ETW.
/// </summary>
public class EtwListener : Listener
{
internal static void EnsureStopped()
{
using (var session = new TraceEventSession("EventSourceTestSession", "EventSourceTestData.etl"))
session.Stop();
}
public EtwListener(string dataFileName = "EventSourceTestData.etl", string sessionName = "EventSourceTestSession")
{
_dataFileName = dataFileName;
// Today you have to be Admin to turn on ETW events (anyone can write ETW events).
if (TraceEventSession.IsElevated() != true)
{
throw new ApplicationException("Need to be elevated to run. ");
}
if (dataFileName == null)
{
Debug.WriteLine("Creating a real time session " + sessionName);
Task.Factory.StartNew(delegate ()
{
var session = new TraceEventSession(sessionName, dataFileName);
session.Source.AllEvents += OnEventHelper;
Debug.WriteLine("Listening for real time events");
_session = session; // Indicate that we are alive.
_session.Source.Process();
Debug.WriteLine("Real time listening stopping.");
});
SpinWait.SpinUntil(() => _session != null); // Wait for real time thread to wake up.
}
else
{
// Normalize to a full path name.
dataFileName = Path.GetFullPath(dataFileName);
Debug.WriteLine("Creating ETW data file " + Path.GetFullPath(dataFileName));
_session = new TraceEventSession(sessionName, dataFileName);
}
}
public override void EventSourceCommand(string eventSourceName, EventCommand command, FilteringOptions options = null)
{
if (command == EventCommand.Enable)
{
if (options == null)
options = new FilteringOptions();
_session.EnableProvider(eventSourceName, (TraceEventLevel)options.Level, (ulong)options.Keywords,
new TraceEventProviderOptions() { Arguments = options.Args });
}
else if (command == EventCommand.Disable)
{
_session.DisableProvider(TraceEventProviders.GetEventSourceGuidFromName(eventSourceName));
}
else
throw new NotImplementedException();
Thread.Sleep(200); // Calls are async, give them time to work.
}
public override void Dispose()
{
_session.Flush();
Thread.Sleep(1010); // Let it drain.
_session.Dispose(); // This also will kill the real time thread
if (_dataFileName != null)
{
using (var traceEventSource = new ETWTraceEventSource(_dataFileName))
{
Debug.WriteLine("Processing data file " + Path.GetFullPath(_dataFileName));
// Parse all the events as best we can, and also send unhandled events there as well.
traceEventSource.Registered.All += OnEventHelper;
traceEventSource.Dynamic.All += OnEventHelper;
traceEventSource.UnhandledEvents += OnEventHelper;
// Process all the events in the file.
traceEventSource.Process();
Debug.WriteLine("Done processing data file " + Path.GetFullPath(_dataFileName));
}
}
}
#region private
private void OnEventHelper(TraceEvent data)
{
// Ignore manifest events.
if ((int)data.ID == 0xFFFE)
return;
this.OnEvent(new EtwEvent(data));
}
/// <summary>
/// EtwEvent implements the 'Event' abstraction for ETW events (it has a TraceEvent in it)
/// </summary>
internal class EtwEvent : Event
{
public override bool IsEtw { get { return true; } }
public override string ProviderName { get { return _data.ProviderName; } }
public override string EventName { get { return _data.EventName; } }
public override object PayloadValue(int propertyIndex, string propertyName)
{
if (propertyName != null)
Assert.Equal(propertyName, _data.PayloadNames[propertyIndex]);
return _data.PayloadValue(propertyIndex);
}
public override string PayloadString(int propertyIndex, string propertyName)
{
Assert.Equal(propertyName, _data.PayloadNames[propertyIndex]);
return _data.PayloadString(propertyIndex);
}
public override int PayloadCount { get { return _data.PayloadNames.Length; } }
public override IList<string> PayloadNames { get { return _data.PayloadNames; } }
#region private
internal EtwEvent(TraceEvent data) { _data = data.Clone(); }
private TraceEvent _data;
#endregion
}
private string _dataFileName;
private volatile TraceEventSession _session;
#endregion
}
#endif //USE_ETW
public class EventListenerListener : Listener
{
private EventListener _listener;
private Action<EventSource> _onEventSourceCreated;
#if FEATURE_ETLEVENTS
public event EventHandler<EventSourceCreatedEventArgs> EventSourceCreated
{
add
{
if (this._listener != null)
this._listener.EventSourceCreated += value;
}
remove
{
if (this._listener != null)
this._listener.EventSourceCreated -= value;
}
}
public event EventHandler<EventWrittenEventArgs> EventWritten
{
add
{
if (this._listener != null)
this._listener.EventWritten += value;
}
remove
{
if (this._listener != null)
this._listener.EventWritten -= value;
}
}
#endif
public EventListenerListener(bool useEventsToListen = false)
{
#if FEATURE_ETLEVENTS
if (useEventsToListen)
{
_listener = new HelperEventListener(null);
_listener.EventSourceCreated += (sender, eventSourceCreatedEventArgs)
=> _onEventSourceCreated?.Invoke(eventSourceCreatedEventArgs.EventSource);
_listener.EventWritten += mListenerEventWritten;
}
else
#endif
{
_listener = new HelperEventListener(this);
}
}
public override void Dispose()
{
EventTestHarness.LogWriteLine("Disposing Listener");
_listener.Dispose();
}
private void DoCommand(EventSource source, EventCommand command, FilteringOptions options)
{
if (command == EventCommand.Enable)
_listener.EnableEvents(source, options.Level, options.Keywords, options.Args);
else if (command == EventCommand.Disable)
_listener.DisableEvents(source);
else
throw new NotImplementedException();
}
public override void EventSourceCommand(string eventSourceName, EventCommand command, FilteringOptions options = null)
{
EventTestHarness.LogWriteLine("Sending command {0} to EventSource {1} Options {2}", eventSourceName, command, options);
if (options == null)
options = new FilteringOptions();
foreach (EventSource source in EventSource.GetSources())
{
if (source.Name == eventSourceName)
{
DoCommand(source, command, options);
return;
}
}
_onEventSourceCreated += delegate (EventSource sourceBeingCreated)
{
if (eventSourceName != null && eventSourceName == sourceBeingCreated.Name)
{
DoCommand(sourceBeingCreated, command, options);
eventSourceName = null; // so we only do it once.
}
};
}
private void mListenerEventWritten(object sender, EventWrittenEventArgs eventData)
{
OnEvent(new EventListenerEvent(eventData));
}
private class HelperEventListener : EventListener
{
private readonly EventListenerListener _forwardTo;
public HelperEventListener(EventListenerListener forwardTo)
{
_forwardTo = forwardTo;
}
protected override void OnEventSourceCreated(EventSource eventSource)
{
base.OnEventSourceCreated(eventSource);
_forwardTo?._onEventSourceCreated?.Invoke(eventSource);
}
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
#if FEATURE_ETLEVENTS
// OnEventWritten is abstract in netfx <= 461
base.OnEventWritten(eventData);
#endif
_forwardTo?.OnEvent?.Invoke(new EventListenerEvent(eventData));
}
}
/// <summary>
/// EtwEvent implements the 'Event' abstraction for TraceListene events (it has a EventWrittenEventArgs in it)
/// </summary>
internal class EventListenerEvent : Event
{
private readonly EventWrittenEventArgs _data;
public override bool IsEventListener { get { return true; } }
public override string ProviderName { get { return _data.EventSource.Name; } }
public override string EventName { get { return _data.EventName; } }
public override IList<string> PayloadNames { get { return _data.PayloadNames; } }
public override int PayloadCount
{
get { return _data.Payload?.Count ?? 0; }
}
internal EventListenerEvent(EventWrittenEventArgs data)
{
_data = data;
}
public override object PayloadValue(int propertyIndex, string propertyName)
{
if (propertyName != null)
Assert.Equal(propertyName, _data.PayloadNames[propertyIndex]);
return _data.Payload[propertyIndex];
}
}
}
}
| |
//-----------------------------------------------------------------------
// This file is part of Microsoft Robotics Developer Studio Code Samples.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// $File: Explorer.cs $ $Revision: 1 $
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using W3C.Soap;
using Microsoft.Ccr.Core;
using Microsoft.Dss.Core;
using Microsoft.Dss.Core.Attributes;
using Microsoft.Dss.ServiceModel.Dssp;
using Microsoft.Dss.Services.Serializer;
using Microsoft.Dss.ServiceModel.DsspServiceBase;
using bumper = Microsoft.Robotics.Services.ContactSensor.Proxy;
using drive = Microsoft.Robotics.Services.Drive.Proxy;
using sicklrf = Microsoft.Robotics.Services.Sensors.SickLRF.Proxy;
using dssp = Microsoft.Dss.ServiceModel.Dssp;
using System.ComponentModel;
namespace Microsoft.Robotics.Services.Explorer
{
[DisplayName("Explorer")]
[Description("Provides access simple exploration behavior for a robot using a differential drive, bumpers, and a laser range finder.")]
[Contract(Contract.Identifier)]
class Explorer : DsspServiceBase
{
#region constants
// The explorer uses there constants to evaluate open space
// and adjust speed and rotation of the differential drive.
// Change those values to match your robot.
// You could expose them on the explorers state type and make the
// service configurable.
/// <summary>
/// Amount to backup when hitting an obstacle.
/// </summary>
const int BackupDistance = -300; // mm
/// <summary>
/// If an obstacle comes within thisdistance the robot stops moving.
/// </summary>
const int ObstacleDistance = 500; // mm
/// <summary>
/// If the robot is mapping and has this much open space ahead it stops mapping
/// and enters the space.
/// </summary>
const int SafeDistance = 2000; // mm
/// <summary>
/// The width of the corridor that must be safe in order to got from mapping to moving.
/// </summary>
const int CorridorWidthMapping = 350; // mm
/// <summary>
/// The minimum free distance that is required to drive with max. velocity.
/// </summary>
const int FreeDistance = 3000; // mm
/// <summary>
/// If the free space is at least this distance the robot operates at 1/2 max. velocity otherwise
/// the robot slows down to 1/4 of max. vel.
/// </summary>
const int AwareOfObstacleDistance = 1500; // mm
/// <summary>
/// The max. velocity with which to move.
/// </summary>
const int MaximumForwardVelocity = 1000; // mm/sec
/// <summary>
/// The with of the corridor in which obstacles effect velocity.
/// </summary>
const int CorridorWidthMoving = 500; // mm
/// <summary>
/// If no laser data is received within this time the robot stops.
/// </summary>
const int WatchdogTimeout = 500; // msec
/// <summary>
/// Interval between timer notifications.
/// </summary>
const int WatchdogInterval = 100; // msec
#endregion
#region main port and state
State _state = new State();
[ServicePort("/explorer")]
ExplorerOperations _mainPort = new ExplorerOperations();
#endregion
#region partners
#region bumper partner
[Partner("Bumper", Contract = bumper.Contract.Identifier, CreationPolicy = PartnerCreationPolicy.UseExisting)]
bumper.ContactSensorArrayOperations _bumperPort = new bumper.ContactSensorArrayOperations();
bumper.ContactSensorArrayOperations _bumperNotify = new bumper.ContactSensorArrayOperations();
#endregion
#region drive partner
[Partner("Drive", Contract = drive.Contract.Identifier, CreationPolicy = PartnerCreationPolicy.UseExisting)]
drive.DriveOperations _drivePort = new drive.DriveOperations();
drive.DriveOperations _driveNotify = new drive.DriveOperations();
#endregion
#region laser range finder partner
[Partner("Laser", Contract = sicklrf.Contract.Identifier, CreationPolicy = PartnerCreationPolicy.UseExistingOrCreate)]
sicklrf.SickLRFOperations _laserPort = new sicklrf.SickLRFOperations();
sicklrf.SickLRFOperations _laserNotify = new sicklrf.SickLRFOperations();
#endregion
#endregion
public Explorer(DsspServiceCreationPort creationPort) :
base(creationPort)
{
}
protected override void Start()
{
#region request handler setup
Activate(
Arbiter.Interleave(
new TeardownReceiverGroup(
Arbiter.Receive<DsspDefaultDrop>(false, _mainPort, DropHandler)
),
new ExclusiveReceiverGroup(
Arbiter.Receive<LaserRangeFinderResetUpdate>(true, _mainPort, LaserRangeFinderResetUpdateHandler),
Arbiter.Receive<LaserRangeFinderUpdate>(true, _mainPort, LaserRangeFinderUpdateHandler),
Arbiter.Receive<BumpersUpdate>(true, _mainPort, BumpersUpdateHandler),
Arbiter.Receive<BumperUpdate>(true, _mainPort, BumperUpdateHandler),
Arbiter.Receive<DriveUpdate>(true, _mainPort, DriveUpdateHandler),
Arbiter.Receive<WatchDogUpdate>(true, _mainPort, WatchDogUpdateHandler)
),
new ConcurrentReceiverGroup(
Arbiter.Receive<Get>(true, _mainPort, GetHandler),
Arbiter.Receive<dssp.DsspDefaultLookup>(true, _mainPort, DefaultLookupHandler)
)
)
);
#endregion
#region notification handler setup
Activate(
Arbiter.Interleave(
new TeardownReceiverGroup(),
new ExclusiveReceiverGroup(),
new ConcurrentReceiverGroup(
Arbiter.Receive<sicklrf.Reset>(true, _laserNotify, LaserResetNotification),
Arbiter.Receive<drive.Update>(true, _driveNotify, DriveUpdateNotification),
Arbiter.Receive<bumper.Replace>(true, _bumperNotify, BumperReplaceNotification),
Arbiter.Receive<bumper.Update>(true, _bumperNotify, BumperUpdateNotification)
)
)
);
// We cannot replicate the activation of laser notifications because the
// handler uses Test() to skip old laser notifications.
Activate(
Arbiter.ReceiveWithIterator<sicklrf.Replace>(false, _laserNotify, LaserReplaceNotification)
);
#endregion
// Start watchdog timer
_mainPort.Post(new WatchDogUpdate(new WatchDogUpdateRequest(DateTime.Now)));
// Create Subscriptions
_bumperPort.Subscribe(_bumperNotify);
_drivePort.Subscribe(_driveNotify);
_laserPort.Subscribe(_laserNotify);
DirectoryInsert();
}
#region DSS operation handlers (Get, Drop)
public void DropHandler(DsspDefaultDrop drop)
{
// Currently it is not possible to activate a handler that returns
// IEnumerator<ITask> in a teardown group. Thus we have to spawn the iterator ourselves
// to acheive the same effect.
// This issue will be addressed in upcomming releases.
SpawnIterator(drop, DoDrop);
}
IEnumerator<ITask> DoDrop(DsspDefaultDrop drop)
{
if (_state.IsActive)
{
LogInfo("Explorer service is being dropped while moving, Requesting Stop.");
yield return Arbiter.Choice(
StopMoving(),
delegate(DefaultUpdateResponseType response) { },
delegate(Fault fault) { }
);
yield return Arbiter.Choice(
DisableMotor(),
delegate(DefaultUpdateResponseType response) { },
delegate(Fault fault) { }
);
}
LogInfo("Dropping Explorer.");
base.DefaultDropHandler(drop);
}
void GetHandler(Get get)
{
get.ResponsePort.Post(_state);
}
#endregion
#region Watch dog timer handlers
void WatchDogUpdateHandler(WatchDogUpdate update)
{
TimeSpan sinceLaser = update.Body.TimeStamp - _state.MostRecentLaser;
if (sinceLaser.TotalMilliseconds >= WatchdogTimeout && !_state.IsUnknown)
{
LogInfo("Stop requested, last laser data seen at " + _state.MostRecentLaser);
StopMoving();
_state.LogicalState = LogicalState.Unknown;
}
Activate(
Arbiter.Receive(
false,
TimeoutPort(WatchdogInterval),
delegate(DateTime ts)
{
_mainPort.Post(new WatchDogUpdate(new WatchDogUpdateRequest(ts)));
}
)
);
update.ResponsePort.Post(DefaultUpdateResponseType.Instance);
}
#endregion
#region Bumper handlers
/// <summary>
/// Handles Replace notifications from the Bumper partner
/// </summary>
/// <remarks>Posts a <typeparamref name="BumpersUpdate"/> to itself.</remarks>
/// <param name="replace">notification</param>
void BumperReplaceNotification(bumper.Replace replace)
{
_mainPort.Post(new BumpersUpdate(replace.Body));
}
/// <summary>
/// Handles Update notification from the Bumper partner
/// </summary>
/// <remarks>Posts a <typeparamref name="BumperUpdate"/> to itself.</remarks>
/// <param name="update">notification</param>
void BumperUpdateNotification(bumper.Update update)
{
_mainPort.Post(new BumperUpdate(update.Body));
}
/// <summary>
/// Handles the <typeparamref name="BumpersUpdate"/> request.
/// </summary>
/// <param name="update">request</param>
void BumpersUpdateHandler(BumpersUpdate update)
{
if (_state.IsMoving && BumpersPressed(update.Body))
{
Bumped();
}
update.ResponsePort.Post(DefaultUpdateResponseType.Instance);
}
/// <summary>
/// Handles the <typeparamref name="BumperUpdate"/> request.
/// </summary>
/// <param name="update">request</param>
void BumperUpdateHandler(BumperUpdate update)
{
if (_state.IsMoving && update.Body.Pressed)
{
Bumped();
}
update.ResponsePort.Post(DefaultUpdateResponseType.Instance);
}
/// <summary>
/// Stops the robot. If the robot was going forward it backs up.
/// </summary>
private void Bumped()
{
if (_state.Velocity <= 0.0)
{
LogInfo("Rear and/or Front bumper pressed, Stopping");
// either a rear bumper or both front and rear
// bumpers are pressed. STOP!
StopTurning();
StopMoving();
_state.LogicalState = LogicalState.Unknown;
_state.Countdown = 3;
}
else
{
LogInfo("Front bumper pressed, Backing up by " + (-BackupDistance) + "mm");
// only a front bumper is pressed.
// move back <BackupDistance> mm;
StopTurning();
Translate(BackupDistance);
_state.LogicalState = LogicalState.Unknown;
_state.Countdown = 5;
}
}
/// <summary>
/// Checks whether at least one of the contact sensors is pressed.
/// </summary>
/// <param name="bumpers"><code>true</code> if at least one bumper in <paramref name="bumpers"/> is pressed, otherwise <code>false</code></param>
/// <returns></returns>
private bool BumpersPressed(bumper.ContactSensorArrayState bumpers)
{
if (bumpers.Sensors == null)
{
return false;
}
foreach (bumper.ContactSensor s in bumpers.Sensors)
{
if (s.Pressed)
{
return true;
}
}
return false;
}
#endregion
#region Drive handlers
/// <summary>
/// Handles Update notification from the Drive partner
/// </summary>
/// <remarks>Posts a <typeparamref name="DriveUpdate"/> request to itself.</remarks>
/// <param name="update">notification</param>
void DriveUpdateNotification(drive.Update update)
{
_mainPort.Post(new DriveUpdate(update.Body));
}
/// <summary>
/// Handles DriveUpdate request
/// </summary>
/// <param name="update">request</param>
void DriveUpdateHandler(DriveUpdate update)
{
_state.DriveState = update.Body;
_state.Velocity = (VelocityFromWheel(update.Body.LeftWheel) + VelocityFromWheel(update.Body.RightWheel)) / 2;
update.ResponsePort.Post(DefaultUpdateResponseType.Instance);
}
/// <summary>
/// Computes the wheel velocity in mm/s.
/// </summary>
/// <param name="wheel">wheel</param>
/// <returns>velocity</returns>
private int VelocityFromWheel(Microsoft.Robotics.Services.Motor.Proxy.WheeledMotorState wheel)
{
if (wheel == null)
{
return 0;
}
return (int)(1000 * wheel.WheelSpeed); // meters to millimeters
}
#endregion
#region Laser handlers
/// <summary>
/// Handles Replace notifications from the Laser partner
/// </summary>
/// <remarks>Posts a <typeparamref name="LaserRangeFinderUpdate"/> to itself.</remarks>
/// <param name="replace">notification</param>
/// <returns>task enumerator</returns>
IEnumerator<ITask> LaserReplaceNotification(sicklrf.Replace replace)
{
// When this handler is called a couple of notifications may
// have piled up. We only want the most recent one.
sicklrf.State laserData = GetMostRecentLaserNotification(replace.Body);
LaserRangeFinderUpdate request = new LaserRangeFinderUpdate(laserData);
_mainPort.Post(request);
yield return Arbiter.Choice(
request.ResponsePort,
delegate(DefaultUpdateResponseType response) { },
delegate(Fault fault) { }
);
// Skip messages that have been queued up in the meantime.
// The notification that are lingering are out of data by now.
GetMostRecentLaserNotification(laserData);
// Reactivate the handler.
Activate(
Arbiter.ReceiveWithIterator<sicklrf.Replace>(false, _laserNotify, LaserReplaceNotification)
);
}
/// <summary>
/// Handles the <typeparamref name="LaserRangeFinderUpdate"/> request.
/// </summary>
/// <param name="update">request</param>
void LaserRangeFinderUpdateHandler(LaserRangeFinderUpdate update)
{
sicklrf.State laserData = update.Body;
_state.MostRecentLaser = laserData.TimeStamp;
int distance = FindNearestObstacleInCorridor(laserData, CorridorWidthMapping, 45);
// AvoidCollision and EnterOpenSpace have precedence over
// all other state transitions and are thus handled first.
AvoidCollision(distance);
EnterOpenSpace(distance);
UpdateLogicalState(laserData, distance);
update.ResponsePort.Post(DefaultUpdateResponseType.Instance);
}
/// <summary>
/// If the robot is mapping and there is sufficient open space directly ahead, enter this space.
/// </summary>
/// <param name="distance"></param>
private void EnterOpenSpace(int distance)
{
if (distance > SafeDistance && _state.IsMapping)
{
// We are mapping but can see plenty of free space ahead.
// The robot should go into this space.
StopTurning();
_state.LogicalState = LogicalState.FreeForwards;
_state.Countdown = 4;
}
}
/// <summary>
/// If the robot is moving and an obstacle is too close, stop and map the environment for a way around it.
/// </summary>
/// <param name="distance"></param>
private void AvoidCollision(int distance)
{
if (distance < ObstacleDistance && _state.IsMoving)
{
//
// We are moving and there is something less than <LaserObstacleDistance>
// millimeters from the center of the robot. STOP.
//
StopMoving();
_state.LogicalState = LogicalState.Unknown;
_state.Countdown = 0;
}
}
/// <summary>
/// Transitions to the most appropriate state.
/// </summary>
/// <param name="laserData">most recently sensed laser range data</param>
/// <param name="distance">closest obstacle in corridor ahead</param>
private void UpdateLogicalState(sicklrf.State laserData, int distance)
{
if (_state.Countdown > 0)
{
_state.Countdown--;
}
else if (_state.IsUnknown)
{
StartMapping(laserData, distance);
}
else if (_state.IsMoving)
{
Move(laserData, distance);
}
else if (_state.IsMapping)
{
Map(laserData, distance);
}
}
/// <summary>
/// Implements the "Moving" meta state.
/// </summary>
/// <param name="laserData">most recently sensed laser range data</param>
/// <param name="distance">closest obstacle in corridor ahead</param>
private void Move(sicklrf.State laserData, int distance)
{
switch (_state.LogicalState)
{
case LogicalState.AdjustHeading:
AdjustHeading();
break;
case LogicalState.FreeForwards:
AdjustVelocity(laserData, distance);
break;
default:
LogInfo("Explorer.Move() called in illegal state");
break;
}
}
/// <summary>
/// Implements the "Mapping" meta state.
/// </summary>
/// <param name="laserData">most recently sensed laser range data</param>
/// <param name="distance">closest obstacle in corridor ahead</param>
private void Map(sicklrf.State laserData, int distance)
{
switch (_state.LogicalState)
{
case LogicalState.RandomTurn:
RandomTurn();
break;
case LogicalState.MapSurroundings:
_state.Mapped = true;
LogInfo("Turning 180 deg to map");
Turn(180);
_state.LogicalState = LogicalState.MapSouth;
_state.Countdown = 15;
break;
case LogicalState.MapSouth:
LogInfo("Mapping the View South");
_state.South = laserData;
Turn(180);
_state.LogicalState = LogicalState.MapNorth;
_state.Countdown = 15;
break;
case LogicalState.MapNorth:
LogInfo("Mapping the View North");
_state.NewHeading = FindBestComposite(_state.South, laserData);
LogInfo("Map suggest turn: " + _state.NewHeading);
_state.South = null;
_state.LogicalState = LogicalState.AdjustHeading;
break;
default:
LogInfo("Explorer.Map() called in illegal state");
break;
}
}
/// <summary>
/// Adjusts the velocity based on environment.
/// </summary>
/// <param name="laserData">most recently sensed laser range data</param>
/// <param name="distance">closest obstacle in corridor ahead</param>
private void AdjustVelocity(sicklrf.State laserData, int distance)
{
_state.Mapped = false;
int test = FindBestFrom(laserData, 0, _state.Velocity / 10, CorridorWidthMoving);
if (distance > FreeDistance)
{
MoveForward(MaximumForwardVelocity);
if (Math.Abs(test) < 10)
{
Turn(test / 2);
}
}
else if (distance > AwareOfObstacleDistance)
{
MoveForward(MaximumForwardVelocity / 2);
if (Math.Abs(test) < 45)
{
Turn(test / 2);
}
}
else
{
MoveForward(MaximumForwardVelocity / 4);
Turn(test);
_state.Countdown = Math.Abs(test / 10);
}
}
/// <summary>
/// Implements the "AdjustHeading" state.
/// </summary>
private void AdjustHeading()
{
LogInfo("Step Turning to: " + _state.NewHeading);
Turn(_state.NewHeading);
_state.LogicalState = LogicalState.FreeForwards;
_state.Countdown = Math.Abs(_state.NewHeading / 10);
}
/// <summary>
/// Implements the "RandomTurn" state.
/// </summary>
private void RandomTurn()
{
_state.NewHeading = new Random().Next(-115, 115);
LogInfo("Start Turning (random) to: " + _state.NewHeading);
Turn(_state.NewHeading);
_state.LogicalState = LogicalState.Unknown;
_state.Countdown = 2 + Math.Abs(_state.NewHeading / 10);
}
/// <summary>
/// Transitions to "Mapping" meta state or "AdjustHeading" state depending on
/// environment.
/// </summary>
/// <param name="laserData">most recently sensed laser range data</param>
/// <param name="distance">closest obstacle in corridor ahead</param>
private void StartMapping(sicklrf.State laserData, int distance)
{
StopMoving();
if (distance < ObstacleDistance)
{
if (_state.Mapped)
{
// We have been mapping before but do not seem to
// have found anything.
_state.LogicalState = LogicalState.RandomTurn;
}
else
{
_state.LogicalState = LogicalState.MapSurroundings;
}
}
else
{
int step = Math.Min(ObstacleDistance, distance - CorridorWidthMapping);
// find the best angle from step mm in front of
// our current position
_state.NewHeading = FindBestFrom(laserData, 0, step, CorridorWidthMapping);
LogInfo("Step: " + step + " Turn: " + _state.NewHeading);
Translate(step);
_state.LogicalState = LogicalState.AdjustHeading;
_state.Countdown = step / 50 + Math.Abs(_state.NewHeading / 10);
}
}
/// <summary>
/// Gets the most recent laser notification. Older notifications are dropped.
/// </summary>
/// <param name="laserData">last known laser data</param>
/// <returns>most recent laser data</returns>
private sicklrf.State GetMostRecentLaserNotification(sicklrf.State laserData)
{
sicklrf.Replace testReplace;
// _laserNotify is a PortSet<>, P3 represents IPort<sicklrf.Replace> that
// the portset contains
int count = _laserNotify.P3.ItemCount - 1;
for (int i = 0; i < count; i++)
{
testReplace = _laserNotify.Test<sicklrf.Replace>();
if (testReplace.Body.TimeStamp > laserData.TimeStamp)
{
laserData = testReplace.Body;
}
}
if (count > 0)
{
LogInfo(string.Format("Dropped {0} laser readings (laser start)", count));
}
return laserData;
}
/// <summary>
/// Handles the reset notification of the Laser partner.
/// </summary>
/// <remarks>Posts a <typeparamref name="LaserRangeFinderResetUpdate"/> to itself.</remarks>
/// <param name="reset">notification</param>
void LaserResetNotification(sicklrf.Reset reset)
{
_mainPort.Post(new LaserRangeFinderResetUpdate(reset.Body));
}
/// <summary>
/// Handle the <typeparamref name="LaserRangeFinderResetUpdate"/> request.
/// </summary>
/// <remarks>Stops the robot.</remarks>
/// <param name="update">request</param>
void LaserRangeFinderResetUpdateHandler(LaserRangeFinderResetUpdate update)
{
if (_state.LogicalState != LogicalState.Unknown)
{
LogInfo("Stop requested: laser reported reset");
StopMoving();
_state.LogicalState = LogicalState.Unknown;
_state.Countdown = 0;
}
update.ResponsePort.Post(DefaultUpdateResponseType.Instance);
}
/// <summary>
/// Respresent a laser range finder reading
/// </summary>
class RangeData
{
/// <summary>
/// Creates a new instance.
/// </summary>
/// <param name="distance">measured distance</param>
/// <param name="heading">heading in degrees</param>
public RangeData(int distance, double heading)
{
_distance = distance;
_heading = heading;
}
int _distance;
double _heading;
/// <summary>
/// Gets the distance in milimeters.
/// </summary>
public int Distance
{
get { return _distance; }
}
/// <summary>
/// Gets the heading in degrees.
/// </summary>
public double Heading
{
get { return _heading; }
}
/// <summary>
/// Comparer to sort instances by distance.
/// </summary>
/// <param name="first">first reading</param>
/// <param name="second">second reading</param>
/// <returns>a value les than 0 if <paramref name="first"/> is closer than <paramref name="second"/>, 0 if both have the same distance, a value greater 0 otherwise</returns>
static public int ByDistance(RangeData first, RangeData second)
{
return first._distance.CompareTo(second._distance);
}
}
/// <summary>
/// Finds the best free corridor (maximum free space ahead) in a 360 degree scan.
/// </summary>
/// <param name="south">the backward half of the scan</param>
/// <param name="north">the forward half of the scan</param>
/// <returns>beast heading in degrees</returns>
private int FindBestComposite(sicklrf.State south, sicklrf.State north)
{
sicklrf.State composite = new sicklrf.State();
composite.DistanceMeasurements = new int[720];
for (int i = 0; i < 720; i++)
{
if (i < 180)
{
composite.DistanceMeasurements[i] = south.DistanceMeasurements[i + 180];
}
else if (i < 540)
{
composite.DistanceMeasurements[i] = north.DistanceMeasurements[i - 180];
}
else
{
composite.DistanceMeasurements[i] = south.DistanceMeasurements[i - 540];
}
}
composite.AngularResolution = 0.5;
composite.AngularRange = 360;
composite.Units = north.Units;
return FindBestFrom(composite, 0, 0, CorridorWidthMoving);
}
/// <summary>
/// Finds the best heading in a 180 degree laser scan
/// </summary>
/// <param name="laserData">laser scan</param>
/// <param name="dx">horizontal offset</param>
/// <param name="dy">vertical offset</param>
/// <param name="width">width of corridor that must be free</param>
/// <returns>best heading in degrees</returns>
private int FindBestFrom(sicklrf.State laserData, int dx, int dy, int width)
{
int count = laserData.DistanceMeasurements.Length;
double span = Math.PI * laserData.AngularRange / 180.0;
List<RangeData> ranges = new List<RangeData>();
for (int i = 0; i < count; i++)
{
int range = laserData.DistanceMeasurements[i];
double angle = span * i / count - span / 2.0;
double x = range * Math.Sin(angle) - dx;
double y = range * Math.Cos(angle) - dy;
angle = Math.Atan2(-x, y);
range = (int)Math.Sqrt(x * x + y * y);
ranges.Add(new RangeData(range, angle));
}
ranges.Sort(RangeData.ByDistance);
for (int i = 0; i < ranges.Count; i++)
{
RangeData curr = ranges[i];
double delta = Math.Atan2(width, curr.Distance);
double low = curr.Heading - delta;
double high = curr.Heading + delta;
for (int j = i + 1; j < ranges.Count; j++)
{
if (ranges[j].Heading > low &&
ranges[j].Heading < high)
{
ranges.RemoveAt(j);
j--;
}
}
}
ranges.Reverse();
int bestDistance = ranges[0].Distance;
double bestHeading = ranges[0].Heading;
Random rand = new Random();
for (int i = 0; i < ranges.Count; i++)
{
if (ranges[i].Distance < bestDistance)
{
break;
}
if (rand.Next(i + 1) == 0)
{
bestHeading = ranges[i].Heading;
}
}
return -(int)Math.Round(180 * bestHeading / Math.PI);
}
/// <summary>
/// Finds closest obstacle in a corridor.
/// </summary>
/// <param name="laserData">laser scan</param>
/// <param name="width">corridor width</param>
/// <param name="fov">field of view in degrees</param>
/// <returns>distance to the closest obstacle</returns>
private int FindNearestObstacleInCorridor(sicklrf.State laserData, int width, int fov)
{
int index;
int best = 8192;
int count = laserData.DistanceMeasurements.Length;
double rangeLow = -laserData.AngularRange / 2.0;
double rangeHigh = laserData.AngularRange / 2.0;
double span = laserData.AngularRange;
for (index = 0; index < count; index++)
{
double angle = rangeLow + (span * index) / count;
if (Math.Abs(angle) < fov)
{
angle = angle * Math.PI / 180;
int range = laserData.DistanceMeasurements[index];
int x = (int)(range * Math.Sin(angle));
int y = (int)(range * Math.Cos(angle));
if (Math.Abs(x) < width)
{
if (range < best)
{
best = range;
}
}
}
}
return best;
}
#endregion
#region Drive helper method
/// <summary>
/// Sets the forward velocity of the drive.
/// </summary>
/// <param name="speed">velocity in mm/s</param>
/// <returns>response port</returns>
private PortSet<DefaultUpdateResponseType, Fault> MoveForward(int speed)
{
LogInfo(string.Format("MoveForward speed={0}", speed));
if ((_state.DriveState == null || !_state.DriveState.IsEnabled) && speed != 0)
{
EnableMotor();
}
drive.SetDriveSpeedRequest request = new drive.SetDriveSpeedRequest();
request.LeftWheelSpeed = (double)speed / 1000.0; // millimeters to meters
request.RightWheelSpeed = (double)speed / 1000.0; // millimeters to meters
return _drivePort.SetDriveSpeed(request);
}
/// <summary>
/// Turns the drive relative to its current heading.
/// </summary>
/// <param name="angle">angle in degrees</param>
/// <returns>response port</returns>
PortSet<DefaultUpdateResponseType, Fault> Turn(int angle)
{
if (_state.DriveState == null || !_state.DriveState.IsEnabled)
{
EnableMotor();
}
drive.RotateDegreesRequest request = new drive.RotateDegreesRequest();
request.Degrees = (double)(-angle);
return _drivePort.RotateDegrees(request);
}
/// <summary>
/// Moves the drive forward for the specified distance.
/// </summary>
/// <param name="step">distance in mm</param>
/// <returns>response port</returns>
PortSet<DefaultUpdateResponseType, Fault> Translate(int step)
{
if (_state.DriveState == null || !_state.DriveState.IsEnabled)
{
EnableMotor();
}
drive.DriveDistanceRequest request = new drive.DriveDistanceRequest();
request.Distance = (double)step / 1000.0; // millimeters to meters
return _drivePort.DriveDistance(request);
}
/// <summary>
/// Sets the velocity of the drive to 0.
/// </summary>
/// <returns></returns>
PortSet<DefaultUpdateResponseType, Fault> StopMoving()
{
return MoveForward(0);
}
/// <summary>
/// Sets the turning velocity to 0.
/// </summary>
/// <returns>response port</returns>
PortSet<DefaultUpdateResponseType, Fault> StopTurning()
{
return Turn(0);
}
/// <summary>
/// Enables the drive
/// </summary>
/// <returns>response port</returns>
PortSet<DefaultUpdateResponseType, Fault> EnableMotor()
{
return EnableMotor(true);
}
/// <summary>
/// Disables the drive
/// </summary>
/// <returns>repsonse port</returns>
PortSet<DefaultUpdateResponseType, Fault> DisableMotor()
{
return EnableMotor(false);
}
/// <summary>
/// Sets the drives enabled state.
/// </summary>
/// <param name="enable">new enables state</param>
/// <returns>response port</returns>
PortSet<DefaultUpdateResponseType, Fault> EnableMotor(bool enable)
{
drive.EnableDriveRequest request = new drive.EnableDriveRequest();
request.Enable = enable;
return _drivePort.EnableDrive(request);
}
#endregion
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Compute.V1.Snippets
{
using Google.Api.Gax;
using System;
using System.Linq;
using System.Threading.Tasks;
using lro = Google.LongRunning;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedSnapshotsClientSnippets
{
/// <summary>Snippet for Delete</summary>
public void DeleteRequestObject()
{
// Snippet: Delete(DeleteSnapshotRequest, CallSettings)
// Create client
SnapshotsClient snapshotsClient = SnapshotsClient.Create();
// Initialize request argument(s)
DeleteSnapshotRequest request = new DeleteSnapshotRequest
{
RequestId = "",
Project = "",
Snapshot = "",
};
// Make the request
lro::Operation<Operation, Operation> response = snapshotsClient.Delete(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = snapshotsClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteRequestObjectAsync()
{
// Snippet: DeleteAsync(DeleteSnapshotRequest, CallSettings)
// Additional: DeleteAsync(DeleteSnapshotRequest, CancellationToken)
// Create client
SnapshotsClient snapshotsClient = await SnapshotsClient.CreateAsync();
// Initialize request argument(s)
DeleteSnapshotRequest request = new DeleteSnapshotRequest
{
RequestId = "",
Project = "",
Snapshot = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await snapshotsClient.DeleteAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await snapshotsClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void Delete()
{
// Snippet: Delete(string, string, CallSettings)
// Create client
SnapshotsClient snapshotsClient = SnapshotsClient.Create();
// Initialize request argument(s)
string project = "";
string snapshot = "";
// Make the request
lro::Operation<Operation, Operation> response = snapshotsClient.Delete(project, snapshot);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = snapshotsClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteAsync()
{
// Snippet: DeleteAsync(string, string, CallSettings)
// Additional: DeleteAsync(string, string, CancellationToken)
// Create client
SnapshotsClient snapshotsClient = await SnapshotsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string snapshot = "";
// Make the request
lro::Operation<Operation, Operation> response = await snapshotsClient.DeleteAsync(project, snapshot);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await snapshotsClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Get</summary>
public void GetRequestObject()
{
// Snippet: Get(GetSnapshotRequest, CallSettings)
// Create client
SnapshotsClient snapshotsClient = SnapshotsClient.Create();
// Initialize request argument(s)
GetSnapshotRequest request = new GetSnapshotRequest
{
Project = "",
Snapshot = "",
};
// Make the request
Snapshot response = snapshotsClient.Get(request);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetRequestObjectAsync()
{
// Snippet: GetAsync(GetSnapshotRequest, CallSettings)
// Additional: GetAsync(GetSnapshotRequest, CancellationToken)
// Create client
SnapshotsClient snapshotsClient = await SnapshotsClient.CreateAsync();
// Initialize request argument(s)
GetSnapshotRequest request = new GetSnapshotRequest
{
Project = "",
Snapshot = "",
};
// Make the request
Snapshot response = await snapshotsClient.GetAsync(request);
// End snippet
}
/// <summary>Snippet for Get</summary>
public void Get()
{
// Snippet: Get(string, string, CallSettings)
// Create client
SnapshotsClient snapshotsClient = SnapshotsClient.Create();
// Initialize request argument(s)
string project = "";
string snapshot = "";
// Make the request
Snapshot response = snapshotsClient.Get(project, snapshot);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetAsync()
{
// Snippet: GetAsync(string, string, CallSettings)
// Additional: GetAsync(string, string, CancellationToken)
// Create client
SnapshotsClient snapshotsClient = await SnapshotsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string snapshot = "";
// Make the request
Snapshot response = await snapshotsClient.GetAsync(project, snapshot);
// End snippet
}
/// <summary>Snippet for GetIamPolicy</summary>
public void GetIamPolicyRequestObject()
{
// Snippet: GetIamPolicy(GetIamPolicySnapshotRequest, CallSettings)
// Create client
SnapshotsClient snapshotsClient = SnapshotsClient.Create();
// Initialize request argument(s)
GetIamPolicySnapshotRequest request = new GetIamPolicySnapshotRequest
{
Resource = "",
Project = "",
OptionsRequestedPolicyVersion = 0,
};
// Make the request
Policy response = snapshotsClient.GetIamPolicy(request);
// End snippet
}
/// <summary>Snippet for GetIamPolicyAsync</summary>
public async Task GetIamPolicyRequestObjectAsync()
{
// Snippet: GetIamPolicyAsync(GetIamPolicySnapshotRequest, CallSettings)
// Additional: GetIamPolicyAsync(GetIamPolicySnapshotRequest, CancellationToken)
// Create client
SnapshotsClient snapshotsClient = await SnapshotsClient.CreateAsync();
// Initialize request argument(s)
GetIamPolicySnapshotRequest request = new GetIamPolicySnapshotRequest
{
Resource = "",
Project = "",
OptionsRequestedPolicyVersion = 0,
};
// Make the request
Policy response = await snapshotsClient.GetIamPolicyAsync(request);
// End snippet
}
/// <summary>Snippet for GetIamPolicy</summary>
public void GetIamPolicy()
{
// Snippet: GetIamPolicy(string, string, CallSettings)
// Create client
SnapshotsClient snapshotsClient = SnapshotsClient.Create();
// Initialize request argument(s)
string project = "";
string resource = "";
// Make the request
Policy response = snapshotsClient.GetIamPolicy(project, resource);
// End snippet
}
/// <summary>Snippet for GetIamPolicyAsync</summary>
public async Task GetIamPolicyAsync()
{
// Snippet: GetIamPolicyAsync(string, string, CallSettings)
// Additional: GetIamPolicyAsync(string, string, CancellationToken)
// Create client
SnapshotsClient snapshotsClient = await SnapshotsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string resource = "";
// Make the request
Policy response = await snapshotsClient.GetIamPolicyAsync(project, resource);
// End snippet
}
/// <summary>Snippet for List</summary>
public void ListRequestObject()
{
// Snippet: List(ListSnapshotsRequest, CallSettings)
// Create client
SnapshotsClient snapshotsClient = SnapshotsClient.Create();
// Initialize request argument(s)
ListSnapshotsRequest request = new ListSnapshotsRequest
{
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<SnapshotList, Snapshot> response = snapshotsClient.List(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Snapshot item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (SnapshotList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Snapshot item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Snapshot> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Snapshot item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListRequestObjectAsync()
{
// Snippet: ListAsync(ListSnapshotsRequest, CallSettings)
// Create client
SnapshotsClient snapshotsClient = await SnapshotsClient.CreateAsync();
// Initialize request argument(s)
ListSnapshotsRequest request = new ListSnapshotsRequest
{
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<SnapshotList, Snapshot> response = snapshotsClient.ListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Snapshot item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((SnapshotList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Snapshot item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Snapshot> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Snapshot item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for List</summary>
public void List()
{
// Snippet: List(string, string, int?, CallSettings)
// Create client
SnapshotsClient snapshotsClient = SnapshotsClient.Create();
// Initialize request argument(s)
string project = "";
// Make the request
PagedEnumerable<SnapshotList, Snapshot> response = snapshotsClient.List(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (Snapshot item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (SnapshotList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Snapshot item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Snapshot> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Snapshot item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListAsync()
{
// Snippet: ListAsync(string, string, int?, CallSettings)
// Create client
SnapshotsClient snapshotsClient = await SnapshotsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
// Make the request
PagedAsyncEnumerable<SnapshotList, Snapshot> response = snapshotsClient.ListAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Snapshot item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((SnapshotList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Snapshot item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Snapshot> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Snapshot item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for SetIamPolicy</summary>
public void SetIamPolicyRequestObject()
{
// Snippet: SetIamPolicy(SetIamPolicySnapshotRequest, CallSettings)
// Create client
SnapshotsClient snapshotsClient = SnapshotsClient.Create();
// Initialize request argument(s)
SetIamPolicySnapshotRequest request = new SetIamPolicySnapshotRequest
{
Resource = "",
Project = "",
GlobalSetPolicyRequestResource = new GlobalSetPolicyRequest(),
};
// Make the request
Policy response = snapshotsClient.SetIamPolicy(request);
// End snippet
}
/// <summary>Snippet for SetIamPolicyAsync</summary>
public async Task SetIamPolicyRequestObjectAsync()
{
// Snippet: SetIamPolicyAsync(SetIamPolicySnapshotRequest, CallSettings)
// Additional: SetIamPolicyAsync(SetIamPolicySnapshotRequest, CancellationToken)
// Create client
SnapshotsClient snapshotsClient = await SnapshotsClient.CreateAsync();
// Initialize request argument(s)
SetIamPolicySnapshotRequest request = new SetIamPolicySnapshotRequest
{
Resource = "",
Project = "",
GlobalSetPolicyRequestResource = new GlobalSetPolicyRequest(),
};
// Make the request
Policy response = await snapshotsClient.SetIamPolicyAsync(request);
// End snippet
}
/// <summary>Snippet for SetIamPolicy</summary>
public void SetIamPolicy()
{
// Snippet: SetIamPolicy(string, string, GlobalSetPolicyRequest, CallSettings)
// Create client
SnapshotsClient snapshotsClient = SnapshotsClient.Create();
// Initialize request argument(s)
string project = "";
string resource = "";
GlobalSetPolicyRequest globalSetPolicyRequestResource = new GlobalSetPolicyRequest();
// Make the request
Policy response = snapshotsClient.SetIamPolicy(project, resource, globalSetPolicyRequestResource);
// End snippet
}
/// <summary>Snippet for SetIamPolicyAsync</summary>
public async Task SetIamPolicyAsync()
{
// Snippet: SetIamPolicyAsync(string, string, GlobalSetPolicyRequest, CallSettings)
// Additional: SetIamPolicyAsync(string, string, GlobalSetPolicyRequest, CancellationToken)
// Create client
SnapshotsClient snapshotsClient = await SnapshotsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string resource = "";
GlobalSetPolicyRequest globalSetPolicyRequestResource = new GlobalSetPolicyRequest();
// Make the request
Policy response = await snapshotsClient.SetIamPolicyAsync(project, resource, globalSetPolicyRequestResource);
// End snippet
}
/// <summary>Snippet for SetLabels</summary>
public void SetLabelsRequestObject()
{
// Snippet: SetLabels(SetLabelsSnapshotRequest, CallSettings)
// Create client
SnapshotsClient snapshotsClient = SnapshotsClient.Create();
// Initialize request argument(s)
SetLabelsSnapshotRequest request = new SetLabelsSnapshotRequest
{
Resource = "",
Project = "",
GlobalSetLabelsRequestResource = new GlobalSetLabelsRequest(),
};
// Make the request
lro::Operation<Operation, Operation> response = snapshotsClient.SetLabels(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = snapshotsClient.PollOnceSetLabels(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetLabelsAsync</summary>
public async Task SetLabelsRequestObjectAsync()
{
// Snippet: SetLabelsAsync(SetLabelsSnapshotRequest, CallSettings)
// Additional: SetLabelsAsync(SetLabelsSnapshotRequest, CancellationToken)
// Create client
SnapshotsClient snapshotsClient = await SnapshotsClient.CreateAsync();
// Initialize request argument(s)
SetLabelsSnapshotRequest request = new SetLabelsSnapshotRequest
{
Resource = "",
Project = "",
GlobalSetLabelsRequestResource = new GlobalSetLabelsRequest(),
};
// Make the request
lro::Operation<Operation, Operation> response = await snapshotsClient.SetLabelsAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await snapshotsClient.PollOnceSetLabelsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetLabels</summary>
public void SetLabels()
{
// Snippet: SetLabels(string, string, GlobalSetLabelsRequest, CallSettings)
// Create client
SnapshotsClient snapshotsClient = SnapshotsClient.Create();
// Initialize request argument(s)
string project = "";
string resource = "";
GlobalSetLabelsRequest globalSetLabelsRequestResource = new GlobalSetLabelsRequest();
// Make the request
lro::Operation<Operation, Operation> response = snapshotsClient.SetLabels(project, resource, globalSetLabelsRequestResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = snapshotsClient.PollOnceSetLabels(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetLabelsAsync</summary>
public async Task SetLabelsAsync()
{
// Snippet: SetLabelsAsync(string, string, GlobalSetLabelsRequest, CallSettings)
// Additional: SetLabelsAsync(string, string, GlobalSetLabelsRequest, CancellationToken)
// Create client
SnapshotsClient snapshotsClient = await SnapshotsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string resource = "";
GlobalSetLabelsRequest globalSetLabelsRequestResource = new GlobalSetLabelsRequest();
// Make the request
lro::Operation<Operation, Operation> response = await snapshotsClient.SetLabelsAsync(project, resource, globalSetLabelsRequestResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await snapshotsClient.PollOnceSetLabelsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for TestIamPermissions</summary>
public void TestIamPermissionsRequestObject()
{
// Snippet: TestIamPermissions(TestIamPermissionsSnapshotRequest, CallSettings)
// Create client
SnapshotsClient snapshotsClient = SnapshotsClient.Create();
// Initialize request argument(s)
TestIamPermissionsSnapshotRequest request = new TestIamPermissionsSnapshotRequest
{
Resource = "",
Project = "",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
// Make the request
TestPermissionsResponse response = snapshotsClient.TestIamPermissions(request);
// End snippet
}
/// <summary>Snippet for TestIamPermissionsAsync</summary>
public async Task TestIamPermissionsRequestObjectAsync()
{
// Snippet: TestIamPermissionsAsync(TestIamPermissionsSnapshotRequest, CallSettings)
// Additional: TestIamPermissionsAsync(TestIamPermissionsSnapshotRequest, CancellationToken)
// Create client
SnapshotsClient snapshotsClient = await SnapshotsClient.CreateAsync();
// Initialize request argument(s)
TestIamPermissionsSnapshotRequest request = new TestIamPermissionsSnapshotRequest
{
Resource = "",
Project = "",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
// Make the request
TestPermissionsResponse response = await snapshotsClient.TestIamPermissionsAsync(request);
// End snippet
}
/// <summary>Snippet for TestIamPermissions</summary>
public void TestIamPermissions()
{
// Snippet: TestIamPermissions(string, string, TestPermissionsRequest, CallSettings)
// Create client
SnapshotsClient snapshotsClient = SnapshotsClient.Create();
// Initialize request argument(s)
string project = "";
string resource = "";
TestPermissionsRequest testPermissionsRequestResource = new TestPermissionsRequest();
// Make the request
TestPermissionsResponse response = snapshotsClient.TestIamPermissions(project, resource, testPermissionsRequestResource);
// End snippet
}
/// <summary>Snippet for TestIamPermissionsAsync</summary>
public async Task TestIamPermissionsAsync()
{
// Snippet: TestIamPermissionsAsync(string, string, TestPermissionsRequest, CallSettings)
// Additional: TestIamPermissionsAsync(string, string, TestPermissionsRequest, CancellationToken)
// Create client
SnapshotsClient snapshotsClient = await SnapshotsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string resource = "";
TestPermissionsRequest testPermissionsRequestResource = new TestPermissionsRequest();
// Make the request
TestPermissionsResponse response = await snapshotsClient.TestIamPermissionsAsync(project, resource, testPermissionsRequestResource);
// End snippet
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using Xunit.Abstractions;
using System.IO;
using System.Collections;
using System.Xml.Schema;
namespace System.Xml.Tests
{
//[TestCase(Name = "TC_SchemaSet_Remove", Desc = "")]
public class TC_SchemaSet_Remove : TC_SchemaSetBase
{
private ITestOutputHelper _output;
public TC_SchemaSet_Remove(ITestOutputHelper output)
{
_output = output;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v1 - Remove with null", Priority = 0)]
[InlineData()]
[Theory]
public void v1()
{
try
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.Remove(null);
}
catch (ArgumentNullException)
{
// GLOBALIZATION
return;
}
Assert.True(false);
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v2 - Remove with just added schema", Priority = 0)]
[InlineData()]
[Theory]
public void v2()
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
sc.Compile();
sc.Remove(Schema1);
CError.Compare(sc.Count, 0, "Count");
ICollection Col = sc.Schemas();
CError.Compare(Col.Count, 0, "ICollection.Count");
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v3 - Remove first added schema, check the rest", Priority = 0)]
[InlineData()]
[Theory]
public void v3()
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
XmlSchema Schema2 = sc.Add("test", TestData._XsdNoNs);
sc.Compile();
sc.Remove(Schema1);
CError.Compare(sc.Count, 1, "Count");
ICollection Col = sc.Schemas();
CError.Compare(Col.Count, 1, "ICollection.Count");
CError.Compare(sc.Contains("test"), true, "Contains");
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v4.6 - Remove A(ns-a) include B(ns-a) which includes C(ns-a) ", Priority = 1, Params = new object[] { "include_v7_a.xsd" })]
[InlineData("include_v7_a.xsd")]
//[Variation(Desc = "v4.5 - Remove: A with NS includes B and C with no NS", Priority = 1, Params = new object[] { "include_v6_a.xsd" })]
[InlineData("include_v6_a.xsd")]
//[Variation(Desc = "v4.4 - Remove: A with NS includes B and C with no NS, B also includes C", Priority = 1, Params = new object[] { "include_v5_a.xsd" })]
[InlineData("include_v5_a.xsd")]
//[Variation(Desc = "v4.3 - Remove: A with NS includes B with no NS, which includes C with no NS", Priority = 1, Params = new object[] { "include_v4_a.xsd" })]
[InlineData("include_v4_a.xsd")]
//[Variation(Desc = "v4.2 - Remove: A with no NS includes B with no NS", Params = new object[] { "include_v3_a.xsd" })]
[InlineData("include_v3_a.xsd")]
//[Variation(Desc = "v4.1 - Remove: A with NS includes B with no NS", Params = new object[] { "include_v1_a.xsd", })]
[InlineData("include_v1_a.xsd")]
[Theory]
public void v4(object param0)
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
try
{
XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
XmlSchema Schema2 = sc.Add(null, Path.Combine(TestData._Root, param0.ToString())); // param as filename
sc.Compile();
sc.Remove(Schema2);
CError.Compare(sc.Count, 1, "Count");
ICollection Col = sc.Schemas();
CError.Compare(Col.Count, 1, "ICollection.Count");
}
catch (Exception)
{
Assert.True(false);
}
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v5.3 - Remove: A(ns-a) which imports B (no ns)", Priority = 1, Params = new object[] { "import_v4_a.xsd", 2 })]
[InlineData("import_v4_a.xsd", 2)]
//[Variation(Desc = "v5.2 - Remove: A(ns-a) improts B (ns-b)", Priority = 1, Params = new object[] { "import_v2_a.xsd", 2 })]
[InlineData("import_v2_a.xsd", 2)]
//[Variation(Desc = "v5.1 - Remove: A with NS imports B with no NS", Priority = 1, Params = new object[] { "import_v1_a.xsd", 2 })]
[InlineData("import_v1_a.xsd", 2)]
[Theory]
public void v5(object param0, object param1)
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
try
{
XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
XmlSchema Schema2 = sc.Add(null, Path.Combine(TestData._Root, param0.ToString())); // param as filename
sc.Compile();
sc.Remove(Schema2);
CError.Compare(sc.Count, param1, "Count");
ICollection Col = sc.Schemas();
CError.Compare(Col.Count, param1, "ICollection.Count");
}
catch (Exception)
{
Assert.True(false);
}
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v6 - Remove: Add B(NONS) to a namespace, Add A(ns-a) which imports B, Remove B(nons)", Priority = 1)]
[InlineData()]
[Theory]
public void v6()
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
try
{
XmlSchema Schema1 = sc.Add("ns-b", Path.Combine(TestData._Root, "import_v4_b.xsd"));
XmlSchema Schema2 = sc.Add(null, Path.Combine(TestData._Root, "import_v5_a.xsd")); // param as filename
sc.Compile();
sc.Remove(Schema1);
CError.Compare(sc.Count, 2, "Count");
ICollection Col = sc.Schemas();
CError.Compare(Col.Count, 2, "ICollection.Count");
CError.Compare(sc.Contains("ns-b"), false, "Contains");
CError.Compare(sc.Contains(string.Empty), true, "Contains");
CError.Compare(sc.Contains("ns-a"), true, "Contains");
}
catch (Exception)
{
Assert.True(false);
}
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v7 - Remove: Add B(NONS) to a namespace, Add A(ns-a) which improts B, Remove B(ns-b)", Priority = 1)]
[InlineData()]
[Theory]
public void v7()
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
try
{
XmlSchema Schema1 = sc.Add("ns-b", Path.Combine(TestData._Root, "import_v4_b.xsd"));
XmlSchema Schema2 = sc.Add(null, Path.Combine(TestData._Root, "import_v5_a.xsd")); // param as filename
sc.Compile();
ICollection col = sc.Schemas(string.Empty);
foreach (XmlSchema schema in col)
{
sc.Remove(schema); //should remove just one
}
CError.Compare(sc.Count, 2, "Count");
ICollection Col = sc.Schemas();
CError.Compare(Col.Count, 2, "ICollection.Count");
CError.Compare(sc.Contains("ns-b"), true, "Contains");
CError.Compare(sc.Contains(string.Empty), false, "Contains");
CError.Compare(sc.Contains("ns-a"), true, "Contains");
}
catch (Exception)
{
Assert.True(false);
}
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v8.2 - Remove: A(ns-a) imports B(NO NS) imports C (ns-c)", Priority = 1, Params = new object[] { "import_v10_a.xsd", "ns-a", "", "ns-c" })]
[InlineData("import_v10_a.xsd", "ns-a", "", "ns-c")]
//[Variation(Desc = "v8.1 - Remove: A(ns-a) imports B(ns-b) imports C (ns-c)", Priority = 1, Params = new object[] { "import_v9_a.xsd", "ns-a", "ns-b", "ns-c" })]
[InlineData("import_v9_a.xsd", "ns-a", "ns-b", "ns-c")]
[Theory]
public void v8(object param0, object param1, object param2, object param3)
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
try
{
XmlSchema Schema1 = sc.Add(null, Path.Combine(TestData._Root, param0.ToString()));
sc.Compile();
CError.Compare(sc.Count, 3, "Count");
ICollection col = sc.Schemas(param2.ToString());
foreach (XmlSchema schema in col)
{
sc.Remove(schema); //should remove just one
}
CError.Compare(sc.Count, 2, "Count");
CError.Compare(sc.Contains(param2.ToString()), false, "Contains");
col = sc.Schemas(param3.ToString());
foreach (XmlSchema schema in col)
{
sc.Remove(schema); //should remove just one
}
CError.Compare(sc.Count, 1, "Count");
CError.Compare(sc.Contains(param3.ToString()), false, "Contains");
CError.Compare(sc.Contains(param1.ToString()), true, "Contains");
}
catch (Exception e)
{
_output.WriteLine(e.ToString());
Assert.True(false);
}
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v9 - Remove: A imports B and B and C, B imports C and D, C imports D and A", Priority = 1, Params = new object[] { "import_v13_a.xsd" })]
[InlineData("import_v13_a.xsd")]
[Theory]
public void v9(object param0)
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
try
{
XmlSchema Schema1 = sc.Add(null, Path.Combine(TestData._Root, param0.ToString()));
sc.Compile();
CError.Compare(sc.Count, 4, "Count");
ICollection col = sc.Schemas("ns-d");
foreach (XmlSchema schema in col)
{
sc.Remove(schema); //should remove just one
}
CError.Compare(sc.Count, 3, "Count");
CError.Compare(sc.Contains("ns-d"), false, "Contains");
col = sc.Schemas("ns-c");
foreach (XmlSchema schema in col)
{
sc.Remove(schema); //should remove just one
}
CError.Compare(sc.Count, 2, "Count");
CError.Compare(sc.Contains("ns-c"), false, "Contains");
col = sc.Schemas("ns-b");
foreach (XmlSchema schema in col)
{
sc.Remove(schema); //should remove just one
}
CError.Compare(sc.Count, 1, "Count");
CError.Compare(sc.Contains("ns-b"), false, "Contains");
CError.Compare(sc.Contains("ns-a"), true, "Contains");
}
catch (Exception e)
{
_output.WriteLine(e.ToString());
Assert.True(false);
}
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v10 - Import: B(ns-b) added, A(ns-a) imports B's NS", Priority = 2)]
[InlineData()]
[Theory]
public void v10()
{
try
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
sc.Add(null, Path.Combine(TestData._Root, "import_v16_b.xsd"));
XmlSchema parent = sc.Add(null, Path.Combine(TestData._Root, "import_v16_a.xsd"));
sc.Compile();
sc.Remove(parent);
CError.Compare(sc.Count, 1, "Count");
CError.Compare(sc.Contains("ns-b"), true, "Contains");
return;
}
catch (XmlSchemaException e)
{
_output.WriteLine("Exception : " + e.Message);
}
Assert.True(false);
}
//[Variation(Desc = "v11.2 - Remove: A(ns-a) improts B (ns-b), Remove imported schema", Priority = 2, Params = new object[] { "import_v2_a.xsd", "import_v2_b.xsd" })]
[InlineData("import_v2_a.xsd", "import_v2_b.xsd")]
//[Variation(Desc = "v11.1 - Remove: A with NS imports B with no NS, Remove imported schema", Priority = 2, Params = new object[] { "import_v1_a.xsd", "include_v1_b.xsd" })]
[InlineData("import_v1_a.xsd", "include_v1_b.xsd")]
[Theory]
public void v11(object param0, object param1)
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
try
{
XmlSchema Schema1 = sc.Add(null, Path.Combine(TestData._Root, param0.ToString())); // param as filename
XmlSchema Schema2 = sc.Add(null, Path.Combine(TestData._Root, param1.ToString())); // param as filename
sc.Compile();
CError.Compare(sc.Count, 2, "Count");
sc.Remove(Schema2);
sc.Compile();
CError.Compare(sc.Count, 1, "Count");
CError.Compare(sc.GlobalElements.Count, 2, "GlobalElems Count");
}
catch (Exception e)
{
_output.WriteLine(e.ToString());
Assert.True(false);
}
return;
}
//[Variation(Desc = "v20 - 358206 : Removing the last schema from the set should clear the global tables", Priority = 2)]
[InlineData()]
[Theory]
public void v20()
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
XmlSchema Schema = sc.Add(null, TestData._XsdAuthor); // param as filename
sc.Compile();
CError.Compare(sc.Count, 1, "Count before remove");
sc.Remove(Schema);
sc.Compile();
CError.Compare(sc.Count, 0, "Count after remove");
CError.Compare(sc.GlobalElements.Count, 0, "GlobalElems Count");
return;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.Configuration;
using Orleans.Internal;
using Orleans.LeaseProviders;
using Orleans.Runtime;
using Orleans.Timers;
namespace Orleans.Streams
{
/// <summary>
/// LeaseBasedQueueBalancer. This balancer supports queue balancing in cluster auto-scale scenarios,
/// unexpected server failure scenarios, and tries to support ideal distribution as much as possible.
/// </summary>
public class LeaseBasedQueueBalancer : QueueBalancerBase, IStreamQueueBalancer
{
private class AcquiredQueue
{
public int LeaseOrder { get; set; }
public QueueId QueueId { get; set; }
public AcquiredLease AcquiredLease { get; set; }
public AcquiredQueue(int order, QueueId queueId, AcquiredLease lease)
{
this.LeaseOrder = order;
this.QueueId = queueId;
this.AcquiredLease = lease;
}
}
private readonly LeaseBasedQueueBalancerOptions options;
private readonly ILeaseProvider leaseProvider;
private readonly ITimerRegistry timerRegistry;
private readonly AsyncSerialExecutor executor = new AsyncSerialExecutor();
private int allQueuesCount;
private readonly List<AcquiredQueue> myQueues = new List<AcquiredQueue>();
private IDisposable leaseMaintenanceTimer;
private IDisposable leaseAquisitionTimer;
private RoundRobinSelector<QueueId> queueSelector;
private int responsibility;
private int leaseOrder;
/// <summary>
/// Constructor
/// </summary>
public LeaseBasedQueueBalancer(string name, LeaseBasedQueueBalancerOptions options, ILeaseProvider leaseProvider, ITimerRegistry timerRegistry, IServiceProvider services, ILoggerFactory loggerFactory)
: base(services, loggerFactory.CreateLogger($"{typeof(LeaseBasedQueueBalancer).FullName}.{name}"))
{
this.options = options;
this.leaseProvider = leaseProvider;
this.timerRegistry = timerRegistry;
}
public static IStreamQueueBalancer Create(IServiceProvider services, string name)
{
var options = services.GetOptionsByName<LeaseBasedQueueBalancerOptions>(name);
var leaseProvider = services.GetServiceByName<ILeaseProvider>(name)
?? services.GetRequiredService<ILeaseProvider>();
return ActivatorUtilities.CreateInstance<LeaseBasedQueueBalancer>(services, name, options, leaseProvider);
}
/// <inheritdoc/>
public override Task Initialize(IStreamQueueMapper queueMapper)
{
if (base.Cancellation.IsCancellationRequested) throw new InvalidOperationException("Cannot initialize a terminated balancer.");
if (queueMapper == null)
{
throw new ArgumentNullException("queueMapper");
}
var allQueues = queueMapper.GetAllQueues().ToList();
this.allQueuesCount = allQueues.Count;
//Selector default to round robin selector now, but we can make a further change to make selector configurable if needed. Selector algorithm could
//be affecting queue balancing stablization time in cluster initializing and auto-scaling
this.queueSelector = new RoundRobinSelector<QueueId>(allQueues, new Random(this.GetHashCode()));
return base.Initialize(queueMapper);
}
/// <inheritdoc/>
public override async Task Shutdown()
{
if (base.Cancellation.IsCancellationRequested) return;
this.myQueues.Clear();
this.responsibility = 0;
this.leaseMaintenanceTimer?.Dispose();
this.leaseMaintenanceTimer = null;
this.leaseAquisitionTimer?.Dispose();
this.leaseAquisitionTimer = null;
await base.Shutdown();
//release all owned leases
await this.executor.AddNext(this.ReleaseLeasesToMeetResponsibility);
}
/// <inheritdoc/>
public override IEnumerable<QueueId> GetMyQueues()
{
if (base.Cancellation.IsCancellationRequested) throw new InvalidOperationException("Cannot aquire queues from a terminated balancer.");
return this.myQueues.Select(queue => queue.QueueId);
}
private async Task MaintainLeases(object state)
{
try
{
await this.executor.AddNext(this.MaintainLeases);
}
catch (Exception ex)
{
this.Logger.LogError(ex, "Maintaining leases failed");
}
}
private async Task MaintainLeases()
{
if (base.Cancellation.IsCancellationRequested) return;
var oldQueues = new HashSet<QueueId>(this.myQueues.Select(queue => queue.QueueId));
try
{
bool allLeasesRenewed = await this.RenewLeases();
// if we lost some leases during renew after leaseAquisitionTimer stopped, restart it
if (!allLeasesRenewed &&
this.leaseAquisitionTimer == null &&
!base.Cancellation.IsCancellationRequested)
{
this.leaseAquisitionTimer = this.timerRegistry.RegisterTimer(null, this.AcquireLeasesToMeetResponsibility, null, TimeSpan.Zero, this.options.LeaseAquisitionPeriod);
}
}
finally
{
await this.NotifyOnChange(oldQueues);
}
}
private async Task AcquireLeasesToMeetResponsibility(object state)
{
try
{
await this.executor.AddNext(this.AcquireLeasesToMeetResponsibility);
}
catch (Exception ex)
{
this.Logger.LogError(ex, "Acquiring min leases failed");
}
}
private async Task AcquireLeasesToMeetResponsibility()
{
if (base.Cancellation.IsCancellationRequested) return;
var oldQueues = new HashSet<QueueId>(this.myQueues.Select(queue => queue.QueueId));
try
{
if (this.myQueues.Count < this.responsibility)
{
await this.AcquireLeasesToMeetExpectation(this.responsibility, this.options.LeaseLength.Divide(10));
}
else if (this.myQueues.Count > this.responsibility)
{
await this.ReleaseLeasesToMeetResponsibility();
}
}
finally
{
await this.NotifyOnChange(oldQueues);
if (this.myQueues.Count == this.responsibility)
{
this.leaseAquisitionTimer?.Dispose();
this.leaseAquisitionTimer = null;
}
}
}
private async Task ReleaseLeasesToMeetResponsibility()
{
if (base.Cancellation.IsCancellationRequested) return;
if (this.Logger.IsEnabled(LogLevel.Trace))
{
this.Logger.LogTrace("ReleaseLeasesToMeetResponsibility. QueueCount: {QueueCount}, Responsibility: {Responsibility}", this.myQueues.Count, this.responsibility);
}
var queueCountToRelease = this.myQueues.Count - this.responsibility;
if (queueCountToRelease <= 0)
return;
// Remove oldest acquired queues first, this provides max recovery time for the queues
// being moved.
// TODO: Consider making this behavior configurable/plugable - jbragg
AcquiredLease[] queuesToGiveUp = this.myQueues
.OrderBy(queue => queue.LeaseOrder)
.Take(queueCountToRelease)
.Select(queue => queue.AcquiredLease)
.ToArray();
// Remove queues from list even if release fails, since we can let the lease expire
// TODO: mark for removal instead so we don't renew, and only remove leases that have not expired. - jbragg
for(int index = this.myQueues.Count-1; index >= 0; index--)
{
if(queuesToGiveUp.Contains(this.myQueues[index].AcquiredLease))
{
this.myQueues.RemoveAt(index);
}
}
await this.leaseProvider.Release(this.options.LeaseCategory, queuesToGiveUp);
//remove queuesToGiveUp from myQueue list after the balancer released the leases on them
this.Logger.LogInformation("Released leases for {QueueCount} queues", queueCountToRelease);
this.Logger.LogInformation("Holding leases for {QueueCount} of an expected {MinQueueCount} queues.", this.myQueues.Count, this.responsibility);
}
private async Task AcquireLeasesToMeetExpectation(int expectedTotalLeaseCount, TimeSpan timeout)
{
if (base.Cancellation.IsCancellationRequested) return;
if (this.Logger.IsEnabled(LogLevel.Trace))
{
this.Logger.LogTrace("AcquireLeasesToMeetExpectation. QueueCount: {QueueCount}, ExpectedTotalLeaseCount: {ExpectedTotalLeaseCount}", this.myQueues.Count, expectedTotalLeaseCount);
}
var leasesToAquire = expectedTotalLeaseCount - this.myQueues.Count;
if (leasesToAquire <= 0) return;
// tracks how many remaining possible leases there are.
var possibleLeaseCount = this.queueSelector.Count - this.myQueues.Count;
if (this.Logger.IsEnabled(LogLevel.Debug))
{
this.Logger.LogDebug("Holding leased for {QueueCount} queues. Trying to acquire {AquireQueueCount} queues to reach {TargetQueueCount} of a possible {PossibleLeaseCount}", this.myQueues.Count, leasesToAquire, expectedTotalLeaseCount, possibleLeaseCount);
}
ValueStopwatch sw = ValueStopwatch.StartNew();
// try to acquire leases until we have no more to aquire or no more possible
while (!base.Cancellation.IsCancellationRequested && leasesToAquire > 0 && possibleLeaseCount > 0)
{
//select new queues to acquire
List<QueueId> expectedQueues = this.queueSelector.NextSelection(leasesToAquire, this.myQueues.Select(queue=>queue.QueueId).ToList());
// build lease request from each queue
LeaseRequest[] leaseRequests = expectedQueues
.Select(queue => new LeaseRequest() {
ResourceKey = queue.ToString(),
Duration = this.options.LeaseLength
})
.ToArray();
AcquireLeaseResult[] results = await this.leaseProvider.Acquire(this.options.LeaseCategory, leaseRequests);
//add successfully acquired queue to myQueues list
for (var i = 0; i < results.Length; i++)
{
AcquireLeaseResult result = results[i];
switch (result.StatusCode)
{
case ResponseCode.OK:
{
this.myQueues.Add(new AcquiredQueue(this.leaseOrder++, expectedQueues[i], result.AcquiredLease));
break;
}
case ResponseCode.TransientFailure:
{
this.Logger.LogWarning(result.FailureException, "Failed to acquire lease {LeaseKey} due to transient error.", result.AcquiredLease.ResourceKey);
break;
}
// this is expected much of the time
case ResponseCode.LeaseNotAvailable:
{
if (this.Logger.IsEnabled(LogLevel.Debug))
{
this.Logger.LogDebug(result.FailureException, "Failed to acquire lease {LeaseKey} due to {Reason}.", result.AcquiredLease.ResourceKey, result.StatusCode);
}
break;
}
// An acquire call should not return this code, so log as error
case ResponseCode.InvalidToken:
{
this.Logger.LogError(result.FailureException, "Failed to aquire acquire {LeaseKey} unexpected invalid token.", result.AcquiredLease.ResourceKey);
break;
}
default:
{
this.Logger.LogError(result.FailureException, "Unexpected response to acquire request of lease {LeaseKey}. StatusCode {StatusCode}.", result.AcquiredLease.ResourceKey, result.StatusCode);
break;
}
}
}
possibleLeaseCount -= expectedQueues.Count;
leasesToAquire = expectedTotalLeaseCount - this.myQueues.Count;
if (this.Logger.IsEnabled(LogLevel.Debug))
{
this.Logger.LogDebug("Holding leased for {QueueCount} queues. Trying to acquire {AquireQueueCount} queues to reach {TargetQueueCount} of a possible {PossibleLeaseCount} lease", this.myQueues.Count, leasesToAquire, expectedTotalLeaseCount, possibleLeaseCount);
}
if (sw.Elapsed > timeout)
{
// blown our alotted time, try again next period
break;
}
}
this.Logger.LogInformation("Holding leases for {QueueCount} of an expected {MinQueueCount} queues.", this.myQueues.Count, this.responsibility);
}
/// <summary>
/// Renew leases
/// </summary>
/// <returns>bool - false if we failed to renew all leases</returns>
private async Task<bool> RenewLeases()
{
bool allRenewed = true;
if (base.Cancellation.IsCancellationRequested) return false;
if (this.Logger.IsEnabled(LogLevel.Trace))
{
this.Logger.LogTrace("RenewLeases. QueueCount: {QueueCount}", this.myQueues.Count);
}
if (this.myQueues.Count <= 0)
return allRenewed;
var results = await this.leaseProvider.Renew(this.options.LeaseCategory, this.myQueues.Select(queue => queue.AcquiredLease).ToArray());
//update myQueues list with successfully renewed leases
for (var i = 0; i < results.Length; i++)
{
AcquireLeaseResult result = results[i];
switch (result.StatusCode)
{
case ResponseCode.OK:
{
this.myQueues[i].AcquiredLease = result.AcquiredLease;
break;
}
case ResponseCode.TransientFailure:
{
this.myQueues.RemoveAt(i);
allRenewed &= false;
this.Logger.LogWarning(result.FailureException, "Failed to renew lease {LeaseKey} due to transient error.", result.AcquiredLease.ResourceKey);
break;
}
// these can occure if lease has expired and/or someone else has taken it
case ResponseCode.InvalidToken:
case ResponseCode.LeaseNotAvailable:
{
this.myQueues.RemoveAt(i);
allRenewed &= false;
this.Logger.LogWarning(result.FailureException, "Failed to renew lease {LeaseKey} due to {Reason}.", result.AcquiredLease.ResourceKey, result.StatusCode);
break;
}
default:
{
this.myQueues.RemoveAt(i);
allRenewed &= false;
this.Logger.LogError(result.FailureException, "Unexpected response to renew of lease {LeaseKey}. StatusCode {StatusCode}.", result.AcquiredLease.ResourceKey, result.StatusCode);
break;
}
}
}
this.Logger.LogInformation("Renewed leases for {QueueCount} queues.", this.myQueues.Count);
return allRenewed;
}
private Task NotifyOnChange(HashSet<QueueId> oldQueues)
{
if (base.Cancellation.IsCancellationRequested) return Task.CompletedTask;
var newQueues = new HashSet<QueueId>(this.myQueues.Select(queue => queue.QueueId));
//if queue changed, notify listeners
return !oldQueues.SetEquals(newQueues)
? this.NotifyListeners()
: Task.CompletedTask;
}
protected override void OnClusterMembershipChange(HashSet<SiloAddress> activeSilos)
{
if (base.Cancellation.IsCancellationRequested) return;
this.ScheduleUpdateResponsibilities(activeSilos).Ignore();
}
private async Task ScheduleUpdateResponsibilities(HashSet<SiloAddress> activeSilos)
{
if (base.Cancellation.IsCancellationRequested) return;
try
{
await this.executor.AddNext(() => UpdateResponsibilities(activeSilos));
}
catch (Exception ex)
{
this.Logger.LogError(ex, "Updating Responsibilities");
}
}
/// <summary>
/// Checks to see if this balancer should be greedy, which means it attempts to grab one
/// more queue than the non-greedy balancers.
/// </summary>
/// <param name="overflow">number of free queues, assuming all balancers meet their minimum responsibilities</param>
/// <param name="activeSilos">number of active silos hosting queues</param>
/// <returns>bool - true indicates that the balancer should try to acquire one
/// more queue than the non-greedy balancers</returns>
private bool AmGreedy(int overflow, HashSet<SiloAddress> activeSilos)
{
// If using multiple stream providers, this will select the same silos to be greedy for
// all providers, aggravating inbalance as stream provider count increases.
// TODO: consider making this behavior configurable/plugable - jbragg
// TODO: use heap? - jbragg
return activeSilos.OrderBy(silo => silo)
.Take(overflow)
.Contains(base.SiloAddress);
}
private async Task UpdateResponsibilities(HashSet<SiloAddress> activeSilos)
{
if (base.Cancellation.IsCancellationRequested) return;
var activeSiloCount = Math.Max(1, activeSilos.Count);
this.responsibility = this.allQueuesCount / activeSiloCount;
var overflow = this.allQueuesCount % activeSiloCount;
if(overflow != 0 && this.AmGreedy(overflow, activeSilos))
{
this.responsibility++;
}
if (this.Logger.IsEnabled(LogLevel.Debug))
{
this.Logger.LogDebug("Updating Responsibilities for {QueueCount} queue over {SiloCount} silos. Need {MinQueueCount} queues, have {MyQueueCount}",
this.allQueuesCount, activeSiloCount, this.responsibility, this.myQueues.Count);
}
if (this.myQueues.Count < this.responsibility && this.leaseAquisitionTimer == null)
{
this.leaseAquisitionTimer = this.timerRegistry.RegisterTimer(
null,
this.AcquireLeasesToMeetResponsibility,
null,
this.options.LeaseAquisitionPeriod,
this.options.LeaseAquisitionPeriod);
}
if (this.leaseMaintenanceTimer == null)
{
this.leaseMaintenanceTimer = this.timerRegistry.RegisterTimer(
null,
this.MaintainLeases,
null,
this.options.LeaseRenewPeriod,
this.options.LeaseRenewPeriod);
}
await this.AcquireLeasesToMeetResponsibility();
}
}
}
| |
/*
* Copyright 2004,2006 The Poderosa Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* $Id: TerminalOptionPanel.cs,v 1.6 2012/03/17 14:53:10 kzmi Exp $
*/
using System;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Drawing;
using Poderosa.ConnectionParam;
using Poderosa.Util;
using Poderosa.UI;
using Poderosa.Usability;
using Poderosa.Preferences;
using Poderosa.Terminal;
using System.Collections.Generic;
namespace Poderosa.Forms {
internal class TerminalOptionPanel : UserControl {
private System.Windows.Forms.Label _charDecodeErrorBehaviorLabel;
private ComboBox _charDecodeErrorBehaviorBox;
private System.Windows.Forms.Label _bufferSizeLabel;
private TextBox _bufferSize;
private Label _additionalWordElementLabel;
private TextBox _additionalWordElementBox;
private Label _disconnectNotificationLabel;
private ComboBox _disconnectNotification;
private CheckBox _closeOnDisconnect;
private CheckBox _beepOnBellChar;
private CheckBox _allowsScrollInAppMode;
private CheckBox _keepAliveCheck;
private TextBox _keepAliveIntervalBox;
private Label _keepAliveLabel;
private System.Windows.Forms.GroupBox _defaultLogGroup;
private CheckBox _autoLogCheckBox;
private System.Windows.Forms.Label _defaultLogTypeLabel;
private ComboBox _defaultLogTypeBox;
private System.Windows.Forms.Label _defaultLogDirectoryLabel;
private TextBox _defaultLogDirectory;
private System.Windows.Forms.Button _dirSelect;
private GroupBox _shellSupportGroup;
private CheckBox _enableComplementForNewConnections;
private CheckBox _commandPopupAlwaysOnTop;
private GroupBox _copyAndPasteGroup;
private CheckBox _alertOnPasteNewLineCharCheck;
private CheckBox _commandPopupInTaskBar;
public TerminalOptionPanel() {
InitializeComponent();
FillText();
}
private void InitializeComponent() {
this._charDecodeErrorBehaviorLabel = new System.Windows.Forms.Label();
this._charDecodeErrorBehaviorBox = new System.Windows.Forms.ComboBox();
this._bufferSizeLabel = new System.Windows.Forms.Label();
this._bufferSize = new System.Windows.Forms.TextBox();
this._additionalWordElementLabel = new System.Windows.Forms.Label();
this._additionalWordElementBox = new System.Windows.Forms.TextBox();
this._disconnectNotificationLabel = new System.Windows.Forms.Label();
this._disconnectNotification = new System.Windows.Forms.ComboBox();
this._closeOnDisconnect = new System.Windows.Forms.CheckBox();
this._beepOnBellChar = new System.Windows.Forms.CheckBox();
this._allowsScrollInAppMode = new System.Windows.Forms.CheckBox();
this._keepAliveCheck = new System.Windows.Forms.CheckBox();
this._keepAliveIntervalBox = new System.Windows.Forms.TextBox();
this._keepAliveLabel = new System.Windows.Forms.Label();
this._defaultLogGroup = new System.Windows.Forms.GroupBox();
this._defaultLogTypeLabel = new System.Windows.Forms.Label();
this._defaultLogTypeBox = new System.Windows.Forms.ComboBox();
this._defaultLogDirectoryLabel = new System.Windows.Forms.Label();
this._defaultLogDirectory = new System.Windows.Forms.TextBox();
this._dirSelect = new System.Windows.Forms.Button();
this._autoLogCheckBox = new System.Windows.Forms.CheckBox();
this._shellSupportGroup = new System.Windows.Forms.GroupBox();
this._enableComplementForNewConnections = new System.Windows.Forms.CheckBox();
this._commandPopupAlwaysOnTop = new System.Windows.Forms.CheckBox();
this._commandPopupInTaskBar = new System.Windows.Forms.CheckBox();
this._copyAndPasteGroup = new System.Windows.Forms.GroupBox();
this._alertOnPasteNewLineCharCheck = new System.Windows.Forms.CheckBox();
this._defaultLogGroup.SuspendLayout();
this._shellSupportGroup.SuspendLayout();
this._copyAndPasteGroup.SuspendLayout();
this.SuspendLayout();
//
// _charDecodeErrorBehaviorLabel
//
this._charDecodeErrorBehaviorLabel.Location = new System.Drawing.Point(24, 8);
this._charDecodeErrorBehaviorLabel.Name = "_charDecodeErrorBehaviorLabel";
this._charDecodeErrorBehaviorLabel.Size = new System.Drawing.Size(160, 23);
this._charDecodeErrorBehaviorLabel.TabIndex = 0;
this._charDecodeErrorBehaviorLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _charDecodeErrorBehaviorBox
//
this._charDecodeErrorBehaviorBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this._charDecodeErrorBehaviorBox.Location = new System.Drawing.Point(232, 8);
this._charDecodeErrorBehaviorBox.Name = "_charDecodeErrorBehaviorBox";
this._charDecodeErrorBehaviorBox.Size = new System.Drawing.Size(152, 20);
this._charDecodeErrorBehaviorBox.TabIndex = 1;
//
// _bufferSizeLabel
//
this._bufferSizeLabel.Location = new System.Drawing.Point(24, 32);
this._bufferSizeLabel.Name = "_bufferSizeLabel";
this._bufferSizeLabel.Size = new System.Drawing.Size(96, 23);
this._bufferSizeLabel.TabIndex = 2;
this._bufferSizeLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _bufferSize
//
this._bufferSize.Location = new System.Drawing.Point(232, 32);
this._bufferSize.MaxLength = 5;
this._bufferSize.Name = "_bufferSize";
this._bufferSize.Size = new System.Drawing.Size(72, 19);
this._bufferSize.TabIndex = 3;
//
// _additionalWordElementLabel
//
this._additionalWordElementLabel.Location = new System.Drawing.Point(24, 56);
this._additionalWordElementLabel.Name = "_additionalWordElementLabel";
this._additionalWordElementLabel.Size = new System.Drawing.Size(200, 23);
this._additionalWordElementLabel.TabIndex = 4;
this._additionalWordElementLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _additionalWordElementBox
//
this._additionalWordElementBox.Location = new System.Drawing.Point(232, 56);
this._additionalWordElementBox.Name = "_additionalWordElementBox";
this._additionalWordElementBox.Size = new System.Drawing.Size(144, 19);
this._additionalWordElementBox.TabIndex = 5;
//
// _disconnectNotificationLabel
//
this._disconnectNotificationLabel.Location = new System.Drawing.Point(24, 80);
this._disconnectNotificationLabel.Name = "_disconnectNotificationLabel";
this._disconnectNotificationLabel.Size = new System.Drawing.Size(160, 23);
this._disconnectNotificationLabel.TabIndex = 6;
this._disconnectNotificationLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _disconnectNotification
//
this._disconnectNotification.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this._disconnectNotification.Location = new System.Drawing.Point(232, 80);
this._disconnectNotification.Name = "_disconnectNotification";
this._disconnectNotification.Size = new System.Drawing.Size(152, 20);
this._disconnectNotification.TabIndex = 7;
//
// _closeOnDisconnect
//
this._closeOnDisconnect.FlatStyle = System.Windows.Forms.FlatStyle.System;
this._closeOnDisconnect.Location = new System.Drawing.Point(24, 104);
this._closeOnDisconnect.Name = "_closeOnDisconnect";
this._closeOnDisconnect.Size = new System.Drawing.Size(192, 20);
this._closeOnDisconnect.TabIndex = 8;
//
// _beepOnBellChar
//
this._beepOnBellChar.FlatStyle = System.Windows.Forms.FlatStyle.System;
this._beepOnBellChar.Location = new System.Drawing.Point(24, 128);
this._beepOnBellChar.Name = "_beepOnBellChar";
this._beepOnBellChar.Size = new System.Drawing.Size(288, 20);
this._beepOnBellChar.TabIndex = 9;
//
// _allowsScrollInAppMode
//
this._allowsScrollInAppMode.FlatStyle = System.Windows.Forms.FlatStyle.System;
this._allowsScrollInAppMode.Location = new System.Drawing.Point(24, 152);
this._allowsScrollInAppMode.Name = "_allowsScrollInAppMode";
this._allowsScrollInAppMode.Size = new System.Drawing.Size(288, 20);
this._allowsScrollInAppMode.TabIndex = 11;
//
// _keepAliveCheck
//
this._keepAliveCheck.FlatStyle = System.Windows.Forms.FlatStyle.System;
this._keepAliveCheck.Location = new System.Drawing.Point(24, 176);
this._keepAliveCheck.Name = "_keepAliveCheck";
this._keepAliveCheck.Size = new System.Drawing.Size(244, 20);
this._keepAliveCheck.TabIndex = 12;
this._keepAliveCheck.CheckedChanged += new System.EventHandler(this.OnKeepAliveCheckChanged);
//
// _keepAliveIntervalBox
//
this._keepAliveIntervalBox.Location = new System.Drawing.Point(276, 176);
this._keepAliveIntervalBox.MaxLength = 2;
this._keepAliveIntervalBox.Name = "_keepAliveIntervalBox";
this._keepAliveIntervalBox.Size = new System.Drawing.Size(40, 19);
this._keepAliveIntervalBox.TabIndex = 13;
this._keepAliveIntervalBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// _keepAliveLabel
//
this._keepAliveLabel.Location = new System.Drawing.Point(316, 176);
this._keepAliveLabel.Name = "_keepAliveLabel";
this._keepAliveLabel.Size = new System.Drawing.Size(50, 20);
this._keepAliveLabel.TabIndex = 14;
this._keepAliveLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _defaultLogGroup
//
this._defaultLogGroup.Controls.Add(this._defaultLogTypeLabel);
this._defaultLogGroup.Controls.Add(this._defaultLogTypeBox);
this._defaultLogGroup.Controls.Add(this._defaultLogDirectoryLabel);
this._defaultLogGroup.Controls.Add(this._defaultLogDirectory);
this._defaultLogGroup.Controls.Add(this._dirSelect);
this._defaultLogGroup.FlatStyle = System.Windows.Forms.FlatStyle.System;
this._defaultLogGroup.Location = new System.Drawing.Point(16, 204);
this._defaultLogGroup.Name = "_defaultLogGroup";
this._defaultLogGroup.Size = new System.Drawing.Size(392, 76);
this._defaultLogGroup.TabIndex = 16;
this._defaultLogGroup.TabStop = false;
//
// _defaultLogTypeLabel
//
this._defaultLogTypeLabel.Location = new System.Drawing.Point(8, 20);
this._defaultLogTypeLabel.Name = "_defaultLogTypeLabel";
this._defaultLogTypeLabel.Size = new System.Drawing.Size(96, 23);
this._defaultLogTypeLabel.TabIndex = 16;
this._defaultLogTypeLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _defaultLogTypeBox
//
this._defaultLogTypeBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this._defaultLogTypeBox.Location = new System.Drawing.Point(128, 20);
this._defaultLogTypeBox.Name = "_defaultLogTypeBox";
this._defaultLogTypeBox.Size = new System.Drawing.Size(176, 20);
this._defaultLogTypeBox.TabIndex = 17;
//
// _defaultLogDirectoryLabel
//
this._defaultLogDirectoryLabel.Location = new System.Drawing.Point(8, 48);
this._defaultLogDirectoryLabel.Name = "_defaultLogDirectoryLabel";
this._defaultLogDirectoryLabel.Size = new System.Drawing.Size(112, 23);
this._defaultLogDirectoryLabel.TabIndex = 18;
this._defaultLogDirectoryLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _defaultLogDirectory
//
this._defaultLogDirectory.Location = new System.Drawing.Point(128, 48);
this._defaultLogDirectory.Name = "_defaultLogDirectory";
this._defaultLogDirectory.Size = new System.Drawing.Size(176, 19);
this._defaultLogDirectory.TabIndex = 19;
//
// _dirSelect
//
this._dirSelect.FlatStyle = System.Windows.Forms.FlatStyle.System;
this._dirSelect.Location = new System.Drawing.Point(312, 48);
this._dirSelect.Name = "_dirSelect";
this._dirSelect.Size = new System.Drawing.Size(19, 19);
this._dirSelect.TabIndex = 20;
this._dirSelect.Text = "...";
this._dirSelect.Click += new System.EventHandler(this.OnSelectLogDirectory);
//
// _autoLogCheckBox
//
this._autoLogCheckBox.Checked = true;
this._autoLogCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this._autoLogCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System;
this._autoLogCheckBox.Location = new System.Drawing.Point(24, 200);
this._autoLogCheckBox.Name = "_autoLogCheckBox";
this._autoLogCheckBox.Size = new System.Drawing.Size(200, 24);
this._autoLogCheckBox.TabIndex = 15;
this._autoLogCheckBox.CheckedChanged += new System.EventHandler(this.OnAutoLogCheckBoxClick);
//
// _shellSupportGroup
//
this._shellSupportGroup.Controls.Add(this._enableComplementForNewConnections);
this._shellSupportGroup.Controls.Add(this._commandPopupAlwaysOnTop);
this._shellSupportGroup.Controls.Add(this._commandPopupInTaskBar);
this._shellSupportGroup.FlatStyle = System.Windows.Forms.FlatStyle.System;
this._shellSupportGroup.Location = new System.Drawing.Point(16, 284);
this._shellSupportGroup.Name = "_shellSupportGroup";
this._shellSupportGroup.Size = new System.Drawing.Size(392, 86);
this._shellSupportGroup.TabIndex = 17;
this._shellSupportGroup.TabStop = false;
//
// _enableComplementForNewConnections
//
this._enableComplementForNewConnections.FlatStyle = System.Windows.Forms.FlatStyle.System;
this._enableComplementForNewConnections.Location = new System.Drawing.Point(8, 12);
this._enableComplementForNewConnections.Name = "_enableComplementForNewConnections";
this._enableComplementForNewConnections.Size = new System.Drawing.Size(375, 24);
this._enableComplementForNewConnections.TabIndex = 21;
//
// _commandPopupAlwaysOnTop
//
this._commandPopupAlwaysOnTop.FlatStyle = System.Windows.Forms.FlatStyle.System;
this._commandPopupAlwaysOnTop.Location = new System.Drawing.Point(8, 34);
this._commandPopupAlwaysOnTop.Name = "_commandPopupAlwaysOnTop";
this._commandPopupAlwaysOnTop.Size = new System.Drawing.Size(375, 24);
this._commandPopupAlwaysOnTop.TabIndex = 22;
//
// _commandPopupInTaskBar
//
this._commandPopupInTaskBar.FlatStyle = System.Windows.Forms.FlatStyle.System;
this._commandPopupInTaskBar.Location = new System.Drawing.Point(8, 56);
this._commandPopupInTaskBar.Name = "_commandPopupInTaskBar";
this._commandPopupInTaskBar.Size = new System.Drawing.Size(375, 24);
this._commandPopupInTaskBar.TabIndex = 23;
//
// _copyAndPasteGroup
//
this._copyAndPasteGroup.Controls.Add(this._alertOnPasteNewLineCharCheck);
this._copyAndPasteGroup.FlatStyle = System.Windows.Forms.FlatStyle.System;
this._copyAndPasteGroup.Location = new System.Drawing.Point(16, 374);
this._copyAndPasteGroup.Name = "_copyAndPasteGroup";
this._copyAndPasteGroup.Size = new System.Drawing.Size(392, 42);
this._copyAndPasteGroup.TabIndex = 18;
this._copyAndPasteGroup.TabStop = false;
//
// _alertOnPasteNewLineCharCheck
//
this._alertOnPasteNewLineCharCheck.FlatStyle = System.Windows.Forms.FlatStyle.System;
this._alertOnPasteNewLineCharCheck.Location = new System.Drawing.Point(8, 12);
this._alertOnPasteNewLineCharCheck.Name = "_alertOnPasteNewLineCharCheck";
this._alertOnPasteNewLineCharCheck.Size = new System.Drawing.Size(375, 24);
this._alertOnPasteNewLineCharCheck.TabIndex = 0;
this._alertOnPasteNewLineCharCheck.UseVisualStyleBackColor = true;
//
// TerminalOptionPanel
//
this.BackColor = System.Drawing.SystemColors.Window;
this.Controls.Add(this._copyAndPasteGroup);
this.Controls.Add(this._charDecodeErrorBehaviorLabel);
this.Controls.Add(this._charDecodeErrorBehaviorBox);
this.Controls.Add(this._bufferSizeLabel);
this.Controls.Add(this._bufferSize);
this.Controls.Add(this._additionalWordElementLabel);
this.Controls.Add(this._additionalWordElementBox);
this.Controls.Add(this._disconnectNotificationLabel);
this.Controls.Add(this._disconnectNotification);
this.Controls.Add(this._closeOnDisconnect);
this.Controls.Add(this._beepOnBellChar);
this.Controls.Add(this._allowsScrollInAppMode);
this.Controls.Add(this._autoLogCheckBox);
this.Controls.Add(this._keepAliveCheck);
this.Controls.Add(this._keepAliveIntervalBox);
this.Controls.Add(this._keepAliveLabel);
this.Controls.Add(this._defaultLogGroup);
this.Controls.Add(this._shellSupportGroup);
this.Name = "TerminalOptionPanel";
this.Size = new System.Drawing.Size(426, 423);
this._defaultLogGroup.ResumeLayout(false);
this._defaultLogGroup.PerformLayout();
this._shellSupportGroup.ResumeLayout(false);
this._copyAndPasteGroup.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
private void FillText() {
StringResource sr = OptionDialogPlugin.Instance.Strings;
this._charDecodeErrorBehaviorLabel.Text = sr.GetString("Form.OptionDialog._charDecodeErrorBehaviorLabel");
this._bufferSizeLabel.Text = sr.GetString("Form.OptionDialog._bufferSizeLabel");
this._disconnectNotificationLabel.Text = sr.GetString("Form.OptionDialog._disconnectNotificationLabel");
this._closeOnDisconnect.Text = sr.GetString("Form.OptionDialog._closeOnDisconnect");
this._beepOnBellChar.Text = sr.GetString("Form.OptionDialog._beepOnBellChar");
this._allowsScrollInAppMode.Text = sr.GetString("Form.OptionDialog._allowsScrollInAppMode");
this._keepAliveCheck.Text = sr.GetString("Form.OptionDialog._keepAliveCheck");
this._keepAliveLabel.Text = sr.GetString("Form.OptionDialog._keepAliveLabel");
this._defaultLogTypeLabel.Text = sr.GetString("Form.OptionDialog._defaultLogTypeLabel");
this._defaultLogDirectoryLabel.Text = sr.GetString("Form.OptionDialog._defaultLogDirectoryLabel");
this._autoLogCheckBox.Text = sr.GetString("Form.OptionDialog._autoLogCheckBox");
this._additionalWordElementLabel.Text = sr.GetString("Form.OptionDialog._additionalWordElementLabel");
this._shellSupportGroup.Text = sr.GetString("Form.OptionDialog._shellSupportGroup");
this._enableComplementForNewConnections.Text = sr.GetString("Form.OptionDialog._enableComplementForNewConnections");
this._commandPopupAlwaysOnTop.Text = sr.GetString("Form.OptionDialog._commandPopupAlwaysOnTop");
this._commandPopupInTaskBar.Text = sr.GetString("Form.OptionDialog._commandPopupInTaskBar");
this._alertOnPasteNewLineCharCheck.Text = sr.GetString("Form.OptionDialog._alertOnPasteNewLineCharCheck");
_charDecodeErrorBehaviorBox.Items.AddRange(EnumListItem<WarningOption>.GetListItems());
_disconnectNotification.Items.AddRange(EnumListItem<WarningOption>.GetListItems());
_defaultLogTypeBox.Items.AddRange(EnumListItem<LogType>.GetListItemsExcept(LogType.None));
}
public void InitUI(ITerminalEmulatorOptions options) {
_bufferSize.Text = options.TerminalBufferSize.ToString();
_closeOnDisconnect.Checked = options.CloseOnDisconnect;
_disconnectNotification.SelectedItem = options.DisconnectNotification; // select EnumListItem<T> by T
_beepOnBellChar.Checked = options.BeepOnBellChar;
_charDecodeErrorBehaviorBox.SelectedItem = options.CharDecodeErrorBehavior; // select EnumListItem<T> by T
_allowsScrollInAppMode.Checked = options.AllowsScrollInAppMode;
_keepAliveCheck.Checked = options.KeepAliveInterval != 0;
_keepAliveIntervalBox.Enabled = _keepAliveCheck.Checked;
_keepAliveIntervalBox.Text = (options.KeepAliveInterval / 60000).ToString();
_autoLogCheckBox.Checked = options.DefaultLogType != LogType.None;
_defaultLogTypeBox.SelectedItem = options.DefaultLogType; // select EnumListItem<T> by T
_defaultLogDirectory.Text = options.DefaultLogDirectory;
_additionalWordElementBox.Text = options.AdditionalWordElement;
_enableComplementForNewConnections.Checked = options.EnableComplementForNewConnections;
_commandPopupAlwaysOnTop.Checked = options.CommandPopupAlwaysOnTop;
_commandPopupInTaskBar.Checked = options.CommandPopupInTaskBar;
_alertOnPasteNewLineCharCheck.Checked = options.AlertOnPasteNewLineChar;
}
public bool Commit(ITerminalEmulatorOptions options) {
StringResource sr = OptionDialogPlugin.Instance.Strings;
bool successful = false;
string itemname = null;
try {
options.CloseOnDisconnect = _closeOnDisconnect.Checked;
options.BeepOnBellChar = _beepOnBellChar.Checked;
options.AllowsScrollInAppMode = _allowsScrollInAppMode.Checked;
itemname = sr.GetString("Caption.OptionDialog.BufferLineCount");
options.TerminalBufferSize = Int32.Parse(_bufferSize.Text);
itemname = sr.GetString("Caption.OptionDialog.MRUCount");
options.CharDecodeErrorBehavior = ((EnumListItem<WarningOption>)_charDecodeErrorBehaviorBox.SelectedItem).Value;
options.DisconnectNotification = ((EnumListItem<WarningOption>)_disconnectNotification.SelectedItem).Value;
if (_keepAliveCheck.Checked) {
itemname = sr.GetString("Caption.OptionDialog.KeepAliveInterval");
options.KeepAliveInterval = Int32.Parse(_keepAliveIntervalBox.Text) * 60000;
}
else
options.KeepAliveInterval = 0;
foreach (char ch in _additionalWordElementBox.Text) {
if (ch >= 0x100) {
GUtil.Warning(this, sr.GetString("Message.OptionDialog.InvalidAdditionalWordElement"));
return false;
}
}
options.AdditionalWordElement = _additionalWordElementBox.Text;
if (_autoLogCheckBox.Checked) {
if (_defaultLogDirectory.Text.Length == 0) {
GUtil.Warning(this, sr.GetString("Message.OptionDialog.EmptyLogDirectory"));
return false;
}
options.DefaultLogType = ((EnumListItem<LogType>)_defaultLogTypeBox.SelectedItem).Value;
if (!Directory.Exists(_defaultLogDirectory.Text)) {
if (GUtil.AskUserYesNo(this, String.Format(sr.GetString("Message.OptionDialog.AskCreateDirectory"), _defaultLogDirectory.Text)) == DialogResult.Yes) {
try {
System.IO.Directory.CreateDirectory(_defaultLogDirectory.Text);
}
catch (Exception) {
GUtil.Warning(this, String.Format(sr.GetString("Message.OptionDialog.FailedCreateDirectory")));
}
}
else
return false;
}
options.DefaultLogDirectory = _defaultLogDirectory.Text;
}
else
options.DefaultLogType = LogType.None;
options.EnableComplementForNewConnections = _enableComplementForNewConnections.Checked;
options.CommandPopupAlwaysOnTop = _commandPopupAlwaysOnTop.Checked;
options.CommandPopupInTaskBar = _commandPopupInTaskBar.Checked;
options.AlertOnPasteNewLineChar = _alertOnPasteNewLineCharCheck.Checked;
successful = true;
}
catch (InvalidOptionException ex) {
GUtil.Warning(this, ex.Message);
}
catch (Exception) {
GUtil.Warning(this, String.Format(sr.GetString("Message.OptionDialog.InvalidItem"), itemname));
}
return successful;
}
private void OnSelectLogDirectory(object sender, EventArgs e) {
StringResource sr = OptionDialogPlugin.Instance.Strings;
FolderBrowserDialog dlg = new FolderBrowserDialog();
dlg.ShowNewFolderButton = true;
dlg.Description = sr.GetString("Caption.OptionDialog.DefaultLogDirectory");
if (_defaultLogDirectory.Text.Length > 0 && Directory.Exists(_defaultLogDirectory.Text))
dlg.SelectedPath = _defaultLogDirectory.Text;
if (dlg.ShowDialog(this) == DialogResult.OK)
_defaultLogDirectory.Text = dlg.SelectedPath;
}
private void OnAutoLogCheckBoxClick(object sender, EventArgs args) {
bool e = _autoLogCheckBox.Checked;
_defaultLogTypeBox.Enabled = e;
if (_defaultLogTypeBox.SelectedIndex == -1)
_defaultLogTypeBox.SelectedIndex = 0;
_defaultLogDirectory.Enabled = e;
_dirSelect.Enabled = e;
}
private void OnKeepAliveCheckChanged(object sender, EventArgs args) {
_keepAliveIntervalBox.Enabled = _keepAliveCheck.Checked;
}
}
internal class TerminalOptionPanelExtension : OptionPanelExtensionBase {
private TerminalOptionPanel _innerPanel;
private Control _panel;
public TerminalOptionPanelExtension()
: base("Form.OptionDialog._terminalPanel", 1) {
}
public override string[] PreferenceFolderIDsToEdit {
get {
return new string[] { "org.poderosa.terminalemulator" };
}
}
public override Control ContentPanel {
get {
return _panel;
}
}
public override void InitiUI(IPreferenceFolder[] values) {
if (_innerPanel == null)
_innerPanel = new TerminalOptionPanel();
if (_panel == null)
_panel = CreateScrollablePanel(_innerPanel);
_innerPanel.InitUI((ITerminalEmulatorOptions)values[0].QueryAdapter(typeof(ITerminalEmulatorOptions)));
}
public override bool Commit(IPreferenceFolder[] values) {
Debug.Assert(_innerPanel != null);
return _innerPanel.Commit((ITerminalEmulatorOptions)values[0].QueryAdapter(typeof(ITerminalEmulatorOptions)));
}
public override void Dispose() {
if (_panel != null) {
if (_panel.Container == null)
_panel.Dispose();
_panel = null;
_innerPanel = null;
}
}
}
}
| |
// CRC32.cs - Computes CRC32 data checksum of a data stream
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
namespace ICSharpCode.SharpZipLib.Checksums
{
/// <summary>
/// Generate a table for a byte-wise 32-bit CRC calculation on the polynomial:
/// x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
///
/// Polynomials over GF(2) are represented in binary, one bit per coefficient,
/// with the lowest powers in the most significant bit. Then adding polynomials
/// is just exclusive-or, and multiplying a polynomial by x is a right shift by
/// one. If we call the above polynomial p, and represent a byte as the
/// polynomial q, also with the lowest power in the most significant bit (so the
/// byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
/// where a mod b means the remainder after dividing a by b.
///
/// This calculation is done using the shift-register method of multiplying and
/// taking the remainder. The register is initialized to zero, and for each
/// incoming bit, x^32 is added mod p to the register if the bit is a one (where
/// x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
/// x (which is shifting right by one and adding x^32 mod p if the bit shifted
/// out is a one). We start with the highest power (least significant bit) of
/// q and repeat for all eight bits of q.
///
/// The table is simply the CRC of all possible eight bit values. This is all
/// the information needed to generate CRC's on data a byte at a time for all
/// combinations of CRC register values and incoming bytes.
/// </summary>
public sealed class Crc32 : IChecksum
{
const uint CrcSeed = 0xFFFFFFFF;
readonly static uint[] CrcTable = new uint[] {
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419,
0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4,
0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07,
0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856,
0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,
0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4,
0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3,
0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A,
0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599,
0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190,
0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F,
0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E,
0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED,
0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950,
0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3,
0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A,
0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5,
0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010,
0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17,
0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6,
0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615,
0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344,
0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,
0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A,
0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1,
0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C,
0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF,
0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE,
0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31,
0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C,
0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B,
0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,
0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1,
0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278,
0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7,
0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66,
0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605,
0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8,
0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B,
0x2D02EF8D
};
internal static uint ComputeCrc32(uint oldCrc, byte value)
{
return (uint)(Crc32.CrcTable[(oldCrc ^ value) & 0xFF] ^ (oldCrc >> 8));
}
/// <summary>
/// The crc data checksum so far.
/// </summary>
uint crc;
/// <summary>
/// Returns the CRC32 data checksum computed so far.
/// </summary>
public long Value {
get {
return (long)crc;
}
set {
crc = (uint)value;
}
}
/// <summary>
/// Resets the CRC32 data checksum as if no update was ever called.
/// </summary>
public void Reset()
{
crc = 0;
}
/// <summary>
/// Updates the checksum with the int bval.
/// </summary>
/// <param name = "value">
/// the byte is taken as the lower 8 bits of value
/// </param>
public void Update(int value)
{
crc ^= CrcSeed;
crc = CrcTable[(crc ^ value) & 0xFF] ^ (crc >> 8);
crc ^= CrcSeed;
}
/// <summary>
/// Updates the checksum with the bytes taken from the array.
/// </summary>
/// <param name="buffer">
/// buffer an array of bytes
/// </param>
public void Update(byte[] buffer)
{
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
Update(buffer, 0, buffer.Length);
}
/// <summary>
/// Adds the byte array to the data checksum.
/// </summary>
/// <param name = "buffer">
/// The buffer which contains the data
/// </param>
/// <param name = "offset">
/// The offset in the buffer where the data starts
/// </param>
/// <param name = "count">
/// The number of data bytes to update the CRC with.
/// </param>
public void Update(byte[] buffer, int offset, int count)
{
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
if ( count < 0 ) {
#if NETCF_1_0 || UNITY_WINRT
throw new ArgumentOutOfRangeException("count");
#else
throw new ArgumentOutOfRangeException("count", "Count cannot be less than zero");
#endif
}
if (offset < 0 || offset + count > buffer.Length) {
throw new ArgumentOutOfRangeException("offset");
}
crc ^= CrcSeed;
while (--count >= 0) {
crc = CrcTable[(crc ^ buffer[offset++]) & 0xFF] ^ (crc >> 8);
}
crc ^= CrcSeed;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Correspondence.Mementos;
using Correspondence.Queries;
using Correspondence.Strategy;
using Correspondence.Conditions;
using System.Threading.Tasks;
using Assisticant.Fields;
using Correspondence.Debugging;
using Correspondence.WorkQueues;
using Correspondence.Threading;
namespace Correspondence
{
class Model
{
public const short MaxDataLength = 1024;
private const long ClientDatabaseId = 0;
private readonly Community _community;
private readonly IStorageStrategy _storageStrategy;
private readonly IWorkQueue _workQueue;
private bool _clientApp = true;
private IDictionary<CorrespondenceFactType, ICorrespondenceFactFactory> _factoryByType =
new Dictionary<CorrespondenceFactType, ICorrespondenceFactFactory>();
private IDictionary<CorrespondenceFactType, List<QueryInvalidator>> _queryInvalidatorsByType =
new Dictionary<CorrespondenceFactType, List<QueryInvalidator>>();
private IDictionary<CorrespondenceFactType, List<Unpublisher>> _unpublishersByType =
new Dictionary<CorrespondenceFactType, List<Unpublisher>>();
private IDictionary<CorrespondenceFactType, FactMetadata> _metadataByFactType = new Dictionary<CorrespondenceFactType, FactMetadata>();
private IDictionary<FactID, CorrespondenceFact> _factByID = new Dictionary<FactID, CorrespondenceFact>();
private IDictionary<FactMemento, CorrespondenceFact> _factByMemento = new Dictionary<FactMemento, CorrespondenceFact>();
private IDictionary<FactMemento, Observable<CorrespondenceFact>> _findFactByMemento = new Dictionary<FactMemento, Observable<CorrespondenceFact>>();
private Observable<Exception> _lastException = new Observable<Exception>();
public event Action<CorrespondenceFact> FactAdded;
public event Action FactReceived;
public AsyncSemaphore _lock = new AsyncSemaphore();
public Model(Community community, IStorageStrategy storageStrategy, IWorkQueue workQueue)
{
_community = community;
_storageStrategy = storageStrategy;
_workQueue = workQueue;
}
public bool ClientApp
{
get { return _clientApp; }
set { _clientApp = value; }
}
public void AddType(CorrespondenceFactType type, ICorrespondenceFactFactory factory, FactMetadata factMetadata)
{
_factoryByType[type] = factory;
_metadataByFactType.Add(type, factMetadata);
}
public void AddQuery(CorrespondenceFactType type, QueryDefinition query)
{
// Invert the query.
new QueryInverter(type, delegate(CorrespondenceFactType targetType, QueryDefinition inverse)
{
// Record the inverse as a query invalidator by the target type.
List<QueryInvalidator> invalidators;
if (!_queryInvalidatorsByType.TryGetValue(targetType, out invalidators))
{
invalidators = new List<QueryInvalidator>();
_queryInvalidatorsByType.Add(targetType, invalidators);
}
invalidators.Add(new QueryInvalidator(inverse, query));
})
.InvertQuery(query.Joins);
}
public void AddUnpublisher(RoleMemento role, Condition publishCondition)
{
// Invert the query.
var queryInverter = new QueryInverter(role.DeclaringType, delegate(CorrespondenceFactType targetType, QueryDefinition inverse)
{
// Record the inverse as an unpublisher by the target type.
List<Unpublisher> unpublishers;
if (!_unpublishersByType.TryGetValue(targetType, out unpublishers))
{
unpublishers = new List<Unpublisher>();
_unpublishersByType.Add(targetType, unpublishers);
}
unpublishers.Add(new Unpublisher(inverse, publishCondition, role));
});
queryInverter.HandleCondition(publishCondition);
}
public async Task<T> AddFactAsync<T>(T prototype) where T : CorrespondenceFact
{
return await AddFactAsync<T>(prototype, 0);
}
private async Task<T> AddFactAsync<T>(T prototype, int peerId) where T : CorrespondenceFact
{
// Save invalidate actions until after the lock
// because they reenter if a fact is removed.
Dictionary<InvalidatedQuery, InvalidatedQuery> invalidatedQueries = new Dictionary<InvalidatedQuery, InvalidatedQuery>();
await _lock.WaitAsync();
try
{
if (prototype.InternalCommunity != null)
throw new CorrespondenceException("A fact may only belong to one community");
foreach (RoleMemento role in prototype.PredecessorRoles)
{
PredecessorBase predecessor = prototype.GetPredecessor(role);
if (predecessor.Community != null && predecessor.Community != _community)
throw new CorrespondenceException("A fact cannot be added to a different community than its predecessors.");
}
FactMemento memento = CreateMementoFromFact(prototype);
// See if we already have the fact in memory.
CorrespondenceFact fact;
if (_factByMemento.TryGetValue(memento, out fact))
return (T)fact;
FactID id = await AddFactMementoAsync(peerId, memento, invalidatedQueries);
// Turn the prototype into the real fact.
prototype.ID = id;
prototype.SetCommunity(_community);
_factByID.Add(prototype.ID, prototype);
_factByMemento.Add(memento, prototype);
}
finally
{
_lock.Release();
}
foreach (InvalidatedQuery invalidatedQuery in invalidatedQueries.Keys)
invalidatedQuery.Invalidate();
if (FactAdded != null)
FactAdded(prototype);
return prototype;
}
public T FindFact<T>(T prototype)
where T : CorrespondenceFact
{
lock (this)
{
ICorrespondenceFactFactory factory;
FactMemento memento = CreateMementoFromFact(prototype, out factory);
Observable<CorrespondenceFact> independent;
if (!_findFactByMemento.TryGetValue(memento, out independent))
{
var completion = new TaskCompletionSource<CorrespondenceFact>();
CorrespondenceFact fact = factory.GetUnloadedInstance();
fact.SetLoadedTask(completion.Task);
independent = new Observable<CorrespondenceFact>(fact);
_findFactByMemento.Add(memento, independent);
_workQueue.Perform(() =>
FindFactAndStoreAsync(
memento, prototype, factory, independent, completion));
}
return (T)independent.Value;
}
}
public async Task<CorrespondenceFact> LoadFactAsync(string factName)
{
await _lock.WaitAsync();
try
{
FactID? id = await _storageStrategy.GetIDAsync(factName);
if (id.HasValue)
return await GetFactByIDInternalAsync(id.Value);
else
return null;
}
finally
{
_lock.Release();
}
}
public async Task SetFactAsync(string factName, CorrespondenceFact obj)
{
await _lock.WaitAsync();
try
{
await _storageStrategy.SetIDAsync(factName, obj.ID);
}
finally
{
_lock.Release();
}
}
public async Task<GetResultMemento> GetMessageBodiesAsync(TimestampID timestamp, int peerId, List<UnpublishMemento> unpublishedMessages)
{
await _lock.WaitAsync();
try
{
FactTreeMemento result = new FactTreeMemento(ClientDatabaseId);
IEnumerable<MessageMemento> recentMessages = await _storageStrategy.LoadRecentMessagesForServerAsync(peerId, timestamp);
foreach (MessageMemento message in recentMessages)
{
if (message.FactId.key > timestamp.Key)
timestamp = new TimestampID(ClientDatabaseId, message.FactId.key);
FactMemento newFact = await AddToFactTreeInternalAsync(result, message.FactId, peerId);
FactMetadata factMetadata;
if (newFact != null && _metadataByFactType.TryGetValue(newFact.FactType, out factMetadata))
{
IEnumerable<CorrespondenceFactType> convertableTypes = factMetadata.ConvertableTypes;
foreach (CorrespondenceFactType convertableType in convertableTypes)
{
List<Unpublisher> unpublishers;
if (_unpublishersByType.TryGetValue(convertableType, out unpublishers))
{
foreach (Unpublisher unpublisher in unpublishers)
{
IEnumerable<FactID> messageIds = await _storageStrategy.QueryForIdsAsync(unpublisher.MessageFacts, message.FactId);
foreach (FactID messageId in messageIds)
{
ConditionEvaluator conditionEvaluator = new ConditionEvaluator(_storageStrategy);
bool published = await conditionEvaluator.EvaluateAsync(messageId, unpublisher.PublishCondition);
if (!published)
{
await AddToFactTreeInternalAsync(result, messageId, peerId);
UnpublishMemento unpublishMemento = new UnpublishMemento(messageId, unpublisher.Role);
if (!unpublishedMessages.Contains(unpublishMemento))
unpublishedMessages.Add(unpublishMemento);
}
}
}
}
}
}
}
return new GetResultMemento(result, timestamp);
}
finally
{
_lock.Release();
}
}
public async Task<FactMemento> AddToFactTreeAsync(FactTreeMemento messageBody, FactID factId, int peerId)
{
await _lock.WaitAsync();
try
{
return await AddToFactTreeInternalAsync(messageBody, factId, peerId);
}
finally
{
_lock.Release();
}
}
public async Task ReceiveMessage(FactTreeMemento messageBody, int peerId)
{
Dictionary<InvalidatedQuery, InvalidatedQuery> invalidatedQueries = new Dictionary<InvalidatedQuery, InvalidatedQuery>();
await _lock.WaitAsync();
try
{
IDictionary<FactID, FactID> localIdByRemoteId = new Dictionary<FactID, FactID>();
foreach (IdentifiedFactBase identifiedFact in messageBody.Facts)
{
FactID localId = await ReceiveFactAsync(identifiedFact, peerId, invalidatedQueries, localIdByRemoteId);
FactID remoteId = identifiedFact.Id;
localIdByRemoteId.Add(remoteId, localId);
}
}
finally
{
_lock.Release();
}
foreach (InvalidatedQuery invalidatedQuery in invalidatedQueries.Keys)
invalidatedQuery.Invalidate();
}
private async Task<FactID> ReceiveFactAsync(IdentifiedFactBase identifiedFact, int peerId, Dictionary<InvalidatedQuery, InvalidatedQuery> invalidatedQueries, IDictionary<FactID, FactID> localIdByRemoteId)
{
if (identifiedFact is IdentifiedFactMemento)
{
IdentifiedFactMemento identifiedFactMemento = (IdentifiedFactMemento)identifiedFact;
FactMemento translatedMemento = new FactMemento(identifiedFactMemento.Memento.FactType);
translatedMemento.Data = identifiedFactMemento.Memento.Data;
translatedMemento.AddPredecessors(identifiedFactMemento.Memento.Predecessors
.Select(remote =>
{
FactID localFactId;
return !localIdByRemoteId.TryGetValue(remote.ID, out localFactId)
? null
: new PredecessorMemento(remote.Role, localFactId, remote.IsPivot);
})
.Where(pred => pred != null));
FactID localId = await AddFactMementoAsync(peerId, translatedMemento, invalidatedQueries);
await _storageStrategy.SaveShareAsync(peerId, identifiedFact.Id, localId);
return localId;
}
else
{
IdentifiedFactRemote identifiedFactRemote = (IdentifiedFactRemote)identifiedFact;
return await _storageStrategy.GetFactIDFromShareAsync(peerId, identifiedFactRemote.RemoteId);
}
}
public async Task<CorrespondenceFact> GetFactByIDAsync(FactID id)
{
await _lock.WaitAsync();
try
{
return await GetFactByIDInternalAsync(id);
}
finally
{
_lock.Release();
}
}
public async Task<Guid> GetClientDatabaseGuidAsync()
{
await _lock.WaitAsync();
try
{
return await _storageStrategy.GetClientGuidAsync();
}
finally
{
_lock.Release();
}
}
internal async Task<List<CorrespondenceFact>> ExecuteQueryAsync(QueryDefinition queryDefinition, FactID startingId, QueryOptions options)
{
await _lock.WaitAsync();
try
{
List<IdentifiedFactMemento> facts = await _storageStrategy.QueryForFactsAsync(queryDefinition, startingId, options);
return facts
.Select(m => GetFactByIdAndMemento(m.Id, m.Memento))
.Where(m => m != null)
.ToList();
}
finally
{
_lock.Release();
}
}
private async Task<CorrespondenceFact> GetFactByIDInternalAsync(FactID id)
{
// Check for null.
if (id.key == 0)
return null;
// See if the object is already loaded.
CorrespondenceFact obj;
if (_factByID.TryGetValue(id, out obj))
return obj;
// If not, load it from storage.
FactMemento memento = await _storageStrategy.LoadAsync(id);
return CreateFactFromMemento(id, memento);
}
private async Task<FactMemento> AddToFactTreeInternalAsync(FactTreeMemento messageBody, FactID factId, int peerId)
{
if (!messageBody.Contains(factId))
{
CorrespondenceFact fact = await GetFactByIDInternalAsync(factId);
if (fact != null)
{
FactID? remoteId = await _storageStrategy.GetRemoteIdAsync(factId, peerId);
if (remoteId.HasValue)
{
messageBody.Add(new IdentifiedFactRemote(factId, remoteId.Value));
}
else
{
FactMemento factMemento = CreateMementoFromFact(fact);
foreach (PredecessorMemento predecessor in factMemento.Predecessors)
await AddToFactTreeInternalAsync(messageBody, predecessor.ID, peerId);
messageBody.Add(new IdentifiedFactMemento(factId, factMemento));
return factMemento;
}
}
return null;
}
else
{
IdentifiedFactBase identifiedFact = messageBody.Get(factId);
if (identifiedFact is IdentifiedFactMemento)
return ((IdentifiedFactMemento)identifiedFact).Memento;
else
return null;
}
}
private CorrespondenceFact GetFactByIdAndMemento(FactID id, FactMemento memento)
{
// Check for null.
if (id.key == 0)
return null;
// See if the fact is already loaded.
CorrespondenceFact fact;
if (_factByID.TryGetValue(id, out fact))
return fact;
// If not, create it from the memento.
return CreateFactFromMemento(id, memento);
}
private CorrespondenceFact CreateFactFromMemento(FactID id, FactMemento memento)
{
try
{
ClearException();
System.Diagnostics.Debug.Assert(
!_factByMemento.ContainsKey(memento),
"A memento already in memory is being reloaded");
// Invoke the factory to create the object.
if (memento == null)
throw new CorrespondenceException("Failed to load fact");
CorrespondenceFact fact = HydrateFact(memento);
fact.ID = id;
fact.SetCommunity(_community);
_factByID.Add(fact.ID, fact);
_factByMemento.Add(memento, fact);
return fact;
}
catch (Exception ex)
{
HandleException(ex);
return null;
}
}
private CorrespondenceFact HydrateFact(FactMemento memento)
{
ICorrespondenceFactFactory factory;
if (!_factoryByType.TryGetValue(memento.FactType, out factory))
throw new CorrespondenceException(string.Format("Unknown type: {0}", memento.FactType));
CorrespondenceFact fact = factory.CreateFact(memento);
if (fact == null)
throw new CorrespondenceException("Failed to create fact");
return fact;
}
private FactMemento CreateMementoFromFact(CorrespondenceFact prototype)
{
ICorrespondenceFactFactory factory;
return CreateMementoFromFact(prototype, out factory);
}
private FactMemento CreateMementoFromFact(CorrespondenceFact prototype, out ICorrespondenceFactFactory factory)
{
// Get the type of the object.
CorrespondenceFactType type = prototype.GetCorrespondenceFactType();
// Find the factory for that type.
if (!_factoryByType.TryGetValue(type, out factory))
throw new CorrespondenceException(string.Format("Add the type {0} or the assembly that contains it to the community.", type));
// Create the memento.
FactMemento memento = new FactMemento(type);
foreach (RoleMemento role in prototype.PredecessorRoles)
{
PredecessorBase predecessor = prototype.GetPredecessor(role);
foreach (FactID id in predecessor.InternalFactIds)
memento.AddPredecessor(role, id, role.IsPivot);
}
using (MemoryStream data = new MemoryStream())
{
using (BinaryWriter output = new BinaryWriter(data))
{
factory.WriteFactData(prototype, output);
}
memento.Data = data.ToArray();
if (memento.Data.Length > MaxDataLength)
throw new CorrespondenceException(string.Format("Fact data length {0} exceeded the maximum bytes allowable ({1}).", memento.Data.Length, Model.MaxDataLength));
}
return memento;
}
private async Task<FactID> AddFactMementoAsync(int peerId, FactMemento memento, Dictionary<InvalidatedQuery, InvalidatedQuery> invalidatedQueries)
{
// Set the ID and add the object to the community.
var result = await _storageStrategy.SaveAsync(memento, peerId);
FactID id = result.Id;
if (result.WasSaved)
{
// Invalidate all of the queries affected by the new object.
List<QueryInvalidator> invalidators;
FactMetadata metadata;
if (_metadataByFactType.TryGetValue(memento.FactType, out metadata))
{
foreach (CorrespondenceFactType factType in metadata.ConvertableTypes)
if (_queryInvalidatorsByType.TryGetValue(factType, out invalidators))
{
foreach (QueryInvalidator invalidator in invalidators)
{
List<FactID> targetFactIds;
if (invalidator.TargetFacts.CanExecuteFromMemento)
// If the inverse query is simple, the results are already in the memento.
targetFactIds = invalidator.TargetFacts.ExecuteFromMemento(memento);
else
// The query is more complex, so go to the storage strategy.
targetFactIds = (await _storageStrategy.QueryForIdsAsync(invalidator.TargetFacts, id)).ToList();
foreach (FactID targetObjectId in targetFactIds)
{
CorrespondenceFact targetObject;
if (_factByID.TryGetValue(targetObjectId, out targetObject))
{
QueryDefinition invalidQuery = invalidator.InvalidQuery;
InvalidatedQuery query = new InvalidatedQuery(targetObject, invalidQuery);
if (!invalidatedQueries.ContainsKey(query))
invalidatedQueries.Add(query, query);
}
}
}
}
}
if (FactReceived != null)
FactReceived();
}
return id;
}
private async Task FindFactAndStoreAsync(FactMemento memento, CorrespondenceFact prototype, ICorrespondenceFactFactory factory, Observable<CorrespondenceFact> independent, TaskCompletionSource<CorrespondenceFact> completion)
{
CorrespondenceFact fact;
await _lock.WaitAsync();
try
{
// See if we already have the fact in memory.
if (!_factByMemento.TryGetValue(memento, out fact))
{
// If the object is already in storage, load it.
FactID? existingFactId = await _storageStrategy.FindExistingFactAsync(memento);
if (existingFactId.HasValue)
{
prototype.ID = existingFactId.Value;
prototype.SetCommunity(_community);
_factByID.Add(prototype.ID, prototype);
_factByMemento.Add(memento, prototype);
fact = prototype;
}
else
{
// The object does not exist.
fact = factory.GetNullInstance();
}
}
}
finally
{
_lock.Release();
}
lock (this)
{
independent.Value = fact;
}
completion.SetResult(fact);
}
private void ClearException()
{
lock (this)
{
_lastException.Value = null;
}
}
private void HandleException(Exception exception)
{
lock (this)
{
_lastException.Value = exception;
}
}
public Exception LastException
{
get
{
lock (this)
{
return _lastException;
}
}
}
public TypeDescriptor[] TypeDescriptors
{
get
{
return _storageStrategy.GetAllTypes()
.Select(type => new TypeDescriptor(type, GetPageOfFactsForType))
.ToArray();
}
}
internal List<FactDescriptor> GetPageOfFactsForType(CorrespondenceFactType type, int page)
{
return _storageStrategy.GetPageOfFactsForType(type, page)
.Select(fact => new FactDescriptor(fact.Id, fact.Memento, LoadFactById, LoadSuccessorsById))
.ToList();
}
internal FactDescriptor LoadFactDescriptorById(CorrespondenceFact fact)
{
return new FactDescriptor(
fact.ID,
this.CreateMementoFromFact(fact),
LoadFactById,
LoadSuccessorsById);
}
internal FactMemento LoadFactById(FactID factId)
{
return Task.Run(async delegate
{
return await _storageStrategy.LoadAsync(factId);
}).Result;
}
internal List<IdentifiedFactMemento> LoadSuccessorsById(FactID factId)
{
return _storageStrategy.GetAllSuccessors(factId);
}
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using NUnit.Compatibility;
using NUnit.Framework.Api;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.TestData.ActionAttributeTests;
namespace NUnit.Framework
{
[TestFixture, NonParallelizable]
public class ActionAttributeTests
{
// NOTE: An earlier version of this fixture attempted to test
// the exact order of all actions. However, the order of execution
// of the individual tests cannot be predicted reliably across
// different runtimes, so we now look only at the relative position
// of before and after actions with respect to the test.
private static readonly string ASSEMBLY_PATH = AssemblyHelper.GetAssemblyPath(typeof(ActionAttributeFixture).GetTypeInfo().Assembly);
private static readonly string ASSEMBLY_NAME = System.IO.Path.GetFileName(ASSEMBLY_PATH);
private ITestResult _result = null;
private int _numEvents = -1;
[OneTimeSetUp]
public void Setup()
{
var runner = new NUnitTestAssemblyRunner(new DefaultTestAssemblyBuilder());
ActionAttributeFixture.ClearResults();
IDictionary<string, object> options = new Dictionary<string, object>();
options["LOAD"] = new string[] { "NUnit.TestData.ActionAttributeTests" };
// No need for the overhead of parallel execution here
options["NumberOfTestWorkers"] = 0;
Assert.NotNull(runner.Load(ASSEMBLY_PATH, options), "Assembly not loaded");
Assert.That(runner.LoadedTest.RunState, Is.EqualTo(RunState.Runnable));
_result = runner.Run(TestListener.NULL, TestFilter.Empty);
_numEvents = ActionAttributeFixture.Events.Count;
}
[Test]
public void TestsRunSuccessfully()
{
Assert.That(_result.ResultState, Is.EqualTo(ResultState.Success));
//foreach(string message in ActionAttributeFixture.Events)
// Console.WriteLine(message);
}
[Test]
public void ExpectedOutput_InCorrectOrder()
{
var notFound = new List<string>();
var notExpected = new List<string>();
foreach (var item in ExpectedEvents)
if (!ActionAttributeFixture.Events.Contains(item))
notFound.Add(item);
foreach (var item in ActionAttributeFixture.Events)
if (!ExpectedEvents.Contains(item))
notExpected.Add(item);
if (notFound.Count > 0 || notExpected.Count > 0)
{
var sb = new StringBuilder("Expected and actual events do not match.");
if (notFound.Count > 0)
{
sb.Append(Environment.NewLine + " Missing:");
foreach (var item in notFound)
sb.Append(Environment.NewLine + " " + item);
}
if (notExpected.Count > 0)
{
sb.Append(Environment.NewLine + " Extra:");
foreach (var item in notExpected)
sb.Append(Environment.NewLine + " " + item);
}
Assert.Fail(sb.ToString());
}
}
[Test]
public void ActionsWrappingAssembly()
{
CheckActionsOnSuite(ASSEMBLY_NAME, 0, _numEvents - 1, ExpectedAssemblyActions);
}
[Test]
public void ActionsWrappingSetUpFixture()
{
int firstAction = NumAssemblyActions;
int lastAction = _numEvents - firstAction - 1;
CheckActionsOnSuite("ActionAttributeTests", firstAction, lastAction, ExpectedSetUpFixtureActions);
}
[Test]
public void ActionsWrappingTestFixture()
{
int firstAction = NumAssemblyActions + NumSetUpFixtureActions;
int lastAction = _numEvents - firstAction - 1;
CheckActionsOnSuite("ActionAttributeFixture", firstAction, lastAction, ExpectedTestFixtureActions);
}
[Test]
public void ActionsWrappingParameterizedMethodSuite()
{
int case1 = ActionAttributeFixture.Events.IndexOf("CaseOne");
int case2 = ActionAttributeFixture.Events.IndexOf("CaseTwo");
Assume.That(case1, Is.GreaterThanOrEqualTo(0));
Assume.That(case2, Is.GreaterThanOrEqualTo(0));
int firstAction = Math.Min(case1, case2) - NumTestCaseActions - NumParameterizedTestActions;
int lastAction = Math.Max(case1, case2) + NumTestCaseActions + NumParameterizedTestActions;
CheckActionsOnSuite("ParameterizedTest", firstAction, lastAction, "OnMethod", "OnMethod");
}
[Test]
public void CorrectNumberOfEventsReceived()
{
Assert.That(ActionAttributeFixture.Events.Count, Is.EqualTo(
NumTestCaseEvents + 2 * (NumParameterizedTestActions + NumTestFixtureActions + NumSetUpFixtureActions + NumAssemblyActions)));
}
[TestCase("CaseOne")]
[TestCase("CaseTwo")]
[TestCase("SimpleTest")]
public void ActionsWrappingTestMethod(string testName)
{
CheckActionsOnTestCase(testName);
}
#region Helper Methods
private void CheckActionsOnSuite(string suiteName, int firstEvent, int lastEvent, params string[] tags)
{
for (int i = 0; i < tags.Length; i++)
CheckBeforeAfterActionPair(firstEvent + i, lastEvent - i, suiteName, tags[i]);
if (firstEvent > 0)
{
var beforeEvent = ActionAttributeFixture.Events[firstEvent - 1];
Assert.That(beforeEvent, Does.Not.StartWith(suiteName), "Extra ActionAttribute Before: {0}", beforeEvent);
}
if (lastEvent < ActionAttributeFixture.Events.Count - 1)
{
var afterEvent = ActionAttributeFixture.Events[lastEvent + 1];
Assert.That(afterEvent, Does.Not.StartWith(suiteName), "Extra ActionAttribute After: {0}", afterEvent);
}
}
private void CheckActionsOnTestCase(string testName)
{
var index = ActionAttributeFixture.Events.IndexOf(testName);
Assert.That(index, Is.GreaterThanOrEqualTo(0), "{0} did not execute", testName);
var numActions = ExpectedTestCaseActions.Length;
for (int i = 0; i < numActions; i++)
CheckBeforeAfterActionPair(index - i - 1, index + i + 1, testName, ExpectedTestCaseActions[i]);
Assert.That(ActionAttributeFixture.Events[index - numActions - 1], Does.Not.StartWith(testName), "Extra ActionAttribute Before");
Assert.That(ActionAttributeFixture.Events[index + numActions + 1], Does.Not.StartWith(testName), "Extra ActionAttribute After");
}
private void CheckBeforeAfterActionPair(int index1, int index2, string testName, string tag)
{
var event1 = ActionAttributeFixture.Events[index1];
var event2 = ActionAttributeFixture.Events[index2];
Assert.That(event1, Does.StartWith(testName + "." + tag + ".Before"));
Assert.That(event2, Does.StartWith(testName + "." + tag + ".After"));
int index = event1.LastIndexOf('.');
var target1 = event1.Substring(index); // Target is last in string
Assert.That(event2, Does.EndWith(target1), "Event mismatch");
}
#endregion
#region Expected Attributes and Events
private static readonly string[] ExpectedAssemblyActions = new string[] {
"OnAssembly", "OnAssembly", "OnAssembly" };
private static readonly string[] ExpectedSetUpFixtureActions = new string[] {
"OnBaseSetupFixture", "OnBaseSetupFixture", "OnBaseSetupFixture",
"OnSetupFixture", "OnSetupFixture", "OnSetupFixture"
};
private static readonly string[] ExpectedTestFixtureActions = new string[] {
"OnBaseInterface", "OnBaseInterface", "OnBaseInterface",
"OnBaseFixture", "OnBaseFixture", "OnBaseFixture",
"OnInterface", "OnInterface", "OnInterface",
"OnFixture", "OnFixture", "OnFixture"
};
private static readonly string[] ExpectedParameterizedTestActions = new string[] {
"OnMethod", "OnMethod"
};
private static readonly string[] ExpectedTestCaseActions = new string[] {
"OnMethod", "OnMethod", "OnMethod",
"SetUpTearDown",
"OnFixture", "OnFixture",
"OnInterface", "OnInterface",
"OnBaseFixture", "OnBaseFixture",
"OnBaseInterface", "OnBaseInterface",
"OnSetupFixture", "OnSetupFixture",
"OnBaseSetupFixture", "OnBaseSetupFixture",
"OnAssembly", "OnAssembly"
};
// The exact order of events may vary, depending on the runtime framework
// in use. Consequently, we test heuristically. The following list is
// only one possible ordering of events.
private static readonly List<string> ExpectedEvents = new List<string>(new string[] {
ASSEMBLY_NAME + ".OnAssembly.Before.Test, Suite",
ASSEMBLY_NAME + ".OnAssembly.Before.Suite",
ASSEMBLY_NAME + ".OnAssembly.Before.Default",
"ActionAttributeTests.OnBaseSetupFixture.Before.Test, Suite",
"ActionAttributeTests.OnBaseSetupFixture.Before.Suite",
"ActionAttributeTests.OnBaseSetupFixture.Before.Default",
"ActionAttributeTests.OnSetupFixture.Before.Test, Suite",
"ActionAttributeTests.OnSetupFixture.Before.Suite",
"ActionAttributeTests.OnSetupFixture.Before.Default",
"ActionAttributeFixture.OnBaseInterface.Before.Test, Suite",
"ActionAttributeFixture.OnBaseInterface.Before.Suite",
"ActionAttributeFixture.OnBaseInterface.Before.Default",
"ActionAttributeFixture.OnBaseFixture.Before.Test, Suite",
"ActionAttributeFixture.OnBaseFixture.Before.Suite",
"ActionAttributeFixture.OnBaseFixture.Before.Default",
"ActionAttributeFixture.OnInterface.Before.Test, Suite",
"ActionAttributeFixture.OnInterface.Before.Suite",
"ActionAttributeFixture.OnInterface.Before.Default",
"ActionAttributeFixture.OnFixture.Before.Test, Suite",
"ActionAttributeFixture.OnFixture.Before.Suite",
"ActionAttributeFixture.OnFixture.Before.Default",
"ParameterizedTest.OnMethod.Before.Test, Suite",
"ParameterizedTest.OnMethod.Before.Suite",
"CaseOne.OnAssembly.Before.Test, Suite",
"CaseOne.OnAssembly.Before.Test",
"CaseOne.OnBaseSetupFixture.Before.Test, Suite",
"CaseOne.OnBaseSetupFixture.Before.Test",
"CaseOne.OnSetupFixture.Before.Test, Suite",
"CaseOne.OnSetupFixture.Before.Test",
"CaseOne.OnBaseInterface.Before.Test, Suite",
"CaseOne.OnBaseInterface.Before.Test",
"CaseOne.OnBaseFixture.Before.Test, Suite",
"CaseOne.OnBaseFixture.Before.Test",
"CaseOne.OnInterface.Before.Test, Suite",
"CaseOne.OnInterface.Before.Test",
"CaseOne.OnFixture.Before.Test, Suite",
"CaseOne.OnFixture.Before.Test",
"CaseOne.SetUpTearDown.Before.Test",
"CaseOne.OnMethod.Before.Test, Suite",
"CaseOne.OnMethod.Before.Test",
"CaseOne.OnMethod.Before.Default",
"CaseOne",
"CaseOne.OnMethod.After.Default",
"CaseOne.OnMethod.After.Test",
"CaseOne.OnMethod.After.Test, Suite",
"CaseOne.SetUpTearDown.After.Test",
"CaseOne.OnFixture.After.Test",
"CaseOne.OnFixture.After.Test, Suite",
"CaseOne.OnInterface.After.Test",
"CaseOne.OnInterface.After.Test, Suite",
"CaseOne.OnBaseFixture.After.Test",
"CaseOne.OnBaseFixture.After.Test, Suite",
"CaseOne.OnBaseInterface.After.Test",
"CaseOne.OnBaseInterface.After.Test, Suite",
"CaseOne.OnSetupFixture.After.Test",
"CaseOne.OnSetupFixture.After.Test, Suite",
"CaseOne.OnBaseSetupFixture.After.Test",
"CaseOne.OnBaseSetupFixture.After.Test, Suite",
"CaseOne.OnAssembly.After.Test",
"CaseOne.OnAssembly.After.Test, Suite",
"CaseTwo.OnAssembly.Before.Test, Suite",
"CaseTwo.OnAssembly.Before.Test",
"CaseTwo.OnBaseSetupFixture.Before.Test, Suite",
"CaseTwo.OnBaseSetupFixture.Before.Test",
"CaseTwo.OnSetupFixture.Before.Test, Suite",
"CaseTwo.OnSetupFixture.Before.Test",
"CaseTwo.OnBaseInterface.Before.Test, Suite",
"CaseTwo.OnBaseInterface.Before.Test",
"CaseTwo.OnBaseFixture.Before.Test",
"CaseTwo.OnBaseFixture.Before.Test, Suite",
"CaseTwo.OnInterface.Before.Test, Suite",
"CaseTwo.OnInterface.Before.Test",
"CaseTwo.OnFixture.Before.Test, Suite",
"CaseTwo.OnFixture.Before.Test",
"CaseTwo.SetUpTearDown.Before.Test",
"CaseTwo.OnMethod.Before.Test, Suite",
"CaseTwo.OnMethod.Before.Test",
"CaseTwo.OnMethod.Before.Default",
"CaseTwo",
"CaseTwo.OnMethod.After.Default",
"CaseTwo.OnMethod.After.Test",
"CaseTwo.OnMethod.After.Test, Suite",
"CaseTwo.SetUpTearDown.After.Test",
"CaseTwo.OnFixture.After.Test",
"CaseTwo.OnFixture.After.Test, Suite",
"CaseTwo.OnInterface.After.Test",
"CaseTwo.OnInterface.After.Test, Suite",
"CaseTwo.OnBaseFixture.After.Test",
"CaseTwo.OnBaseFixture.After.Test, Suite",
"CaseTwo.OnBaseInterface.After.Test",
"CaseTwo.OnBaseInterface.After.Test, Suite",
"CaseTwo.OnSetupFixture.After.Test",
"CaseTwo.OnSetupFixture.After.Test, Suite",
"CaseTwo.OnBaseSetupFixture.After.Test",
"CaseTwo.OnBaseSetupFixture.After.Test, Suite",
"CaseTwo.OnAssembly.After.Test",
"CaseTwo.OnAssembly.After.Test, Suite",
"ParameterizedTest.OnMethod.After.Suite",
"ParameterizedTest.OnMethod.After.Test, Suite",
"SimpleTest.OnAssembly.Before.Test, Suite",
"SimpleTest.OnAssembly.Before.Test",
"SimpleTest.OnBaseSetupFixture.Before.Test, Suite",
"SimpleTest.OnBaseSetupFixture.Before.Test",
"SimpleTest.OnSetupFixture.Before.Test, Suite",
"SimpleTest.OnSetupFixture.Before.Test",
"SimpleTest.OnBaseInterface.Before.Test, Suite",
"SimpleTest.OnBaseInterface.Before.Test",
"SimpleTest.OnBaseFixture.Before.Test, Suite",
"SimpleTest.OnBaseFixture.Before.Test",
"SimpleTest.OnInterface.Before.Test, Suite",
"SimpleTest.OnInterface.Before.Test",
"SimpleTest.OnFixture.Before.Test, Suite",
"SimpleTest.OnFixture.Before.Test",
"SimpleTest.SetUpTearDown.Before.Test",
"SimpleTest.OnMethod.Before.Test, Suite",
"SimpleTest.OnMethod.Before.Test",
"SimpleTest.OnMethod.Before.Default",
"SimpleTest",
"SimpleTest.OnMethod.After.Default",
"SimpleTest.OnMethod.After.Test",
"SimpleTest.OnMethod.After.Test, Suite",
"SimpleTest.SetUpTearDown.After.Test",
"SimpleTest.OnFixture.After.Test",
"SimpleTest.OnFixture.After.Test, Suite",
"SimpleTest.OnInterface.After.Test",
"SimpleTest.OnInterface.After.Test, Suite",
"SimpleTest.OnBaseFixture.After.Test",
"SimpleTest.OnBaseFixture.After.Test, Suite",
"SimpleTest.OnBaseInterface.After.Test",
"SimpleTest.OnBaseInterface.After.Test, Suite",
"SimpleTest.OnSetupFixture.After.Test",
"SimpleTest.OnSetupFixture.After.Test, Suite",
"SimpleTest.OnBaseSetupFixture.After.Test",
"SimpleTest.OnBaseSetupFixture.After.Test, Suite",
"SimpleTest.OnAssembly.After.Test",
"SimpleTest.OnAssembly.After.Test, Suite",
"ActionAttributeFixture.OnFixture.After.Default",
"ActionAttributeFixture.OnFixture.After.Suite",
"ActionAttributeFixture.OnFixture.After.Test, Suite",
"ActionAttributeFixture.OnInterface.After.Default",
"ActionAttributeFixture.OnInterface.After.Suite",
"ActionAttributeFixture.OnInterface.After.Test, Suite",
"ActionAttributeFixture.OnBaseFixture.After.Default",
"ActionAttributeFixture.OnBaseFixture.After.Suite",
"ActionAttributeFixture.OnBaseFixture.After.Test, Suite",
"ActionAttributeFixture.OnBaseInterface.After.Default",
"ActionAttributeFixture.OnBaseInterface.After.Suite",
"ActionAttributeFixture.OnBaseInterface.After.Test, Suite",
"ActionAttributeTests.OnSetupFixture.After.Default",
"ActionAttributeTests.OnSetupFixture.After.Suite",
"ActionAttributeTests.OnSetupFixture.After.Test, Suite",
"ActionAttributeTests.OnBaseSetupFixture.After.Default",
"ActionAttributeTests.OnBaseSetupFixture.After.Suite",
"ActionAttributeTests.OnBaseSetupFixture.After.Test, Suite",
ASSEMBLY_NAME + ".OnAssembly.After.Default",
ASSEMBLY_NAME + ".OnAssembly.After.Suite",
ASSEMBLY_NAME + ".OnAssembly.After.Test, Suite"
});
private static readonly int NumTestCaseActions = ExpectedTestCaseActions.Length;
private static readonly int EventsPerTestCase = 2 * NumTestCaseActions + 1;
private static readonly int NumTestCaseEvents = 3 * EventsPerTestCase;
private static readonly int NumParameterizedTestActions = ExpectedParameterizedTestActions.Length;
private static readonly int NumTestFixtureActions = ExpectedTestFixtureActions.Length;
private static readonly int NumSetUpFixtureActions = ExpectedSetUpFixtureActions.Length;
private static readonly int NumAssemblyActions = ExpectedAssemblyActions.Length;
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void BitFieldExtractUInt32()
{
var test = new ScalarBinaryOpTest__BitFieldExtractUInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.ReadUnaligned
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.ReadUnaligned
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.ReadUnaligned
test.RunLclVarScenario_UnsafeRead();
// 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 ScalarBinaryOpTest__BitFieldExtractUInt32
{
private struct TestStruct
{
public UInt32 _fld1;
public UInt16 _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
testStruct._fld1 = 0x1E000000;
testStruct._fld2 = 0x0419;
return testStruct;
}
public void RunStructFldScenario(ScalarBinaryOpTest__BitFieldExtractUInt32 testClass)
{
var result = Bmi1.BitFieldExtract(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
private static UInt32 _data1;
private static UInt16 _data2;
private static UInt32 _clsVar1;
private static UInt16 _clsVar2;
private UInt32 _fld1;
private UInt16 _fld2;
static ScalarBinaryOpTest__BitFieldExtractUInt32()
{
_clsVar1 = 0x1E000000;
_clsVar2 = 0x0419;
}
public ScalarBinaryOpTest__BitFieldExtractUInt32()
{
Succeeded = true;
_fld1 = 0x1E000000;
_fld2 = 0x0419;
_data1 = 0x1E000000;
_data2 = 0x0419;
}
public bool IsSupported => Bmi1.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Bmi1.BitFieldExtract(
Unsafe.ReadUnaligned<UInt32>(ref Unsafe.As<UInt32, byte>(ref _data1)),
Unsafe.ReadUnaligned<UInt16>(ref Unsafe.As<UInt16, byte>(ref _data2))
);
ValidateResult(_data1, _data2, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Bmi1).GetMethod(nameof(Bmi1.BitFieldExtract), new Type[] { typeof(UInt32), typeof(UInt16) })
.Invoke(null, new object[] {
Unsafe.ReadUnaligned<UInt32>(ref Unsafe.As<UInt32, byte>(ref _data1)),
Unsafe.ReadUnaligned<UInt16>(ref Unsafe.As<UInt16, byte>(ref _data2))
});
ValidateResult(_data1, _data2, (UInt32)result);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Bmi1.BitFieldExtract(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var data1 = Unsafe.ReadUnaligned<UInt32>(ref Unsafe.As<UInt32, byte>(ref _data1));
var data2 = Unsafe.ReadUnaligned<UInt16>(ref Unsafe.As<UInt16, byte>(ref _data2));
var result = Bmi1.BitFieldExtract(data1, data2);
ValidateResult(data1, data2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ScalarBinaryOpTest__BitFieldExtractUInt32();
var result = Bmi1.BitFieldExtract(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Bmi1.BitFieldExtract(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Bmi1.BitFieldExtract(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(UInt32 left, UInt16 right, UInt32 result, [CallerMemberName] string method = "")
{
var isUnexpectedResult = false;
uint expectedResult = 15; isUnexpectedResult = (expectedResult != result);
if (isUnexpectedResult)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Bmi1)}.{nameof(Bmi1.BitFieldExtract)}<UInt32>(UInt32, UInt16): BitFieldExtract failed:");
TestLibrary.TestFramework.LogInformation($" left: {left}");
TestLibrary.TestFramework.LogInformation($" right: {right}");
TestLibrary.TestFramework.LogInformation($" result: {result}");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using InfluxDB.Net.Enums;
using InfluxDB.Net.Models;
using Tharga.InfluxCapacitor.Entities;
using Tharga.InfluxCapacitor.Interface;
namespace Tharga.InfluxCapacitor
{
public class Measure : IMeasure
{
private readonly IQueue _queue;
public Measure(IQueue queue)
{
_queue = queue;
}
public T Execute<T>(Func<IMeasurement, T> action)
{
return Execute(GetName(action.Method.Name), action);
}
public T Execute<T>(Func<T> action)
{
return Execute(GetName(action.Method.Name), action);
}
public void Execute(Action action)
{
Execute(GetName(action.Method.Name), action);
}
public void Execute(Action<IMeasurement> action)
{
Execute(GetName(action.Method.Name), action);
}
public async Task ExecuteAsync(Func<Task> action)
{
var m = new Measurement();
await DoExecuteAsync(GetName(action.Method.Name), m, async () =>
{
await action();
return true;
});
}
public async Task ExecuteAsync(Func<IMeasurement, Task> action)
{
var m = new Measurement();
await DoExecuteAsync(GetName(action.Method.Name), m, async () =>
{
await action(m);
return true;
});
}
public async Task<T> ExecuteAsync<T>(Func<IMeasurement, Task<T>> action)
{
var m = new Measurement();
return await DoExecuteAsync(GetName(action.Method.Name), m, async () => await action(m));
}
public async Task<T> ExecuteAsync<T>(Func<Task<T>> action)
{
var m = new Measurement();
return await DoExecuteAsync(GetName(action.Method.Name), m, async () => await action());
}
public T Execute<T>(string measurement, Func<IMeasurement, T> action)
{
var m = new Measurement();
return DoExecute(measurement, m, () => action(m));
}
public T Execute<T>(string measurement, Func<T> action)
{
return DoExecute(measurement, new Measurement(), action);
}
public void Execute(string measurement, Action action)
{
DoExecute(measurement, new Measurement(), () =>
{
action();
return true;
});
}
public void Execute(string measurement, Action<IMeasurement> action)
{
var m = new Measurement();
DoExecute(measurement, m, () =>
{
action(m);
return true;
});
}
public async Task ExecuteAsync(string measurement, Func<IMeasurement, Task> action)
{
var m = new Measurement();
await DoExecuteAsync(measurement, m, async () =>
{
await action(m);
return true;
});
}
public async Task<T> ExecuteAsync<T>(string measurement, Func<IMeasurement, Task<T>> action)
{
var m = new Measurement();
return await DoExecuteAsync(measurement, m, async () => await action(m));
}
private string GetName(string name)
{
var p1 = name.IndexOf("<", StringComparison.Ordinal);
var p2 = name.IndexOf(">", p1, StringComparison.Ordinal);
var result = name.Substring(p1 + 1, p2 - p1 - 1);
return result;
}
private T DoExecute<T>(string measurement, Measurement m, Func<T> action)
{
var point = Prepare(ref measurement, m);
try
{
var response = action();
return PrepareResult(m, point, response);
}
catch (Exception exp)
{
PrepareException(m, point, exp);
throw;
}
}
private async Task<T> DoExecuteAsync<T>(string measurement, Measurement m, Func<Task<T>> action)
{
var point = Prepare(ref measurement, m);
try
{
var response = await action();
return PrepareResult(m, point, response);
}
catch (Exception exp)
{
PrepareException(m, point, exp);
throw;
}
}
private static Point Prepare(ref string measurement, Measurement m)
{
if (string.IsNullOrEmpty(measurement))
measurement = "Unknown";
var point = new Point
{
Measurement = measurement,
Precision = TimeUnit.Milliseconds,
Timestamp = DateTime.UtcNow,
};
m.Stopwatch.Reset();
m.Stopwatch.Start();
return point;
}
private T PrepareResult<T>(Measurement m, Point point, T response)
{
m.Stopwatch.Stop();
m.AddTag("isSuccess", true);
Finalize(m, point);
return response;
}
private void PrepareException(Measurement m, Point point, Exception exp)
{
m.Stopwatch.Stop();
m.AddTag("isSuccess", false);
m.AddTag("exception", exp.Message);
Finalize(m, point);
}
private void Finalize(IMeasurement m, Point point)
{
m.AddField("elapsed", m.GetElapsed().TotalMilliseconds);
m.AddTag("isCheckpoint", false);
point.Fields = m.Fields;
point.Tags = m.Tags;
_queue.Enqueue(point);
if (m.Checkpoints.Any())
{
//NOTE: Prepare all checkpoints
var prev = TimeSpan.Zero;
var index = 0;
foreach (var checkpoint in m.Checkpoints)
{
var pointFields = point.Fields.Where(x => x.Key != "value").ToDictionary(x => x.Key, x => x.Value);
var pointTags = point.Tags.Where(x => x.Key != "checkpoint" && x.Key != "isCheckpoint" && x.Key != "index").ToDictionary(x => x.Key, x => x.Value);
pointFields.Add("value", (checkpoint.Value - prev).TotalMilliseconds);
pointTags.Add("isCheckpoint", true);
pointTags.Add("checkpoint", checkpoint.Key);
pointTags.Add("index", index++);
var check = new Point
{
Measurement = point.Measurement,
Fields = pointFields,
Tags = pointTags,
Timestamp = point.Timestamp,
Precision = point.Precision,
};
_queue.Enqueue(check);
prev = checkpoint.Value;
}
//NOTE: Prepare the end point checkpoint
{
var pointFields = point.Fields.Where(x => x.Key != "value").ToDictionary(x => x.Key, x => x.Value);
var pointTags = point.Tags.Where(x => x.Key != "elapsed" && x.Key != "isCheckpoint").ToDictionary(x => x.Key, x => x.Value);
pointFields.Add("value", (m.GetElapsed() - prev).TotalMilliseconds);
pointTags.Add("isCheckpoint", true);
pointTags.Add("checkpoint", "End");
pointTags.Add("index", index);
var check = new Point
{
Measurement = point.Measurement,
Fields = pointFields,
Tags = pointTags,
Timestamp = point.Timestamp,
Precision = point.Precision,
};
_queue.Enqueue(check);
}
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Xml;
using SharpVectors.Net;
namespace SharpVectors.Renderers.Forms
{
public class SvgCacheManager : ICacheManager
{
private string cacheDir;
private string cacheDocPath;
private XmlDocument cacheDoc = new XmlDocument();
public SvgCacheManager()
{
cacheDir = Path.Combine(
SvgApplicationContext.ExecutableDirectory.FullName,
"cache/");
cacheDocPath = Path.Combine(cacheDir, "cache.xml");
loadDoc();
}
public SvgCacheManager(string cacheDir)
{
this.cacheDir = Path.Combine(
SvgApplicationContext.ExecutableDirectory.FullName,
cacheDir);
cacheDocPath = Path.Combine(cacheDir, "cache.xml");
loadDoc();
}
private void loadDoc()
{
if(File.Exists(cacheDocPath))
{
cacheDoc.Load(cacheDocPath);
}
else
{
Directory.CreateDirectory(Directory.GetParent(cacheDocPath).FullName);
cacheDoc.LoadXml("<cache />");
}
}
private void saveDoc()
{
cacheDoc.Save(cacheDocPath);
}
private XmlElement lastCacheElm;
private Uri lastUri;
private XmlElement getCacheElm(Uri uri)
{
if(uri == lastUri && lastCacheElm != null)
{
return lastCacheElm;
}
else
{
//string xpath = "/cache/resource[@url='" + uri.ToString() + "']";
string xpath = "/cache/resource[@url='" + uri.ToString().Replace("'", "'") + "']";
XmlNode node = cacheDoc.SelectSingleNode(xpath);
if(node != null)
{
lastCacheElm = node as XmlElement;
}
else
{
lastCacheElm = cacheDoc.CreateElement("resource");
cacheDoc.DocumentElement.AppendChild(lastCacheElm);
lastCacheElm.SetAttribute("url", uri.ToString());
}
lastUri = uri;
return lastCacheElm;
}
}
private Uri getLocalPathUri(XmlElement cacheElm)
{
if(cacheElm.HasAttribute("local-path"))
{
string path = Path.Combine(cacheDir, cacheElm.GetAttribute("local-path"));
if(File.Exists(path))
{
path = "file:///" + path.Replace('\\', '/');
return new Uri(path);
}
else
{
cacheElm.RemoveAttribute("local-path");
return null;
}
}
else
{
return null;
}
}
public long Size
{
get
{
DirectoryInfo di = new DirectoryInfo(cacheDir);
FileInfo[] files = di.GetFiles();
long size = 0;
foreach(FileInfo file in files)
{
size += file.Length;
}
return size;
}
}
public void Clear()
{
DirectoryInfo di = new DirectoryInfo(cacheDir);
FileInfo[] files = di.GetFiles();
foreach(FileInfo file in files)
{
try
{
file.Delete();
}
catch{}
}
cacheDoc = new XmlDocument();
loadDoc();
}
public CacheInfo GetCacheInfo(Uri uri)
{
XmlElement cacheElm = getCacheElm(uri);
DateTime expires = DateTime.MinValue;
if(cacheElm.HasAttribute("expires"))
{
expires = DateTime.Parse(cacheElm.GetAttribute("expires"));
}
DateTime lastModified = DateTime.MinValue;
if(cacheElm.HasAttribute("last-modified"))
{
lastModified = DateTime.Parse(cacheElm.GetAttribute("last-modified"));
}
Uri cachedUri = getLocalPathUri(cacheElm);
return new CacheInfo(expires, cacheElm.GetAttribute("etag"), lastModified, cachedUri, cacheElm.GetAttribute("content-type"));
}
public void SetCacheInfo(Uri uri, CacheInfo cacheInfo, Stream stream)
{
XmlElement cacheElm = getCacheElm(uri);
if(cacheInfo != null)
{
if(cacheInfo.ETag != null)
{
cacheElm.SetAttribute("etag", cacheInfo.ETag);
}
else
{
cacheElm.RemoveAttribute("etag");
}
if(cacheInfo.ContentType != null)
{
cacheElm.SetAttribute("content-type", cacheInfo.ContentType);
}
else
{
cacheElm.RemoveAttribute("content-type");
}
if(cacheInfo.Expires != DateTime.MinValue)
{
cacheElm.SetAttribute("expires", cacheInfo.Expires.ToString("s"));
}
else
{
cacheElm.RemoveAttribute("expires");
}
if(cacheInfo.LastModified != DateTime.MinValue)
{
cacheElm.SetAttribute("last-modified", cacheInfo.LastModified.ToString("s"));
}
else
{
cacheElm.RemoveAttribute("last-modified");
}
}
if(stream != null)
{
string localPath;
if(cacheElm.HasAttribute("local-path"))
{
localPath = cacheElm.GetAttribute("local-path");
}
else
{
localPath = Guid.NewGuid().ToString() + ".cache";
cacheElm.SetAttribute("local-path", localPath);
}
stream.Position = 0;
int count;
byte[] buffer = new byte[4096];
FileStream fs = File.OpenWrite(Path.Combine(cacheDir, localPath));
while((count = stream.Read(buffer, 0, 4096)) > 0) fs.Write(buffer, 0, count);
fs.Flush();
fs.Close();
}
saveDoc();
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.LayoutRenderers
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
using Internal.Fakeables;
using NLog.Config;
using NLog.Internal;
using NLog.Targets;
/// <summary>
/// XML event description compatible with log4j, Chainsaw and NLogViewer.
/// </summary>
[LayoutRenderer("log4jxmlevent")]
public class Log4JXmlEventLayoutRenderer : LayoutRenderer, IUsesStackTrace
{
private static readonly DateTime log4jDateBase = new DateTime(1970, 1, 1);
private static readonly string dummyNamespace = "http://nlog-project.org/dummynamespace/" + Guid.NewGuid();
private static readonly string dummyNLogNamespace = "http://nlog-project.org/dummynamespace/" + Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="Log4JXmlEventLayoutRenderer" /> class.
/// </summary>
public Log4JXmlEventLayoutRenderer() : this(AppDomainWrapper.CurrentDomain)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Log4JXmlEventLayoutRenderer" /> class.
/// </summary>
public Log4JXmlEventLayoutRenderer(IAppDomain appDomain)
{
this.IncludeNLogData = true;
this.NdcItemSeparator = " ";
#if SILVERLIGHT
this.AppInfo = "Silverlight Application";
#else
this.AppInfo = string.Format(
CultureInfo.InvariantCulture,
"{0}({1})",
appDomain.FriendlyName,
ThreadIDHelper.Instance.CurrentProcessID);
#endif
this.Parameters = new List<NLogViewerParameterInfo>();
}
/// <summary>
/// Gets or sets a value indicating whether to include NLog-specific extensions to log4j schema.
/// </summary>
/// <docgen category='Payload Options' order='10' />
[DefaultValue(true)]
public bool IncludeNLogData { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the XML should use spaces for indentation.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool IndentXml { get; set; }
/// <summary>
/// Gets or sets the AppInfo field. By default it's the friendly name of the current AppDomain.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public string AppInfo { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to include call site (class and method name) in the information sent over the network.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool IncludeCallSite { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to include source info (file name and line number) in the information sent over the network.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool IncludeSourceInfo { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsContext"/> dictionary.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool IncludeMdc { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to include contents of the <see cref="NestedDiagnosticsContext"/> stack.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool IncludeNdc { get; set; }
/// <summary>
/// Gets or sets the NDC item separator.
/// </summary>
/// <docgen category='Payload Options' order='10' />
[DefaultValue(" ")]
public string NdcItemSeparator { get; set; }
/// <summary>
/// Gets the level of stack trace information required by the implementing class.
/// </summary>
StackTraceUsage IUsesStackTrace.StackTraceUsage
{
get
{
if (this.IncludeSourceInfo)
{
return StackTraceUsage.Max;
}
if (this.IncludeCallSite)
{
return StackTraceUsage.WithoutSource;
}
return StackTraceUsage.None;
}
}
internal IList<NLogViewerParameterInfo> Parameters { get; set; }
internal void AppendToStringBuilder(StringBuilder sb, LogEventInfo logEvent)
{
this.Append(sb, logEvent);
}
/// <summary>
/// Renders the XML logging event and appends it to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="logEvent">Logging event.</param>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
var settings = new XmlWriterSettings
{
Indent = this.IndentXml,
ConformanceLevel = ConformanceLevel.Fragment,
IndentChars = " ",
};
var sb = new StringBuilder();
using (XmlWriter xtw = XmlWriter.Create(sb, settings))
{
xtw.WriteStartElement("log4j", "event", dummyNamespace);
xtw.WriteAttributeSafeString("xmlns", "nlog", null, dummyNLogNamespace);
xtw.WriteAttributeSafeString("logger", logEvent.LoggerName);
xtw.WriteAttributeSafeString("level", logEvent.Level.Name.ToUpper(CultureInfo.InvariantCulture));
xtw.WriteAttributeSafeString("timestamp", Convert.ToString((long)(logEvent.TimeStamp.ToUniversalTime() - log4jDateBase).TotalMilliseconds, CultureInfo.InvariantCulture));
xtw.WriteAttributeSafeString("thread", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture));
xtw.WriteElementSafeString("log4j", "message", dummyNamespace, logEvent.FormattedMessage);
if (logEvent.Exception != null)
{
xtw.WriteElementSafeString("log4j", "throwable", dummyNamespace, logEvent.Exception.ToString());
}
if (this.IncludeNdc)
{
xtw.WriteElementSafeString("log4j", "NDC", dummyNamespace, string.Join(this.NdcItemSeparator, NestedDiagnosticsContext.GetAllMessages()));
}
if (logEvent.Exception != null)
{
xtw.WriteStartElement("log4j", "throwable", dummyNamespace);
xtw.WriteSafeCData(logEvent.Exception.ToString());
xtw.WriteEndElement();
}
if (this.IncludeCallSite || this.IncludeSourceInfo)
{
System.Diagnostics.StackFrame frame = logEvent.UserStackFrame;
if (frame != null)
{
MethodBase methodBase = frame.GetMethod();
Type type = methodBase.DeclaringType;
xtw.WriteStartElement("log4j", "locationInfo", dummyNamespace);
if (type != null)
{
xtw.WriteAttributeSafeString("class", type.FullName);
}
xtw.WriteAttributeSafeString("method", methodBase.ToString());
#if !SILVERLIGHT
if (this.IncludeSourceInfo)
{
xtw.WriteAttributeSafeString("file", frame.GetFileName());
xtw.WriteAttributeSafeString("line", frame.GetFileLineNumber().ToString(CultureInfo.InvariantCulture));
}
#endif
xtw.WriteEndElement();
if (this.IncludeNLogData)
{
xtw.WriteElementSafeString("nlog", "eventSequenceNumber", dummyNLogNamespace, logEvent.SequenceID.ToString(CultureInfo.InvariantCulture));
xtw.WriteStartElement("nlog", "locationInfo", dummyNLogNamespace);
if (type != null)
{
xtw.WriteAttributeSafeString("assembly", type.Assembly.FullName);
}
xtw.WriteEndElement();
xtw.WriteStartElement("nlog", "properties", dummyNLogNamespace);
foreach (var contextProperty in logEvent.Properties)
{
xtw.WriteStartElement("nlog", "data", dummyNLogNamespace);
xtw.WriteAttributeSafeString("name", Convert.ToString(contextProperty.Key, CultureInfo.InvariantCulture));
xtw.WriteAttributeSafeString("value", Convert.ToString(contextProperty.Value, CultureInfo.InvariantCulture));
xtw.WriteEndElement();
}
xtw.WriteEndElement();
}
}
}
xtw.WriteStartElement("log4j", "properties", dummyNamespace);
if (this.IncludeMdc)
{
foreach (KeyValuePair<string, string> entry in MappedDiagnosticsContext.ThreadDictionary)
{
xtw.WriteStartElement("log4j", "data", dummyNamespace);
xtw.WriteAttributeSafeString("name", entry.Key);
xtw.WriteAttributeSafeString("value", entry.Value);
xtw.WriteEndElement();
}
}
foreach (NLogViewerParameterInfo parameter in this.Parameters)
{
xtw.WriteStartElement("log4j", "data", dummyNamespace);
xtw.WriteAttributeSafeString("name", parameter.Name);
xtw.WriteAttributeSafeString("value", parameter.Layout.Render(logEvent));
xtw.WriteEndElement();
}
xtw.WriteStartElement("log4j", "data", dummyNamespace);
xtw.WriteAttributeSafeString("name", "log4japp");
xtw.WriteAttributeSafeString("value", this.AppInfo);
xtw.WriteEndElement();
xtw.WriteStartElement("log4j", "data", dummyNamespace);
xtw.WriteAttributeSafeString("name", "log4jmachinename");
#if SILVERLIGHT
xtw.WriteAttributeSafeString("value", "silverlight");
#else
xtw.WriteAttributeSafeString("value", Environment.MachineName);
#endif
xtw.WriteEndElement();
xtw.WriteEndElement();
xtw.WriteEndElement();
xtw.Flush();
// get rid of 'nlog' and 'log4j' namespace declarations
sb.Replace(" xmlns:log4j=\"" + dummyNamespace + "\"", string.Empty);
sb.Replace(" xmlns:nlog=\"" + dummyNLogNamespace + "\"", string.Empty);
builder.Append(sb.ToString());
}
}
}
}
| |
/*
* [The "BSD license"]
* Copyright (c) 2013 Terence Parr
* Copyright (c) 2013 Sam Harwell
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 Antlr4.Runtime.Sharpen;
namespace Antlr4.Runtime.Misc
{
/// <summary>An immutable inclusive interval a..b.</summary>
/// <remarks>An immutable inclusive interval a..b.</remarks>
public struct Interval
{
public static readonly Antlr4.Runtime.Misc.Interval Invalid = new Antlr4.Runtime.Misc.Interval(-1, -2);
/// <summary>The start of the interval.</summary>
/// <remarks>The start of the interval.</remarks>
public readonly int a;
/// <summary>The end of the interval (inclusive).</summary>
/// <remarks>The end of the interval (inclusive).</remarks>
public readonly int b;
public Interval(int a, int b)
{
this.a = a;
this.b = b;
}
/// <summary>
/// Interval objects are used readonly so share all with the
/// same single value a==b up to some max size.
/// </summary>
/// <remarks>
/// Interval objects are used readonly so share all with the
/// same single value a==b up to some max size. Use an array as a perfect hash.
/// Return shared object for 0..INTERVAL_POOL_MAX_VALUE or a new
/// Interval object with a..a in it. On Java.g4, 218623 IntervalSets
/// have a..a (set with 1 element).
/// </remarks>
public static Antlr4.Runtime.Misc.Interval Of(int a, int b)
{
return new Antlr4.Runtime.Misc.Interval(a, b);
}
/// <summary>return number of elements between a and b inclusively.</summary>
/// <remarks>
/// return number of elements between a and b inclusively. x..x is length 1.
/// if b < a, then length is 0. 9..10 has length 2.
/// </remarks>
public int Length
{
get
{
if (b < a)
{
return 0;
}
return b - a + 1;
}
}
public override bool Equals(object o)
{
if (!(o is Antlr4.Runtime.Misc.Interval))
{
return false;
}
Antlr4.Runtime.Misc.Interval other = (Antlr4.Runtime.Misc.Interval)o;
return this.a == other.a && this.b == other.b;
}
public override int GetHashCode()
{
int hash = 23;
hash = hash * 31 + a;
hash = hash * 31 + b;
return hash;
}
/// <summary>Does this start completely before other? Disjoint</summary>
public bool StartsBeforeDisjoint(Antlr4.Runtime.Misc.Interval other)
{
return this.a < other.a && this.b < other.a;
}
/// <summary>Does this start at or before other? Nondisjoint</summary>
public bool StartsBeforeNonDisjoint(Antlr4.Runtime.Misc.Interval other)
{
return this.a <= other.a && this.b >= other.a;
}
/// <summary>Does this.a start after other.b? May or may not be disjoint</summary>
public bool StartsAfter(Antlr4.Runtime.Misc.Interval other)
{
return this.a > other.a;
}
/// <summary>Does this start completely after other? Disjoint</summary>
public bool StartsAfterDisjoint(Antlr4.Runtime.Misc.Interval other)
{
return this.a > other.b;
}
/// <summary>Does this start after other? NonDisjoint</summary>
public bool StartsAfterNonDisjoint(Antlr4.Runtime.Misc.Interval other)
{
return this.a > other.a && this.a <= other.b;
}
// this.b>=other.b implied
/// <summary>Are both ranges disjoint? I.e., no overlap?</summary>
public bool Disjoint(Antlr4.Runtime.Misc.Interval other)
{
return StartsBeforeDisjoint(other) || StartsAfterDisjoint(other);
}
/// <summary>Are two intervals adjacent such as 0..41 and 42..42?</summary>
public bool Adjacent(Antlr4.Runtime.Misc.Interval other)
{
return this.a == other.b + 1 || this.b == other.a - 1;
}
public bool ProperlyContains(Antlr4.Runtime.Misc.Interval other)
{
return other.a >= this.a && other.b <= this.b;
}
/// <summary>Return the interval computed from combining this and other</summary>
public Antlr4.Runtime.Misc.Interval Union(Antlr4.Runtime.Misc.Interval other)
{
return Antlr4.Runtime.Misc.Interval.Of(Math.Min(a, other.a), Math.Max(b, other.b));
}
/// <summary>Return the interval in common between this and o</summary>
public Antlr4.Runtime.Misc.Interval Intersection(Antlr4.Runtime.Misc.Interval other)
{
return Antlr4.Runtime.Misc.Interval.Of(Math.Max(a, other.a), Math.Min(b, other.b));
}
/// <summary>
/// Return the interval with elements from
/// <c>this</c>
/// not in
/// <paramref name="other"/>
/// ;
/// <paramref name="other"/>
/// must not be totally enclosed (properly contained)
/// within
/// <c>this</c>
/// , which would result in two disjoint intervals
/// instead of the single one returned by this method.
/// </summary>
public Antlr4.Runtime.Misc.Interval? DifferenceNotProperlyContained(Antlr4.Runtime.Misc.Interval other)
{
Antlr4.Runtime.Misc.Interval? diff = null;
// other.a to left of this.a (or same)
if (other.StartsBeforeNonDisjoint(this))
{
diff = Antlr4.Runtime.Misc.Interval.Of(Math.Max(this.a, other.b + 1), this.b);
}
else
{
// other.a to right of this.a
if (other.StartsAfterNonDisjoint(this))
{
diff = Antlr4.Runtime.Misc.Interval.Of(this.a, other.a - 1);
}
}
return diff;
}
public override string ToString()
{
return a + ".." + b;
}
}
}
| |
namespace FCT.LLC.BusinessService.Entities
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Runtime.Serialization;
[DataContract]
[DebuggerStepThrough]
[GeneratedCode("System.Runtime.Serialization", "4.0.0.0")]
[Table("tblDeal")]
public partial class tblDeal
{
public tblDeal()
{
tblDealContacts = new HashSet<tblDealContact>();
tblMortgagors = new HashSet<tblMortgagor>();
tblMortgages = new HashSet<tblMortgage>();
tblProperties = new HashSet<tblProperty>();
}
[DataMember]
[Key]
public int DealID { get; set; }
[DataMember]
[StringLength(11)]
public string FCTRefNum { get; set; }
[DataMember]
[NotMapped]
public string FCTURN { get; set; }
[DataMember]
[StringLength(50)]
public string LenderRefNum { get; set; }
[DataMember]
public int? LenderID { get; set; }
[DataMember]
[Column(TypeName = "smalldatetime")]
public DateTime? RFIReceiveDate { get; set; }
[DataMember]
public int? BranchID { get; set; }
[DataMember]
public int? ContactID { get; set; }
[DataMember]
public int? MortgageCentreID { get; set; }
[DataMember]
public int? MtgCentreContactID { get; set; }
[DataMember]
[StringLength(6000)]
public string LenderComment { get; set; }
[DataMember]
[StringLength(50)]
public string Status { get; set; }
[DataMember]
public DateTime? StatusDate { get; set; }
[DataMember]
public int? StatusUserID { get; set; }
[DataMember]
[StringLength(50)]
public string StatusUserType { get; set; }
[DataMember]
[StringLength(1000)]
public string StatusReason { get; set; }
[DataMember]
public int? StatusReasonID { get; set; }
[DataMember]
public int LawyerID { get; set; }
[DataMember]
public bool? LawyerDeclinedFlag { get; set; }
[DataMember]
[Column(TypeName = "smalldatetime")]
public DateTime? LawyerAcceptDeclinedDate { get; set; }
[DataMember]
[Column(TypeName = "smalldatetime")]
public DateTime? FinalDocsPostedDate { get; set; }
[DataMember]
public bool? UserNotification { get; set; }
[DataMember]
public bool? LendersAttentionFlag { get; set; }
[DataMember]
public bool? Promotion { get; set; }
[DataMember]
public int? FundStatusID { get; set; }
[DataMember]
public int? Sequence { get; set; }
[DataMember]
public bool? FundsDisbursed { get; set; }
[DataMember]
[Column(TypeName = "smalldatetime")]
public DateTime? FundRequestDate { get; set; }
[DataMember]
[StringLength(20)]
public string LawyerMatterNumber { get; set; }
[DataMember]
public bool? IsLLC { get; set; }
[DataMember]
public bool? LenderNewNotes { get; set; }
[DataMember]
public bool? LenderUpdated { get; set; }
[DataMember]
public int? CreditCardID { get; set; }
[DataMember]
[Column(TypeName = "timestamp")]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[MaxLength(8)]
public byte[] LastModified { get; set; }
[DataMember]
// [Required]
[StringLength(20)]
public string BusinessModel { get; set; }
[DataMember]
public int? BCOnlineID { get; set; }
[DataMember]
public int? BillingAmountDetailID { get; set; }
[DataMember]
[StringLength(50)]
public string LawyerApplication { get; set; }
[DataMember]
public int? ActionableNotesCompleted { get; set; }
[DataMember]
public int? FinalReportNotificationNo { get; set; }
[DataMember]
public int? ServiceAddressTypeID { get; set; }
[DataMember]
public int? MailingAddressTypeID { get; set; }
[DataMember]
public int? MortgageOwningBranchID { get; set; }
[DataMember]
public bool? IsRFF { get; set; }
[DataMember]
[StringLength(2000)]
public string Encumbrances { get; set; }
[DataMember]
public int? DealTrustAccountID { get; set; }
[DataMember]
public int? MtgOwningBranchContactID { get; set; }
[DataMember]
public int? FundingPaymentMethodID { get; set; }
[DataMember]
[StringLength(25)]
public string LenderDealRefNumber { get; set; }
[DataMember]
public bool? LawyerAmendmentImmediate { get; set; }
[DataMember]
public bool? LawyerAmendmentSROT { get; set; }
[DataMember]
[StringLength(1000)]
public string RFFComment { get; set; }
[DataMember]
public DateTime? RFFClosingDate { get; set; }
[DataMember]
public bool? IsSubmissionPending { get; set; }
[DataMember]
public DateTime? LawyerAppointmentDate { get; set; }
[DataMember]
[StringLength(100)]
public string LenderRepresentativeFirstName { get; set; }
[DataMember]
[StringLength(50)]
public string LenderRepresentativeLastName { get; set; }
[DataMember]
[StringLength(100)]
public string LenderRepresentativeTitle { get; set; }
[DataMember]
[StringLength(100)]
public string DistrictName { get; set; }
[DataMember]
public int? DealClosingOptionID { get; set; }
[DataMember]
public int? SavedDocumentClosingOptionID { get; set; }
[DataMember]
[StringLength(20)]
public string LenderSecurityType { get; set; }
[DataMember]
public DateTime? RFFNotifiedDate { get; set; }
[DataMember]
public int? LenderDealAlternateID { get; set; }
[DataMember]
public int? DealScopeID { get; set; }
[DataMember]
public int? PrimaryDealContactID { get; set; }
[DataMember]
[StringLength(20)]
public string LawyerActingFor { get; set; }
[DataMember]
[StringLength(20)]
public string DealType { get; set; }
[DataMember]
public string LenderFINumber { get; set; }
[DataMember]
public bool IsLawyerConfirmedClosing { get; set; }
[DataMember]
public virtual tblDealScope tblDealScope { get; set; }
[DataMember]
public virtual tblLawyer tblLawyer { get; set; }
[DataMember]
public virtual ICollection<tblDealContact> tblDealContacts { get; set; }
[DataMember]
public virtual ICollection<tblMortgagor> tblMortgagors { get; set; }
[DataMember]
public virtual ICollection<tblProperty> tblProperties { get; set; }
[DataMember]
public virtual ICollection<tblMortgage> tblMortgages { get; set; }
[DataMember]
public virtual tblLender tblLender { get; set; }
[DataMember]
public virtual ICollection<tblNote> tblNotes { get; set; }
[DataMember]
public virtual ICollection<tblMilestone> tblMilestones { get; set; }
[DataMember]
public virtual ICollection<tblDealHistory> tblDealHistory { get; set; }
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ServerManagement
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// REST API for Azure Server Management Service
/// </summary>
public partial class ServerManagementClient : Microsoft.Rest.ServiceClient<ServerManagementClient>, IServerManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Client Api Version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IGatewayOperations.
/// </summary>
public virtual IGatewayOperations Gateway { get; private set; }
/// <summary>
/// Gets the INodeOperations.
/// </summary>
public virtual INodeOperations Node { get; private set; }
/// <summary>
/// Gets the ISessionOperations.
/// </summary>
public virtual ISessionOperations Session { get; private set; }
/// <summary>
/// Gets the IPowerShellOperations.
/// </summary>
public virtual IPowerShellOperations PowerShell { get; private set; }
/// <summary>
/// Initializes a new instance of the ServerManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected ServerManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the ServerManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected ServerManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the ServerManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected ServerManagementClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the ServerManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected ServerManagementClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the ServerManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ServerManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the ServerManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ServerManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the ServerManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ServerManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the ServerManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ServerManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.Gateway = new GatewayOperations(this);
this.Node = new NodeOperations(this);
this.Session = new SessionOperations(this);
this.PowerShell = new PowerShellOperations(this);
this.BaseUri = new System.Uri("https://management.azure.com");
this.ApiVersion = "2016-07-01-preview";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter());
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter());
DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Diagnostics.CodeAnalysis;
namespace WeifenLuo.WinFormsUI.Docking
{
internal interface IContentFocusManager
{
void Activate(IDockContent content);
void GiveUpFocus(IDockContent content);
void AddToList(IDockContent content);
void RemoveFromList(IDockContent content);
}
partial class DockPanel
{
private interface IFocusManager
{
void SuspendFocusTracking();
void ResumeFocusTracking();
bool IsFocusTrackingSuspended { get; }
IDockContent ActiveContent { get; }
DockPane ActivePane { get; }
IDockContent ActiveDocument { get; }
DockPane ActiveDocumentPane { get; }
}
private class FocusManagerImpl : Component, IContentFocusManager, IFocusManager
{
private class HookEventArgs : EventArgs
{
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
public int HookCode;
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
public IntPtr wParam;
public IntPtr lParam;
}
private class LocalWindowsHook : IDisposable
{
// Internal properties
private IntPtr m_hHook = IntPtr.Zero;
private NativeMethods.HookProc m_filterFunc = null;
private Win32.HookType m_hookType;
// Event delegate
public delegate void HookEventHandler(object sender, HookEventArgs e);
// Event: HookInvoked
public event HookEventHandler HookInvoked;
protected void OnHookInvoked(HookEventArgs e)
{
if (HookInvoked != null)
HookInvoked(this, e);
}
public LocalWindowsHook(Win32.HookType hook)
{
m_hookType = hook;
m_filterFunc = new NativeMethods.HookProc(this.CoreHookProc);
}
// Default filter function
public IntPtr CoreHookProc(int code, IntPtr wParam, IntPtr lParam)
{
if (code < 0)
return NativeMethods.CallNextHookEx(m_hHook, code, wParam, lParam);
// Let clients determine what to do
HookEventArgs e = new HookEventArgs();
e.HookCode = code;
e.wParam = wParam;
e.lParam = lParam;
OnHookInvoked(e);
// Yield to the next hook in the chain
return NativeMethods.CallNextHookEx(m_hHook, code, wParam, lParam);
}
// Install the hook
public void Install()
{
if (m_hHook != IntPtr.Zero)
Uninstall();
int threadId = NativeMethods.GetCurrentThreadId();
m_hHook = NativeMethods.SetWindowsHookEx(m_hookType, m_filterFunc, IntPtr.Zero, threadId);
}
// Uninstall the hook
public void Uninstall()
{
if (m_hHook != IntPtr.Zero)
{
NativeMethods.UnhookWindowsHookEx(m_hHook);
m_hHook = IntPtr.Zero;
}
}
~LocalWindowsHook()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
Uninstall();
}
}
// Use a static instance of the windows hook to prevent stack overflows in the windows kernel.
[ThreadStatic]
private static LocalWindowsHook sm_localWindowsHook;
private readonly LocalWindowsHook.HookEventHandler m_hookEventHandler;
public FocusManagerImpl(DockPanel dockPanel)
{
m_dockPanel = dockPanel;
if (Win32Helper.IsRunningOnMono)
return;
m_hookEventHandler = new LocalWindowsHook.HookEventHandler(HookEventHandler);
// Ensure the windows hook has been created for this thread
if (sm_localWindowsHook == null)
{
sm_localWindowsHook = new LocalWindowsHook(Win32.HookType.WH_CALLWNDPROCRET);
sm_localWindowsHook.Install();
}
sm_localWindowsHook.HookInvoked += m_hookEventHandler;
}
private DockPanel m_dockPanel;
public DockPanel DockPanel
{
get { return m_dockPanel; }
}
private bool m_disposed = false;
protected override void Dispose(bool disposing)
{
if (!m_disposed && disposing)
{
if (!Win32Helper.IsRunningOnMono)
{
sm_localWindowsHook.HookInvoked -= m_hookEventHandler;
}
m_disposed = true;
}
base.Dispose(disposing);
}
private IDockContent m_contentActivating = null;
private IDockContent ContentActivating
{
get { return m_contentActivating; }
set { m_contentActivating = value; }
}
public void Activate(IDockContent content)
{
if (IsFocusTrackingSuspended)
{
ContentActivating = content;
return;
}
if (content == null)
return;
DockContentHandler handler = content.DockHandler;
if (handler.Form.IsDisposed)
return; // Should not reach here, but better than throwing an exception
if (ContentContains(content, handler.ActiveWindowHandle))
{
if (!Win32Helper.IsRunningOnMono)
{
NativeMethods.SetFocus(handler.ActiveWindowHandle);
}
}
if (handler.Form.ContainsFocus)
return;
if (handler.Form.SelectNextControl(handler.Form.ActiveControl, true, true, true, true))
return;
if (Win32Helper.IsRunningOnMono)
return;
// Since DockContent Form is not selectalbe, use Win32 SetFocus instead
NativeMethods.SetFocus(handler.Form.Handle);
}
private List<IDockContent> m_listContent = new List<IDockContent>();
private List<IDockContent> ListContent
{
get { return m_listContent; }
}
public void AddToList(IDockContent content)
{
if (ListContent.Contains(content) || IsInActiveList(content))
return;
ListContent.Add(content);
}
public void RemoveFromList(IDockContent content)
{
if (IsInActiveList(content))
RemoveFromActiveList(content);
if (ListContent.Contains(content))
ListContent.Remove(content);
}
private IDockContent m_lastActiveContent = null;
private IDockContent LastActiveContent
{
get { return m_lastActiveContent; }
set { m_lastActiveContent = value; }
}
private bool IsInActiveList(IDockContent content)
{
return !(content.DockHandler.NextActive == null && LastActiveContent != content);
}
private void AddLastToActiveList(IDockContent content)
{
IDockContent last = LastActiveContent;
if (last == content)
return;
DockContentHandler handler = content.DockHandler;
if (IsInActiveList(content))
RemoveFromActiveList(content);
handler.PreviousActive = last;
handler.NextActive = null;
LastActiveContent = content;
if (last != null)
last.DockHandler.NextActive = LastActiveContent;
}
private void RemoveFromActiveList(IDockContent content)
{
if (LastActiveContent == content)
LastActiveContent = content.DockHandler.PreviousActive;
IDockContent prev = content.DockHandler.PreviousActive;
IDockContent next = content.DockHandler.NextActive;
if (prev != null)
prev.DockHandler.NextActive = next;
if (next != null)
next.DockHandler.PreviousActive = prev;
content.DockHandler.PreviousActive = null;
content.DockHandler.NextActive = null;
}
public void GiveUpFocus(IDockContent content)
{
DockContentHandler handler = content.DockHandler;
if (!handler.Form.ContainsFocus)
return;
if (IsFocusTrackingSuspended)
DockPanel.DummyControl.Focus();
if (LastActiveContent == content)
{
IDockContent prev = handler.PreviousActive;
if (prev != null)
Activate(prev);
else if (ListContent.Count > 0)
Activate(ListContent[ListContent.Count - 1]);
}
else if (LastActiveContent != null)
Activate(LastActiveContent);
else if (ListContent.Count > 0)
Activate(ListContent[ListContent.Count - 1]);
}
private static bool ContentContains(IDockContent content, IntPtr hWnd)
{
Control control = Control.FromChildHandle(hWnd);
for (Control parent = control; parent != null; parent = parent.Parent)
if (parent == content.DockHandler.Form)
return true;
return false;
}
private uint m_countSuspendFocusTracking = 0;
public void SuspendFocusTracking()
{
if (m_disposed)
return;
if (m_countSuspendFocusTracking++ == 0)
{
if (!Win32Helper.IsRunningOnMono)
sm_localWindowsHook.HookInvoked -= m_hookEventHandler;
}
}
public void ResumeFocusTracking()
{
if (m_disposed || m_countSuspendFocusTracking == 0)
return;
if (--m_countSuspendFocusTracking == 0)
{
if (ContentActivating != null)
{
Activate(ContentActivating);
ContentActivating = null;
}
if (!Win32Helper.IsRunningOnMono)
sm_localWindowsHook.HookInvoked += m_hookEventHandler;
if (!InRefreshActiveWindow)
RefreshActiveWindow();
}
}
public bool IsFocusTrackingSuspended
{
get { return m_countSuspendFocusTracking != 0; }
}
// Windows hook event handler
private void HookEventHandler(object sender, HookEventArgs e)
{
Win32.Msgs msg = (Win32.Msgs)Marshal.ReadInt32(e.lParam, IntPtr.Size * 3);
if (msg == Win32.Msgs.WM_KILLFOCUS)
{
IntPtr wParam = Marshal.ReadIntPtr(e.lParam, IntPtr.Size * 2);
DockPane pane = GetPaneFromHandle(wParam);
if (pane == null)
RefreshActiveWindow();
}
else if (msg == Win32.Msgs.WM_SETFOCUS || msg == Win32.Msgs.WM_MDIACTIVATE)
RefreshActiveWindow();
}
private DockPane GetPaneFromHandle(IntPtr hWnd)
{
Control control = Control.FromChildHandle(hWnd);
IDockContent content = null;
DockPane pane = null;
for (; control != null; control = control.Parent)
{
content = control as IDockContent;
if (content != null)
content.DockHandler.ActiveWindowHandle = hWnd;
if (content != null && content.DockHandler.DockPanel == DockPanel)
return content.DockHandler.Pane;
pane = control as DockPane;
if (pane != null && pane.DockPanel == DockPanel)
break;
}
return pane;
}
private bool m_inRefreshActiveWindow = false;
private bool InRefreshActiveWindow
{
get { return m_inRefreshActiveWindow; }
}
private void RefreshActiveWindow()
{
SuspendFocusTracking();
m_inRefreshActiveWindow = true;
DockPane oldActivePane = ActivePane;
IDockContent oldActiveContent = ActiveContent;
IDockContent oldActiveDocument = ActiveDocument;
SetActivePane();
SetActiveContent();
SetActiveDocumentPane();
SetActiveDocument();
DockPanel.AutoHideWindow.RefreshActivePane();
ResumeFocusTracking();
m_inRefreshActiveWindow = false;
if (oldActiveContent != ActiveContent)
DockPanel.OnActiveContentChanged(EventArgs.Empty);
if (oldActiveDocument != ActiveDocument)
DockPanel.OnActiveDocumentChanged(EventArgs.Empty);
if (oldActivePane != ActivePane)
DockPanel.OnActivePaneChanged(EventArgs.Empty);
}
private DockPane m_activePane = null;
public DockPane ActivePane
{
get { return m_activePane; }
}
private void SetActivePane()
{
DockPane value = Win32Helper.IsRunningOnMono ? null : GetPaneFromHandle(NativeMethods.GetFocus());
if (m_activePane == value)
return;
if (m_activePane != null)
m_activePane.SetIsActivated(false);
m_activePane = value;
if (m_activePane != null)
m_activePane.SetIsActivated(true);
}
private IDockContent m_activeContent = null;
public IDockContent ActiveContent
{
get { return m_activeContent; }
}
internal void SetActiveContent()
{
IDockContent value = ActivePane == null ? null : ActivePane.ActiveContent;
if (m_activeContent == value)
return;
if (m_activeContent != null)
m_activeContent.DockHandler.IsActivated = false;
m_activeContent = value;
if (m_activeContent != null)
{
m_activeContent.DockHandler.IsActivated = true;
if (!DockHelper.IsDockStateAutoHide((m_activeContent.DockHandler.DockState)))
AddLastToActiveList(m_activeContent);
}
}
private DockPane m_activeDocumentPane = null;
public DockPane ActiveDocumentPane
{
get { return m_activeDocumentPane; }
}
private void SetActiveDocumentPane()
{
DockPane value = null;
if (ActivePane != null && ActivePane.DockState == DockState.Document)
value = ActivePane;
if (value == null && DockPanel.DockWindows != null)
{
if (ActiveDocumentPane == null)
value = DockPanel.DockWindows[DockState.Document].DefaultPane;
else if (ActiveDocumentPane.DockPanel != DockPanel || ActiveDocumentPane.DockState != DockState.Document)
value = DockPanel.DockWindows[DockState.Document].DefaultPane;
else
value = ActiveDocumentPane;
}
if (m_activeDocumentPane == value)
return;
if (m_activeDocumentPane != null)
m_activeDocumentPane.SetIsActiveDocumentPane(false);
m_activeDocumentPane = value;
if (m_activeDocumentPane != null)
m_activeDocumentPane.SetIsActiveDocumentPane(true);
}
private IDockContent m_activeDocument = null;
public IDockContent ActiveDocument
{
get { return m_activeDocument; }
}
private void SetActiveDocument()
{
IDockContent value = ActiveDocumentPane == null ? null : ActiveDocumentPane.ActiveContent;
if (m_activeDocument == value)
return;
m_activeDocument = value;
}
}
private IFocusManager FocusManager
{
get { return m_focusManager; }
}
internal IContentFocusManager ContentFocusManager
{
get { return m_focusManager; }
}
internal void SaveFocus()
{
DummyControl.Focus();
}
[Browsable(false)]
public IDockContent ActiveContent
{
get { return FocusManager.ActiveContent; }
}
[Browsable(false)]
public DockPane ActivePane
{
get { return FocusManager.ActivePane; }
}
[Browsable(false)]
public IDockContent ActiveDocument
{
get { return FocusManager.ActiveDocument; }
}
[Browsable(false)]
public DockPane ActiveDocumentPane
{
get { return FocusManager.ActiveDocumentPane; }
}
private static readonly object ActiveDocumentChangedEvent = new object();
[LocalizedCategory("Category_PropertyChanged")]
[LocalizedDescription("DockPanel_ActiveDocumentChanged_Description")]
public event EventHandler ActiveDocumentChanged
{
add { Events.AddHandler(ActiveDocumentChangedEvent, value); }
remove { Events.RemoveHandler(ActiveDocumentChangedEvent, value); }
}
protected virtual void OnActiveDocumentChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[ActiveDocumentChangedEvent];
if (handler != null)
handler(this, e);
}
private static readonly object ActiveContentChangedEvent = new object();
[LocalizedCategory("Category_PropertyChanged")]
[LocalizedDescription("DockPanel_ActiveContentChanged_Description")]
public event EventHandler ActiveContentChanged
{
add { Events.AddHandler(ActiveContentChangedEvent, value); }
remove { Events.RemoveHandler(ActiveContentChangedEvent, value); }
}
protected void OnActiveContentChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[ActiveContentChangedEvent];
if (handler != null)
handler(this, e);
}
private static readonly object ActivePaneChangedEvent = new object();
[LocalizedCategory("Category_PropertyChanged")]
[LocalizedDescription("DockPanel_ActivePaneChanged_Description")]
public event EventHandler ActivePaneChanged
{
add { Events.AddHandler(ActivePaneChangedEvent, value); }
remove { Events.RemoveHandler(ActivePaneChangedEvent, value); }
}
protected virtual void OnActivePaneChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[ActivePaneChangedEvent];
if (handler != null)
handler(this, e);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.DotNet.XUnitExtensions;
using Xunit;
using Xunit.Abstractions;
namespace System.IO.Tests
{
public class FileSystemWatcherTests : FileSystemWatcherTest
{
private static void ValidateDefaults(FileSystemWatcher watcher, string path, string filter)
{
Assert.False(watcher.EnableRaisingEvents);
Assert.Equal(filter, watcher.Filter);
Assert.False(watcher.IncludeSubdirectories);
Assert.Equal(8192, watcher.InternalBufferSize);
Assert.Equal(NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName, watcher.NotifyFilter);
Assert.Equal(path, watcher.Path);
}
[Fact]
public void FileSystemWatcher_NewFileInfoAction_TriggersNothing()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
{
Action action = () => new FileInfo(file.Path);
ExpectEvent(watcher, 0, action, expectedPath: file.Path);
}
}
[Fact]
public void FileSystemWatcher_FileInfoGetter_TriggersNothing()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
{
FileAttributes res;
Action action = () => res = new FileInfo(file.Path).Attributes;
ExpectEvent(watcher, 0, action, expectedPath: file.Path);
}
}
[Fact]
public void FileSystemWatcher_EmptyAction_TriggersNothing()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
{
Action action = () => { };
ExpectEvent(watcher, 0, action, expectedPath: file.Path);
}
}
[Fact]
public void FileSystemWatcher_ctor()
{
string path = string.Empty;
string pattern = "*";
using (FileSystemWatcher watcher = new FileSystemWatcher())
ValidateDefaults(watcher, path, pattern);
}
[Fact]
public void FileSystemWatcher_ctor_path()
{
string path = @".";
string pattern = "*";
using (FileSystemWatcher watcher = new FileSystemWatcher(path))
ValidateDefaults(watcher, path, pattern);
}
[Fact]
public void FileSystemWatcher_ctor_path_pattern()
{
string path = @".";
string pattern = "honey.jar";
using (FileSystemWatcher watcher = new FileSystemWatcher(path, pattern))
ValidateDefaults(watcher, path, pattern);
}
[Fact]
public void FileSystemWatcher_ctor_NullStrings()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
{
// Null filter
Assert.Throws<ArgumentNullException>("filter", () => new FileSystemWatcher(testDirectory.Path, null));
// Null path
Assert.Throws<ArgumentNullException>("path", () => new FileSystemWatcher(null, null));
Assert.Throws<ArgumentNullException>("path", () => new FileSystemWatcher(null));
Assert.Throws<ArgumentNullException>("path", () => new FileSystemWatcher(null, "*"));
}
}
[Fact]
public void FileSystemWatcher_ctor_InvalidStrings()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
{
// Empty path
AssertExtensions.Throws<ArgumentException>("path", () => new FileSystemWatcher(string.Empty));
AssertExtensions.Throws<ArgumentException>("path", () => new FileSystemWatcher(string.Empty, "*"));
// Invalid directory
AssertExtensions.Throws<ArgumentException>("path", () => new FileSystemWatcher(GetTestFilePath()));
AssertExtensions.Throws<ArgumentException>("path", () => new FileSystemWatcher(GetTestFilePath(), "*"));
}
}
[Fact]
public void FileSystemWatcher_Changed()
{
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
var handler = new FileSystemEventHandler((o, e) => { });
// add / remove
watcher.Changed += handler;
watcher.Changed -= handler;
// shouldn't throw
watcher.Changed -= handler;
}
}
[Fact]
public void FileSystemWatcher_Created()
{
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
var handler = new FileSystemEventHandler((o, e) => { });
// add / remove
watcher.Created += handler;
watcher.Created -= handler;
// shouldn't throw
watcher.Created -= handler;
}
}
[Fact]
public void FileSystemWatcher_Deleted()
{
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
var handler = new FileSystemEventHandler((o, e) => { });
// add / remove
watcher.Deleted += handler;
watcher.Deleted -= handler;
// shouldn't throw
watcher.Deleted -= handler;
}
}
[Fact]
public void FileSystemWatcher_Disposed()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Dispose();
watcher.Dispose(); // shouldn't throw
Assert.Throws<ObjectDisposedException>(() => watcher.EnableRaisingEvents = true);
}
[Fact]
public void FileSystemWatcher_EnableRaisingEvents()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
{
FileSystemWatcher watcher = new FileSystemWatcher(testDirectory.Path);
Assert.False(watcher.EnableRaisingEvents);
watcher.EnableRaisingEvents = true;
Assert.True(watcher.EnableRaisingEvents);
watcher.EnableRaisingEvents = false;
Assert.False(watcher.EnableRaisingEvents);
}
}
[Fact]
public void FileSystemWatcher_Error()
{
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
var handler = new ErrorEventHandler((o, e) => { });
// add / remove
watcher.Error += handler;
watcher.Error -= handler;
// shouldn't throw
watcher.Error -= handler;
}
}
[Fact]
public void FileSystemWatcher_Filter()
{
FileSystemWatcher watcher = new FileSystemWatcher();
Assert.Equal("*", watcher.Filter);
// Null and empty should be mapped to "*"
watcher.Filter = null;
Assert.Equal("*", watcher.Filter);
watcher.Filter = string.Empty;
Assert.Equal("*", watcher.Filter);
watcher.Filter = " ";
Assert.Equal(" ", watcher.Filter);
watcher.Filter = "\0";
Assert.Equal("\0", watcher.Filter);
watcher.Filter = "\n";
Assert.Equal("\n", watcher.Filter);
watcher.Filter = "abc.dll";
Assert.Equal("abc.dll", watcher.Filter);
if (!(PlatformDetection.IsOSX))
{
watcher.Filter = "ABC.DLL";
Assert.Equal("ABC.DLL", watcher.Filter);
}
// We can make this setting by first changing to another value then back.
watcher.Filter = null;
watcher.Filter = "ABC.DLL";
Assert.Equal("ABC.DLL", watcher.Filter);
}
[Fact]
public void FileSystemWatcher_IncludeSubdirectories()
{
FileSystemWatcher watcher = new FileSystemWatcher();
Assert.False(watcher.IncludeSubdirectories);
watcher.IncludeSubdirectories = true;
Assert.True(watcher.IncludeSubdirectories);
watcher.IncludeSubdirectories = false;
Assert.False(watcher.IncludeSubdirectories);
}
[Fact]
public void FileSystemWatcher_InternalBufferSize()
{
FileSystemWatcher watcher = new FileSystemWatcher();
Assert.Equal(8192, watcher.InternalBufferSize);
watcher.InternalBufferSize = 20000;
Assert.Equal(20000, watcher.InternalBufferSize);
watcher.InternalBufferSize = int.MaxValue;
Assert.Equal(int.MaxValue, watcher.InternalBufferSize);
// FSW enforces a minimum value of 4096
watcher.InternalBufferSize = 0;
Assert.Equal(4096, watcher.InternalBufferSize);
watcher.InternalBufferSize = -1;
Assert.Equal(4096, watcher.InternalBufferSize);
watcher.InternalBufferSize = int.MinValue;
Assert.Equal(4096, watcher.InternalBufferSize);
watcher.InternalBufferSize = 4095;
Assert.Equal(4096, watcher.InternalBufferSize);
}
[Fact]
public void FileSystemWatcher_NotifyFilter()
{
FileSystemWatcher watcher = new FileSystemWatcher();
Assert.Equal(NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName, watcher.NotifyFilter);
var notifyFilters = Enum.GetValues(typeof(NotifyFilters)).Cast<NotifyFilters>();
foreach (NotifyFilters filterValue in notifyFilters)
{
watcher.NotifyFilter = filterValue;
Assert.Equal(filterValue, watcher.NotifyFilter);
}
var allFilters = notifyFilters.Aggregate((mask, flag) => mask | flag);
watcher.NotifyFilter = allFilters;
Assert.Equal(allFilters, watcher.NotifyFilter);
// This doesn't make sense, but it is permitted.
watcher.NotifyFilter = 0;
Assert.Equal((NotifyFilters)0, watcher.NotifyFilter);
// These throw InvalidEnumException on desktop, but ArgumentException on K
Assert.ThrowsAny<ArgumentException>(() => watcher.NotifyFilter = (NotifyFilters)(-1));
Assert.ThrowsAny<ArgumentException>(() => watcher.NotifyFilter = (NotifyFilters)int.MinValue);
Assert.ThrowsAny<ArgumentException>(() => watcher.NotifyFilter = (NotifyFilters)int.MaxValue);
Assert.ThrowsAny<ArgumentException>(() => watcher.NotifyFilter = allFilters + 1);
// Simulate a bit added to the flags
Assert.ThrowsAny<ArgumentException>(() => watcher.NotifyFilter = allFilters | (NotifyFilters)((int)notifyFilters.Max() << 1));
}
[Fact]
public void FileSystemWatcher_OnChanged()
{
using (TestFileSystemWatcher watcher = new TestFileSystemWatcher())
{
bool eventOccurred = false;
object obj = null;
FileSystemEventArgs actualArgs = null, expectedArgs = new FileSystemEventArgs(WatcherChangeTypes.Changed, "directory", "file");
watcher.Changed += (o, e) =>
{
eventOccurred = true;
obj = o;
actualArgs = e;
};
watcher.CallOnChanged(expectedArgs);
Assert.True(eventOccurred, "Event should be invoked");
Assert.Equal(watcher, obj);
Assert.Equal(expectedArgs, actualArgs);
}
}
[Fact]
public void FileSystemWatcher_OnCreated()
{
using (TestFileSystemWatcher watcher = new TestFileSystemWatcher())
{
bool eventOccurred = false;
object obj = null;
FileSystemEventArgs actualArgs = null, expectedArgs = new FileSystemEventArgs(WatcherChangeTypes.Created, "directory", "file");
watcher.Created += (o, e) =>
{
eventOccurred = true;
obj = o;
actualArgs = e;
};
watcher.CallOnCreated(expectedArgs);
Assert.True(eventOccurred, "Event should be invoked");
Assert.Equal(watcher, obj);
Assert.Equal(expectedArgs, actualArgs);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX | TestPlatforms.Windows)] // Casing matters on Linux
public void FileSystemWatcher_OnCreatedWithMismatchedCasingGivesExpectedFullPath()
{
using (var dir = new TempDirectory(GetTestFilePath()))
using (var fsw = new FileSystemWatcher(dir.Path))
{
AutoResetEvent are = new AutoResetEvent(false);
string fullPath = Path.Combine(dir.Path.ToUpper(), "Foo.txt");
fsw.Created += (o, e) =>
{
Assert.True(fullPath.Equals(e.FullPath, StringComparison.OrdinalIgnoreCase));
are.Set();
};
fsw.EnableRaisingEvents = true;
using (var file = new TempFile(fullPath))
{
ExpectEvent(are, "created");
}
}
}
[Fact]
public void FileSystemWatcher_OnDeleted()
{
using (TestFileSystemWatcher watcher = new TestFileSystemWatcher())
{
bool eventOccurred = false;
object obj = null;
FileSystemEventArgs actualArgs = null, expectedArgs = new FileSystemEventArgs(WatcherChangeTypes.Deleted, "directory", "file");
watcher.Deleted += (o, e) =>
{
eventOccurred = true;
obj = o;
actualArgs = e;
};
watcher.CallOnDeleted(expectedArgs);
Assert.True(eventOccurred, "Event should be invoked");
Assert.Equal(watcher, obj);
Assert.Equal(expectedArgs, actualArgs);
}
}
[Fact]
public void FileSystemWatcher_OnError()
{
using (TestFileSystemWatcher watcher = new TestFileSystemWatcher())
{
bool eventOccurred = false;
object obj = null;
ErrorEventArgs actualArgs = null, expectedArgs = new ErrorEventArgs(new Exception());
watcher.Error += (o, e) =>
{
eventOccurred = true;
obj = o;
actualArgs = e;
};
watcher.CallOnError(expectedArgs);
Assert.True(eventOccurred, "Event should be invoked");
Assert.Equal(watcher, obj);
Assert.Equal(expectedArgs, actualArgs);
}
}
[Fact]
public void FileSystemWatcher_OnRenamed()
{
using (TestFileSystemWatcher watcher = new TestFileSystemWatcher())
{
bool eventOccurred = false;
object obj = null;
RenamedEventArgs actualArgs = null, expectedArgs = new RenamedEventArgs(WatcherChangeTypes.Renamed, "directory", "file", "oldFile");
watcher.Renamed += (o, e) =>
{
eventOccurred = true;
obj = o;
actualArgs = e;
};
watcher.CallOnRenamed(expectedArgs);
Assert.True(eventOccurred, "Event should be invoked");
Assert.Equal(watcher, obj);
Assert.Equal(expectedArgs, actualArgs);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Unix FSW don't trigger on a file rename.
public void FileSystemWatcher_Windows_OnRenameGivesExpectedFullPath()
{
using (var dir = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(dir.Path, "file")))
using (var fsw = new FileSystemWatcher(dir.Path))
{
AutoResetEvent eventOccurred = WatchRenamed(fsw).EventOccured;
string newPath = Path.Combine(dir.Path, "newPath");
fsw.Renamed += (o, e) =>
{
Assert.Equal(file.Path, e.OldFullPath);
Assert.Equal(newPath, e.FullPath);
};
fsw.EnableRaisingEvents = true;
File.Move(file.Path, newPath);
ExpectEvent(eventOccurred, "renamed");
}
}
[Fact]
public void FileSystemWatcher_Path()
{
FileSystemWatcher watcher = new FileSystemWatcher();
Assert.Equal(string.Empty, watcher.Path);
watcher.Path = null;
Assert.Equal(string.Empty, watcher.Path);
watcher.Path = ".";
Assert.Equal(".", watcher.Path);
if (!PlatformDetection.IsInAppContainer)
{
watcher.Path = "..";
Assert.Equal("..", watcher.Path);
}
string currentDir = Path.GetFullPath(".").TrimEnd('.', Path.DirectorySeparatorChar);
watcher.Path = currentDir;
Assert.Equal(currentDir, watcher.Path);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || // expect no change for OrdinalIgnoreCase-equal strings
RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
watcher.Path = currentDir.ToUpperInvariant();
Assert.Equal(currentDir, watcher.Path);
watcher.Path = currentDir.ToLowerInvariant();
Assert.Equal(currentDir, watcher.Path);
}
// expect a change for same "full-path" but different string path, FSW does not normalize
string currentDirRelative = currentDir +
Path.DirectorySeparatorChar + "." +
Path.DirectorySeparatorChar + "." +
Path.DirectorySeparatorChar + "." +
Path.DirectorySeparatorChar + ".";
watcher.Path = currentDirRelative;
Assert.Equal(currentDirRelative, watcher.Path);
// FSW starts with String.Empty and will ignore setting this if it is already set,
// but if you set it after some other valid string has been set it will throw.
Assert.Throws<ArgumentException>(() => watcher.Path = string.Empty);
// Non-existent path
Assert.Throws<ArgumentException>(() => watcher.Path = GetTestFilePath());
// Web path
Assert.Throws<ArgumentException>(() => watcher.Path = "http://localhost");
// File protocol
Assert.Throws<ArgumentException>(() => watcher.Path = "file:///" + currentDir.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
}
[Fact]
public void FileSystemWatcher_Renamed()
{
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
var handler = new RenamedEventHandler((o, e) => { });
// add / remove
watcher.Renamed += handler;
watcher.Renamed -= handler;
// shouldn't throw
watcher.Renamed -= handler;
}
}
[Fact]
public void FileSystemWatcher_StopCalledOnBackgroundThreadDoesNotDeadlock()
{
// Check the case where Stop or Dispose (they do the same thing) is called from
// a FSW event callback and make sure we don't Thread.Join to deadlock
using (var dir = new TempDirectory(GetTestFilePath()))
{
string filePath = Path.Combine(dir.Path, "testfile.txt");
File.Create(filePath).Dispose();
AutoResetEvent are = new AutoResetEvent(false);
FileSystemWatcher watcher = new FileSystemWatcher(Path.GetFullPath(dir.Path), "*");
FileSystemEventHandler callback = (sender, arg) =>
{
watcher.Dispose();
are.Set();
};
watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
watcher.Changed += callback;
watcher.EnableRaisingEvents = true;
File.SetLastWriteTime(filePath, File.GetLastWriteTime(filePath).AddDays(1));
Assert.True(are.WaitOne(10000));
Assert.Throws<ObjectDisposedException>(() => watcher.EnableRaisingEvents = true);
}
}
[Fact]
public void FileSystemWatcher_WatchingAliasedFolderResolvesToRealPathWhenWatching()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, "dir")))
using (var fsw = new FileSystemWatcher(dir.Path))
{
AutoResetEvent are = WatchCreated(fsw).EventOccured;
fsw.Filter = "*";
fsw.EnableRaisingEvents = true;
using (var temp = new TempDirectory(Path.Combine(dir.Path, "foo")))
{
ExpectEvent(are, "created");
}
}
}
[Fact]
public void DefaultFiltersValue()
{
var watcher = new FileSystemWatcher();
Assert.Equal(0, watcher.Filters.Count);
Assert.Empty(watcher.Filters);
Assert.NotNull(watcher.Filters);
Assert.Equal(new string[] { }, watcher.Filters);
}
[Fact]
public void AddFilterToFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
Assert.Equal(2, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "*.dll" }, watcher.Filters);
string[] copied = new string[2];
watcher.Filters.CopyTo(copied, 0);
Assert.Equal(new string[] { "*.pdb", "*.dll" }, copied);
}
[Fact]
public void FiltersCaseSensitive()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("foo");
Assert.Equal("foo", watcher.Filters[0]);
watcher.Filters[0] = "Foo";
Assert.Equal("Foo", watcher.Filters[0]);
}
[Fact]
public void RemoveFilterFromFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Remove("*.pdb");
Assert.DoesNotContain(watcher.Filters, t => t == "*.pdb");
Assert.Equal(new string[] { "*.dll" }, watcher.Filters);
// No Exception is thrown while removing an item which is not present in the list.
watcher.Filters.Remove("*.pdb");
}
[Fact]
public void AddEmptyStringToFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Add(string.Empty);
Assert.Equal(3, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "*.dll", "*" }, watcher.Filters);
}
[Fact]
public void AddNullToFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Add(null);
Assert.Equal(3, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "*.dll", "*" }, watcher.Filters);
}
[Fact]
public void SetEmptyStringToFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters[0] = string.Empty;
Assert.Equal(2, watcher.Filters.Count);
Assert.Equal("*", watcher.Filters[0]);
Assert.Equal(new string[] { "*", "*.dll"}, watcher.Filters);
}
[Fact]
public void RemoveEmptyStringToFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Add(string.Empty);
Assert.Equal(3, watcher.Filters.Count);
watcher.Filters.Remove(string.Empty);
Assert.Equal(3, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "*.dll", "*" }, watcher.Filters);
}
[Fact]
public void RemoveAtFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.RemoveAt(0);
Assert.Equal(1, watcher.Filters.Count);
Assert.Equal("*.dll", watcher.Filter);
Assert.Equal(new string[] {"*.dll" }, watcher.Filters);
}
[Fact]
public void RemoveAtEmptyFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.RemoveAt(0);
Assert.Equal(0, watcher.Filters.Count);
Assert.Equal("*", watcher.Filter);
Assert.Equal(new string[] { }, watcher.Filters);
}
[Fact]
public void SetNullToFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters[0] = null;
Assert.Equal(2, watcher.Filters.Count);
Assert.Equal("*", watcher.Filters[0]);
Assert.Equal(new string[] { "*", "*.dll" }, watcher.Filters);
}
[Fact]
public void ContainsEmptyStringFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Add(string.Empty);
Assert.DoesNotContain(string.Empty, watcher.Filters);
Assert.Contains("*", watcher.Filters);
}
[Fact]
public void ContainsNullFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Add(null);
Assert.DoesNotContain(null, watcher.Filters);
Assert.Contains("*", watcher.Filters);
}
[Fact]
public void ContainsFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
Assert.Contains("*.pdb", watcher.Filters);
}
[Fact]
public void InsertEmptyStringFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Insert(1, string.Empty);
Assert.Equal("*", watcher.Filters[1]);
Assert.Equal(3, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "*", "*.dll" }, watcher.Filters);
}
[Fact]
public void InsertNullFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Insert(1, null);
Assert.Equal("*", watcher.Filters[1]);
Assert.Equal(3, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "*", "*.dll" }, watcher.Filters);
}
[Fact]
public void InsertFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Insert(1, "foo");
Assert.Equal("foo", watcher.Filters[1]);
Assert.Equal(3, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "foo", "*.dll" }, watcher.Filters);
}
[Fact]
public void InsertAtZero()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Insert(0, "foo");
Assert.Equal("foo", watcher.Filters[0]);
Assert.Equal("foo", watcher.Filter);
Assert.Equal(3, watcher.Filters.Count);
Assert.Equal(new string[] { "foo", "*.pdb", "*.dll" }, watcher.Filters);
}
[Fact]
public void IndexOfEmptyStringFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Add(string.Empty);
Assert.Equal(-1, watcher.Filters.IndexOf(string.Empty));
}
[Fact]
public void IndexOfNullFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Add(null);
Assert.Equal(-1, watcher.Filters.IndexOf(null));
}
[Fact]
public void IndexOfFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
Assert.Equal(-1, watcher.Filters.IndexOf("foo"));
Assert.Equal(0, watcher.Filters.IndexOf("*.pdb"));
}
[Fact]
public void GetTypeFilters()
{
var watcher = new FileSystemWatcher();
Assert.IsAssignableFrom<Collection<string>>(watcher.Filters);
}
[Fact]
public void ClearFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Clear();
Assert.Equal(0, watcher.Filters.Count);
Assert.Equal(new string[] { }, watcher.Filters) ;
}
[Fact]
public void GetFilterAfterFiltersClear()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
{
var watcher = new FileSystemWatcher(testDirectory.Path);
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Clear();
Assert.Equal("*", watcher.Filter);
Assert.Equal(new string[] { }, watcher.Filters);
}
}
[Fact]
public void GetFiltersAfterFiltersClear()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
{
var watcher = new FileSystemWatcher(testDirectory.Path);
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Clear();
Assert.Throws<ArgumentOutOfRangeException>(() => watcher.Filters[0]);
Assert.Equal(0, watcher.Filters.Count);
Assert.Empty(watcher.Filters);
Assert.NotNull(watcher.Filters);
}
}
[Fact]
public void InvalidOperationsOnFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
Assert.Throws<ArgumentOutOfRangeException>(() => watcher.Filters.Insert(4, "*"));
watcher.Filters.Clear();
Assert.Throws<ArgumentOutOfRangeException>(() => watcher.Filters[0]);
}
[Fact]
public void SetAndGetFilterProperty()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
{
var watcher = new FileSystemWatcher(testDirectory.Path, "*.pdb");
watcher.Filters.Add("foo");
Assert.Equal(2, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "foo" }, watcher.Filters);
watcher.Filter = "*.doc";
Assert.Equal(1, watcher.Filters.Count);
Assert.Equal("*.doc", watcher.Filter);
Assert.Equal("*.doc", watcher.Filters[0]);
Assert.Equal(new string[] { "*.doc" }, watcher.Filters);
watcher.Filters.Clear();
Assert.Equal("*", watcher.Filter);
}
}
[Fact]
public void SetAndGetFiltersProperty()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
{
var watcher = new FileSystemWatcher(testDirectory.Path, "*.pdb");
watcher.Filters.Add("foo");
Assert.Equal(new string[] { "*.pdb", "foo" }, watcher.Filters);
}
}
[Fact]
public void FileSystemWatcher_File_Delete_MultipleFilters()
{
// Check delete events against multiple filters
DirectoryInfo directory = Directory.CreateDirectory(GetTestFilePath());
FileInfo fileOne = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
FileInfo fileTwo = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
FileInfo fileThree = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
fileOne.Create().Dispose();
fileTwo.Create().Dispose();
fileThree.Create().Dispose();
using (var watcher = new FileSystemWatcher(directory.FullName))
{
watcher.Filters.Add(fileOne.Name);
watcher.Filters.Add(fileTwo.Name);
ExpectEvent(watcher, WatcherChangeTypes.Deleted, () => fileOne.Delete(), cleanup: null, expectedPath : fileOne.FullName);
ExpectEvent(watcher, WatcherChangeTypes.Deleted, () => fileTwo.Delete(), cleanup: null, expectedPath: fileTwo.FullName );
ExpectNoEvent(watcher, WatcherChangeTypes.Deleted, () => fileThree.Delete(), cleanup: null, expectedPath: fileThree.FullName);
}
}
[Fact]
public void FileSystemWatcher_Directory_Create_MultipleFilters()
{
// Check create events against multiple filters
DirectoryInfo directory = Directory.CreateDirectory(GetTestFilePath());
string directoryOne = Path.Combine(directory.FullName, GetTestFileName());
string directoryTwo = Path.Combine(directory.FullName, GetTestFileName());
string directoryThree = Path.Combine(directory.FullName, GetTestFileName());
using (var watcher = new FileSystemWatcher(directory.FullName))
{
watcher.Filters.Add(Path.GetFileName(directoryOne));
watcher.Filters.Add(Path.GetFileName(directoryTwo));
ExpectEvent(watcher, WatcherChangeTypes.Created, () => Directory.CreateDirectory(directoryOne), cleanup: null, expectedPath: directoryOne);
ExpectEvent(watcher, WatcherChangeTypes.Created, () => Directory.CreateDirectory(directoryTwo), cleanup: null, expectedPath: directoryTwo);
ExpectNoEvent(watcher, WatcherChangeTypes.Created, () => Directory.CreateDirectory(directoryThree), cleanup: null, expectedPath: directoryThree);
}
}
[Fact]
public void FileSystemWatcher_Directory_Create_Filter_Ctor()
{
// Check create events against multiple filters
DirectoryInfo directory = Directory.CreateDirectory(GetTestFilePath());
string directoryOne = Path.Combine(directory.FullName, GetTestFileName());
string directoryTwo = Path.Combine(directory.FullName, GetTestFileName());
string directoryThree = Path.Combine(directory.FullName, GetTestFileName());
using (var watcher = new FileSystemWatcher(directory.FullName, Path.GetFileName(directoryOne)))
{
watcher.Filters.Add(Path.GetFileName(directoryTwo));
ExpectEvent(watcher, WatcherChangeTypes.Created, () => Directory.CreateDirectory(directoryOne), cleanup: null, expectedPath: directoryOne);
ExpectEvent(watcher, WatcherChangeTypes.Created, () => Directory.CreateDirectory(directoryTwo), cleanup: null, expectedPath: directoryTwo);
ExpectNoEvent(watcher, WatcherChangeTypes.Created, () => Directory.CreateDirectory(directoryThree), cleanup: null, expectedPath: directoryThree);
}
}
[Fact]
public void FileSystemWatcher_Directory_Delete_MultipleFilters()
{
DirectoryInfo directory = Directory.CreateDirectory(GetTestFilePath());
DirectoryInfo directoryOne = Directory.CreateDirectory(Path.Combine(directory.FullName, GetTestFileName()));
DirectoryInfo directoryTwo = Directory.CreateDirectory(Path.Combine(directory.FullName, GetTestFileName()));
DirectoryInfo directoryThree = Directory.CreateDirectory(Path.Combine(directory.FullName, GetTestFileName()));
using (var watcher = new FileSystemWatcher(directory.FullName))
{
watcher.Filters.Add(Path.GetFileName(directoryOne.FullName));
watcher.Filters.Add(Path.GetFileName(directoryTwo.FullName));
ExpectEvent(watcher, WatcherChangeTypes.Deleted, () => directoryOne.Delete(), cleanup: null, expectedPath: directoryOne.FullName);
ExpectEvent(watcher, WatcherChangeTypes.Deleted, () => directoryTwo.Delete(), cleanup: null, expectedPath: directoryTwo.FullName);
ExpectNoEvent(watcher, WatcherChangeTypes.Deleted, () => directoryThree.Delete(), cleanup: null, expectedPath: directoryThree.FullName);
}
}
[Fact]
public void FileSystemWatcher_File_Create_MultipleFilters()
{
DirectoryInfo directory = Directory.CreateDirectory(GetTestFilePath());
FileInfo fileOne = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
FileInfo fileTwo = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
FileInfo fileThree = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
using (var watcher = new FileSystemWatcher(directory.FullName))
{
watcher.Filters.Add(fileOne.Name);
watcher.Filters.Add(fileTwo.Name);
ExpectEvent(watcher, WatcherChangeTypes.Created, () => fileOne.Create().Dispose(), cleanup: null, expectedPath: fileOne.FullName);
ExpectEvent(watcher, WatcherChangeTypes.Created, () => fileTwo.Create().Dispose(), cleanup: null, expectedPath: fileTwo.FullName);
ExpectNoEvent(watcher, WatcherChangeTypes.Created, () => fileThree.Create().Dispose(), cleanup: null, expectedPath: fileThree.FullName);
}
}
[Fact]
public void FileSystemWatcher_ModifyFiltersConcurrentWithEvents()
{
DirectoryInfo directory = Directory.CreateDirectory(GetTestFilePath());
FileInfo fileOne = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
FileInfo fileTwo = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
FileInfo fileThree = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
using (var watcher = new FileSystemWatcher(directory.FullName))
{
watcher.Filters.Add(fileOne.Name);
watcher.Filters.Add(fileTwo.Name);
var cts = new CancellationTokenSource();
Task modifier = Task.Run(() =>
{
string otherFilter = Guid.NewGuid().ToString("N");
while (!cts.IsCancellationRequested)
{
watcher.Filters.Add(otherFilter);
watcher.Filters.RemoveAt(2);
}
});
ExpectEvent(watcher, WatcherChangeTypes.Created, () => fileOne.Create().Dispose(), cleanup: null, expectedPath: fileOne.FullName);
ExpectEvent(watcher, WatcherChangeTypes.Created, () => fileTwo.Create().Dispose(), cleanup: null, expectedPath: fileTwo.FullName);
ExpectNoEvent(watcher, WatcherChangeTypes.Created, () => fileThree.Create().Dispose(), cleanup: null, expectedPath: fileThree.FullName);
cts.Cancel();
modifier.Wait();
}
}
}
[Collection("NoParallelTests")]
public class DangerousFileSystemWatcherTests : FileSystemWatcherTest
{
[PlatformSpecific(TestPlatforms.Linux)] // Reads MaxUsersWatches from Linux OS files
[OuterLoop("This test will use all available watchers and can cause failures in other concurrent tests or system processes.")]
[Fact]
public void FileSystemWatcher_CreateManyConcurrentWatches()
{
int maxUserWatches = int.Parse(File.ReadAllText("/proc/sys/fs/inotify/max_user_watches"));
using (var dir = new TempDirectory(GetTestFilePath()))
using (var watcher = new FileSystemWatcher(dir.Path) { IncludeSubdirectories = true, NotifyFilter = NotifyFilters.FileName })
{
Action action = () =>
{
// Create enough directories to exceed the number of allowed watches
for (int i = 0; i <= maxUserWatches; i++)
{
Directory.CreateDirectory(Path.Combine(dir.Path, i.ToString()));
}
};
Action cleanup = () =>
{
for (int i = 0; i <= maxUserWatches; i++)
{
Directory.Delete(Path.Combine(dir.Path, i.ToString()));
}
};
ExpectError(watcher, action, cleanup);
// Make sure existing watches still work even after we've had one or more failures
Action createAction = () => File.WriteAllText(Path.Combine(dir.Path, Path.GetRandomFileName()), "text");
Action createCleanup = () => File.Delete(Path.Combine(dir.Path, Path.GetRandomFileName()));
ExpectEvent(watcher, WatcherChangeTypes.Created, createAction, createCleanup);
}
}
}
}
| |
// 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 Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Utilities;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class CompilationContext
{
private static readonly SymbolDisplayFormat s_fullNameFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
internal readonly CSharpCompilation Compilation;
internal readonly Binder NamespaceBinder; // Internal for test purposes.
private readonly MethodSymbol _currentFrame;
private readonly ImmutableArray<LocalSymbol> _locals;
private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables;
private readonly ImmutableHashSet<string> _hoistedParameterNames;
private readonly ImmutableArray<LocalSymbol> _localsForBinding;
private readonly CSharpSyntaxNode _syntax;
private readonly bool _methodNotType;
/// <summary>
/// Create a context to compile expressions within a method scope.
/// </summary>
internal CompilationContext(
CSharpCompilation compilation,
MethodSymbol currentFrame,
ImmutableArray<LocalSymbol> locals,
InScopeHoistedLocals inScopeHoistedLocals,
MethodDebugInfo<TypeSymbol, LocalSymbol> methodDebugInfo,
CSharpSyntaxNode syntax)
{
Debug.Assert((syntax == null) || (syntax is ExpressionSyntax) || (syntax is LocalDeclarationStatementSyntax));
// TODO: syntax.SyntaxTree should probably be added to the compilation,
// but it isn't rooted by a CompilationUnitSyntax so it doesn't work (yet).
_currentFrame = currentFrame;
_syntax = syntax;
_methodNotType = !locals.IsDefault;
// NOTE: Since this is done within CompilationContext, it will not be cached.
// CONSIDER: The values should be the same everywhere in the module, so they
// could be cached.
// (Catch: what happens in a type context without a method def?)
this.Compilation = GetCompilationWithExternAliases(compilation, methodDebugInfo.ExternAliasRecords);
// Each expression compile should use a unique compilation
// to ensure expression-specific synthesized members can be
// added (anonymous types, for instance).
Debug.Assert(this.Compilation != compilation);
this.NamespaceBinder = CreateBinderChain(
this.Compilation,
(PEModuleSymbol)currentFrame.ContainingModule,
currentFrame.ContainingNamespace,
methodDebugInfo.ImportRecordGroups);
if (_methodNotType)
{
_locals = locals;
ImmutableArray<string> displayClassVariableNamesInOrder;
GetDisplayClassVariables(
currentFrame,
_locals,
inScopeHoistedLocals,
out displayClassVariableNamesInOrder,
out _displayClassVariables,
out _hoistedParameterNames);
Debug.Assert(displayClassVariableNamesInOrder.Length == _displayClassVariables.Count);
_localsForBinding = GetLocalsForBinding(_locals, displayClassVariableNamesInOrder, _displayClassVariables);
}
else
{
_locals = ImmutableArray<LocalSymbol>.Empty;
_displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty;
_localsForBinding = ImmutableArray<LocalSymbol>.Empty;
}
// Assert that the cheap check for "this" is equivalent to the expensive check for "this".
Debug.Assert(
_displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()) ==
_displayClassVariables.Values.Any(v => v.Kind == DisplayClassVariableKind.This));
}
internal CommonPEModuleBuilder CompileExpression(
string typeName,
string methodName,
ImmutableArray<Alias> aliases,
Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData,
DiagnosticBag diagnostics,
out ResultProperties resultProperties)
{
var properties = default(ResultProperties);
var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object);
var synthesizedType = new EENamedTypeSymbol(
this.Compilation.SourceModule.GlobalNamespace,
objectType,
_syntax,
_currentFrame,
typeName,
methodName,
this,
(method, diags) =>
{
var hasDisplayClassThis = _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName());
var binder = ExtendBinderChain(
_syntax,
aliases,
method,
this.NamespaceBinder,
hasDisplayClassThis,
_methodNotType);
var statementSyntax = _syntax as StatementSyntax;
return (statementSyntax == null) ?
BindExpression(binder, (ExpressionSyntax)_syntax, diags, out properties) :
BindStatement(binder, statementSyntax, diags, out properties);
});
var module = CreateModuleBuilder(
this.Compilation,
synthesizedType.Methods,
additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType),
synthesizedType: synthesizedType,
testData: testData,
diagnostics: diagnostics);
Debug.Assert(module != null);
this.Compilation.Compile(
module,
win32Resources: null,
xmlDocStream: null,
emittingPdb: false,
diagnostics: diagnostics,
filterOpt: null,
cancellationToken: CancellationToken.None);
if (diagnostics.HasAnyErrors())
{
resultProperties = default(ResultProperties);
return null;
}
// Should be no name mangling since the caller provided explicit names.
Debug.Assert(synthesizedType.MetadataName == typeName);
Debug.Assert(synthesizedType.GetMembers()[0].MetadataName == methodName);
resultProperties = properties;
return module;
}
internal CommonPEModuleBuilder CompileAssignment(
string typeName,
string methodName,
ImmutableArray<Alias> aliases,
Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData,
DiagnosticBag diagnostics,
out ResultProperties resultProperties)
{
var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object);
var synthesizedType = new EENamedTypeSymbol(
Compilation.SourceModule.GlobalNamespace,
objectType,
_syntax,
_currentFrame,
typeName,
methodName,
this,
(method, diags) =>
{
var hasDisplayClassThis = _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName());
var binder = ExtendBinderChain(
_syntax,
aliases,
method,
this.NamespaceBinder,
hasDisplayClassThis,
methodNotType: true);
return BindAssignment(binder, (ExpressionSyntax)_syntax, diags);
});
var module = CreateModuleBuilder(
this.Compilation,
synthesizedType.Methods,
additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType),
synthesizedType: synthesizedType,
testData: testData,
diagnostics: diagnostics);
Debug.Assert(module != null);
this.Compilation.Compile(
module,
win32Resources: null,
xmlDocStream: null,
emittingPdb: false,
diagnostics: diagnostics,
filterOpt: null,
cancellationToken: CancellationToken.None);
if (diagnostics.HasAnyErrors())
{
resultProperties = default(ResultProperties);
return null;
}
// Should be no name mangling since the caller provided explicit names.
Debug.Assert(synthesizedType.MetadataName == typeName);
Debug.Assert(synthesizedType.GetMembers()[0].MetadataName == methodName);
resultProperties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect);
return module;
}
private static string GetNextMethodName(ArrayBuilder<MethodSymbol> builder)
{
return string.Format("<>m{0}", builder.Count);
}
/// <summary>
/// Generate a class containing methods that represent
/// the set of arguments and locals at the current scope.
/// </summary>
internal CommonPEModuleBuilder CompileGetLocals(
string typeName,
ArrayBuilder<LocalAndMethod> localBuilder,
bool argumentsOnly,
ImmutableArray<Alias> aliases,
Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData,
DiagnosticBag diagnostics)
{
var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object);
var allTypeParameters = _currentFrame.GetAllTypeParameters();
var additionalTypes = ArrayBuilder<NamedTypeSymbol>.GetInstance();
EENamedTypeSymbol typeVariablesType = null;
if (!argumentsOnly && (allTypeParameters.Length > 0))
{
// Generate a generic type with matching type parameters.
// A null instance of the type will be used to represent the
// "Type variables" local.
typeVariablesType = new EENamedTypeSymbol(
this.Compilation.SourceModule.GlobalNamespace,
objectType,
_syntax,
_currentFrame,
ExpressionCompilerConstants.TypeVariablesClassName,
(m, t) => ImmutableArray.Create<MethodSymbol>(new EEConstructorSymbol(t)),
allTypeParameters,
(t1, t2) => allTypeParameters.SelectAsArray((tp, i, t) => (TypeParameterSymbol)new SimpleTypeParameterSymbol(t, i, tp.Name), t2));
additionalTypes.Add(typeVariablesType);
}
var synthesizedType = new EENamedTypeSymbol(
Compilation.SourceModule.GlobalNamespace,
objectType,
_syntax,
_currentFrame,
typeName,
(m, container) =>
{
var methodBuilder = ArrayBuilder<MethodSymbol>.GetInstance();
if (!argumentsOnly)
{
// Pseudo-variables: $exception, $ReturnValue, etc.
if (aliases.Length > 0)
{
var sourceAssembly = Compilation.SourceAssembly;
var typeNameDecoder = new EETypeNameDecoder(Compilation, (PEModuleSymbol)_currentFrame.ContainingModule);
foreach (var alias in aliases)
{
if (alias.IsReturnValueWithoutIndex())
{
Debug.Assert(aliases.Count(a => a.Kind == DkmClrAliasKind.ReturnValue) > 1);
continue;
}
var local = PlaceholderLocalSymbol.Create(
typeNameDecoder,
_currentFrame,
sourceAssembly,
alias);
var methodName = GetNextMethodName(methodBuilder);
var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken));
var aliasMethod = this.CreateMethod(container, methodName, syntax, (method, diags) =>
{
var expression = new BoundLocal(syntax, local, constantValueOpt: null, type: local.Type);
return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
});
var flags = local.IsWritable ? DkmClrCompilationResultFlags.None : DkmClrCompilationResultFlags.ReadOnlyResult;
localBuilder.Add(MakeLocalAndMethod(local, aliasMethod, flags));
methodBuilder.Add(aliasMethod);
}
}
// "this" for non-static methods that are not display class methods or
// display class methods where the display class contains "<>4__this".
if (!m.IsStatic && (!IsDisplayClassType(m.ContainingType) || _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName())))
{
var methodName = GetNextMethodName(methodBuilder);
var method = this.GetThisMethod(container, methodName);
localBuilder.Add(new CSharpLocalAndMethod("this", "this", method, DkmClrCompilationResultFlags.None)); // Note: writable in dev11.
methodBuilder.Add(method);
}
}
// Hoisted method parameters (represented as locals in the EE).
if (!_hoistedParameterNames.IsEmpty)
{
int localIndex = 0;
foreach (var local in _localsForBinding)
{
// Since we are showing hoisted method parameters first, the parameters may appear out of order
// in the Locals window if only some of the parameters are hoisted. This is consistent with the
// behavior of the old EE.
if (_hoistedParameterNames.Contains(local.Name))
{
AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localIndex, GetLocalResultFlags(local));
}
localIndex++;
}
}
// Method parameters (except those that have been hoisted).
int parameterIndex = m.IsStatic ? 0 : 1;
foreach (var parameter in m.Parameters)
{
var parameterName = parameter.Name;
if (!_hoistedParameterNames.Contains(parameterName) && GeneratedNames.GetKind(parameterName) == GeneratedNameKind.None)
{
AppendParameterAndMethod(localBuilder, methodBuilder, parameter, container, parameterIndex);
}
parameterIndex++;
}
if (!argumentsOnly)
{
// Locals.
int localIndex = 0;
foreach (var local in _localsForBinding)
{
if (!_hoistedParameterNames.Contains(local.Name))
{
AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localIndex, GetLocalResultFlags(local));
}
localIndex++;
}
// "Type variables".
if ((object)typeVariablesType != null)
{
var methodName = GetNextMethodName(methodBuilder);
var returnType = typeVariablesType.Construct(allTypeParameters.Cast<TypeParameterSymbol, TypeSymbol>());
var method = this.GetTypeVariablesMethod(container, methodName, returnType);
localBuilder.Add(new CSharpLocalAndMethod(
ExpressionCompilerConstants.TypeVariablesLocalName,
ExpressionCompilerConstants.TypeVariablesLocalName,
method,
DkmClrCompilationResultFlags.ReadOnlyResult));
methodBuilder.Add(method);
}
}
return methodBuilder.ToImmutableAndFree();
});
additionalTypes.Add(synthesizedType);
var module = CreateModuleBuilder(
this.Compilation,
synthesizedType.Methods,
additionalTypes: additionalTypes.ToImmutableAndFree(),
synthesizedType: synthesizedType,
testData: testData,
diagnostics: diagnostics);
Debug.Assert(module != null);
this.Compilation.Compile(
module,
win32Resources: null,
xmlDocStream: null,
emittingPdb: false,
diagnostics: diagnostics,
filterOpt: null,
cancellationToken: CancellationToken.None);
return diagnostics.HasAnyErrors() ? null : module;
}
private void AppendLocalAndMethod(
ArrayBuilder<LocalAndMethod> localBuilder,
ArrayBuilder<MethodSymbol> methodBuilder,
LocalSymbol local,
EENamedTypeSymbol container,
int localIndex,
DkmClrCompilationResultFlags resultFlags)
{
var methodName = GetNextMethodName(methodBuilder);
var method = this.GetLocalMethod(container, methodName, local.Name, localIndex);
localBuilder.Add(MakeLocalAndMethod(local, method, resultFlags));
methodBuilder.Add(method);
}
private void AppendParameterAndMethod(
ArrayBuilder<LocalAndMethod> localBuilder,
ArrayBuilder<MethodSymbol> methodBuilder,
ParameterSymbol parameter,
EENamedTypeSymbol container,
int parameterIndex)
{
// Note: The native EE doesn't do this, but if we don't escape keyword identifiers,
// the ResultProvider needs to be able to disambiguate cases like "this" and "@this",
// which it can't do correctly without semantic information.
var name = SyntaxHelpers.EscapeKeywordIdentifiers(parameter.Name);
var methodName = GetNextMethodName(methodBuilder);
var method = this.GetParameterMethod(container, methodName, name, parameterIndex);
localBuilder.Add(new CSharpLocalAndMethod(name, name, method, DkmClrCompilationResultFlags.None));
methodBuilder.Add(method);
}
private static LocalAndMethod MakeLocalAndMethod(LocalSymbol local, MethodSymbol method, DkmClrCompilationResultFlags flags)
{
// Note: The native EE doesn't do this, but if we don't escape keyword identifiers,
// the ResultProvider needs to be able to disambiguate cases like "this" and "@this",
// which it can't do correctly without semantic information.
var escapedName = SyntaxHelpers.EscapeKeywordIdentifiers(local.Name);
var displayName = (local as PlaceholderLocalSymbol)?.DisplayName ?? escapedName;
return new CSharpLocalAndMethod(escapedName, displayName, method, flags);
}
private static EEAssemblyBuilder CreateModuleBuilder(
CSharpCompilation compilation,
ImmutableArray<MethodSymbol> methods,
ImmutableArray<NamedTypeSymbol> additionalTypes,
EENamedTypeSymbol synthesizedType,
Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData,
DiagnosticBag diagnostics)
{
// Each assembly must have a unique name.
var emitOptions = new EmitOptions(outputNameOverride: ExpressionCompilerUtilities.GenerateUniqueName());
var dynamicOperationContextType = GetNonDisplayClassContainer(synthesizedType.SubstitutedSourceType);
string runtimeMetadataVersion = compilation.GetRuntimeMetadataVersion(emitOptions, diagnostics);
var serializationProperties = compilation.ConstructModuleSerializationProperties(emitOptions, runtimeMetadataVersion);
return new EEAssemblyBuilder(compilation.SourceAssembly, emitOptions, methods, serializationProperties, additionalTypes, dynamicOperationContextType, testData);
}
internal EEMethodSymbol CreateMethod(
EENamedTypeSymbol container,
string methodName,
CSharpSyntaxNode syntax,
GenerateMethodBody generateMethodBody)
{
return new EEMethodSymbol(
container,
methodName,
syntax.Location,
_currentFrame,
_locals,
_localsForBinding,
_displayClassVariables,
generateMethodBody);
}
private EEMethodSymbol GetLocalMethod(EENamedTypeSymbol container, string methodName, string localName, int localIndex)
{
var syntax = SyntaxFactory.IdentifierName(localName);
return this.CreateMethod(container, methodName, syntax, (method, diagnostics) =>
{
var local = method.LocalsForBinding[localIndex];
var expression = new BoundLocal(syntax, local, constantValueOpt: local.GetConstantValue(null, null, diagnostics), type: local.Type);
return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
});
}
private EEMethodSymbol GetParameterMethod(EENamedTypeSymbol container, string methodName, string parameterName, int parameterIndex)
{
var syntax = SyntaxFactory.IdentifierName(parameterName);
return this.CreateMethod(container, methodName, syntax, (method, diagnostics) =>
{
var parameter = method.Parameters[parameterIndex];
var expression = new BoundParameter(syntax, parameter);
return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
});
}
private EEMethodSymbol GetThisMethod(EENamedTypeSymbol container, string methodName)
{
var syntax = SyntaxFactory.ThisExpression();
return this.CreateMethod(container, methodName, syntax, (method, diagnostics) =>
{
var expression = new BoundThisReference(syntax, GetNonDisplayClassContainer(container.SubstitutedSourceType));
return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
});
}
private EEMethodSymbol GetTypeVariablesMethod(EENamedTypeSymbol container, string methodName, NamedTypeSymbol typeVariablesType)
{
var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken));
return this.CreateMethod(container, methodName, syntax, (method, diagnostics) =>
{
var type = method.TypeMap.SubstituteNamedType(typeVariablesType);
var expression = new BoundObjectCreationExpression(syntax, type.InstanceConstructors[0]);
var statement = new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
return statement;
});
}
private static BoundStatement BindExpression(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics, out ResultProperties resultProperties)
{
var flags = DkmClrCompilationResultFlags.None;
// In addition to C# expressions, the native EE also supports
// type names which are bound to a representation of the type
// (but not System.Type) that the user can expand to see the
// base type. Instead, we only allow valid C# expressions.
var expression = binder.BindValue(syntax, diagnostics, Binder.BindValueKind.RValue);
if (diagnostics.HasAnyErrors())
{
resultProperties = default(ResultProperties);
return null;
}
try
{
if (MayHaveSideEffectsVisitor.MayHaveSideEffects(expression))
{
flags |= DkmClrCompilationResultFlags.PotentialSideEffect;
}
}
catch (BoundTreeVisitor.CancelledByStackGuardException ex)
{
ex.AddAnError(diagnostics);
resultProperties = default(ResultProperties);
return null;
}
var expressionType = expression.Type;
if ((object)expressionType == null)
{
expression = binder.CreateReturnConversion(
syntax,
diagnostics,
expression,
binder.Compilation.GetSpecialType(SpecialType.System_Object));
if (diagnostics.HasAnyErrors())
{
resultProperties = default(ResultProperties);
return null;
}
}
else if (expressionType.SpecialType == SpecialType.System_Void)
{
flags |= DkmClrCompilationResultFlags.ReadOnlyResult;
Debug.Assert(expression.ConstantValue == null);
resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, isConstant: false);
return new BoundExpressionStatement(syntax, expression) { WasCompilerGenerated = true };
}
else if (expressionType.SpecialType == SpecialType.System_Boolean)
{
flags |= DkmClrCompilationResultFlags.BoolResult;
}
if (!IsAssignableExpression(binder, expression))
{
flags |= DkmClrCompilationResultFlags.ReadOnlyResult;
}
resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, expression.ConstantValue != null);
return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
}
private static BoundStatement BindStatement(Binder binder, StatementSyntax syntax, DiagnosticBag diagnostics, out ResultProperties properties)
{
properties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
return binder.BindStatement(syntax, diagnostics);
}
private static bool IsAssignableExpression(Binder binder, BoundExpression expression)
{
// NOTE: Surprisingly, binder.CheckValueKind will return true (!) for readonly fields
// in contexts where they cannot be assigned - it simply reports a diagnostic.
// Presumably, this is done to avoid producing a confusing error message about the
// field not being an lvalue.
var diagnostics = DiagnosticBag.GetInstance();
var result = binder.CheckValueKind(expression, Binder.BindValueKind.Assignment, diagnostics) &&
!diagnostics.HasAnyErrors();
diagnostics.Free();
return result;
}
private static BoundStatement BindAssignment(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics)
{
var expression = binder.BindValue(syntax, diagnostics, Binder.BindValueKind.RValue);
if (diagnostics.HasAnyErrors())
{
return null;
}
return new BoundExpressionStatement(expression.Syntax, expression) { WasCompilerGenerated = true };
}
private static Binder CreateBinderChain(
CSharpCompilation compilation,
PEModuleSymbol module,
NamespaceSymbol @namespace,
ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups)
{
var stack = ArrayBuilder<string>.GetInstance();
while ((object)@namespace != null)
{
stack.Push(@namespace.Name);
@namespace = @namespace.ContainingNamespace;
}
Binder binder = new BuckStopsHereBinder(compilation);
var hasImports = !importRecordGroups.IsDefaultOrEmpty;
var numImportStringGroups = hasImports ? importRecordGroups.Length : 0;
var currentStringGroup = numImportStringGroups - 1;
// PERF: We used to call compilation.GetCompilationNamespace on every iteration,
// but that involved walking up to the global namespace, which we have to do
// anyway. Instead, we'll inline the functionality into our own walk of the
// namespace chain.
@namespace = compilation.GlobalNamespace;
while (stack.Count > 0)
{
var namespaceName = stack.Pop();
if (namespaceName.Length > 0)
{
// We're re-getting the namespace, rather than using the one containing
// the current frame method, because we want the merged namespace.
@namespace = @namespace.GetNestedNamespace(namespaceName);
Debug.Assert((object)@namespace != null,
$"We worked backwards from symbols to names, but no symbol exists for name '{namespaceName}'");
}
else
{
Debug.Assert((object)@namespace == (object)compilation.GlobalNamespace);
}
Imports imports = null;
if (hasImports)
{
if (currentStringGroup < 0)
{
Debug.WriteLine($"No import string group for namespace '{@namespace}'");
break;
}
var importsBinder = new InContainerBinder(@namespace, binder);
imports = BuildImports(compilation, module, importRecordGroups[currentStringGroup], importsBinder);
currentStringGroup--;
}
binder = new InContainerBinder(@namespace, binder, imports);
}
stack.Free();
if (currentStringGroup >= 0)
{
// CONSIDER: We could lump these into the outermost namespace. It's probably not worthwhile since
// the usings are already for the wrong method.
Debug.WriteLine($"Found {currentStringGroup + 1} import string groups without corresponding namespaces");
}
return binder;
}
private static CSharpCompilation GetCompilationWithExternAliases(CSharpCompilation compilation, ImmutableArray<ExternAliasRecord> externAliasRecords)
{
if (externAliasRecords.IsDefaultOrEmpty)
{
return compilation.Clone();
}
var updatedReferences = ArrayBuilder<MetadataReference>.GetInstance();
var assembliesAndModulesBuilder = ArrayBuilder<Symbol>.GetInstance();
foreach (var reference in compilation.References)
{
updatedReferences.Add(reference);
assembliesAndModulesBuilder.Add(compilation.GetAssemblyOrModuleSymbol(reference));
}
Debug.Assert(assembliesAndModulesBuilder.Count == updatedReferences.Count);
var assembliesAndModules = assembliesAndModulesBuilder.ToImmutableAndFree();
foreach (var externAliasRecord in externAliasRecords)
{
var targetAssembly = externAliasRecord.TargetAssembly as AssemblySymbol;
int index;
if (targetAssembly != null)
{
index = assembliesAndModules.IndexOf(targetAssembly);
}
else
{
index = IndexOfMatchingAssembly((AssemblyIdentity)externAliasRecord.TargetAssembly, assembliesAndModules, compilation.Options.AssemblyIdentityComparer);
}
if (index < 0)
{
Debug.WriteLine($"Unable to find corresponding assembly reference for extern alias '{externAliasRecord}'");
continue;
}
var externAlias = externAliasRecord.Alias;
var assemblyReference = updatedReferences[index];
var oldAliases = assemblyReference.Properties.Aliases;
var newAliases = oldAliases.IsEmpty
? ImmutableArray.Create(MetadataReferenceProperties.GlobalAlias, externAlias)
: oldAliases.Concat(ImmutableArray.Create(externAlias));
// NOTE: Dev12 didn't emit custom debug info about "global", so we don't have
// a good way to distinguish between a module aliased with both (e.g.) "X" and
// "global" and a module aliased with only "X". As in Dev12, we assume that
// "global" is a valid alias to remain at least as permissive as source.
// NOTE: In the event that this introduces ambiguities between two assemblies
// (e.g. because one was "global" in source and the other was "X"), it should be
// possible to disambiguate as long as each assembly has a distinct extern alias,
// not necessarily used in source.
Debug.Assert(newAliases.Contains(MetadataReferenceProperties.GlobalAlias));
// Replace the value in the map with the updated reference.
updatedReferences[index] = assemblyReference.WithAliases(newAliases);
}
compilation = compilation.WithReferences(updatedReferences);
updatedReferences.Free();
return compilation;
}
private static int IndexOfMatchingAssembly(AssemblyIdentity referenceIdentity, ImmutableArray<Symbol> assembliesAndModules, AssemblyIdentityComparer assemblyIdentityComparer)
{
for (int i = 0; i < assembliesAndModules.Length; i++)
{
var assembly = assembliesAndModules[i] as AssemblySymbol;
if (assembly != null && assemblyIdentityComparer.ReferenceMatchesDefinition(referenceIdentity, assembly.Identity))
{
return i;
}
}
return -1;
}
private static Binder ExtendBinderChain(
CSharpSyntaxNode syntax,
ImmutableArray<Alias> aliases,
EEMethodSymbol method,
Binder binder,
bool hasDisplayClassThis,
bool methodNotType)
{
var substitutedSourceMethod = GetSubstitutedSourceMethod(method.SubstitutedSourceMethod, hasDisplayClassThis);
var substitutedSourceType = substitutedSourceMethod.ContainingType;
var stack = ArrayBuilder<NamedTypeSymbol>.GetInstance();
for (var type = substitutedSourceType; (object)type != null; type = type.ContainingType)
{
stack.Add(type);
}
while (stack.Count > 0)
{
substitutedSourceType = stack.Pop();
binder = new InContainerBinder(substitutedSourceType, binder);
if (substitutedSourceType.Arity > 0)
{
binder = new WithTypeArgumentsBinder(substitutedSourceType.TypeArguments, binder);
}
}
stack.Free();
if (substitutedSourceMethod.Arity > 0)
{
binder = new WithTypeArgumentsBinder(substitutedSourceMethod.TypeArguments, binder);
}
if (methodNotType)
{
// Method locals and parameters shadow pseudo-variables.
var typeNameDecoder = new EETypeNameDecoder(binder.Compilation, (PEModuleSymbol)substitutedSourceMethod.ContainingModule);
binder = new PlaceholderLocalBinder(
syntax,
aliases,
method,
typeNameDecoder,
binder);
}
binder = new EEMethodBinder(method, substitutedSourceMethod, binder);
if (methodNotType)
{
binder = new SimpleLocalScopeBinder(method.LocalsForBinding, binder);
}
return binder;
}
private static Imports BuildImports(CSharpCompilation compilation, PEModuleSymbol module, ImmutableArray<ImportRecord> importRecords, InContainerBinder binder)
{
// We make a first pass to extract all of the extern aliases because other imports may depend on them.
var externsBuilder = ArrayBuilder<AliasAndExternAliasDirective>.GetInstance();
foreach (var importRecord in importRecords)
{
if (importRecord.TargetKind != ImportTargetKind.Assembly)
{
continue;
}
var alias = importRecord.Alias;
IdentifierNameSyntax aliasNameSyntax;
if (!TryParseIdentifierNameSyntax(alias, out aliasNameSyntax))
{
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{alias}'");
continue;
}
var externAliasSyntax = SyntaxFactory.ExternAliasDirective(aliasNameSyntax.Identifier);
var aliasSymbol = new AliasSymbol(binder, externAliasSyntax); // Binder is only used to access compilation.
externsBuilder.Add(new AliasAndExternAliasDirective(aliasSymbol, externAliasDirective: null)); // We have one, but we pass null for consistency.
}
var externs = externsBuilder.ToImmutableAndFree();
if (externs.Any())
{
// NB: This binder (and corresponding Imports) is only used to bind the other imports.
// We'll merge the externs into a final Imports object and return that to be used in
// the actual binder chain.
binder = new InContainerBinder(
binder.Container,
binder,
Imports.FromCustomDebugInfo(binder.Compilation, ImmutableDictionary<string, AliasAndUsingDirective>.Empty, ImmutableArray<NamespaceOrTypeAndUsingDirective>.Empty, externs));
}
var usingAliases = ImmutableDictionary.CreateBuilder<string, AliasAndUsingDirective>();
var usingsBuilder = ArrayBuilder<NamespaceOrTypeAndUsingDirective>.GetInstance();
foreach (var importRecord in importRecords)
{
switch (importRecord.TargetKind)
{
case ImportTargetKind.Type:
{
TypeSymbol typeSymbol = (TypeSymbol)importRecord.TargetType;
Debug.Assert((object)typeSymbol != null);
if (typeSymbol.IsErrorType())
{
// Type is unrecognized. The import may have been
// valid in the original source but unnecessary.
continue; // Don't add anything for this import.
}
else if (importRecord.Alias == null && !typeSymbol.IsStatic)
{
// Only static types can be directly imported.
continue;
}
if (!TryAddImport(importRecord.Alias, typeSymbol, usingsBuilder, usingAliases, binder, importRecord))
{
continue;
}
break;
}
case ImportTargetKind.Namespace:
{
var namespaceName = importRecord.TargetString;
NameSyntax targetSyntax;
if (!SyntaxHelpers.TryParseDottedName(namespaceName, out targetSyntax))
{
// DevDiv #999086: Some previous version of VS apparently generated type aliases as "UA{alias} T{alias-qualified type name}".
// Neither Roslyn nor Dev12 parses such imports. However, Roslyn discards them, rather than interpreting them as "UA{alias}"
// (which will rarely work and never be correct).
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid target '{importRecord.TargetString}'");
continue;
}
NamespaceSymbol globalNamespace;
AssemblySymbol targetAssembly = (AssemblySymbol)importRecord.TargetAssembly;
if (targetAssembly != null)
{
if (targetAssembly.IsMissing)
{
Debug.WriteLine($"Import record '{importRecord}' has invalid assembly reference '{targetAssembly.Identity}'");
continue;
}
globalNamespace = targetAssembly.GlobalNamespace;
}
else if (importRecord.TargetAssemblyAlias != null)
{
IdentifierNameSyntax externAliasSyntax = null;
if (!TryParseIdentifierNameSyntax(importRecord.TargetAssemblyAlias, out externAliasSyntax))
{
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{importRecord.TargetAssemblyAlias}'");
continue;
}
var unusedDiagnostics = DiagnosticBag.GetInstance();
var aliasSymbol = (AliasSymbol)binder.BindNamespaceAliasSymbol(externAliasSyntax, unusedDiagnostics);
unusedDiagnostics.Free();
if ((object)aliasSymbol == null)
{
Debug.WriteLine($"Import record '{importRecord}' requires unknown extern alias '{importRecord.TargetAssemblyAlias}'");
continue;
}
globalNamespace = (NamespaceSymbol)aliasSymbol.Target;
}
else
{
globalNamespace = compilation.GlobalNamespace;
}
var namespaceSymbol = BindNamespace(namespaceName, globalNamespace);
if ((object)namespaceSymbol == null)
{
// Namespace is unrecognized. The import may have been
// valid in the original source but unnecessary.
continue; // Don't add anything for this import.
}
if (!TryAddImport(importRecord.Alias, namespaceSymbol, usingsBuilder, usingAliases, binder, importRecord))
{
continue;
}
break;
}
case ImportTargetKind.Assembly:
{
// Handled in first pass (above).
break;
}
default:
{
throw ExceptionUtilities.UnexpectedValue(importRecord.TargetKind);
}
}
}
return Imports.FromCustomDebugInfo(binder.Compilation, usingAliases.ToImmutableDictionary(), usingsBuilder.ToImmutableAndFree(), externs);
}
private static NamespaceSymbol BindNamespace(string namespaceName, NamespaceSymbol globalNamespace)
{
var namespaceSymbol = globalNamespace;
foreach (var name in namespaceName.Split('.'))
{
var members = namespaceSymbol.GetMembers(name);
namespaceSymbol = members.Length == 1
? members[0] as NamespaceSymbol
: null;
if ((object)namespaceSymbol == null)
{
break;
}
}
return namespaceSymbol;
}
private static bool TryAddImport(
string alias,
NamespaceOrTypeSymbol targetSymbol,
ArrayBuilder<NamespaceOrTypeAndUsingDirective> usingsBuilder,
ImmutableDictionary<string, AliasAndUsingDirective>.Builder usingAliases,
InContainerBinder binder,
ImportRecord importRecord)
{
if (alias == null)
{
usingsBuilder.Add(new NamespaceOrTypeAndUsingDirective(targetSymbol, usingDirective: null));
}
else
{
IdentifierNameSyntax aliasSyntax;
if (!TryParseIdentifierNameSyntax(alias, out aliasSyntax))
{
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid alias '{alias}'");
return false;
}
var aliasSymbol = AliasSymbol.CreateCustomDebugInfoAlias(targetSymbol, aliasSyntax.Identifier, binder);
usingAliases.Add(alias, new AliasAndUsingDirective(aliasSymbol, usingDirective: null));
}
return true;
}
private static bool TryParseIdentifierNameSyntax(string name, out IdentifierNameSyntax syntax)
{
Debug.Assert(name != null);
if (name == MetadataReferenceProperties.GlobalAlias)
{
syntax = SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword));
return true;
}
NameSyntax nameSyntax;
if (!SyntaxHelpers.TryParseDottedName(name, out nameSyntax) || nameSyntax.Kind() != SyntaxKind.IdentifierName)
{
syntax = null;
return false;
}
syntax = (IdentifierNameSyntax)nameSyntax;
return true;
}
internal CommonMessageProvider MessageProvider
{
get { return this.Compilation.MessageProvider; }
}
private static DkmClrCompilationResultFlags GetLocalResultFlags(LocalSymbol local)
{
// CONSIDER: We might want to prevent the user from modifying pinned locals -
// that's pretty dangerous.
return local.IsConst
? DkmClrCompilationResultFlags.ReadOnlyResult
: DkmClrCompilationResultFlags.None;
}
/// <summary>
/// Generate the set of locals to use for binding.
/// </summary>
private static ImmutableArray<LocalSymbol> GetLocalsForBinding(
ImmutableArray<LocalSymbol> locals,
ImmutableArray<string> displayClassVariableNamesInOrder,
ImmutableDictionary<string, DisplayClassVariable> displayClassVariables)
{
var builder = ArrayBuilder<LocalSymbol>.GetInstance();
foreach (var local in locals)
{
var name = local.Name;
if (name == null)
{
continue;
}
if (GeneratedNames.GetKind(name) != GeneratedNameKind.None)
{
continue;
}
// Although Roslyn doesn't name synthesized locals unless they are well-known to EE,
// Dev12 did so we need to skip them here.
if (GeneratedNames.IsSynthesizedLocalName(name))
{
continue;
}
builder.Add(local);
}
foreach (var variableName in displayClassVariableNamesInOrder)
{
var variable = displayClassVariables[variableName];
switch (variable.Kind)
{
case DisplayClassVariableKind.Local:
case DisplayClassVariableKind.Parameter:
builder.Add(new EEDisplayClassFieldLocalSymbol(variable));
break;
}
}
return builder.ToImmutableAndFree();
}
/// <summary>
/// Return a mapping of captured variables (parameters, locals, and
/// "this") to locals. The mapping is needed to expose the original
/// local identifiers (those from source) in the binder.
/// </summary>
private static void GetDisplayClassVariables(
MethodSymbol method,
ImmutableArray<LocalSymbol> locals,
InScopeHoistedLocals inScopeHoistedLocals,
out ImmutableArray<string> displayClassVariableNamesInOrder,
out ImmutableDictionary<string, DisplayClassVariable> displayClassVariables,
out ImmutableHashSet<string> hoistedParameterNames)
{
// Calculated the shortest paths from locals to instances of display
// classes. There should not be two instances of the same display
// class immediately within any particular method.
var displayClassTypes = PooledHashSet<NamedTypeSymbol>.GetInstance();
var displayClassInstances = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance();
// Add any display class instances from locals (these will contain any hoisted locals).
foreach (var local in locals)
{
var name = local.Name;
if ((name != null) && (GeneratedNames.GetKind(name) == GeneratedNameKind.DisplayClassLocalOrField))
{
var instance = new DisplayClassInstanceFromLocal((EELocalSymbol)local);
displayClassTypes.Add(instance.Type);
displayClassInstances.Add(new DisplayClassInstanceAndFields(instance));
}
}
foreach (var parameter in method.Parameters)
{
if (GeneratedNames.GetKind(parameter.Name) == GeneratedNameKind.TransparentIdentifier)
{
var instance = new DisplayClassInstanceFromParameter(parameter);
displayClassTypes.Add(instance.Type);
displayClassInstances.Add(new DisplayClassInstanceAndFields(instance));
}
}
var containingType = method.ContainingType;
bool isIteratorOrAsyncMethod = false;
if (IsDisplayClassType(containingType))
{
if (!method.IsStatic)
{
// Add "this" display class instance.
var instance = new DisplayClassInstanceFromParameter(method.ThisParameter);
displayClassTypes.Add(instance.Type);
displayClassInstances.Add(new DisplayClassInstanceAndFields(instance));
}
isIteratorOrAsyncMethod = GeneratedNames.GetKind(containingType.Name) == GeneratedNameKind.StateMachineType;
}
if (displayClassInstances.Any())
{
// Find any additional display class instances breadth first.
for (int depth = 0; GetDisplayClassInstances(displayClassTypes, displayClassInstances, depth) > 0; depth++)
{
}
// The locals are the set of all fields from the display classes.
var displayClassVariableNamesInOrderBuilder = ArrayBuilder<string>.GetInstance();
var displayClassVariablesBuilder = PooledDictionary<string, DisplayClassVariable>.GetInstance();
var parameterNames = PooledHashSet<string>.GetInstance();
if (isIteratorOrAsyncMethod)
{
Debug.Assert(IsDisplayClassType(containingType));
foreach (var field in containingType.GetMembers().OfType<FieldSymbol>())
{
// All iterator and async state machine fields (including hoisted locals) have mangled names, except
// for hoisted parameters (whose field names are always the same as the original source parameters).
var fieldName = field.Name;
if (GeneratedNames.GetKind(fieldName) == GeneratedNameKind.None)
{
parameterNames.Add(fieldName);
}
}
}
else
{
foreach (var p in method.Parameters)
{
parameterNames.Add(p.Name);
}
}
var pooledHoistedParameterNames = PooledHashSet<string>.GetInstance();
foreach (var instance in displayClassInstances)
{
GetDisplayClassVariables(
displayClassVariableNamesInOrderBuilder,
displayClassVariablesBuilder,
parameterNames,
inScopeHoistedLocals,
instance,
pooledHoistedParameterNames);
}
hoistedParameterNames = pooledHoistedParameterNames.ToImmutableHashSet<string>();
pooledHoistedParameterNames.Free();
parameterNames.Free();
displayClassVariableNamesInOrder = displayClassVariableNamesInOrderBuilder.ToImmutableAndFree();
displayClassVariables = displayClassVariablesBuilder.ToImmutableDictionary();
displayClassVariablesBuilder.Free();
}
else
{
hoistedParameterNames = ImmutableHashSet<string>.Empty;
displayClassVariableNamesInOrder = ImmutableArray<string>.Empty;
displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty;
}
displayClassTypes.Free();
displayClassInstances.Free();
}
/// <summary>
/// Return the set of display class instances that can be reached
/// from the given local. A particular display class may be reachable
/// from multiple locals. In those cases, the instance from the
/// shortest path (fewest intermediate fields) is returned.
/// </summary>
private static int GetDisplayClassInstances(
HashSet<NamedTypeSymbol> displayClassTypes,
ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances,
int depth)
{
Debug.Assert(displayClassInstances.All(p => p.Depth <= depth));
var atDepth = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance();
atDepth.AddRange(displayClassInstances.Where(p => p.Depth == depth));
Debug.Assert(atDepth.Count > 0);
int n = 0;
foreach (var instance in atDepth)
{
n += GetDisplayClassInstances(displayClassTypes, displayClassInstances, instance);
}
atDepth.Free();
return n;
}
private static int GetDisplayClassInstances(
HashSet<NamedTypeSymbol> displayClassTypes,
ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances,
DisplayClassInstanceAndFields instance)
{
// Display class instance. The display class fields are variables.
int n = 0;
foreach (var member in instance.Type.GetMembers())
{
if (member.Kind != SymbolKind.Field)
{
continue;
}
var field = (FieldSymbol)member;
var fieldType = field.Type;
var fieldKind = GeneratedNames.GetKind(field.Name);
if (fieldKind == GeneratedNameKind.DisplayClassLocalOrField ||
fieldKind == GeneratedNameKind.TransparentIdentifier ||
IsTransparentIdentifierFieldInAnonymousType(field) ||
(fieldKind == GeneratedNameKind.ThisProxyField && GeneratedNames.GetKind(fieldType.Name) == GeneratedNameKind.LambdaDisplayClass)) // Async lambda case.
{
Debug.Assert(!field.IsStatic);
// A local that is itself a display class instance.
if (displayClassTypes.Add((NamedTypeSymbol)fieldType))
{
var other = instance.FromField(field);
displayClassInstances.Add(other);
n++;
}
}
}
return n;
}
private static bool IsTransparentIdentifierFieldInAnonymousType(FieldSymbol field)
{
string fieldName = field.Name;
if (GeneratedNames.GetKind(fieldName) != GeneratedNameKind.AnonymousTypeField)
{
return false;
}
GeneratedNameKind kind;
int openBracketOffset;
int closeBracketOffset;
if (!GeneratedNames.TryParseGeneratedName(fieldName, out kind, out openBracketOffset, out closeBracketOffset))
{
return false;
}
fieldName = fieldName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1);
return GeneratedNames.GetKind(fieldName) == GeneratedNameKind.TransparentIdentifier;
}
private static void GetDisplayClassVariables(
ArrayBuilder<string> displayClassVariableNamesInOrderBuilder,
Dictionary<string, DisplayClassVariable> displayClassVariablesBuilder,
HashSet<string> parameterNames,
InScopeHoistedLocals inScopeHoistedLocals,
DisplayClassInstanceAndFields instance,
HashSet<string> hoistedParameterNames)
{
// Display class instance. The display class fields are variables.
foreach (var member in instance.Type.GetMembers())
{
if (member.Kind != SymbolKind.Field)
{
continue;
}
var field = (FieldSymbol)member;
var fieldName = field.Name;
REPARSE:
DisplayClassVariableKind variableKind;
string variableName;
GeneratedNameKind fieldKind;
int openBracketOffset;
int closeBracketOffset;
GeneratedNames.TryParseGeneratedName(fieldName, out fieldKind, out openBracketOffset, out closeBracketOffset);
switch (fieldKind)
{
case GeneratedNameKind.AnonymousTypeField:
Debug.Assert(fieldName == field.Name); // This only happens once.
fieldName = fieldName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1);
goto REPARSE;
case GeneratedNameKind.TransparentIdentifier:
// A transparent identifier (field) in an anonymous type synthesized for a transparent identifier.
Debug.Assert(!field.IsStatic);
continue;
case GeneratedNameKind.DisplayClassLocalOrField:
// A local that is itself a display class instance.
Debug.Assert(!field.IsStatic);
continue;
case GeneratedNameKind.HoistedLocalField:
// Filter out hoisted locals that are known to be out-of-scope at the current IL offset.
// Hoisted locals with invalid indices will be included since more information is better
// than less in error scenarios.
if (!inScopeHoistedLocals.IsInScope(fieldName))
{
continue;
}
variableName = fieldName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1);
variableKind = DisplayClassVariableKind.Local;
Debug.Assert(!field.IsStatic);
break;
case GeneratedNameKind.ThisProxyField:
// A reference to "this".
variableName = fieldName;
variableKind = DisplayClassVariableKind.This;
Debug.Assert(!field.IsStatic);
break;
case GeneratedNameKind.None:
// A reference to a parameter or local.
variableName = fieldName;
if (parameterNames.Contains(variableName))
{
variableKind = DisplayClassVariableKind.Parameter;
hoistedParameterNames.Add(variableName);
}
else
{
variableKind = DisplayClassVariableKind.Local;
}
Debug.Assert(!field.IsStatic);
break;
default:
continue;
}
if (displayClassVariablesBuilder.ContainsKey(variableName))
{
// Only expecting duplicates for async state machine
// fields (that should be at the top-level).
Debug.Assert(displayClassVariablesBuilder[variableName].DisplayClassFields.Count() == 1);
Debug.Assert(instance.Fields.Count() >= 1); // greater depth
Debug.Assert((variableKind == DisplayClassVariableKind.Parameter) ||
(variableKind == DisplayClassVariableKind.This));
}
else if (variableKind != DisplayClassVariableKind.This || GeneratedNames.GetKind(instance.Type.ContainingType.Name) != GeneratedNameKind.LambdaDisplayClass)
{
// In async lambdas, the hoisted "this" field in the state machine type will point to the display class instance, if there is one.
// In such cases, we want to add the display class "this" to the map instead (or nothing, if it lacks one).
displayClassVariableNamesInOrderBuilder.Add(variableName);
displayClassVariablesBuilder.Add(variableName, instance.ToVariable(variableName, variableKind, field));
}
}
}
private static bool IsDisplayClassType(NamedTypeSymbol type)
{
switch (GeneratedNames.GetKind(type.Name))
{
case GeneratedNameKind.LambdaDisplayClass:
case GeneratedNameKind.StateMachineType:
return true;
default:
return false;
}
}
private static NamedTypeSymbol GetNonDisplayClassContainer(NamedTypeSymbol type)
{
// 1) Display class and state machine types are always nested within the types
// that use them (so that they can access private members of those types).
// 2) The native compiler used to produce nested display classes for nested lambdas,
// so we may have to walk out more than one level.
while (IsDisplayClassType(type))
{
type = type.ContainingType;
}
Debug.Assert((object)type != null);
return type;
}
/// <summary>
/// Identifies the method in which binding should occur.
/// </summary>
/// <param name="candidateSubstitutedSourceMethod">
/// The symbol of the method that is currently on top of the callstack, with
/// EE type parameters substituted in place of the original type parameters.
/// </param>
/// <param name="sourceMethodMustBeInstance">
/// True if "this" is available via a display class in the current context.
/// </param>
/// <returns>
/// If <paramref name="candidateSubstitutedSourceMethod"/> is compiler-generated,
/// then we will attempt to determine which user-defined method caused it to be
/// generated. For example, if <paramref name="candidateSubstitutedSourceMethod"/>
/// is a state machine MoveNext method, then we will try to find the iterator or
/// async method for which it was generated. If we are able to find the original
/// method, then we will substitute in the EE type parameters. Otherwise, we will
/// return <paramref name="candidateSubstitutedSourceMethod"/>.
/// </returns>
/// <remarks>
/// In the event that the original method is overloaded, we may not be able to determine
/// which overload actually corresponds to the state machine. In particular, we do not
/// have information about the signature of the original method (i.e. number of parameters,
/// parameter types and ref-kinds, return type). However, we conjecture that this
/// level of uncertainty is acceptable, since parameters are managed by a separate binder
/// in the synthesized binder chain and we have enough information to check the other method
/// properties that are used during binding (e.g. static-ness, generic arity, type parameter
/// constraints).
/// </remarks>
internal static MethodSymbol GetSubstitutedSourceMethod(
MethodSymbol candidateSubstitutedSourceMethod,
bool sourceMethodMustBeInstance)
{
var candidateSubstitutedSourceType = candidateSubstitutedSourceMethod.ContainingType;
string desiredMethodName;
if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceType.Name, GeneratedNameKind.StateMachineType, out desiredMethodName) ||
GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceMethod.Name, GeneratedNameKind.LambdaMethod, out desiredMethodName))
{
// We could be in the MoveNext method of an async lambda.
string tempMethodName;
if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(desiredMethodName, GeneratedNameKind.LambdaMethod, out tempMethodName))
{
desiredMethodName = tempMethodName;
var containing = candidateSubstitutedSourceType.ContainingType;
Debug.Assert((object)containing != null);
if (GeneratedNames.GetKind(containing.Name) == GeneratedNameKind.LambdaDisplayClass)
{
candidateSubstitutedSourceType = containing;
sourceMethodMustBeInstance = candidateSubstitutedSourceType.MemberNames.Select(GeneratedNames.GetKind).Contains(GeneratedNameKind.ThisProxyField);
}
}
var desiredTypeParameters = candidateSubstitutedSourceType.OriginalDefinition.TypeParameters;
// Type containing the original iterator, async, or lambda-containing method.
var substitutedSourceType = GetNonDisplayClassContainer(candidateSubstitutedSourceType);
foreach (var candidateMethod in substitutedSourceType.GetMembers().OfType<MethodSymbol>())
{
if (IsViableSourceMethod(candidateMethod, desiredMethodName, desiredTypeParameters, sourceMethodMustBeInstance))
{
return desiredTypeParameters.Length == 0
? candidateMethod
: candidateMethod.Construct(candidateSubstitutedSourceType.TypeArguments);
}
}
Debug.Assert(false, "Why didn't we find a substituted source method for " + candidateSubstitutedSourceMethod + "?");
}
return candidateSubstitutedSourceMethod;
}
private static bool IsViableSourceMethod(
MethodSymbol candidateMethod,
string desiredMethodName, ImmutableArray<TypeParameterSymbol> desiredTypeParameters, bool desiredMethodMustBeInstance)
{
return
!candidateMethod.IsAbstract &&
(!(desiredMethodMustBeInstance && candidateMethod.IsStatic)) &&
candidateMethod.Name == desiredMethodName &&
HaveSameConstraints(candidateMethod.TypeParameters, desiredTypeParameters);
}
private static bool HaveSameConstraints(ImmutableArray<TypeParameterSymbol> candidateTypeParameters, ImmutableArray<TypeParameterSymbol> desiredTypeParameters)
{
int arity = candidateTypeParameters.Length;
if (arity != desiredTypeParameters.Length)
{
return false;
}
else if (arity == 0)
{
return true;
}
var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity);
var candidateTypeMap = new TypeMap(candidateTypeParameters, indexedTypeParameters, allowAlpha: true);
var desiredTypeMap = new TypeMap(desiredTypeParameters, indexedTypeParameters, allowAlpha: true);
return MemberSignatureComparer.HaveSameConstraints(candidateTypeParameters, candidateTypeMap, desiredTypeParameters, desiredTypeMap);
}
private struct DisplayClassInstanceAndFields
{
internal readonly DisplayClassInstance Instance;
internal readonly ConsList<FieldSymbol> Fields;
internal DisplayClassInstanceAndFields(DisplayClassInstance instance) :
this(instance, ConsList<FieldSymbol>.Empty)
{
Debug.Assert(IsDisplayClassType(instance.Type) ||
GeneratedNames.GetKind(instance.Type.Name) == GeneratedNameKind.AnonymousType);
}
private DisplayClassInstanceAndFields(DisplayClassInstance instance, ConsList<FieldSymbol> fields)
{
this.Instance = instance;
this.Fields = fields;
}
internal NamedTypeSymbol Type
{
get { return this.Fields.Any() ? (NamedTypeSymbol)this.Fields.Head.Type : this.Instance.Type; }
}
internal int Depth
{
get { return this.Fields.Count(); }
}
internal DisplayClassInstanceAndFields FromField(FieldSymbol field)
{
Debug.Assert(IsDisplayClassType((NamedTypeSymbol)field.Type) ||
GeneratedNames.GetKind(field.Type.Name) == GeneratedNameKind.AnonymousType);
return new DisplayClassInstanceAndFields(this.Instance, this.Fields.Prepend(field));
}
internal DisplayClassVariable ToVariable(string name, DisplayClassVariableKind kind, FieldSymbol field)
{
return new DisplayClassVariable(name, kind, this.Instance, this.Fields.Prepend(field));
}
}
}
}
| |
//
// MessagePart.cs
//
// Author: Jeffrey Stedfast <[email protected]>
//
// Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.IO;
using System.Threading;
using MimeKit.IO;
namespace MimeKit {
/// <summary>
/// A MIME part containing a <see cref="MimeKit.MimeMessage"/> as its content.
/// </summary>
/// <remarks>
/// Represents MIME entities such as those with a Content-Type of message/rfc822 or message/news.
/// </remarks>
public class MessagePart : MimeEntity
{
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.MessagePart"/> class.
/// </summary>
/// <remarks>
/// This constructor is used by <see cref="MimeKit.MimeParser"/>.
/// </remarks>
/// <param name="args">Information used by the constructor.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="args"/> is <c>null</c>.
/// </exception>
public MessagePart (MimeEntityConstructorArgs args) : base (args)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.MessagePart"/> class.
/// </summary>
/// <remarks>
/// Creates a new <see cref="MessagePart"/>.
/// </remarks>
/// <param name="subtype">The message subtype.</param>
/// <param name="args">An array of initialization parameters: headers and message parts.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="subtype"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="args"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// <para><paramref name="args"/> contains more than one <see cref="MimeKit.MimeMessage"/>.</para>
/// <para>-or-</para>
/// <para><paramref name="args"/> contains one or more arguments of an unknown type.</para>
/// </exception>
public MessagePart (string subtype, params object[] args) : this (subtype)
{
if (args == null)
throw new ArgumentNullException ("args");
MimeMessage message = null;
foreach (object obj in args) {
if (obj == null || TryInit (obj))
continue;
var mesg = obj as MimeMessage;
if (mesg != null) {
if (message != null)
throw new ArgumentException ("MimeMessage should not be specified more than once.");
message = mesg;
continue;
}
throw new ArgumentException ("Unknown initialization parameter: " + obj.GetType ());
}
if (message != null)
Message = message;
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.MessagePart"/> class.
/// </summary>
/// <remarks>
/// Creates a new MIME message entity with the specified subtype.
/// </remarks>
/// <param name="subtype">The message subtype.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="subtype"/> is <c>null</c>.
/// </exception>
public MessagePart (string subtype) : base ("message", subtype)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.MessagePart"/> class.
/// </summary>
/// <remarks>
/// Creates a new message/rfc822 MIME entity.
/// </remarks>
public MessagePart () : base ("message", "rfc822")
{
}
/// <summary>
/// Gets or sets the message content.
/// </summary>
/// <remarks>
/// Gets or sets the message content.
/// </remarks>
/// <value>The message content.</value>
public MimeMessage Message {
get; set;
}
/// <summary>
/// Dispatches to the specific visit method for this MIME entity.
/// </summary>
/// <remarks>
/// This default implementation for <see cref="MimeKit.MessagePart"/> nodes
/// calls <see cref="MimeKit.MimeVisitor.VisitMessagePart"/>. Override this
/// method to call into a more specific method on a derived visitor class
/// of the <see cref="MimeKit.MimeVisitor"/> class. However, it should still
/// support unknown visitors by calling
/// <see cref="MimeKit.MimeVisitor.VisitMessagePart"/>.
/// </remarks>
/// <param name="visitor">The visitor.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="visitor"/> is <c>null</c>.
/// </exception>
public override void Accept (MimeVisitor visitor)
{
if (visitor == null)
throw new ArgumentNullException ("visitor");
visitor.VisitMessagePart (this);
}
/// <summary>
/// Prepare the MIME entity for transport using the specified encoding constraints.
/// </summary>
/// <remarks>
/// Prepares the MIME entity for transport using the specified encoding constraints.
/// </remarks>
/// <param name="constraint">The encoding constraint.</param>
/// <param name="maxLineLength">The maximum number of octets allowed per line (not counting the CRLF). Must be between <c>60</c> and <c>998</c> (inclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <para><paramref name="maxLineLength"/> is not between <c>60</c> and <c>998</c> (inclusive).</para>
/// <para>-or-</para>
/// <para><paramref name="constraint"/> is not a valid value.</para>
/// </exception>
public override void Prepare (EncodingConstraint constraint, int maxLineLength = 78)
{
if (maxLineLength < FormatOptions.MinimumLineLength || maxLineLength > FormatOptions.MaximumLineLength)
throw new ArgumentOutOfRangeException ("maxLineLength");
if (Message != null)
Message.Prepare (constraint, maxLineLength);
}
/// <summary>
/// Writes the <see cref="MimeKit.MessagePart"/> to the output stream.
/// </summary>
/// <remarks>
/// Writes the MIME entity and its message to the output stream.
/// </remarks>
/// <param name="options">The formatting options.</param>
/// <param name="stream">The output stream.</param>
/// <param name="contentOnly"><c>true</c> if only the content should be written; otherwise, <c>false</c>.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="stream"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.OperationCanceledException">
/// The operation was canceled via the cancellation token.
/// </exception>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public override void WriteTo (FormatOptions options, Stream stream, bool contentOnly, CancellationToken cancellationToken = default (CancellationToken))
{
base.WriteTo (options, stream, contentOnly, cancellationToken);
if (Message == null)
return;
if (Message.MboxMarker != null && Message.MboxMarker.Length != 0) {
var cancellable = stream as ICancellableStream;
if (cancellable != null) {
cancellable.Write (Message.MboxMarker, 0, Message.MboxMarker.Length, cancellationToken);
cancellable.Write (options.NewLineBytes, 0, options.NewLineBytes.Length, cancellationToken);
} else {
stream.Write (Message.MboxMarker, 0, Message.MboxMarker.Length);
stream.Write (options.NewLineBytes, 0, options.NewLineBytes.Length);
}
}
Message.WriteTo (options, stream, cancellationToken);
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.LayoutRenderers
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
using Internal.Fakeables;
using NLog.Config;
using NLog.Internal;
using NLog.Targets;
/// <summary>
/// XML event description compatible with log4j, Chainsaw and NLogViewer.
/// </summary>
[LayoutRenderer("log4jxmlevent")]
public class Log4JXmlEventLayoutRenderer : LayoutRenderer, IUsesStackTrace
{
private static readonly DateTime log4jDateBase = new DateTime(1970, 1, 1);
private static readonly string dummyNamespace = "http://nlog-project.org/dummynamespace/" + Guid.NewGuid();
private static readonly string dummyNLogNamespace = "http://nlog-project.org/dummynamespace/" + Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="Log4JXmlEventLayoutRenderer" /> class.
/// </summary>
public Log4JXmlEventLayoutRenderer() : this(AppDomainWrapper.CurrentDomain)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Log4JXmlEventLayoutRenderer" /> class.
/// </summary>
public Log4JXmlEventLayoutRenderer(IAppDomain appDomain)
{
this.IncludeNLogData = true;
this.NdcItemSeparator = " ";
#if SILVERLIGHT
this.AppInfo = "Silverlight Application";
#elif __IOS__
this.AppInfo = "MonoTouch Application";
#else
this.AppInfo = string.Format(
CultureInfo.InvariantCulture,
"{0}({1})",
appDomain.FriendlyName,
ThreadIDHelper.Instance.CurrentProcessID);
#endif
this.Parameters = new List<NLogViewerParameterInfo>();
}
/// <summary>
/// Gets or sets a value indicating whether to include NLog-specific extensions to log4j schema.
/// </summary>
/// <docgen category='Payload Options' order='10' />
[DefaultValue(true)]
public bool IncludeNLogData { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the XML should use spaces for indentation.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool IndentXml { get; set; }
/// <summary>
/// Gets or sets the AppInfo field. By default it's the friendly name of the current AppDomain.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public string AppInfo { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to include call site (class and method name) in the information sent over the network.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool IncludeCallSite { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to include source info (file name and line number) in the information sent over the network.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool IncludeSourceInfo { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsContext"/> dictionary.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool IncludeMdc { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to include contents of the <see cref="NestedDiagnosticsContext"/> stack.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool IncludeNdc { get; set; }
/// <summary>
/// Gets or sets the NDC item separator.
/// </summary>
/// <docgen category='Payload Options' order='10' />
[DefaultValue(" ")]
public string NdcItemSeparator { get; set; }
/// <summary>
/// Gets the level of stack trace information required by the implementing class.
/// </summary>
StackTraceUsage IUsesStackTrace.StackTraceUsage
{
get
{
if (this.IncludeSourceInfo)
{
return StackTraceUsage.Max;
}
if (this.IncludeCallSite)
{
return StackTraceUsage.WithoutSource;
}
return StackTraceUsage.None;
}
}
internal IList<NLogViewerParameterInfo> Parameters { get; set; }
internal void AppendToStringBuilder(StringBuilder sb, LogEventInfo logEvent)
{
this.Append(sb, logEvent);
}
/// <summary>
/// Renders the XML logging event and appends it to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="logEvent">Logging event.</param>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
var settings = new XmlWriterSettings
{
Indent = this.IndentXml,
ConformanceLevel = ConformanceLevel.Fragment,
IndentChars = " ",
};
var sb = new StringBuilder();
using (XmlWriter xtw = XmlWriter.Create(sb, settings))
{
xtw.WriteStartElement("log4j", "event", dummyNamespace);
xtw.WriteAttributeSafeString("xmlns", "nlog", null, dummyNLogNamespace);
xtw.WriteAttributeSafeString("logger", logEvent.LoggerName);
xtw.WriteAttributeSafeString("level", logEvent.Level.Name.ToUpper(CultureInfo.InvariantCulture));
xtw.WriteAttributeSafeString("timestamp", Convert.ToString((long)(logEvent.TimeStamp.ToUniversalTime() - log4jDateBase).TotalMilliseconds, CultureInfo.InvariantCulture));
xtw.WriteAttributeSafeString("thread", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture));
xtw.WriteElementSafeString("log4j", "message", dummyNamespace, logEvent.FormattedMessage);
if (logEvent.Exception != null)
{
xtw.WriteElementSafeString("log4j", "throwable", dummyNamespace, logEvent.Exception.ToString());
}
if (this.IncludeNdc)
{
xtw.WriteElementSafeString("log4j", "NDC", dummyNamespace, string.Join(this.NdcItemSeparator, NestedDiagnosticsContext.GetAllMessages()));
}
if (logEvent.Exception != null)
{
xtw.WriteStartElement("log4j", "throwable", dummyNamespace);
xtw.WriteSafeCData(logEvent.Exception.ToString());
xtw.WriteEndElement();
}
if (this.IncludeCallSite || this.IncludeSourceInfo)
{
System.Diagnostics.StackFrame frame = logEvent.UserStackFrame;
if (frame != null)
{
MethodBase methodBase = frame.GetMethod();
Type type = methodBase.DeclaringType;
xtw.WriteStartElement("log4j", "locationInfo", dummyNamespace);
if (type != null)
{
xtw.WriteAttributeSafeString("class", type.FullName);
}
xtw.WriteAttributeSafeString("method", methodBase.ToString());
#if !SILVERLIGHT
if (this.IncludeSourceInfo)
{
xtw.WriteAttributeSafeString("file", frame.GetFileName());
xtw.WriteAttributeSafeString("line", frame.GetFileLineNumber().ToString(CultureInfo.InvariantCulture));
}
#endif
xtw.WriteEndElement();
if (this.IncludeNLogData)
{
xtw.WriteElementSafeString("nlog", "eventSequenceNumber", dummyNLogNamespace, logEvent.SequenceID.ToString(CultureInfo.InvariantCulture));
xtw.WriteStartElement("nlog", "locationInfo", dummyNLogNamespace);
if (type != null)
{
xtw.WriteAttributeSafeString("assembly", type.Assembly.FullName);
}
xtw.WriteEndElement();
xtw.WriteStartElement("nlog", "properties", dummyNLogNamespace);
foreach (var contextProperty in logEvent.Properties)
{
xtw.WriteStartElement("nlog", "data", dummyNLogNamespace);
xtw.WriteAttributeSafeString("name", Convert.ToString(contextProperty.Key, CultureInfo.InvariantCulture));
xtw.WriteAttributeSafeString("value", Convert.ToString(contextProperty.Value, CultureInfo.InvariantCulture));
xtw.WriteEndElement();
}
xtw.WriteEndElement();
}
}
}
xtw.WriteStartElement("log4j", "properties", dummyNamespace);
if (this.IncludeMdc)
{
foreach (KeyValuePair<string, object> entry in MappedDiagnosticsContext.ThreadDictionary)
{
xtw.WriteStartElement("log4j", "data", dummyNamespace);
xtw.WriteAttributeSafeString("name", entry.Key);
xtw.WriteAttributeSafeString("value", String.Format(logEvent.FormatProvider, "{0}", entry.Value));
xtw.WriteEndElement();
}
}
foreach (NLogViewerParameterInfo parameter in this.Parameters)
{
xtw.WriteStartElement("log4j", "data", dummyNamespace);
xtw.WriteAttributeSafeString("name", parameter.Name);
xtw.WriteAttributeSafeString("value", parameter.Layout.Render(logEvent));
xtw.WriteEndElement();
}
xtw.WriteStartElement("log4j", "data", dummyNamespace);
xtw.WriteAttributeSafeString("name", "log4japp");
xtw.WriteAttributeSafeString("value", this.AppInfo);
xtw.WriteEndElement();
xtw.WriteStartElement("log4j", "data", dummyNamespace);
xtw.WriteAttributeSafeString("name", "log4jmachinename");
#if SILVERLIGHT
xtw.WriteAttributeSafeString("value", "silverlight");
#else
xtw.WriteAttributeSafeString("value", Environment.MachineName);
#endif
xtw.WriteEndElement();
xtw.WriteEndElement();
xtw.WriteEndElement();
xtw.Flush();
// get rid of 'nlog' and 'log4j' namespace declarations
sb.Replace(" xmlns:log4j=\"" + dummyNamespace + "\"", string.Empty);
sb.Replace(" xmlns:nlog=\"" + dummyNLogNamespace + "\"", string.Empty);
builder.Append(sb.ToString());
}
}
}
}
| |
using System;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using NuGet.VisualStudio;
using NuGetConsole.Implementation.Console;
using NuGetConsole.Implementation.PowerConsole;
namespace NuGetConsole.Implementation
{
/// <summary>
/// This class implements the tool window.
/// </summary>
[Guid("0AD07096-BBA9-4900-A651-0598D26F6D24")]
public sealed class PowerConsoleToolWindow : ToolWindowPane, IOleCommandTarget
{
/// <summary>
/// Get VS IComponentModel service.
/// </summary>
private IComponentModel ComponentModel
{
get
{
return this.GetService<IComponentModel>(typeof(SComponentModel));
}
}
private IProductUpdateService ProductUpdateService
{
get
{
return ComponentModel.GetService<IProductUpdateService>();
}
}
private IPackageRestoreManager PackageRestoreManager
{
get
{
return ComponentModel.GetService<IPackageRestoreManager>();
}
}
/// <summary>
/// Get IWpfConsoleService through MEF.
/// </summary>
private IWpfConsoleService WpfConsoleService
{
get
{
return ComponentModel.GetService<IWpfConsoleService>();
}
}
private PowerConsoleWindow PowerConsoleWindow
{
get
{
return ComponentModel.GetService<IPowerConsoleWindow>() as PowerConsoleWindow;
}
}
private IVsUIShell VsUIShell
{
get
{
return this.GetService<IVsUIShell>(typeof(SVsUIShell));
}
}
private bool IsToolbarEnabled
{
get
{
return _wpfConsole != null &&
_wpfConsole.Dispatcher.IsStartCompleted &&
_wpfConsole.Host != null &&
_wpfConsole.Host.IsCommandEnabled;
}
}
/// <summary>
/// Standard constructor for the tool window.
/// </summary>
public PowerConsoleToolWindow() :
base(null)
{
this.Caption = Resources.ToolWindowTitle;
this.BitmapResourceID = 301;
this.BitmapIndex = 0;
this.ToolBar = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.idToolbar);
}
protected override void Initialize()
{
base.Initialize();
OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
if (mcs != null)
{
// Get list command for the Feed combo
CommandID sourcesListCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidSourcesList);
mcs.AddCommand(new OleMenuCommand(SourcesList_Exec, sourcesListCommandID));
// invoke command for the Feed combo
CommandID sourcesCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidSources);
mcs.AddCommand(new OleMenuCommand(Sources_Exec, sourcesCommandID));
// get default project command
CommandID projectsListCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidProjectsList);
mcs.AddCommand(new OleMenuCommand(ProjectsList_Exec, projectsListCommandID));
// invoke command for the Default project combo
CommandID projectsCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidProjects);
mcs.AddCommand(new OleMenuCommand(Projects_Exec, projectsCommandID));
// clear console command
CommandID clearHostCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidClearHost);
mcs.AddCommand(new OleMenuCommand(ClearHost_Exec, clearHostCommandID));
// terminate command execution command
CommandID stopHostCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidStopHost);
mcs.AddCommand(new OleMenuCommand(StopHost_Exec, stopHostCommandID));
}
}
public override void OnToolWindowCreated()
{
// Register key bindings to use in the editor
var windowFrame = (IVsWindowFrame)Frame;
Guid cmdUi = VSConstants.GUID_TextEditorFactory;
windowFrame.SetGuidProperty((int)__VSFPROPID.VSFPROPID_InheritKeyBindings, ref cmdUi);
// pause for a tiny moment to let the tool window open before initializing the host
var timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(0);
timer.Tick += (o, e) =>
{
timer.Stop();
LoadConsoleEditor();
};
timer.Start();
base.OnToolWindowCreated();
}
protected override void OnClose()
{
base.OnClose();
WpfConsole.Dispose();
}
/// <summary>
/// This override allows us to forward these messages to the editor instance as well
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
protected override bool PreProcessMessage(ref System.Windows.Forms.Message m)
{
IVsWindowPane vsWindowPane = this.VsTextView as IVsWindowPane;
if (vsWindowPane != null)
{
MSG[] pMsg = new MSG[1];
pMsg[0].hwnd = m.HWnd;
pMsg[0].message = (uint)m.Msg;
pMsg[0].wParam = m.WParam;
pMsg[0].lParam = m.LParam;
return vsWindowPane.TranslateAccelerator(pMsg) == 0;
}
return base.PreProcessMessage(ref m);
}
/// <summary>
/// Override to forward to editor or handle accordingly if supported by this tool window.
/// </summary>
int IOleCommandTarget.QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
{
// examine buttons within our toolbar
if (pguidCmdGroup == GuidList.guidNuGetCmdSet)
{
bool isEnabled = IsToolbarEnabled;
if (isEnabled)
{
bool isStopButton = (prgCmds[0].cmdID == 0x0600); // 0x0600 is the Command ID of the Stop button, defined in .vsct
// when command is executing: enable stop button and disable the rest
// when command is not executing: disable the stop button and enable the rest
isEnabled = !isStopButton ^ WpfConsole.Dispatcher.IsExecutingCommand;
}
if (isEnabled)
{
prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED);
}
else
{
prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED);
}
return VSConstants.S_OK;
}
int hr = OleCommandFilter.OLECMDERR_E_NOTSUPPORTED;
if (this.VsTextView != null)
{
IOleCommandTarget cmdTarget = (IOleCommandTarget)VsTextView;
hr = cmdTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
}
if (hr == OleCommandFilter.OLECMDERR_E_NOTSUPPORTED)
{
IOleCommandTarget target = this.GetService(typeof(IOleCommandTarget)) as IOleCommandTarget;
if (target != null)
{
hr = target.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
}
}
return hr;
}
/// <summary>
/// Override to forward to editor or handle accordingly if supported by this tool window.
/// </summary>
int IOleCommandTarget.Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
int hr = OleCommandFilter.OLECMDERR_E_NOTSUPPORTED;
if (this.VsTextView != null)
{
IOleCommandTarget cmdTarget = (IOleCommandTarget)VsTextView;
hr = cmdTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
}
if (hr == OleCommandFilter.OLECMDERR_E_NOTSUPPORTED)
{
IOleCommandTarget target = this.GetService(typeof(IOleCommandTarget)) as IOleCommandTarget;
if (target != null)
{
hr = target.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
}
}
return hr;
}
private void SourcesList_Exec(object sender, EventArgs e)
{
OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs;
if (args != null)
{
if (args.InValue != null || args.OutValue == IntPtr.Zero)
{
throw new ArgumentException("Invalid argument", "e");
}
Marshal.GetNativeVariantForObject(PowerConsoleWindow.PackageSources, args.OutValue);
}
}
/// <summary>
/// Called to retrieve current combo item name or to select a new item.
/// </summary>
private void Sources_Exec(object sender, EventArgs e)
{
OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs;
if (args != null)
{
if (args.InValue != null && args.InValue is int) // Selected a feed
{
int index = (int)args.InValue;
if (index >= 0 && index < PowerConsoleWindow.PackageSources.Length)
{
PowerConsoleWindow.ActivePackageSource = PowerConsoleWindow.PackageSources[index];
}
}
else if (args.OutValue != IntPtr.Zero) // Query selected feed name
{
string displayName = PowerConsoleWindow.ActivePackageSource ?? string.Empty;
Marshal.GetNativeVariantForObject(displayName, args.OutValue);
}
}
}
private void ProjectsList_Exec(object sender, EventArgs e)
{
OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs;
if (args != null)
{
if (args.InValue != null || args.OutValue == IntPtr.Zero)
{
throw new ArgumentException("Invalid argument", "e");
}
// get project list here
Marshal.GetNativeVariantForObject(PowerConsoleWindow.AvailableProjects, args.OutValue);
}
}
/// <summary>
/// Called to retrieve current combo item name or to select a new item.
/// </summary>
private void Projects_Exec(object sender, EventArgs e)
{
OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs;
if (args != null)
{
if (args.InValue != null && args.InValue is int)
{
// Selected a default projects
int index = (int)args.InValue;
if (index >= 0 && index < PowerConsoleWindow.AvailableProjects.Length)
{
PowerConsoleWindow.SetDefaultProjectIndex(index);
}
}
else if (args.OutValue != IntPtr.Zero)
{
string displayName = PowerConsoleWindow.DefaultProject ?? string.Empty;
Marshal.GetNativeVariantForObject(displayName, args.OutValue);
}
}
}
/// <summary>
/// ClearHost command handler.
/// </summary>
private void ClearHost_Exec(object sender, EventArgs e)
{
if (WpfConsole != null)
{
WpfConsole.Dispatcher.ClearConsole();
}
}
private void StopHost_Exec(object sender, EventArgs e)
{
if (WpfConsole != null)
{
WpfConsole.Host.Abort();
}
}
private HostInfo ActiveHostInfo
{
get
{
return PowerConsoleWindow.ActiveHostInfo;
}
}
private void LoadConsoleEditor()
{
if (WpfConsole != null)
{
// allow the console to start writing output
WpfConsole.StartWritingOutput();
FrameworkElement consolePane = WpfConsole.Content as FrameworkElement;
ConsoleParentPane.AddConsoleEditor(consolePane);
// WPF doesn't handle input focus automatically in this scenario. We
// have to set the focus manually, otherwise the editor is displayed but
// not focused and not receiving keyboard inputs until clicked.
if (consolePane != null)
{
PendingMoveFocus(consolePane);
}
}
}
/// <summary>
/// Set pending focus to a console pane. At the time of setting active host,
/// the pane (UIElement) is usually not loaded yet and can't receive focus.
/// In this case, we need to set focus in its Loaded event.
/// </summary>
/// <param name="consolePane"></param>
private void PendingMoveFocus(FrameworkElement consolePane)
{
if (consolePane.IsLoaded && consolePane.IsConnectedToPresentationSource())
{
PendingFocusPane = null;
MoveFocus(consolePane);
}
else
{
PendingFocusPane = consolePane;
}
}
private FrameworkElement _pendingFocusPane;
private FrameworkElement PendingFocusPane
{
get
{
return _pendingFocusPane;
}
set
{
if (_pendingFocusPane != null)
{
_pendingFocusPane.Loaded -= PendingFocusPane_Loaded;
}
_pendingFocusPane = value;
if (_pendingFocusPane != null)
{
_pendingFocusPane.Loaded += PendingFocusPane_Loaded;
}
}
}
private void PendingFocusPane_Loaded(object sender, RoutedEventArgs e)
{
MoveFocus(PendingFocusPane);
PendingFocusPane = null;
}
private void MoveFocus(FrameworkElement consolePane)
{
// TAB focus into editor (consolePane.Focus() does not work due to editor layouts)
consolePane.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
// Try start the console session now. This needs to be after the console
// pane getting focus to avoid incorrect initial editor layout.
StartConsoleSession(consolePane);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Design",
"CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "We really don't want exceptions from the console to bring down VS")]
private void StartConsoleSession(FrameworkElement consolePane)
{
if (WpfConsole != null && WpfConsole.Content == consolePane && WpfConsole.Host != null)
{
try
{
if (WpfConsole.Dispatcher.IsStartCompleted)
{
OnDispatcherStartCompleted();
// if the dispatcher was started before we reach here,
// it means the dispatcher has been in read-only mode (due to _startedWritingOutput = false).
// enable key input now.
WpfConsole.Dispatcher.AcceptKeyInput();
}
else
{
WpfConsole.Dispatcher.StartCompleted += (sender, args) =>
{
OnDispatcherStartCompleted();
};
WpfConsole.Dispatcher.StartWaitingKey += OnDispatcherStartWaitingKey;
WpfConsole.Dispatcher.Start();
}
}
catch (Exception x)
{
// hide the text "initialize host" when an error occurs.
ConsoleParentPane.NotifyInitializationCompleted();
WpfConsole.WriteLine(x.ToString());
ExceptionHelper.WriteToActivityLog(x);
}
}
else
{
ConsoleParentPane.NotifyInitializationCompleted();
}
}
private void OnDispatcherStartWaitingKey(object sender, EventArgs args)
{
WpfConsole.Dispatcher.StartWaitingKey -= OnDispatcherStartWaitingKey;
// we want to hide the text "initialize host..." when waiting for key input
ConsoleParentPane.NotifyInitializationCompleted();
}
private void OnDispatcherStartCompleted()
{
WpfConsole.Dispatcher.StartWaitingKey -= OnDispatcherStartWaitingKey;
ConsoleParentPane.NotifyInitializationCompleted();
// force the UI to update the toolbar
VsUIShell.UpdateCommandUI(0 /* false = update UI asynchronously */);
}
private IWpfConsole _wpfConsole;
/// <summary>
/// Get the WpfConsole of the active host.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private IWpfConsole WpfConsole
{
get
{
if (_wpfConsole == null)
{
Debug.Assert(ActiveHostInfo != null);
try
{
_wpfConsole = ActiveHostInfo.WpfConsole;
}
catch (Exception x)
{
_wpfConsole = ActiveHostInfo.WpfConsole;
_wpfConsole.Write(x.ToString());
}
}
return _wpfConsole;
}
}
private IVsTextView _vsTextView;
/// <summary>
/// Get the VsTextView of current WpfConsole if exists.
/// </summary>
private IVsTextView VsTextView
{
get
{
if (_vsTextView == null && _wpfConsole != null)
{
_vsTextView = (IVsTextView)(WpfConsole.VsTextView);
}
return _vsTextView;
}
}
private ConsoleContainer _consoleParentPane;
/// <summary>
/// Get the parent pane of console panes. This serves as the Content of this tool window.
/// </summary>
private ConsoleContainer ConsoleParentPane
{
get
{
if (_consoleParentPane == null)
{
_consoleParentPane = new ConsoleContainer(ProductUpdateService, PackageRestoreManager);
}
return _consoleParentPane;
}
}
public override object Content
{
get
{
return this.ConsoleParentPane;
}
set
{
base.Content = value;
}
}
}
}
| |
using GalaSoft.MvvmLight.Messaging;
using CodeHub.Helpers;
using CodeHub.Services;
using Octokit;
using System;
using System.Threading;
using System.Threading.Tasks;
using Windows.UI;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using CodeHub.Services.Hilite_me;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Ioc;
using CodeHub.Views;
namespace CodeHub.ViewModels
{
public class FileContentViewmodel : AppViewmodel
{
public Repository _repository;
public Repository Repository
{
get
{
return _repository;
}
set
{
Set(() => Repository, ref _repository, value);
}
}
public bool _isSupportedFile;
public bool IsSupportedFile
{
get
{
return _isSupportedFile;
}
set
{
Set(() => IsSupportedFile, ref _isSupportedFile, value);
}
}
public bool _isImage;
public bool IsImage
{
get
{
return _isImage;
}
set
{
Set(() => IsImage, ref _isImage, value);
}
}
public ImageSource _imageFile;
public ImageSource ImageFile
{
get
{
return _imageFile;
}
set
{
Set(() => ImageFile, ref _imageFile, value);
}
}
public string _path;
public string Path
{
get
{
return _path;
}
set
{
Set(() => Path, ref _path, value);
}
}
// HTMLContent
public string _HTMLContent;
public string HTMLContent
{
get
{
return _HTMLContent;
}
set
{
Set(() => HTMLContent, ref _HTMLContent, value);
}
}
// Text Content
public string _TextContent;
public string TextContent
{
get
{
return _TextContent;
}
set
{
Set(() => TextContent, ref _TextContent, value);
}
}
public string _selectedBranch;
public string SelectedBranch
{
get
{
return _selectedBranch;
}
set
{
Set(() => SelectedBranch, ref _selectedBranch, value);
}
}
public Color _HTMLBackgroundColor = SettingsService.Get<bool>(SettingsKeys.AppLightThemeEnabled) ? Colors.White : Colors.Black;
/// <summary>
/// Gets the base background color for the HTML content
/// </summary>
public Color HTMLBackgroundColor
{
get { return _HTMLBackgroundColor; }
private set
{
Set(() => HTMLBackgroundColor, ref _HTMLBackgroundColor, value);
}
}
/// <summary>
///
/// </summary>
/// <param name="repoPath">Tuple with Repository, path and branch</param>
/// <returns></returns>
public async Task Load(Tuple<Repository, string, string> repoPath)
{
IsSupportedFile = true;
Repository = repoPath.Item1;
Path = repoPath.Item2;
if (GlobalHelper.IsInternet())
{
isLoading = true;
if (string.IsNullOrWhiteSpace(repoPath.Item3))
{
SelectedBranch = await RepositoryUtility.GetDefaultBranch(Repository.Id);
}
else
{
SelectedBranch = repoPath.Item3;
}
IsImage = false;
if ((Path.ToLower().EndsWith(".exe")) ||
(Path.ToLower().EndsWith(".pdf")) ||
(Path.ToLower().EndsWith(".ttf")) ||
(Path.ToLower().EndsWith(".suo")) ||
(Path.ToLower().EndsWith(".mp3")) ||
(Path.ToLower().EndsWith(".mp4")) ||
(Path.ToLower().EndsWith(".avi")))
{
/*
* Unsupported file types
*/
IsSupportedFile = false;
isLoading = false;
return;
}
if ((Path.ToLower()).EndsWith(".png") ||
(Path.ToLower()).EndsWith(".jpg") ||
(Path.ToLower()).EndsWith(".jpeg") ||
(Path.ToLower().EndsWith(".gif")))
{
/*
* Image file types
*/
IsImage = true;
String uri = (await RepositoryUtility.GetRepositoryContentByPath(Repository, Path, SelectedBranch))?[0].Content.DownloadUrl;
if(!string.IsNullOrWhiteSpace(uri))
ImageFile = new BitmapImage(new Uri(uri));
isLoading = false;
return;
}
if ((Path.ToLower()).EndsWith(".md"))
{
/*
* Files with .md extension
*/
TextContent = (await RepositoryUtility.GetRepositoryContentByPath(Repository, Path, SelectedBranch))?[0].Content.Content;
isLoading = false;
return;
}
/*
* Code files
*/
String content = (await RepositoryUtility.GetRepositoryContentByPath(Repository, Path, SelectedBranch))?[0].Content.Content;
if (content == null)
{
IsSupportedFile = false;
isLoading = false;
return;
}
SyntaxHighlightStyleEnum style = (SyntaxHighlightStyleEnum)SettingsService.Get<int>(SettingsKeys.HighlightStyleIndex);
bool lineNumbers = SettingsService.Get<bool>(SettingsKeys.ShowLineNumbers);
HTMLContent = await HiliteAPI.TryGetHighlightedCodeAsync(content, Path, style, lineNumbers, CancellationToken.None);
if (HTMLContent == null)
{
/*
* Plain text files (Getting HTML for syntax highlighting failed)
*/
RepositoryContent result = await RepositoryUtility.GetRepositoryContentTextByPath(Repository, Path, SelectedBranch);
if(result != null)
TextContent = result.Content;
}
if (HTMLContent == null && TextContent == null)
IsSupportedFile = false;
isLoading = false;
}
}
private RelayCommand _repoDetailNavigateCommand;
public RelayCommand RepoDetailNavigateCommand
{
get
{
return _repoDetailNavigateCommand
?? (_repoDetailNavigateCommand = new RelayCommand(
() =>
{
SimpleIoc.Default.GetInstance<Services.IAsyncNavigationService>().NavigateAsync(typeof(RepoDetailView), Repository);
}));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using EPiServer;
using EPiServer.Data;
using EPiServer.DataAbstraction;
using EPiServer.PlugIn;
using EPiServer.Security;
using EPiServer.ServiceLocation;
using EPiServer.Web;
using Geta.SEO.Sitemaps.Configuration;
using Geta.SEO.Sitemaps.Entities;
using Geta.SEO.Sitemaps.Repositories;
namespace Geta.SEO.Sitemaps.Modules.Geta.SEO.Sitemaps
{
[GuiPlugIn(Area = PlugInArea.AdminMenu,
DisplayName = "Search engine sitemap settings",
Description = "Manage the sitemap module settings and content",
Url = "~/Modules/Geta.SEO.Sitemaps/AdminManageSitemap.aspx",
RequiredAccess = AccessLevel.Administer)]
public partial class AdminManageSitemap : SimplePage
{
public Injected<ISitemapRepository> SitemapRepository { get; set; }
public Injected<SiteDefinitionRepository> SiteDefinitionRepository { get; set; }
public Injected<ILanguageBranchRepository> LanguageBranchRepository { get; set; }
protected IList<string> SiteHosts { get; set; }
protected bool ShowLanguageDropDown { get; set; }
protected IList<LanguageBranchData> LanguageBranches { get; set; }
protected SitemapData CurrentSitemapData
{
get { return this.GetDataItem() as SitemapData; }
}
protected const string SitemapHostPostfix = "Sitemap.xml";
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
MasterPageFile = ResolveUrlFromUI("MasterPages/EPiServerUI.master");
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
SiteHosts = GetSiteHosts();
ShowLanguageDropDown = ShouldShowLanguageDropDown();
LanguageBranches = LanguageBranchRepository.Service.ListEnabled().Select(x => new LanguageBranchData
{
DisplayName = x.CurrentUrlSegment,
Language = x.Culture.Name
}).ToList();
LanguageBranches.Insert(0, new LanguageBranchData
{
DisplayName = "*",
Language = ""
});
if (!PrincipalInfo.HasAdminAccess)
{
AccessDenied();
}
if (!IsPostBack)
{
BindList();
}
SystemPrefixControl.Heading = "Search engine sitemap settings";
}
private void BindList()
{
lvwSitemapData.DataSource = SitemapRepository.Service.GetAllSitemapData();
lvwSitemapData.DataBind();
}
protected void btnNew_Click(object sender, EventArgs e)
{
lvwSitemapData.EditIndex = -1;
lvwSitemapData.InsertItemPosition = InsertItemPosition.LastItem;
BindList();
PopulateHostListControl(lvwSitemapData.InsertItem);
}
private void PopulateLanguageListControl(ListViewItem containerItem)
{
var ddl = containerItem.FindControl("ddlLanguage") as DropDownList;
if (ddl == null || containerItem.DataItem == null)
{
return;
}
var data = containerItem.DataItem as SitemapData;
if (data == null)
{
return;
}
if (!string.IsNullOrWhiteSpace(data.Language))
{
var selectedItem = ddl.Items.FindByValue(data.Language);
if (selectedItem != null)
{
ddl.SelectedValue = selectedItem.Value;
}
}
}
private void PopulateHostListControl(ListViewItem containerItem)
{
var siteHosts = SiteHosts;
if (siteHosts.Count() > 1)
{
var ddl = containerItem.FindControl("ddlHostUrls") as DropDownList;
if (ddl != null)
{
ddl.DataSource = siteHosts;
ddl.DataBind();
ddl.Visible = true;
if (containerItem.DataItem != null)
{
var data = containerItem.DataItem as SitemapData;
if (data != null && data.SiteUrl != null && siteHosts.Contains(data.SiteUrl))
{
ddl.SelectedIndex = siteHosts.IndexOf(data.SiteUrl);
}
}
}
}
else
{
var label = containerItem.FindControl("lblHostUrl") as Label;
if (label != null)
{
label.Text = siteHosts.ElementAt(0);
label.Visible = true;
}
}
}
protected void lvwSitemapData_ItemCommand(object sender, ListViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "Insert":
{
InsertSitemapData(e.Item);
break;
}
case "Update":
{
UpdateSitemapData(Identity.Parse(e.CommandArgument.ToString()), e.Item);
break;
}
case "Delete":
{
DeleteSitemapData(Identity.Parse(e.CommandArgument.ToString()));
break;
}
case "ViewSitemap":
{
ViewSitemap(Identity.Parse(e.CommandArgument.ToString()));
break;
}
}
}
private void InsertSitemapData(ListViewItem insertItem)
{
var sitemapData = new SitemapData
{
SiteUrl = GetSelectedSiteUrl(insertItem),
Host = ((TextBox)insertItem.FindControl("txtHost")).Text + SitemapHostPostfix,
Language = ((DropDownList)insertItem.FindControl("ddlLanguage")).SelectedValue,
EnableLanguageFallback = ((CheckBox)insertItem.FindControl("cbEnableLanguageFallback")).Checked,
IncludeAlternateLanguagePages = ((CheckBox)insertItem.FindControl("cbIncludeAlternateLanguagePages")).Checked,
PathsToAvoid = GetDirectoryList(insertItem, "txtDirectoriesToAvoid"),
PathsToInclude = GetDirectoryList(insertItem, "txtDirectoriesToInclude"),
IncludeDebugInfo = ((CheckBox)insertItem.FindControl("cbIncludeDebugInfo")).Checked,
SitemapFormat = GetSitemapFormat(insertItem),
RootPageId = TryParse(((TextBox)insertItem.FindControl("txtRootPageId")).Text)
};
SitemapRepository.Service.Save(sitemapData);
CloseInsert();
BindList();
}
private static string GetSelectedSiteUrl(Control containerControl)
{
var ddl = containerControl.FindControl("ddlHostUrls") as DropDownList;
if (ddl != null && ddl.Items.Count > 0)
{
return ddl.SelectedItem.Text;
}
var label = containerControl.FindControl("lblHostUrl") as Label;
return label != null ? label.Text : null;
}
private static int TryParse(string strValue)
{
int rv;
int.TryParse(strValue, out rv);
return rv;
}
private IList<string> GetDirectoryList(Control containerControl, string fieldName)
{
string strValue = ((TextBox)containerControl.FindControl(fieldName)).Text.Trim();
if (string.IsNullOrEmpty(strValue))
{
return null;
}
return new List<string>(Url.Encode(strValue).Split(';'));
}
protected string GetDirectoriesString(Object directoryListObject)
{
if (directoryListObject == null)
{
return string.Empty;
}
return String.Join(";", ((IList<string>)directoryListObject));
}
protected string GetLanguage(string language)
{
if (!string.IsNullOrWhiteSpace(language) && SiteDefinition.WildcardHostName.Equals(language) == false)
{
var languageBranch = LanguageBranchRepository.Service.Load(language);
return string.Format("{0}/", languageBranch.CurrentUrlSegment);
}
return string.Empty;
}
protected bool ShouldShowLanguageDropDown()
{
return SitemapSettings.Instance.EnableLanguageDropDownInAdmin;
}
private SitemapFormat GetSitemapFormat(Control container)
{
if (((RadioButton)container.FindControl("rbMobile")).Checked)
{
return SitemapFormat.Mobile;
}
if (((RadioButton)container.FindControl("rbCommerce")).Checked)
{
return SitemapFormat.Commerce;
}
if (((RadioButton)container.FindControl("rbStandardAndCommerce")).Checked)
{
return SitemapFormat.StandardAndCommerce;
}
return SitemapFormat.Standard;
}
private void UpdateSitemapData(Identity id, ListViewItem item)
{
var sitemapData = SitemapRepository.Service.GetSitemapData(id);
if (sitemapData == null)
{
return;
}
sitemapData.Host = ((TextBox)item.FindControl("txtHost")).Text + SitemapHostPostfix;
sitemapData.Language = ((DropDownList)item.FindControl("ddlLanguage")).SelectedValue;
sitemapData.EnableLanguageFallback = ((CheckBox)item.FindControl("cbEnableLanguageFallback")).Checked;
sitemapData.IncludeAlternateLanguagePages = ((CheckBox) item.FindControl("cbIncludeAlternateLanguagePages")).Checked;
sitemapData.PathsToAvoid = GetDirectoryList(item, "txtDirectoriesToAvoid");
sitemapData.PathsToInclude = GetDirectoryList(item, "txtDirectoriesToInclude");
sitemapData.IncludeDebugInfo = ((CheckBox)item.FindControl("cbIncludeDebugInfo")).Checked;
sitemapData.SitemapFormat = GetSitemapFormat(item);
sitemapData.RootPageId = TryParse(((TextBox)item.FindControl("txtRootPageId")).Text);
sitemapData.SiteUrl = GetSelectedSiteUrl(item);
SitemapRepository.Service.Save(sitemapData);
lvwSitemapData.EditIndex = -1;
BindList();
}
private void DeleteSitemapData(Identity id)
{
SitemapRepository.Service.Delete(id);
BindList();
}
private void ViewSitemap(Identity id)
{
var data = SitemapRepository.Service.GetSitemapData(id).Data;
Response.ContentType = "text/xml";
Response.BinaryWrite(data);
Response.End();
}
protected void lvwSitemapData_ItemDataBound(object sender, ListViewItemEventArgs e)
{
PopulateHostListControl(e.Item);
PopulateLanguageListControl(e.Item);
}
protected IList<string> GetSiteHosts()
{
var siteDefinitionRepository = SiteDefinitionRepository.Service;
IList<SiteDefinition> hosts = siteDefinitionRepository.List().ToList();
var siteUrls = new List<string>(hosts.Count);
foreach (var siteInformation in hosts)
{
siteUrls.Add(siteInformation.SiteUrl.ToString());
foreach (var host in siteInformation.Hosts)
{
if (host.Name == "*" || host.Name.Equals(siteInformation.SiteUrl.Host, StringComparison.InvariantCultureIgnoreCase))
{
continue;
}
siteUrls.Add(string.Format("{0}://{1}/", siteInformation.SiteUrl.Scheme, host.Name));
}
}
return siteUrls;
}
protected string GetSiteUrl(Object evaluatedUrl)
{
if (evaluatedUrl != null)
{
return evaluatedUrl.ToString();
}
//get current site url
return SiteDefinition.Current.SiteUrl.ToString();
}
protected void lvwSitemapData_ItemInserting(object sender, ListViewInsertEventArgs e)
{
}
protected void lvwSitemapData_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
}
protected void lvwSitemapData_ItemEditing(object sender, ListViewEditEventArgs e)
{
CloseInsert();
lvwSitemapData.EditIndex = e.NewEditIndex;
BindList();
}
protected void lvwSitemapData_ItemCanceling(object sender, ListViewCancelEventArgs e)
{
if (e.CancelMode == ListViewCancelMode.CancelingInsert)
{
CloseInsert();
}
else
{
lvwSitemapData.EditIndex = -1;
}
BindList();
}
private void CloseInsert()
{
lvwSitemapData.InsertItemPosition = InsertItemPosition.None;
}
protected void lvwSitemapData_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
}
protected static string GetHostNameEditPart(string hostName)
{
return hostName.Substring(0, hostName.IndexOf(SitemapHostPostfix, StringComparison.InvariantCulture));
}
}
public class LanguageBranchData
{
public string Language { get; set; }
public string DisplayName { get; set; }
}
}
| |
// 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Security.Cryptography
{
public abstract partial class AsymmetricAlgorithm : System.IDisposable
{
protected int KeySizeValue;
protected System.Security.Cryptography.KeySizes[] LegalKeySizesValue;
protected AsymmetricAlgorithm() { }
public virtual string KeyExchangeAlgorithm { get { throw null; } }
public virtual int KeySize { get { throw null; } set { } }
public virtual System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
public virtual string SignatureAlgorithm { get { throw null; } }
public void Clear() { }
public static System.Security.Cryptography.AsymmetricAlgorithm Create() { throw null; }
public static System.Security.Cryptography.AsymmetricAlgorithm Create(string algName) { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public virtual byte[] ExportEncryptedPkcs8PrivateKey(System.ReadOnlySpan<byte> passwordBytes, System.Security.Cryptography.PbeParameters pbeParameters) { throw null; }
public virtual byte[] ExportEncryptedPkcs8PrivateKey(System.ReadOnlySpan<char> password, System.Security.Cryptography.PbeParameters pbeParameters) { throw null; }
public virtual byte[] ExportPkcs8PrivateKey() { throw null; }
public virtual byte[] ExportSubjectPublicKeyInfo() { throw null; }
public virtual void FromXmlString(string xmlString) { }
public virtual void ImportEncryptedPkcs8PrivateKey(System.ReadOnlySpan<byte> passwordBytes, System.ReadOnlySpan<byte> source, out int bytesRead) { throw null; }
public virtual void ImportEncryptedPkcs8PrivateKey(System.ReadOnlySpan<char> password, System.ReadOnlySpan<byte> source, out int bytesRead) { throw null; }
public virtual void ImportPkcs8PrivateKey(System.ReadOnlySpan<byte> source, out int bytesRead) { throw null; }
public virtual void ImportSubjectPublicKeyInfo(System.ReadOnlySpan<byte> source, out int bytesRead) { throw null; }
public virtual string ToXmlString(bool includePrivateParameters) { throw null; }
public virtual bool TryExportEncryptedPkcs8PrivateKey(System.ReadOnlySpan<byte> passwordBytes, System.Security.Cryptography.PbeParameters pbeParameters, System.Span<byte> destination, out int bytesWritten) { throw null; }
public virtual bool TryExportEncryptedPkcs8PrivateKey(System.ReadOnlySpan<char> password, System.Security.Cryptography.PbeParameters pbeParameters, System.Span<byte> destination, out int bytesWritten) { throw null; }
public virtual bool TryExportPkcs8PrivateKey(System.Span<byte> destination, out int bytesWritten) { throw null; }
public virtual bool TryExportSubjectPublicKeyInfo(System.Span<byte> destination, out int bytesWritten) { throw null; }
}
public enum CipherMode
{
CBC = 1,
ECB = 2,
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
OFB = 3,
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
CFB = 4,
CTS = 5,
}
public static partial class CryptographicOperations
{
public static bool FixedTimeEquals(System.ReadOnlySpan<byte> left, System.ReadOnlySpan<byte> right) { throw null; }
public static void ZeroMemory(System.Span<byte> buffer) { }
}
public partial class CryptographicUnexpectedOperationException : System.Security.Cryptography.CryptographicException
{
public CryptographicUnexpectedOperationException() { }
protected CryptographicUnexpectedOperationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public CryptographicUnexpectedOperationException(string message) { }
public CryptographicUnexpectedOperationException(string message, System.Exception inner) { }
public CryptographicUnexpectedOperationException(string format, string insert) { }
}
public partial class CryptoStream : System.IO.Stream, System.IDisposable
{
public CryptoStream(System.IO.Stream stream, System.Security.Cryptography.ICryptoTransform transform, System.Security.Cryptography.CryptoStreamMode mode) { }
public CryptoStream(System.IO.Stream stream, System.Security.Cryptography.ICryptoTransform transform, System.Security.Cryptography.CryptoStreamMode mode, bool leaveOpen) { }
public override bool CanRead { get { throw null; } }
public override bool CanSeek { get { throw null; } }
public override bool CanWrite { get { throw null; } }
public bool HasFlushedFinalBlock { get { throw null; } }
public override long Length { get { throw null; } }
public override long Position { get { throw null; } set { } }
public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { throw null; }
public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { throw null; }
public void Clear() { }
protected override void Dispose(bool disposing) { }
public override System.Threading.Tasks.ValueTask DisposeAsync() { throw null; }
public override int EndRead(System.IAsyncResult asyncResult) { throw null; }
public override void EndWrite(System.IAsyncResult asyncResult) { }
public override void Flush() { }
public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
public void FlushFinalBlock() { }
public override int Read(byte[] buffer, int offset, int count) { throw null; }
public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; }
public override int ReadByte() { throw null; }
public override long Seek(long offset, System.IO.SeekOrigin origin) { throw null; }
public override void SetLength(long value) { }
public override void Write(byte[] buffer, int offset, int count) { }
public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; }
public override void WriteByte(byte value) { }
}
public enum CryptoStreamMode
{
Read = 0,
Write = 1,
}
public abstract partial class HashAlgorithm : System.IDisposable, System.Security.Cryptography.ICryptoTransform
{
protected int HashSizeValue;
protected internal byte[] HashValue;
protected int State;
protected HashAlgorithm() { }
public virtual bool CanReuseTransform { get { throw null; } }
public virtual bool CanTransformMultipleBlocks { get { throw null; } }
public virtual byte[] Hash { get { throw null; } }
public virtual int HashSize { get { throw null; } }
public virtual int InputBlockSize { get { throw null; } }
public virtual int OutputBlockSize { get { throw null; } }
public void Clear() { }
public byte[] ComputeHash(byte[] buffer) { throw null; }
public byte[] ComputeHash(byte[] buffer, int offset, int count) { throw null; }
public byte[] ComputeHash(System.IO.Stream inputStream) { throw null; }
public static System.Security.Cryptography.HashAlgorithm Create() { throw null; }
public static System.Security.Cryptography.HashAlgorithm Create(string hashName) { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
protected abstract void HashCore(byte[] array, int ibStart, int cbSize);
protected virtual void HashCore(System.ReadOnlySpan<byte> source) { }
protected abstract byte[] HashFinal();
public abstract void Initialize();
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { throw null; }
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { throw null; }
public bool TryComputeHash(System.ReadOnlySpan<byte> source, System.Span<byte> destination, out int bytesWritten) { throw null; }
protected virtual bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; }
}
public readonly partial struct HashAlgorithmName : System.IEquatable<System.Security.Cryptography.HashAlgorithmName>
{
private readonly object _dummy;
public HashAlgorithmName(string name) { throw null; }
public static System.Security.Cryptography.HashAlgorithmName MD5 { get { throw null; } }
public string Name { get { throw null; } }
public static System.Security.Cryptography.HashAlgorithmName SHA1 { get { throw null; } }
public static System.Security.Cryptography.HashAlgorithmName SHA256 { get { throw null; } }
public static System.Security.Cryptography.HashAlgorithmName SHA384 { get { throw null; } }
public static System.Security.Cryptography.HashAlgorithmName SHA512 { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public bool Equals(System.Security.Cryptography.HashAlgorithmName other) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Security.Cryptography.HashAlgorithmName left, System.Security.Cryptography.HashAlgorithmName right) { throw null; }
public static bool operator !=(System.Security.Cryptography.HashAlgorithmName left, System.Security.Cryptography.HashAlgorithmName right) { throw null; }
public override string ToString() { throw null; }
}
public abstract partial class HMAC : System.Security.Cryptography.KeyedHashAlgorithm
{
protected HMAC() { }
protected int BlockSizeValue { get { throw null; } set { } }
public string HashName { get { throw null; } set { } }
public override byte[] Key { get { throw null; } set { } }
public static new System.Security.Cryptography.HMAC Create() { throw null; }
public static new System.Security.Cryptography.HMAC Create(string algorithmName) { throw null; }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] rgb, int ib, int cb) { }
protected override void HashCore(System.ReadOnlySpan<byte> source) { }
protected override byte[] HashFinal() { throw null; }
public override void Initialize() { }
protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; }
}
public partial interface ICryptoTransform : System.IDisposable
{
bool CanReuseTransform { get; }
bool CanTransformMultipleBlocks { get; }
int InputBlockSize { get; }
int OutputBlockSize { get; }
int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset);
byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount);
}
public abstract partial class KeyedHashAlgorithm : System.Security.Cryptography.HashAlgorithm
{
protected byte[] KeyValue;
protected KeyedHashAlgorithm() { }
public virtual byte[] Key { get { throw null; } set { } }
public static new System.Security.Cryptography.KeyedHashAlgorithm Create() { throw null; }
public static new System.Security.Cryptography.KeyedHashAlgorithm Create(string algName) { throw null; }
protected override void Dispose(bool disposing) { }
}
public sealed partial class KeySizes
{
public KeySizes(int minSize, int maxSize, int skipSize) { }
public int MaxSize { get { throw null; } }
public int MinSize { get { throw null; } }
public int SkipSize { get { throw null; } }
}
public enum PaddingMode
{
None = 1,
PKCS7 = 2,
Zeros = 3,
ANSIX923 = 4,
ISO10126 = 5,
}
public enum PbeEncryptionAlgorithm
{
Unknown = 0,
Aes128Cbc = 1,
Aes192Cbc = 2,
Aes256Cbc = 3,
TripleDes3KeyPkcs12 = 4,
}
public sealed partial class PbeParameters
{
public PbeParameters(System.Security.Cryptography.PbeEncryptionAlgorithm encryptionAlgorithm, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, int iterationCount) { }
public System.Security.Cryptography.PbeEncryptionAlgorithm EncryptionAlgorithm { get { throw null; } }
public System.Security.Cryptography.HashAlgorithmName HashAlgorithm { get { throw null; } }
public int IterationCount { get { throw null; } }
}
public abstract partial class SymmetricAlgorithm : System.IDisposable
{
protected int BlockSizeValue;
protected int FeedbackSizeValue;
protected byte[] IVValue;
protected int KeySizeValue;
protected byte[] KeyValue;
protected System.Security.Cryptography.KeySizes[] LegalBlockSizesValue;
protected System.Security.Cryptography.KeySizes[] LegalKeySizesValue;
protected System.Security.Cryptography.CipherMode ModeValue;
protected System.Security.Cryptography.PaddingMode PaddingValue;
protected SymmetricAlgorithm() { }
public virtual int BlockSize { get { throw null; } set { } }
public virtual int FeedbackSize { get { throw null; } set { } }
public virtual byte[] IV { get { throw null; } set { } }
public virtual byte[] Key { get { throw null; } set { } }
public virtual int KeySize { get { throw null; } set { } }
public virtual System.Security.Cryptography.KeySizes[] LegalBlockSizes { get { throw null; } }
public virtual System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
public virtual System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } }
public virtual System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } }
public void Clear() { }
public static System.Security.Cryptography.SymmetricAlgorithm Create() { throw null; }
public static System.Security.Cryptography.SymmetricAlgorithm Create(string algName) { throw null; }
public virtual System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; }
public abstract System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV);
public virtual System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; }
public abstract System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV);
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public abstract void GenerateIV();
public abstract void GenerateKey();
public bool ValidKeySize(int bitLength) { throw null; }
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="OrderManager.cs" company="Sitecore Corporation">
// Copyright (c) Sitecore Corporation 1999-2015
// </copyright>
// <summary>
// Defines the OrderProvider class. Provides order management functionality such as creating, updating and selecting orders.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
// -------------------------------------------------------------------------------------------
namespace Sitecore.Ecommerce.Orders
{
using System;
using System.Collections.Generic;
using System.Linq;
using Configuration;
using Data;
using Diagnostics;
using DomainModel.Carts;
using DomainModel.Configurations;
using DomainModel.Data;
using DomainModel.Orders;
using DomainModel.Payments;
using Payments;
using Search;
using SecurityModel;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Exceptions;
using Statuses;
using Utils;
/// <summary>
/// Defines the OrderProvider class. Provides order management functionality such as creating, updating and selecting orders.
/// </summary>
/// <typeparam name="T">The order type</typeparam>
[Obsolete]
public class OrderManager<T> : IOrderManager<T> where T : DomainModel.Orders.Order
{
/// <summary>
/// The entity helper instance.
/// </summary>
private readonly EntityHelper entityHelper;
/// <summary>
/// The order display template Id.
/// </summary>
private readonly ID orderItemTempalteId = new ID(Settings.GetSetting("Ecommerce.Order.OrderItemTempalteId"));
/// <summary>
/// The order line template Id.
/// </summary>
private readonly TemplateID orderLineItemTempalteId = new TemplateID(new ID(Settings.GetSetting("Ecommerce.Order.OrderLineItemTempalteId")));
/// <summary>
/// The search provider.
/// </summary>
private ISearchProvider searchProvider;
/// <summary>
/// Initializes a new instance of the <see cref="OrderManager<T>"/> class.
/// </summary>
/// <param name="searchProvider">The search provider.</param>
/// <param name="orderIdGenerator">The order id generator.</param>
public OrderManager(ISearchProvider searchProvider, OrderIDGenerator orderIdGenerator)
{
this.entityHelper = Context.Entity.Resolve<EntityHelper>();
this.searchProvider = searchProvider;
this.OrderIDGenerator = orderIdGenerator;
BusinessCatalogSettings settings = Context.Entity.GetConfiguration<BusinessCatalogSettings>();
Assert.IsNotNull(settings, typeof(BusinessCatalogSettings), "Unable initialize BusinessCatalogSettings.");
Assert.IsNotNullOrEmpty(settings.OrdersLink, "Unable initialize Orders root item.");
this.Database = Sitecore.Context.ContentDatabase;
this.ItemId = settings.OrdersLink;
}
/// <summary>
/// Gets or sets the order number generator.
/// </summary>
/// <value>
/// The order number generator.
/// </value>
public OrderIDGenerator OrderIDGenerator { get; set; }
/// <summary>
/// Gets or sets the database.
/// </summary>
/// <value>The database.</value>
protected Database Database { get; set; }
/// <summary>
/// Gets or sets the item id.
/// </summary>
/// <value>The item id.</value>
protected string ItemId { get; set; }
/// <summary>
/// Gets or sets the search provider.
/// </summary>
/// <value>The search provider.</value>
protected virtual ISearchProvider SearchProvider
{
get { return this.searchProvider; }
set { this.searchProvider = value; }
}
/// <summary>
/// Gets the orders source item.
/// </summary>
/// <value>The orders item.</value>
private Item OrdersItem
{
get
{
Assert.IsNotNull(this.Database, "Orders database not found.");
return this.Database.GetItem(this.ItemId);
}
}
#region Implementation of the IOrderManager
/// <summary>
/// Gets the order number.
/// </summary>
/// <returns>
/// If ordernumber exists, returns ordernumber, else returns null.
/// </returns>
public virtual string GenerateOrderNumber()
{
return this.OrderIDGenerator.Generate();
}
/// <summary>
/// Gets the order.
/// </summary>
/// <param name="orderNumber">The order number.</param>
/// <returns>The order.</returns>
public virtual T GetOrder(string orderNumber)
{
Query query = new Query();
query.Add(new FieldQuery("OrderNumber", orderNumber, MatchVariant.Exactly));
return this.GetOrders(query).FirstOrDefault();
}
/// <summary>
/// Gets the orders.
/// </summary>
/// <typeparam name="TQuery">The type of the query.</typeparam>
/// <param name="searchQuery">The search query.</param>
/// <returns>The order collection</returns>
public virtual IEnumerable<T> GetOrders<TQuery>(TQuery searchQuery)
{
return this.GetOrdersItems(searchQuery).Select<Item, T>(this.GetOrderFromItem);
}
/// <summary>
/// Gets the orders.
/// </summary>
/// <typeparam name="TQuery">The type of the query.</typeparam>
/// <param name="query">The query.</param>
/// <param name="pageIndex">Index of the page.</param>
/// <param name="pageSize">Size of the page.</param>
/// <returns>The orders.</returns>
public virtual IEnumerable<T> GetOrders<TQuery>(TQuery query, int pageIndex, int pageSize)
{
return this.GetOrdersItems(query).Skip(pageIndex * pageSize).Take(pageSize).Select<Item, T>(this.GetOrderFromItem);
}
/// <summary>
/// Gets the orders count.
/// </summary>
/// <typeparam name="TQuery">The type of the query.</typeparam>
/// <param name="query">The query.</param>
/// <returns>Return selected orders count.</returns>
public virtual int GetOrdersCount<TQuery>(TQuery query)
{
return this.GetOrdersItems(query).Count();
}
/// <summary>
/// Gets the orders items.
/// </summary>
/// <typeparam name="TQuery">The type of the query.</typeparam>
/// <param name="searchQuery">The search query.</param>
/// <returns>Returns orders items.</returns>
protected virtual IEnumerable<Item> GetOrdersItems<TQuery>(TQuery searchQuery)
{
Assert.ArgumentNotNull(searchQuery, "Query");
Assert.IsTrue(searchQuery is Query, "Query type is invalid");
Query query = searchQuery as Query;
if (string.IsNullOrEmpty(query.SearchRoot))
{
Item orderRoot = this.OrdersItem;
Assert.IsNotNull(orderRoot, "Orders root item is null");
query.SearchRoot = orderRoot.ID.ToString();
}
AttributeQuery templateId = new AttributeQuery("TemplateId", this.orderItemTempalteId.ToString(), MatchVariant.Exactly);
if (!query.Contains(templateId))
{
if (!query.IsEmpty())
{
query.AppendCondition(QueryCondition.And);
}
query.Add(templateId);
}
return this.SearchProvider.Search(query, this.OrdersItem.Database).OrderByDescending(itm => itm["OrderNumber"]);
}
/// <summary>
/// Creates the order.
/// </summary>
/// <typeparam name="TShoppingCart">The type of the shopping cart.</typeparam>
/// <param name="shoppingCart">The shopping cart.</param>
/// <returns>The order.</returns>
/// <exception cref="ConfigurationException">The Order/Default Status For Order Registration setting did't contain a valid Status item.</exception>
/// <exception cref="Exception"><c>Exception</c>.</exception>
public virtual T CreateOrder<TShoppingCart>(TShoppingCart shoppingCart) where TShoppingCart : ShoppingCart
{
Assert.IsNotNull(shoppingCart, "Shopping Cart is null");
Events.Event.RaiseEvent("order:creating", this);
TemplateItem orderTemplateItem = this.Database.GetTemplate(this.orderItemTempalteId);
Assert.IsNotNull(orderTemplateItem, "Order item template is null");
T order = Context.Entity.Resolve<T>();
this.entityHelper.CopyPropertiesValues(shoppingCart, ref order);
foreach (ShoppingCartLine line in shoppingCart.ShoppingCartLines)
{
DomainModel.Orders.OrderLine orderLine = Context.Entity.Resolve<DomainModel.Orders.OrderLine>();
orderLine.Product = line.Product;
orderLine.Totals = line.Totals;
orderLine.Quantity = line.Quantity;
orderLine.FriendlyUrl = line.FriendlyUrl;
order.OrderLines.Add(orderLine);
}
// NOTE: Save transaction number.
ITransactionData transactionData = Context.Entity.Resolve<ITransactionData>();
string transactionNumber = TypeUtil.TryParse(transactionData.GetPersistentValue(shoppingCart.OrderNumber, TransactionConstants.TransactionNumber), string.Empty);
if (!string.IsNullOrEmpty(transactionNumber))
{
order.TransactionNumber = transactionNumber;
}
order.OrderDate = DateTime.Now;
order.Status = Context.Entity.Resolve<NewOrder>();
order.ProcessStatus();
Item orderItem;
using (new SecurityDisabler())
{
orderItem = this.OrdersItem.Add(shoppingCart.OrderNumber, orderTemplateItem);
Assert.IsNotNull(orderItem, "Failed to create to order item");
if (order is IEntity)
{
((IEntity)order).Alias = orderItem.ID.ToString();
}
}
try
{
this.SaveOrder(orderItem, order);
}
catch
{
using (new SecurityDisabler())
{
orderItem.Delete();
}
throw;
}
Events.Event.RaiseEvent("order:created", this, order);
return order;
}
/// <summary>
/// Saves the order.
/// </summary>
/// <param name="order">The order.</param>
/// <exception cref="ConfigurationException">The Order id is invalid.</exception>
public virtual void SaveOrder(T order)
{
Assert.ArgumentNotNull(order, "order");
Item orderItem = this.GetOrderItem(order);
Events.Event.RaiseEvent("order:saving", this, this.GetOrder(order.OrderNumber), order);
this.SaveOrder(orderItem, order);
Events.Event.RaiseEvent("order:saved", this, order);
}
#endregion
/// <summary>
/// Saves the order.
/// </summary>
/// <param name="orderItem">The order item.</param>
/// <param name="order">The order.</param>
protected virtual void SaveOrder(Item orderItem, T order)
{
Assert.ArgumentNotNull(orderItem, "orderItem");
Assert.ArgumentNotNull(order, "order");
IDataMapper dataMapper = Context.Entity.Resolve<IDataMapper>();
dataMapper.SaveEntity(order, orderItem, "OrderMappingRule");
using (new SecurityDisabler())
{
foreach (DomainModel.Orders.OrderLine orderLine in order.OrderLines)
{
Query query = new Query();
query.SearchRoot = orderItem.ID.ToString();
query.AppendAttribute("templateid", this.orderLineItemTempalteId.ToString(), MatchVariant.Exactly);
query.AppendCondition(QueryCondition.And);
query.AppendField("id", orderLine.Product.Code, MatchVariant.Exactly);
Item orderLineItem = this.SearchProvider.Search(query, this.Database).FirstOrDefault();
if (orderLineItem == null)
{
orderLineItem = orderItem.Add(orderLine.Product.Code, this.orderLineItemTempalteId);
}
dataMapper.SaveEntity(orderLine, orderLineItem, "OrderLineMappingRule");
}
}
}
/// <summary>
/// Gets the order from item.
/// </summary>
/// <param name="orderItem">The order item.</param>
/// <returns>The order from item.</returns>
protected virtual T GetOrderFromItem(Item orderItem)
{
if (orderItem == null)
{
return Context.Entity.Resolve<T>();
}
IDataMapper dataMapper = Context.Entity.Resolve<IDataMapper>();
T order = dataMapper.GetEntity<T>(orderItem, "OrderMappingRule");
order.OrderLines = new List<DomainModel.Orders.OrderLine>();
foreach (Item orderLineItem in orderItem.Children)
{
DomainModel.Orders.OrderLine orderLine = dataMapper.GetEntity<DomainModel.Orders.OrderLine>(orderLineItem, "OrderLineMappingRule");
orderLine.Id = orderLineItem.ID.ToString();
Assert.IsNotNull(orderLine.Product, "There is no products in the orderline");
order.OrderLines.Add(orderLine);
}
return order;
}
/// <summary>
/// Gets the order item.
/// </summary>
/// <param name="order">The order.</param>
/// <returns>The order item.</returns>
/// <exception cref="ConfigurationException">The Order id is null or empty.</exception>
/// <exception cref="InvalidOperationException">The order number is null or empty.</exception>
protected virtual Item GetOrderItem(T order)
{
if (order is IEntity)
{
IEntity entity = order as IEntity;
if (!string.IsNullOrEmpty(entity.Alias) || ID.IsID(entity.Alias))
{
Item item = this.Database.GetItem(entity.Alias);
if (item != null)
{
return item;
}
}
}
if (string.IsNullOrEmpty(order.OrderNumber))
{
Log.Warn("The order number is null or empty.", this);
throw new InvalidOperationException("The order number is null or empty.");
}
string orderItemTemplateId = string.IsNullOrEmpty(this.entityHelper.GetTemplate(typeof(T)))
? this.orderItemTempalteId.ToString()
: this.entityHelper.GetTemplate(typeof(T));
string number = this.entityHelper.GetField<T>(i => i.OrderNumber);
if (string.IsNullOrEmpty(number))
{
Log.Warn(string.Concat("Field name is undefined. Type: ", typeof(T).ToString(), ". Property: 'OrderNumber'."), this);
number = "OrderNumber";
}
Query query = new Query { SearchRoot = this.OrdersItem.ID.ToString() };
query.AppendAttribute("TemplateId", orderItemTemplateId, MatchVariant.Exactly);
query.AppendCondition(QueryCondition.And);
query.AppendField(number, order.OrderNumber, MatchVariant.Exactly);
return this.SearchProvider.Search(query, this.Database).FirstOrDefault();
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.RDS.Model
{
/// <summary>
/// Container for the parameters to the DescribeReservedDBInstancesOfferings operation.
/// <para> Lists available reserved DB Instance offerings. </para>
/// </summary>
/// <seealso cref="Amazon.RDS.AmazonRDS.DescribeReservedDBInstancesOfferings"/>
public class DescribeReservedDBInstancesOfferingsRequest : AmazonWebServiceRequest
{
private string reservedDBInstancesOfferingId;
private string dBInstanceClass;
private string duration;
private string productDescription;
private string offeringType;
private bool? multiAZ;
private int? maxRecords;
private string marker;
/// <summary>
/// The offering identifier filter value. Specify this parameter to show only the available offering that matches the specified reservation
/// identifier. Example: <c>438012d3-4052-4cc7-b2e3-8d3372e0e706</c>
///
/// </summary>
public string ReservedDBInstancesOfferingId
{
get { return this.reservedDBInstancesOfferingId; }
set { this.reservedDBInstancesOfferingId = value; }
}
/// <summary>
/// Sets the ReservedDBInstancesOfferingId property
/// </summary>
/// <param name="reservedDBInstancesOfferingId">The value to set for the ReservedDBInstancesOfferingId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeReservedDBInstancesOfferingsRequest WithReservedDBInstancesOfferingId(string reservedDBInstancesOfferingId)
{
this.reservedDBInstancesOfferingId = reservedDBInstancesOfferingId;
return this;
}
// Check to see if ReservedDBInstancesOfferingId property is set
internal bool IsSetReservedDBInstancesOfferingId()
{
return this.reservedDBInstancesOfferingId != null;
}
/// <summary>
/// The DB Instance class filter value. Specify this parameter to show only the available offerings matching the specified DB Instance class.
///
/// </summary>
public string DBInstanceClass
{
get { return this.dBInstanceClass; }
set { this.dBInstanceClass = value; }
}
/// <summary>
/// Sets the DBInstanceClass property
/// </summary>
/// <param name="dBInstanceClass">The value to set for the DBInstanceClass property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeReservedDBInstancesOfferingsRequest WithDBInstanceClass(string dBInstanceClass)
{
this.dBInstanceClass = dBInstanceClass;
return this;
}
// Check to see if DBInstanceClass property is set
internal bool IsSetDBInstanceClass()
{
return this.dBInstanceClass != null;
}
/// <summary>
/// Duration filter value, specified in years or seconds. Specify this parameter to show only reservations for this duration. Valid Values: <c>1
/// | 3 | 31536000 | 94608000</c>
///
/// </summary>
public string Duration
{
get { return this.duration; }
set { this.duration = value; }
}
/// <summary>
/// Sets the Duration property
/// </summary>
/// <param name="duration">The value to set for the Duration property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeReservedDBInstancesOfferingsRequest WithDuration(string duration)
{
this.duration = duration;
return this;
}
// Check to see if Duration property is set
internal bool IsSetDuration()
{
return this.duration != null;
}
/// <summary>
/// Product description filter value. Specify this parameter to show only the available offerings matching the specified product description.
///
/// </summary>
public string ProductDescription
{
get { return this.productDescription; }
set { this.productDescription = value; }
}
/// <summary>
/// Sets the ProductDescription property
/// </summary>
/// <param name="productDescription">The value to set for the ProductDescription property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeReservedDBInstancesOfferingsRequest WithProductDescription(string productDescription)
{
this.productDescription = productDescription;
return this;
}
// Check to see if ProductDescription property is set
internal bool IsSetProductDescription()
{
return this.productDescription != null;
}
/// <summary>
/// The offering type filter value. Specify this parameter to show only the available offerings matching the specified offering type. Valid
/// Values: <c>"Light Utilization" | "Medium Utilization" | "Heavy Utilization" </c>
///
/// </summary>
public string OfferingType
{
get { return this.offeringType; }
set { this.offeringType = value; }
}
/// <summary>
/// Sets the OfferingType property
/// </summary>
/// <param name="offeringType">The value to set for the OfferingType property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeReservedDBInstancesOfferingsRequest WithOfferingType(string offeringType)
{
this.offeringType = offeringType;
return this;
}
// Check to see if OfferingType property is set
internal bool IsSetOfferingType()
{
return this.offeringType != null;
}
/// <summary>
/// The Multi-AZ filter value. Specify this parameter to show only the available offerings matching the specified Multi-AZ parameter.
///
/// </summary>
public bool MultiAZ
{
get { return this.multiAZ ?? default(bool); }
set { this.multiAZ = value; }
}
/// <summary>
/// Sets the MultiAZ property
/// </summary>
/// <param name="multiAZ">The value to set for the MultiAZ property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeReservedDBInstancesOfferingsRequest WithMultiAZ(bool multiAZ)
{
this.multiAZ = multiAZ;
return this;
}
// Check to see if MultiAZ property is set
internal bool IsSetMultiAZ()
{
return this.multiAZ.HasValue;
}
/// <summary>
/// The maximum number of records to include in the response. If more than the <c>MaxRecords</c> value is available, a pagination token called a
/// marker is included in the response so that the following results can be retrieved. Default: 100 Constraints: minimum 20, maximum 100
///
/// </summary>
public int MaxRecords
{
get { return this.maxRecords ?? default(int); }
set { this.maxRecords = value; }
}
/// <summary>
/// Sets the MaxRecords property
/// </summary>
/// <param name="maxRecords">The value to set for the MaxRecords property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeReservedDBInstancesOfferingsRequest WithMaxRecords(int maxRecords)
{
this.maxRecords = maxRecords;
return this;
}
// Check to see if MaxRecords property is set
internal bool IsSetMaxRecords()
{
return this.maxRecords.HasValue;
}
/// <summary>
/// An optional pagination token provided by a previous request. If this parameter is specified, the response includes only records beyond the
/// marker, up to the value specified by <c>MaxRecords</c>.
///
/// </summary>
public string Marker
{
get { return this.marker; }
set { this.marker = value; }
}
/// <summary>
/// Sets the Marker property
/// </summary>
/// <param name="marker">The value to set for the Marker property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeReservedDBInstancesOfferingsRequest WithMarker(string marker)
{
this.marker = marker;
return this;
}
// Check to see if Marker property is set
internal bool IsSetMarker()
{
return this.marker != null;
}
}
}
| |
//
// System.Web.Security.SqlMembershipProvider
//
// Authors:
// Ben Maurer ([email protected])
// Lluis Sanchez Gual ([email protected])
//
// (C) 2003 Ben Maurer
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_2_0
using System.Collections;
using System.Collections.Specialized;
using System.Text;
namespace System.Web.Security {
public class SqlMembershipProvider : MembershipProvider {
[MonoTODO]
public override bool ChangePassword (string username, string oldPwd, string newPwd)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override bool ChangePasswordQuestionAndAnswer (string username, string password, string newPwdQuestion, string newPwdAnswer)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override MembershipUser CreateUser (string username, string password, string email, string pwdQuestion, string pwdAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override bool DeleteUser (string username, bool deleteAllRelatedData)
{
throw new NotImplementedException ();
}
[MonoTODO]
public virtual string GeneratePassword ()
{
throw new NotImplementedException ();
}
[MonoTODO]
public override MembershipUserCollection FindUsersByEmail (string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override MembershipUserCollection FindUsersByName (string nameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override MembershipUserCollection GetAllUsers (int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override int GetNumberOfUsersOnline ()
{
throw new NotImplementedException ();
}
[MonoTODO]
public override string GetPassword (string username, string answer)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override MembershipUser GetUser (string username, bool userIsOnline)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override MembershipUser GetUser (object providerUserKey, bool userIsOnline)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override string GetUserNameByEmail (string email)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override void Initialize (string name, NameValueCollection config)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override string ResetPassword (string username, string answer)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override void UpdateUser (MembershipUser user)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override bool ValidateUser (string username, string password)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override bool UnlockUser (string userName)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override string ApplicationName {
get { throw new NotImplementedException (); }
set { throw new NotImplementedException (); }
}
[MonoTODO]
public virtual string Description {
get { throw new NotImplementedException (); }
}
[MonoTODO]
public override bool EnablePasswordReset {
get { throw new NotImplementedException (); }
}
[MonoTODO]
public override bool EnablePasswordRetrieval {
get { throw new NotImplementedException (); }
}
[MonoTODO]
public override MembershipPasswordFormat PasswordFormat {
get { throw new NotImplementedException (); }
}
[MonoTODO]
public override bool RequiresQuestionAndAnswer {
get { throw new NotImplementedException (); }
}
[MonoTODO]
public override bool RequiresUniqueEmail {
get { throw new NotImplementedException (); }
}
[MonoTODO]
public override int MaxInvalidPasswordAttempts {
get { throw new NotImplementedException (); }
}
[MonoTODO]
public override int MinRequiredNonAlphanumericCharacters {
get { throw new NotImplementedException (); }
}
[MonoTODO]
public override int MinRequiredPasswordLength {
get { throw new NotImplementedException (); }
}
[MonoTODO]
public override int PasswordAttemptWindow {
get { throw new NotImplementedException (); }
}
[MonoTODO]
public override string PasswordStrengthRegularExpression {
get { throw new NotImplementedException (); }
}
}
}
#endif
| |
using System.Data;
using Orchard.Data.Migration;
using Orchard.ContentManagement.MetaData;
using Orchard.Core.Contents.Extensions;
using Orchard.Indexing;
using oforms.Models;
namespace oforms {
public class Migrations : DataMigrationImpl {
public int Create() {
// Creating table OFormPartRecord
SchemaBuilder.CreateTable("OFormPartRecord", table => table
.ContentPartRecord()
.Column("Name", DbType.String, x => x.Unique())
.Column("Method", DbType.String)
.Column("InnerHtml", DbType.String)
.Column("Action", DbType.String)
.Column("RedirectUrl", DbType.String)
.Column("CanUploadFiles", DbType.Boolean)
.Column("UploadFileSizeLimit", DbType.Int64)
.Column("UploadFileType", DbType.String)
.Column("UseCaptcha", DbType.Boolean)
.Column("SendEmail", DbType.Boolean)
.Column("EmailFromName", DbType.String)
.Column("EmailFrom", DbType.String)
.Column("EmailSubject", DbType.String)
.Column("EmailSendTo", DbType.String)
.Column("EmailTemplate", DbType.String)
);
return 1;
}
public int UpdateFrom1()
{
SchemaBuilder.AlterTable("OFormPartRecord",
table =>
{
table.AddColumn("SaveResultsToDB", DbType.Boolean);
table.AddColumn("ValRequiredFields", DbType.String);
table.AddColumn("ValNumbersOnly", DbType.String);
table.AddColumn("ValLettersOnly", DbType.String);
table.AddColumn("ValLettersAndNumbersOnly", DbType.String);
table.AddColumn("ValDate", DbType.String);
table.AddColumn("ValEmail", DbType.String);
table.AddColumn("ValUrl", DbType.String);
}
);
return 2;
}
public int UpdateFrom2()
{
SchemaBuilder.AlterTable("OFormPartRecord",
table =>
{
table.AlterColumn("InnerHtml", x => x.WithType(DbType.String).Unlimited());
table.AlterColumn("EmailTemplate", x => x.WithType(DbType.String).Unlimited());
}
);
return 3;
}
public int UpdateFrom3()
{
SchemaBuilder.CreateTable("OFormResultRecord",
table => table
.Column<int>("Id", x => x.PrimaryKey().Identity())
.Column<string>("Xml", x => x.Unlimited())
.Column<int>("OFormPartRecord_Id")
);
return 4;
}
public int UpdateFrom4()
{
SchemaBuilder.AlterTable("OFormResultRecord",
table => {
table.AddColumn("CreatedDate", DbType.DateTime);
table.AddColumn("Ip", DbType.String);
}
);
return 5;
}
public int UpdateFrom5()
{
SchemaBuilder.AlterTable("OFormPartRecord",
table =>
{
table.AlterColumn("ValRequiredFields", x => x.WithType(DbType.String).WithLength(800));
table.AlterColumn("ValNumbersOnly", x => x.WithType(DbType.String).WithLength(800));
table.AlterColumn("ValLettersOnly", x => x.WithType(DbType.String).WithLength(800));
table.AlterColumn("ValLettersAndNumbersOnly", x => x.WithType(DbType.String).WithLength(800));
table.AlterColumn("ValDate", x => x.WithType(DbType.String).WithLength(800));
table.AlterColumn("ValEmail", x => x.WithType(DbType.String).WithLength(800));
table.AlterColumn("ValUrl", x => x.WithType(DbType.String).WithLength(800));
}
);
return 6;
}
public int UpdateFrom6()
{
SchemaBuilder.CreateTable("OFormFileRecord",
table =>
{
table.Column<int>("Id", x => x.PrimaryKey().Identity());
table.Column<int>("OFormResultRecord_Id");
table.Column<string>("FieldName");
table.Column<string>("OriginalName");
table.Column<string>("ContentType");
table.Column<byte[]>("Bytes", x => x.WithType(DbType.Binary).Unlimited());
table.Column<long>("Size");
}
);
return 7;
}
public int UpdateFrom7()
{
SchemaBuilder.AlterTable("OFormResultRecord",
table =>
{
table.AddColumn<string>("CreatedBy");
}
);
SchemaBuilder.AlterTable("OFormPartRecord",
table =>
{
table.AddColumn<string>("SuccessMessage", x => x.WithType(DbType.String).WithLength(500)
.WithDefault("Form submitted successfully"));
}
);
return 8;
}
public int UpdateFrom8()
{
ContentDefinitionManager.AlterPartDefinition(typeof(OFormPart).Name, cfg => cfg.Attachable());
ContentDefinitionManager.AlterTypeDefinition("OForm",
cfg => cfg
.WithPart(typeof(OFormPart).Name)
.WithPart("TitlePart")
.WithPart("AutoroutePart", builder => builder
.WithSetting("AutorouteSettings.AllowCustomPattern", "true")
.WithSetting("AutorouteSettings.AutomaticAdjustmentOnEdit", "false")
.WithSetting("AutorouteSettings.PatternDefinitions", "[{Name:'Title', Pattern: '{Content.Slug}', Description: 'my-from'}]")
.WithSetting("AutorouteSettings.DefaultPatternIndex", "0"))
.WithPart("MenuPart"));
return 9;
}
public int UpdateFrom9()
{
ContentDefinitionManager.AlterTypeDefinition("OFormWidget", cfg => cfg
.WithPart(typeof(OFormPart).Name)
.WithPart("WidgetPart")
.WithPart("CommonPart")
.WithSetting("Stereotype", "Widget"));
return 10;
}
public int UpdateFrom10()
{
SchemaBuilder.AlterTable("OFormPartRecord",
table =>
{
table.AddColumn<string>("Target");
}
);
return 11;
}
public int UpdateFrom11()
{
SchemaBuilder.CreateTable("OFormSettingsPartRecord",
table => table.ContentPartRecord()
.Column<string>("SerialKey")
);
return 12;
}
public int UpdateFrom12()
{
SchemaBuilder.DropTable("OFormSettingsPartRecord");
return 13;
}
}
}
| |
using System;
using System.Globalization;
using System.Security.Claims;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Constants;
using BTCPayServer.Abstractions.Extensions;
using BTCPayServer.Abstractions.Models;
using BTCPayServer.Data;
using BTCPayServer.Events;
using BTCPayServer.Fido2;
using BTCPayServer.Fido2.Models;
using BTCPayServer.Logging;
using BTCPayServer.Models.AccountViewModels;
using BTCPayServer.Services;
using Fido2NetLib;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using NBitcoin.DataEncoders;
using Newtonsoft.Json.Linq;
using NicolasDorier.RateLimits;
namespace BTCPayServer.Controllers
{
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public class UIAccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
readonly RoleManager<IdentityRole> _RoleManager;
readonly SettingsRepository _SettingsRepository;
readonly Configuration.BTCPayServerOptions _Options;
private readonly BTCPayServerEnvironment _btcPayServerEnvironment;
private readonly Fido2Service _fido2Service;
private readonly LnurlAuthService _lnurlAuthService;
private readonly LinkGenerator _linkGenerator;
private readonly UserLoginCodeService _userLoginCodeService;
private readonly EventAggregator _eventAggregator;
readonly ILogger _logger;
public Logs Logs { get; }
public UIAccountController(
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager,
SignInManager<ApplicationUser> signInManager,
SettingsRepository settingsRepository,
Configuration.BTCPayServerOptions options,
BTCPayServerEnvironment btcPayServerEnvironment,
EventAggregator eventAggregator,
Fido2Service fido2Service,
UserLoginCodeService userLoginCodeService,
LnurlAuthService lnurlAuthService,
LinkGenerator linkGenerator,
Logs logs)
{
_userManager = userManager;
_signInManager = signInManager;
_RoleManager = roleManager;
_SettingsRepository = settingsRepository;
_Options = options;
_btcPayServerEnvironment = btcPayServerEnvironment;
_fido2Service = fido2Service;
_lnurlAuthService = lnurlAuthService;
_linkGenerator = linkGenerator;
_userLoginCodeService = userLoginCodeService;
_eventAggregator = eventAggregator;
_logger = logs.PayServer;
Logs = logs;
}
[TempData]
public string ErrorMessage
{
get; set;
}
[HttpGet("/login")]
[AllowAnonymous]
public async Task<IActionResult> Login(string returnUrl = null, string email = null)
{
if (User.Identity.IsAuthenticated && string.IsNullOrEmpty(returnUrl))
return await RedirectToLocal();
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
if (!CanLoginOrRegister())
{
SetInsecureFlags();
}
ViewData["ReturnUrl"] = returnUrl;
return View(nameof(Login), new LoginViewModel() { Email = email });
}
[HttpPost("/login/code")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[RateLimitsFilter(ZoneLimits.Login, Scope = RateLimitsScope.RemoteAddress)]
public async Task<IActionResult> LoginWithCode(string loginCode, string returnUrl = null)
{
if (!string.IsNullOrEmpty(loginCode))
{
var userId = _userLoginCodeService.Verify(loginCode);
if (userId is null)
{
ModelState.AddModelError(string.Empty,
"Login code was invalid");
return await Login(returnUrl, null);
}
var user = await _userManager.FindByIdAsync(userId);
_logger.LogInformation("User with ID {UserId} logged in with a login code.", user.Id);
await _signInManager.SignInAsync(user, false, "LoginCode");
return await RedirectToLocal(returnUrl);
}
return await Login(returnUrl, null);
}
[HttpPost("/login")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[RateLimitsFilter(ZoneLimits.Login, Scope = RateLimitsScope.RemoteAddress)]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
if (!CanLoginOrRegister())
{
return RedirectToAction("Login");
}
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
// Require the user to have a confirmed email before they can log on.
var user = await _userManager.FindByEmailAsync(model.Email);
if (user != null)
{
if (user.RequiresEmailConfirmation && !await _userManager.IsEmailConfirmedAsync(user))
{
ModelState.AddModelError(string.Empty,
"You must have a confirmed email to log in.");
return View(model);
}
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
var fido2Devices = await _fido2Service.HasCredentials(user.Id);
var lnurlAuthCredentials = await _lnurlAuthService.HasCredentials(user.Id);
if (!await _userManager.IsLockedOutAsync(user) && (fido2Devices || lnurlAuthCredentials))
{
if (await _userManager.CheckPasswordAsync(user, model.Password))
{
LoginWith2faViewModel twoFModel = null;
if (user.TwoFactorEnabled)
{
// we need to do an actual sign in attempt so that 2fa can function in next step
await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: true);
twoFModel = new LoginWith2faViewModel
{
RememberMe = model.RememberMe
};
}
return View("SecondaryLogin", new SecondaryLoginViewModel()
{
LoginWith2FaViewModel = twoFModel,
LoginWithFido2ViewModel = fido2Devices? await BuildFido2ViewModel(model.RememberMe, user): null,
LoginWithLNURLAuthViewModel = lnurlAuthCredentials? await BuildLNURLAuthViewModel(model.RememberMe, user): null,
});
}
else
{
var incrementAccessFailedResult = await _userManager.AccessFailedAsync(user);
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
_logger.LogInformation($"User '{user.Id}' logged in.");
return await RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return View("SecondaryLogin", new SecondaryLoginViewModel()
{
LoginWith2FaViewModel = new LoginWith2faViewModel()
{
RememberMe = model.RememberMe
}
});
}
if (result.IsLockedOut)
{
_logger.LogWarning($"User '{user.Id}' account locked out.");
return RedirectToAction(nameof(Lockout));
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
private async Task<LoginWithFido2ViewModel> BuildFido2ViewModel(bool rememberMe, ApplicationUser user)
{
if (_btcPayServerEnvironment.IsSecure)
{
var r = await _fido2Service.RequestLogin(user.Id);
if (r is null)
{
return null;
}
return new LoginWithFido2ViewModel()
{
Data = r,
UserId = user.Id,
RememberMe = rememberMe
};
}
return null;
}
private async Task<LoginWithLNURLAuthViewModel> BuildLNURLAuthViewModel(bool rememberMe, ApplicationUser user)
{
if (_btcPayServerEnvironment.IsSecure)
{
var r = await _lnurlAuthService.RequestLogin(user.Id);
if (r is null)
{
return null;
}
return new LoginWithLNURLAuthViewModel()
{
RememberMe = rememberMe,
UserId = user.Id,
LNURLEndpoint = new Uri(_linkGenerator.GetUriByAction(
action: nameof(UILNURLAuthController.LoginResponse),
controller: "UILNURLAuth",
values: new { userId = user.Id, action="login", tag="login", k1= Encoders.Hex.EncodeData(r) }, Request.Scheme, Request.Host, Request.PathBase))
};
}
return null;
}
[HttpPost("/login/lnurlauth")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LoginWithLNURLAuth(LoginWithLNURLAuthViewModel viewModel, string returnUrl = null)
{
if (!CanLoginOrRegister())
{
return RedirectToAction("Login");
}
ViewData["ReturnUrl"] = returnUrl;
var user = await _userManager.FindByIdAsync(viewModel.UserId);
if (user == null)
{
return NotFound();
}
var errorMessage = string.Empty;
try
{
var k1 = Encoders.Hex.DecodeData(viewModel.LNURLEndpoint.ParseQueryString().Get("k1"));
if (_lnurlAuthService.FinalLoginStore.TryRemove(viewModel.UserId, out var storedk1) &&
storedk1.SequenceEqual(k1))
{
_lnurlAuthService.FinalLoginStore.TryRemove(viewModel.UserId, out _);
await _signInManager.SignInAsync(user, viewModel.RememberMe, "FIDO2");
_logger.LogInformation("User logged in.");
return await RedirectToLocal(returnUrl);
}
errorMessage = "Invalid login attempt.";
}
catch (Exception e)
{
errorMessage = e.Message;
}
ModelState.AddModelError(string.Empty, errorMessage);
return View("SecondaryLogin", new SecondaryLoginViewModel()
{
LoginWithFido2ViewModel = (await _fido2Service.HasCredentials(user.Id)) ? await BuildFido2ViewModel(viewModel.RememberMe, user) : null,
LoginWithLNURLAuthViewModel = viewModel,
LoginWith2FaViewModel = !user.TwoFactorEnabled
? null
: new LoginWith2faViewModel()
{
RememberMe = viewModel.RememberMe
}
});
}
[HttpPost("/login/fido2")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LoginWithFido2(LoginWithFido2ViewModel viewModel, string returnUrl = null)
{
if (!CanLoginOrRegister())
{
return RedirectToAction("Login");
}
ViewData["ReturnUrl"] = returnUrl;
var user = await _userManager.FindByIdAsync(viewModel.UserId);
if (user == null)
{
return NotFound();
}
var errorMessage = string.Empty;
try
{
if (await _fido2Service.CompleteLogin(viewModel.UserId, JObject.Parse(viewModel.Response).ToObject<AuthenticatorAssertionRawResponse>()))
{
await _signInManager.SignInAsync(user, viewModel.RememberMe, "FIDO2");
_logger.LogInformation("User logged in.");
return await RedirectToLocal(returnUrl);
}
errorMessage = "Invalid login attempt.";
}
catch (Fido2VerificationException e)
{
errorMessage = e.Message;
}
ModelState.AddModelError(string.Empty, errorMessage);
viewModel.Response = null;
return View("SecondaryLogin", new SecondaryLoginViewModel()
{
LoginWithFido2ViewModel = viewModel,
LoginWithLNURLAuthViewModel = (await _lnurlAuthService.HasCredentials(user.Id)) ? await BuildLNURLAuthViewModel(viewModel.RememberMe, user) : null,
LoginWith2FaViewModel = !user.TwoFactorEnabled
? null
: new LoginWith2faViewModel()
{
RememberMe = viewModel.RememberMe
}
});
}
[HttpGet("/login/2fa")]
[AllowAnonymous]
public async Task<IActionResult> LoginWith2fa(bool rememberMe, string returnUrl = null)
{
if (!CanLoginOrRegister())
{
return RedirectToAction("Login");
}
// Ensure the user has gone through the username & password screen first
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new ApplicationException($"Unable to load two-factor authentication user.");
}
ViewData["ReturnUrl"] = returnUrl;
return View("SecondaryLogin", new SecondaryLoginViewModel()
{
LoginWith2FaViewModel = new LoginWith2faViewModel { RememberMe = rememberMe },
LoginWithFido2ViewModel = (await _fido2Service.HasCredentials(user.Id)) ? await BuildFido2ViewModel(rememberMe, user) : null,
LoginWithLNURLAuthViewModel = (await _lnurlAuthService.HasCredentials(user.Id)) ? await BuildLNURLAuthViewModel(rememberMe, user) : null,
});
}
[HttpPost("/login/2fa")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LoginWith2fa(LoginWith2faViewModel model, bool rememberMe, string returnUrl = null)
{
if (!CanLoginOrRegister())
{
return RedirectToAction("Login");
}
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var authenticatorCode = model.TwoFactorCode.Replace(" ", string.Empty, StringComparison.InvariantCulture).Replace("-", string.Empty, StringComparison.InvariantCulture);
var result = await _signInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, rememberMe, model.RememberMachine);
if (result.Succeeded)
{
_logger.LogInformation("User with ID {UserId} logged in with 2fa.", user.Id);
return await RedirectToLocal(returnUrl);
}
else if (result.IsLockedOut)
{
_logger.LogWarning("User with ID {UserId} account locked out.", user.Id);
return RedirectToAction(nameof(Lockout));
}
else
{
_logger.LogWarning("Invalid authenticator code entered for user with ID {UserId}.", user.Id);
ModelState.AddModelError(string.Empty, "Invalid authenticator code.");
return View("SecondaryLogin", new SecondaryLoginViewModel()
{
LoginWith2FaViewModel = model,
LoginWithFido2ViewModel = (await _fido2Service.HasCredentials(user.Id)) ? await BuildFido2ViewModel(rememberMe, user) : null,
LoginWithLNURLAuthViewModel = (await _lnurlAuthService.HasCredentials(user.Id)) ? await BuildLNURLAuthViewModel(rememberMe, user) : null,
});
}
}
[HttpGet("/login/recovery-code")]
[AllowAnonymous]
public async Task<IActionResult> LoginWithRecoveryCode(string returnUrl = null)
{
if (!CanLoginOrRegister())
{
return RedirectToAction("Login");
}
// Ensure the user has gone through the username & password screen first
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new ApplicationException($"Unable to load two-factor authentication user.");
}
ViewData["ReturnUrl"] = returnUrl;
return View();
}
[HttpPost("/login/recovery-code")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LoginWithRecoveryCode(LoginWithRecoveryCodeViewModel model, string returnUrl = null)
{
if (!CanLoginOrRegister())
{
return RedirectToAction("Login");
}
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new ApplicationException($"Unable to load two-factor authentication user.");
}
var recoveryCode = model.RecoveryCode.Replace(" ", string.Empty, StringComparison.InvariantCulture);
var result = await _signInManager.TwoFactorRecoveryCodeSignInAsync(recoveryCode);
if (result.Succeeded)
{
_logger.LogInformation("User with ID {UserId} logged in with a recovery code.", user.Id);
return await RedirectToLocal(returnUrl);
}
if (result.IsLockedOut)
{
_logger.LogWarning("User with ID {UserId} account locked out.", user.Id);
return RedirectToAction(nameof(Lockout));
}
else
{
_logger.LogWarning("Invalid recovery code entered for user with ID {UserId}", user.Id);
ModelState.AddModelError(string.Empty, "Invalid recovery code entered.");
return View();
}
}
[HttpGet("/login/lockout")]
[AllowAnonymous]
public IActionResult Lockout()
{
return View();
}
[HttpGet("/register")]
[AllowAnonymous]
[RateLimitsFilter(ZoneLimits.Register, Scope = RateLimitsScope.RemoteAddress)]
public async Task<IActionResult> Register(string returnUrl = null, bool logon = true)
{
if (!CanLoginOrRegister())
{
SetInsecureFlags();
}
var policies = await _SettingsRepository.GetSettingAsync<PoliciesSettings>() ?? new PoliciesSettings();
if (policies.LockSubscription && !User.IsInRole(Roles.ServerAdmin))
return RedirectToAction(nameof(UIHomeController.Index), "UIHome");
ViewData["ReturnUrl"] = returnUrl;
return View();
}
[HttpPost("/register")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null, bool logon = true)
{
if (!CanLoginOrRegister())
{
return RedirectToAction("Register");
}
ViewData["ReturnUrl"] = returnUrl;
ViewData["Logon"] = logon.ToString(CultureInfo.InvariantCulture).ToLowerInvariant();
var policies = await _SettingsRepository.GetSettingAsync<PoliciesSettings>() ?? new PoliciesSettings();
if (policies.LockSubscription && !User.IsInRole(Roles.ServerAdmin))
return RedirectToAction(nameof(UIHomeController.Index), "UIHome");
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
RequiresEmailConfirmation = policies.RequiresConfirmedEmail,
Created = DateTimeOffset.UtcNow
};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var admin = await _userManager.GetUsersInRoleAsync(Roles.ServerAdmin);
if (admin.Count == 0 || (model.IsAdmin && _Options.CheatMode))
{
await _RoleManager.CreateAsync(new IdentityRole(Roles.ServerAdmin));
await _userManager.AddToRoleAsync(user, Roles.ServerAdmin);
var settings = await _SettingsRepository.GetSettingAsync<ThemeSettings>();
settings.FirstRun = false;
await _SettingsRepository.UpdateSetting<ThemeSettings>(settings);
await _SettingsRepository.FirstAdminRegistered(policies, _Options.UpdateUrl != null, _Options.DisableRegistration, Logs);
RegisteredAdmin = true;
}
_eventAggregator.Publish(new UserRegisteredEvent()
{
RequestUri = Request.GetAbsoluteRootUri(),
User = user,
Admin = RegisteredAdmin
});
RegisteredUserId = user.Id;
if (!policies.RequiresConfirmedEmail)
{
if (logon)
await _signInManager.SignInAsync(user, isPersistent: false);
return await RedirectToLocal(returnUrl);
}
else
{
TempData[WellKnownTempData.SuccessMessage] = "Account created, please confirm your email";
return View();
}
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
// Properties used by tests
public string RegisteredUserId { get; set; }
public bool RegisteredAdmin { get; set; }
[HttpGet("/logout")]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
HttpContext.DeleteUserPrefsCookie();
_logger.LogInformation("User logged out.");
return RedirectToAction(nameof(UIAccountController.Login));
}
[HttpGet("/register/confirm-email")]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return RedirectToAction(nameof(UIHomeController.Index), "UIHome");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{userId}'.");
}
var result = await _userManager.ConfirmEmailAsync(user, code);
if (!await _userManager.HasPasswordAsync(user))
{
TempData.SetStatusMessageModel(new StatusMessageModel()
{
Severity = StatusMessageModel.StatusSeverity.Info,
Message = "Your email has been confirmed but you still need to set your password."
});
return RedirectToAction("SetPassword", new { email = user.Email, code = await _userManager.GeneratePasswordResetTokenAsync(user) });
}
if (result.Succeeded)
{
TempData.SetStatusMessageModel(new StatusMessageModel()
{
Severity = StatusMessageModel.StatusSeverity.Success,
Message = "Your email has been confirmed."
});
return RedirectToAction("Login", new { email = user.Email });
}
return View("Error");
}
[HttpGet("/login/forgot-password")]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View();
}
[HttpPost("/login/forgot-password")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[RateLimitsFilter(ZoneLimits.ForgotPassword, Scope = RateLimitsScope.RemoteAddress)]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByEmailAsync(model.Email);
if (user == null || (user.RequiresEmailConfirmation && !(await _userManager.IsEmailConfirmedAsync(user))))
{
// Don't reveal that the user does not exist or is not confirmed
return RedirectToAction(nameof(ForgotPasswordConfirmation));
}
_eventAggregator.Publish(new UserPasswordResetRequestedEvent()
{
User = user,
RequestUri = Request.GetAbsoluteRootUri()
});
return RedirectToAction(nameof(ForgotPasswordConfirmation));
}
// If we got this far, something failed, redisplay form
return View(model);
}
[HttpGet("/login/forgot-password/confirm")]
[AllowAnonymous]
public IActionResult ForgotPasswordConfirmation()
{
return View();
}
[HttpGet("/login/set-password")]
[AllowAnonymous]
public async Task<IActionResult> SetPassword(string code = null, string userId = null, string email = null)
{
if (code == null)
{
throw new ApplicationException("A code must be supplied for password reset.");
}
if (!string.IsNullOrEmpty(userId))
{
var user = await _userManager.FindByIdAsync(userId);
email = user?.Email;
}
var model = new SetPasswordViewModel { Code = code, Email = email, EmailSetInternally = !string.IsNullOrEmpty(email) };
return View(model);
}
[HttpPost("/login/set-password")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.FindByEmailAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction(nameof(Login));
}
var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
TempData.SetStatusMessageModel(new StatusMessageModel()
{
Severity = StatusMessageModel.StatusSeverity.Success,
Message = "Password successfully set."
});
return RedirectToAction(nameof(Login));
}
AddErrors(result);
return View(model);
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private async Task<IActionResult> RedirectToLocal(string returnUrl = null)
{
if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
// After login, if there is an app on "/", we should redirect to BTCPay explicit home route, and not to the app.
var policies = await _SettingsRepository.GetPolicies();
if (policies?.RootAppId is not null && policies?.RootAppType is not null)
return RedirectToAction(nameof(UIHomeController.Home), "UIHome");
if (policies?.DomainToAppMapping is { } mapping)
{
var matchedDomainMapping = mapping.FirstOrDefault(item =>
item.Domain.Equals(this.HttpContext.Request.Host.Host, StringComparison.InvariantCultureIgnoreCase));
if (matchedDomainMapping is not null)
return RedirectToAction(nameof(UIHomeController.Home), "UIHome");
}
return RedirectToAction(nameof(UIHomeController.Index), "UIHome");
}
}
private bool CanLoginOrRegister()
{
return _btcPayServerEnvironment.IsDeveloping || _btcPayServerEnvironment.IsSecure;
}
private void SetInsecureFlags()
{
TempData.SetStatusMessageModel(new StatusMessageModel()
{
Severity = StatusMessageModel.StatusSeverity.Error,
Message = "You cannot login over an insecure connection. Please use HTTPS or Tor."
});
ViewData["disabled"] = true;
}
#endregion
}
}
| |
//---------------------------------------------------------------------
// <copyright file="CellTreeSimplifier.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Data.Common.Utils;
using System.Data.Mapping.ViewGeneration.Structures;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Data.Metadata.Edm;
using System.Linq;
namespace System.Data.Mapping.ViewGeneration
{
// This class simplifies an extent's view. Given a view, runs the TM/SP
// rules to remove unnecessary self-joins or self-unions
internal class CellTreeSimplifier : InternalBase
{
#region Fields
private ViewgenContext m_viewgenContext;
#endregion
#region Constructor
private CellTreeSimplifier(ViewgenContext context)
{
m_viewgenContext = context;
}
#endregion
#region Exposed Methods
// effects: see CellTreeNode.Simplify below
internal static CellTreeNode MergeNodes(CellTreeNode rootNode)
{
CellTreeSimplifier simplifier = new CellTreeSimplifier(rootNode.ViewgenContext);
return simplifier.SimplifyTreeByMergingNodes(rootNode);
}
// effects: Simplifies the tree rooted at rootNode and returns a new
// tree -- it ensures that the returned tree has at most one node for
// any particular extent unless the tree has nodes of the same extent
// embedded two leaves below LASJ or LOJ, e.g., if we have a tree
// (where Ni indicates a node for extent i - one Ni can be different
// from anohter Ni:
// [N0 IJ N1] LASJ N0 --> This will not be simplified
// canBooleansOverlap indicates whether an original input cell
// contributes to multiple nodes in this tree, e.g., V1 IJ V2 UNION V2 IJ V3
private CellTreeNode SimplifyTreeByMergingNodes(CellTreeNode rootNode)
{
if (rootNode is LeafCellTreeNode)
{ // View already simple!
return rootNode;
}
Debug.Assert(rootNode.OpType == CellTreeOpType.LOJ || rootNode.OpType == CellTreeOpType.IJ ||
rootNode.OpType == CellTreeOpType.FOJ || rootNode.OpType == CellTreeOpType.Union ||
rootNode.OpType == CellTreeOpType.LASJ,
"Only handle these operations");
// Before we apply any rule, check if we can improve the opportunity to
// collapse the nodes
rootNode = RestructureTreeForMerges(rootNode);
List<CellTreeNode> children = rootNode.Children;
Debug.Assert(children.Count > 0, "OpCellTreeNode has no children?");
// Apply recursively
for (int i = 0; i < children.Count; i++)
{
children[i] = SimplifyTreeByMergingNodes(children[i]);
}
// Essentially, we have a node with IJ, LOJ, U or FOJ type that
// has some children. Check if some of the children can be merged
// with one another using the corresponding TM/SP rule
// Ops such as IJ, Union and FOJ are associative, i.e., A op (B
// op C) is the same as (A op B) op C. This is not true for LOJ
// and LASJ
bool isAssociativeOp = CellTreeNode.IsAssociativeOp(rootNode.OpType);
if (isAssociativeOp)
{
// Group all the leaf cells of an extent together so that we can
// later simply run through them without running nested loops
// We do not do this for LOJ/LASJ nodes since LOJ (LASJ) is not commutative
// (or associative);
children = GroupLeafChildrenByExtent(children);
}
else
{
children = GroupNonAssociativeLeafChildren(children);
}
// childrenSet keeps track of the children that need to be procesed/partitioned
OpCellTreeNode newNode = new OpCellTreeNode(m_viewgenContext, rootNode.OpType);
CellTreeNode lastChild = null;
bool skipRest = false;
foreach (CellTreeNode child in children)
{
if (lastChild == null)
{
// First time in the loop. Just set lastChild
lastChild = child;
continue;
}
bool mergedOk = false;
// try to merge lastChild and child
if (false == skipRest && lastChild.OpType == CellTreeOpType.Leaf &&
child.OpType == CellTreeOpType.Leaf)
{
// Both are cell queries. Can try to merge them
// We do not add lastChild since it could merge
// further. It will be added in a later loop or outside the loop
mergedOk = TryMergeCellQueries(rootNode.OpType, ref lastChild, child);
}
if (false == mergedOk)
{
// No merge occurred. Simply add the previous child as it
// is (Note lastChild will be added in the next loop or if
// the loop finishes, outside the loop
newNode.Add(lastChild);
lastChild = child;
if (false == isAssociativeOp)
{
// LOJ is not associative:
// (P loj PA) loj PO != P loj (PA loj PO). The RHS does not have
// Persons who have orders but no addresses
skipRest = true;
}
}
}
newNode.Add(lastChild);
CellTreeNode result = newNode.AssociativeFlatten();
return result;
}
#endregion
#region Private Methods
// effects: Restructure tree so that it is better positioned for merges
private CellTreeNode RestructureTreeForMerges(CellTreeNode rootNode)
{
List<CellTreeNode> children = rootNode.Children;
if (CellTreeNode.IsAssociativeOp(rootNode.OpType) == false || children.Count <= 1)
{
return rootNode;
}
// If this node's operator is associative and each child's
// operator is also associative, check if there is a common set
// of leaf nodes across all grandchildren
Set<LeafCellTreeNode> commonGrandChildren = GetCommonGrandChildren(children);
if (commonGrandChildren == null)
{
return rootNode;
}
CellTreeOpType commonChildOpType = children[0].OpType;
// We do have the structure that we are looking for
// (common op2 gc2) op1 (common op2 gc3) op1 (common op2 gc4) becomes
// common op2 (gc2 op1 gc3 op1 gc4)
// e.g., (A IJ B IJ X IJ Y) UNION (A IJ B IJ Y IJ Z) UNION (A IJ B IJ R IJ S)
// becomes A IJ B IJ ((X IJ Y) UNION (Y IJ Z) UNION (R IJ S))
// From each child in children, get the nodes other than commonGrandChildren - these are gc2, gc3, ...
// Each gc2 must be connected by op2 as before, i.e., ABC + ACD = A(BC + CD)
// All children must be OpCellTreeNodes!
List<OpCellTreeNode> newChildren = new List<OpCellTreeNode>(children.Count);
foreach (OpCellTreeNode child in children)
{
// Remove all children in child that belong to commonGrandChildren
// All grandChildren must be leaf nodes at this point
List<LeafCellTreeNode> newGrandChildren = new List<LeafCellTreeNode>(child.Children.Count);
foreach (LeafCellTreeNode grandChild in child.Children)
{
if (commonGrandChildren.Contains(grandChild) == false)
{
newGrandChildren.Add(grandChild);
}
}
// In the above example, child.OpType is IJ
Debug.Assert(child.OpType == commonChildOpType);
OpCellTreeNode newChild = new OpCellTreeNode(m_viewgenContext, child.OpType,
Helpers.AsSuperTypeList<LeafCellTreeNode, CellTreeNode>(newGrandChildren));
newChildren.Add(newChild);
}
// Connect gc2 op1 gc3 op1 gc4 - op1 is UNION in this
// ((X IJ Y) UNION (Y IJ Z) UNION (R IJ S))
// rootNode.Type is UNION
CellTreeNode remainingNodes = new OpCellTreeNode(m_viewgenContext, rootNode.OpType,
Helpers.AsSuperTypeList<OpCellTreeNode, CellTreeNode>(newChildren));
// Take the common grandchildren and connect via commonChildType
// i.e., A IJ B
CellTreeNode commonNodes = new OpCellTreeNode(m_viewgenContext, commonChildOpType,
Helpers.AsSuperTypeList<LeafCellTreeNode, CellTreeNode>(commonGrandChildren));
// Connect both by commonChildType
CellTreeNode result = new OpCellTreeNode(m_viewgenContext, commonChildOpType,
new CellTreeNode[] { commonNodes, remainingNodes });
result = result.AssociativeFlatten();
return result;
}
// effects: Given a set of nodes, determines if all nodes are the exact same associative opType AND
// there are leaf children that are common across the children "nodes". If there are any,
// returns them. Else return null
private static Set<LeafCellTreeNode> GetCommonGrandChildren(List<CellTreeNode> nodes)
{
Set<LeafCellTreeNode> commonLeaves = null;
// We could make this general and apply recursively but we don't for now
// Look for a tree of the form: (common op2 gc2) op1 (common op2 gc3) op1 (common op2 gc4)
// e.g., (A IJ B IJ X IJ Y) UNION (A IJ B IJ Y IJ Z) UNION (A IJ B IJ R IJ S)
// Where op1 and op2 are associative and common, gc2 etc are leaf nodes
CellTreeOpType commonChildOpType = CellTreeOpType.Leaf;
foreach (CellTreeNode node in nodes)
{
OpCellTreeNode opNode = node as OpCellTreeNode;
if (opNode == null)
{
return null;
}
Debug.Assert(opNode.OpType != CellTreeOpType.Leaf, "Leaf type for op cell node?");
// Now check for whether the op is associative and the same as the previous one
if (commonChildOpType == CellTreeOpType.Leaf)
{
commonChildOpType = opNode.OpType;
}
else if (CellTreeNode.IsAssociativeOp(opNode.OpType) == false || commonChildOpType != opNode.OpType)
{
return null;
}
// Make sure all the children are leaf children
Set<LeafCellTreeNode> nodeChildrenSet = new Set<LeafCellTreeNode>(LeafCellTreeNode.EqualityComparer);
foreach (CellTreeNode grandChild in opNode.Children)
{
LeafCellTreeNode leafGrandChild = grandChild as LeafCellTreeNode;
if (leafGrandChild == null)
{
return null;
}
nodeChildrenSet.Add(leafGrandChild);
}
if (commonLeaves == null)
{
commonLeaves = nodeChildrenSet;
}
else
{
commonLeaves.Intersect(nodeChildrenSet);
}
}
if (commonLeaves.Count == 0)
{
// No restructuring possible
return null;
}
return commonLeaves;
}
// effects: Given a list of node, produces a new list in which all
// leaf nodes of the same extent are adjacent to each other. Non-leaf
// nodes are also adjacent to each other. CHANGE_[....]_IMPROVE: Merge with GroupByRightExtent
private static List<CellTreeNode> GroupLeafChildrenByExtent(List<CellTreeNode> nodes)
{
// Keep track of leaf cells for each extent
KeyToListMap<EntitySetBase, CellTreeNode> extentMap =
new KeyToListMap<EntitySetBase, CellTreeNode>(EqualityComparer<EntitySetBase>.Default);
List<CellTreeNode> newNodes = new List<CellTreeNode>();
foreach (CellTreeNode node in nodes)
{
LeafCellTreeNode leafNode = node as LeafCellTreeNode;
// All non-leaf nodes are added to the result now
// leaf nodes are added outside the loop
if (leafNode != null)
{
extentMap.Add(leafNode.LeftCellWrapper.RightCellQuery.Extent, leafNode);
}
else
{
newNodes.Add(node);
}
}
// Go through the map and add the leaf children
newNodes.AddRange(extentMap.AllValues);
return newNodes;
}
// effects: A restrictive version of GroupLeafChildrenByExtent --
// only for LASJ and LOJ nodes (works for LOJ only when A LOJ B LOJ C
// s.t., B and C are subsets of A -- in our case that is how LOJs are constructed
private static List<CellTreeNode> GroupNonAssociativeLeafChildren(List<CellTreeNode> nodes)
{
// Keep track of leaf cells for each extent ignoring the 0th child
KeyToListMap<EntitySetBase, CellTreeNode> extentMap =
new KeyToListMap<EntitySetBase, CellTreeNode>(EqualityComparer<EntitySetBase>.Default);
List<CellTreeNode> newNodes = new List<CellTreeNode>();
List<CellTreeNode> nonLeafNodes = new List<CellTreeNode>();
// Add the 0th child
newNodes.Add(nodes[0]);
for (int i = 1; i < nodes.Count; i++)
{
CellTreeNode node = nodes[i];
LeafCellTreeNode leafNode = node as LeafCellTreeNode;
// All non-leaf nodes are added to the result now
// leaf nodes are added outside the loop
if (leafNode != null)
{
extentMap.Add(leafNode.LeftCellWrapper.RightCellQuery.Extent, leafNode);
}
else
{
nonLeafNodes.Add(node);
}
}
// Go through the map and add the leaf children
// If a group of nodes exists for the 0th node's extent -- place
// that group first
LeafCellTreeNode firstNode = nodes[0] as LeafCellTreeNode;
if (firstNode != null)
{
EntitySetBase firstExtent = firstNode.LeftCellWrapper.RightCellQuery.Extent;
if (extentMap.ContainsKey(firstExtent))
{
newNodes.AddRange(extentMap.ListForKey(firstExtent));
// Remove this set from the map
extentMap.RemoveKey(firstExtent);
}
}
newNodes.AddRange(extentMap.AllValues);
newNodes.AddRange(nonLeafNodes);
return newNodes;
}
// requires: node1 and node2 are two children of the same parent
// connected by opType
// effects: Given two cell tree nodes, node1 and node2, runs the
// TM/SP rule on them to merge them (if they belong to the same
// extent). Returns true if the merge succeeds
private bool TryMergeCellQueries(CellTreeOpType opType, ref CellTreeNode node1,
CellTreeNode node2)
{
LeafCellTreeNode leaf1 = node1 as LeafCellTreeNode;
LeafCellTreeNode leaf2 = node2 as LeafCellTreeNode;
Debug.Assert(leaf1 != null, "Merge only possible on leaf nodes (1)");
Debug.Assert(leaf2 != null, "Merge only possible on leaf nodes (2)");
CellQuery mergedLeftCellQuery;
CellQuery mergedRightCellQuery;
if (!TryMergeTwoCellQueries(leaf1.LeftCellWrapper.RightCellQuery, leaf2.LeftCellWrapper.RightCellQuery, opType, m_viewgenContext.MemberMaps.RightDomainMap, out mergedRightCellQuery))
{
return false;
}
if (!TryMergeTwoCellQueries(leaf1.LeftCellWrapper.LeftCellQuery, leaf2.LeftCellWrapper.LeftCellQuery, opType, m_viewgenContext.MemberMaps.LeftDomainMap, out mergedLeftCellQuery))
{
return false;
}
// Create a temporary node and add the two children
// so that we can get the merged selectiondomains and attributes
// Note that temp.SelectionDomain below determines the domain
// based on the opType, e.g., for IJ, it intersects the
// multiconstants of all the children
OpCellTreeNode temp = new OpCellTreeNode(m_viewgenContext, opType);
temp.Add(node1);
temp.Add(node2);
// Note: We are losing the original cell number information here and the line number information
// But we will not raise any
// We do not create CellExpressions with LOJ, FOJ - canBooleansOverlap is true for validation
CellTreeOpType inputOpType = opType;
if (opType == CellTreeOpType.FOJ || opType == CellTreeOpType.LOJ)
{
inputOpType = CellTreeOpType.IJ;
}
LeftCellWrapper wrapper = new LeftCellWrapper(m_viewgenContext.ViewTarget, temp.Attributes,
temp.LeftFragmentQuery,
mergedLeftCellQuery,
mergedRightCellQuery,
m_viewgenContext.MemberMaps,
leaf1.LeftCellWrapper.Cells.Concat(leaf2.LeftCellWrapper.Cells));
node1 = new LeafCellTreeNode(m_viewgenContext, wrapper, temp.RightFragmentQuery);
return true;
}
// effects: Merges query2 with this according to the TM/SP rules for opType and
// returns the merged result. canBooleansOverlap indicates whether the bools in this and query2 can overlap, i.e.
// the same cells may have contributed to query2 and this earlier in the merge process
internal bool TryMergeTwoCellQueries(CellQuery query1, CellQuery query2, CellTreeOpType opType,
MemberDomainMap memberDomainMap, out CellQuery mergedQuery)
{
mergedQuery = null;
// Initialize g1 and g2 according to the TM/SP rules for IJ, LOJ, Union, FOJ cases
BoolExpression g1 = null;
BoolExpression g2 = null;
switch (opType)
{
case CellTreeOpType.IJ:
break;
case CellTreeOpType.LOJ:
case CellTreeOpType.LASJ:
g2 = BoolExpression.True;
break;
case CellTreeOpType.FOJ:
case CellTreeOpType.Union:
g1 = BoolExpression.True;
g2 = BoolExpression.True;
break;
default:
Debug.Fail("Unsupported operator");
break;
}
Dictionary<MemberPath, MemberPath> remap =
new Dictionary<MemberPath, MemberPath>(MemberPath.EqualityComparer);
//Continue merging only if both queries are over the same source
MemberPath newRoot;
if (!query1.Extent.Equals(query2.Extent))
{ // could not merge
return false;
}
else
{
newRoot = query1.SourceExtentMemberPath;
}
// Conjuncts for ANDing with the previous whereClauses
BoolExpression conjunct1 = BoolExpression.True;
BoolExpression conjunct2 = BoolExpression.True;
BoolExpression whereClause = null;
switch (opType)
{
case CellTreeOpType.IJ:
// Project[D1, D2, A, B, C] Select[cond1 and cond2] (T)
// We simply merge the two lists of booleans -- no conjuct is added
// conjunct1 and conjunct2 don't change
// query1.WhereCaluse AND query2.WhereCaluse
Debug.Assert(g1 == null && g2 == null, "IJ does not affect g1 and g2");
whereClause = BoolExpression.CreateAnd(query1.WhereClause, query2.WhereClause);
break;
case CellTreeOpType.LOJ:
// conjunct1 does not change since D1 remains as is
// Project[D1, (expr2 and cond2 and G2) as D2, A, B, C] Select[cond1] (T)
// D1 does not change. New d2 is the list of booleans expressions
// for query2 ANDed with g2 AND query2.WhereClause
Debug.Assert(g1 == null, "LOJ does not affect g1");
conjunct2 = BoolExpression.CreateAnd(query2.WhereClause, g2);
// Just query1's whereclause
whereClause = query1.WhereClause;
break;
case CellTreeOpType.FOJ:
case CellTreeOpType.Union:
// Project[(expr1 and cond1 and G1) as D1, (expr2 and cond2 and G2) as D2, A, B, C] Select[cond1] (T)
// New D1 is a list -- newD1 = D1 AND query1.WhereClause AND g1
// New D1 is a list -- newD2 = D2 AND query2.WhereClause AND g2
conjunct1 = BoolExpression.CreateAnd(query1.WhereClause, g1);
conjunct2 = BoolExpression.CreateAnd(query2.WhereClause, g2);
// The new whereClause -- g1 AND query1.WhereCaluse OR g2 AND query2.WhereClause
whereClause = BoolExpression.CreateOr(BoolExpression.CreateAnd(query1.WhereClause, g1),
BoolExpression.CreateAnd(query2.WhereClause, g2));
break;
case CellTreeOpType.LASJ:
// conjunct1 does not change since D1 remains as is
// Project[D1, (expr2 and cond2 and G2) as D2, A, B, C] Select[cond1] (T)
// D1 does not change. New d2 is the list of booleans expressions
// for query2 ANDed with g2 AND NOT query2.WhereClause
Debug.Assert(g1 == null, "LASJ does not affect g1");
conjunct2 = BoolExpression.CreateAnd(query2.WhereClause, g2);
whereClause = BoolExpression.CreateAnd(query1.WhereClause, BoolExpression.CreateNot(conjunct2));
break;
default:
Debug.Fail("Unsupported operator");
break;
}
// Create the various remapped parts for the cell query --
// boolean expressions, merged slots, whereclause, duplicate
// elimination, join tree
List<BoolExpression> boolExprs =
MergeBoolExpressions(query1, query2, conjunct1, conjunct2, opType);
//BoolExpression.RemapBools(boolExprs, remap);
ProjectedSlot[] mergedSlots;
if (false == ProjectedSlot.TryMergeRemapSlots(query1.ProjectedSlots, query2.ProjectedSlots, out mergedSlots))
{
// merging failed because two different right slots go to same left slot
return false;
}
whereClause = whereClause.RemapBool(remap);
CellQuery.SelectDistinct elimDupl = MergeDupl(query1.SelectDistinctFlag, query2.SelectDistinctFlag);
whereClause.ExpensiveSimplify();
mergedQuery = new CellQuery(mergedSlots, whereClause,
boolExprs, elimDupl, newRoot);
return true;
}
// effects: Given two duplicate eliination choices, returns an OR of them
static private CellQuery.SelectDistinct MergeDupl(CellQuery.SelectDistinct d1, CellQuery.SelectDistinct d2)
{
if (d1 == CellQuery.SelectDistinct.Yes || d2 == CellQuery.SelectDistinct.Yes)
{
return CellQuery.SelectDistinct.Yes;
}
else
{
return CellQuery.SelectDistinct.No;
}
}
// requires: query1 has the same number of boolean expressions as
// query2. There should be no index i for which query1's bools[i] !=
// null and query2's bools[i] != null
// effects: Given two cellqueries query1 and query2, merges their
// boolean expressions while ANDING query1 bools with conjunct1 and
// query2's bools with conjunct2 and returns the result
static private List<BoolExpression>
MergeBoolExpressions(CellQuery query1, CellQuery query2,
BoolExpression conjunct1, BoolExpression conjunct2, CellTreeOpType opType)
{
List<BoolExpression> bools1 = query1.BoolVars;
List<BoolExpression> bools2 = query2.BoolVars;
// Add conjuncts to both sets if needed
if (false == conjunct1.IsTrue)
{
bools1 = BoolExpression.AddConjunctionToBools(bools1, conjunct1);
}
if (false == conjunct2.IsTrue)
{
bools2 = BoolExpression.AddConjunctionToBools(bools2, conjunct2);
}
// Perform merge
Debug.Assert(bools1.Count == bools2.Count);
List<BoolExpression> bools = new List<BoolExpression>();
// Both bools1[i] and bools2[i] be null for some of the i's. When
// we merge two (leaf) cells (say), only one boolean each is set
// in it; the rest are all nulls. If the SP/TM rules have been
// applied, more than one boolean may be non-null in a cell query
for (int i = 0; i < bools1.Count; i++)
{
BoolExpression merged = null;
if (bools1[i] == null)
{
merged = bools2[i];
}
else if (bools2[i] == null)
{
merged = bools1[i];
}
else
{
if (opType == CellTreeOpType.IJ)
{
merged = BoolExpression.CreateAnd(bools1[i], bools2[i]);
}
else if (opType == CellTreeOpType.Union)
{
merged = BoolExpression.CreateOr(bools1[i], bools2[i]);
}
else if (opType == CellTreeOpType.LASJ)
{
merged = BoolExpression.CreateAnd(bools1[i],
BoolExpression.CreateNot(bools2[i]));
}
else
{
Debug.Fail("No other operation expected for boolean merge");
}
}
if (merged != null)
{
merged.ExpensiveSimplify();
}
bools.Add(merged);
}
return bools;
}
#endregion
#region String methods
internal override void ToCompactString(StringBuilder builder)
{
m_viewgenContext.MemberMaps.ProjectedSlotMap.ToCompactString(builder);
}
#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 implementation follows RFC 2898 recommendations. See http://www.ietf.org/rfc/Rfc2898.txt
// It uses HMACSHA1 as the underlying pseudorandom function.
namespace System.Security.Cryptography {
using System.Globalization;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Cryptography.X509Certificates;
[System.Runtime.InteropServices.ComVisible(true)]
public class Rfc2898DeriveBytes : DeriveBytes
{
private byte[] m_buffer;
private byte[] m_salt;
private HMACSHA1 m_hmacsha1; // The pseudo-random generator function used in PBKDF2
private byte[] m_password;
private CspParameters m_cspParams = new CspParameters();
private uint m_iterations;
private uint m_block;
private int m_startIndex;
private int m_endIndex;
private const int BlockSize = 20;
//
// public constructors
//
public Rfc2898DeriveBytes(string password, int saltSize) : this(password, saltSize, 1000) {}
// This method needs to be safe critical, because in debug builds the C# compiler will include null
// initialization of the _safeProvHandle field in the method. Since SafeProvHandle is critical, a
// transparent reference triggers an error using PasswordDeriveBytes.
[SecuritySafeCritical]
public Rfc2898DeriveBytes(string password, int saltSize, int iterations) {
if (saltSize < 0)
throw new ArgumentOutOfRangeException("saltSize", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
byte[] salt = new byte[saltSize];
Utils.StaticRandomNumberGenerator.GetBytes(salt);
Salt = salt;
IterationCount = iterations;
m_password = new UTF8Encoding(false).GetBytes(password);
m_hmacsha1 = new HMACSHA1(m_password);
Initialize();
}
public Rfc2898DeriveBytes(string password, byte[] salt) : this(password, salt, 1000) {}
public Rfc2898DeriveBytes(string password, byte[] salt, int iterations) : this (new UTF8Encoding(false).GetBytes(password), salt, iterations) {}
// This method needs to be safe critical, because in debug builds the C# compiler will include null
// initialization of the _safeProvHandle field in the method. Since SafeProvHandle is critical, a
// transparent reference triggers an error using PasswordDeriveBytes.
[SecuritySafeCritical]
public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations) {
Salt = salt;
IterationCount = iterations;
m_password = password;
m_hmacsha1 = new HMACSHA1(password);
Initialize();
}
//
// public properties
//
public int IterationCount {
get { return (int) m_iterations; }
set {
if (value <= 0)
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
Contract.EndContractBlock();
m_iterations = (uint) value;
Initialize();
}
}
public byte[] Salt {
get { return (byte[]) m_salt.Clone(); }
set {
if (value == null)
throw new ArgumentNullException("value");
if (value.Length < 8)
throw new ArgumentException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_FewBytesSalt"));
Contract.EndContractBlock();
m_salt = (byte[]) value.Clone();
Initialize();
}
}
//
// public methods
//
public override byte[] GetBytes(int cb) {
if (cb <= 0)
throw new ArgumentOutOfRangeException("cb", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
Contract.EndContractBlock();
byte[] password = new byte[cb];
int offset = 0;
int size = m_endIndex - m_startIndex;
if (size > 0) {
if (cb >= size) {
Buffer.InternalBlockCopy(m_buffer, m_startIndex, password, 0, size);
m_startIndex = m_endIndex = 0;
offset += size;
} else {
Buffer.InternalBlockCopy(m_buffer, m_startIndex, password, 0, cb);
m_startIndex += cb;
return password;
}
}
Contract.Assert(m_startIndex == 0 && m_endIndex == 0, "Invalid start or end index in the internal buffer." );
while(offset < cb) {
byte[] T_block = Func();
int remainder = cb - offset;
if(remainder > BlockSize) {
Buffer.InternalBlockCopy(T_block, 0, password, offset, BlockSize);
offset += BlockSize;
} else {
Buffer.InternalBlockCopy(T_block, 0, password, offset, remainder);
offset += remainder;
Buffer.InternalBlockCopy(T_block, remainder, m_buffer, m_startIndex, BlockSize - remainder);
m_endIndex += (BlockSize - remainder);
return password;
}
}
return password;
}
public override void Reset() {
Initialize();
}
protected override void Dispose(bool disposing) {
base.Dispose(disposing);
if (disposing) {
if (m_hmacsha1 != null) {
((IDisposable)m_hmacsha1).Dispose();
}
if (m_buffer != null) {
Array.Clear(m_buffer, 0, m_buffer.Length);
}
if (m_salt != null) {
Array.Clear(m_salt, 0, m_salt.Length);
}
}
}
private void Initialize() {
if (m_buffer != null)
Array.Clear(m_buffer, 0, m_buffer.Length);
m_buffer = new byte[BlockSize];
m_block = 1;
m_startIndex = m_endIndex = 0;
}
// This function is defined as follow :
// Func (S, i) = HMAC(S || i) | HMAC2(S || i) | ... | HMAC(iterations) (S || i)
// where i is the block number.
private byte[] Func () {
byte[] INT_block = Utils.Int(m_block);
m_hmacsha1.TransformBlock(m_salt, 0, m_salt.Length, null, 0);
m_hmacsha1.TransformBlock(INT_block, 0, INT_block.Length, null, 0);
m_hmacsha1.TransformFinalBlock(EmptyArray<Byte>.Value, 0, 0);
byte[] temp = m_hmacsha1.HashValue;
m_hmacsha1.Initialize();
byte[] ret = temp;
for (int i = 2; i <= m_iterations; i++) {
m_hmacsha1.TransformBlock(temp, 0, temp.Length, null, 0);
m_hmacsha1.TransformFinalBlock(EmptyArray<Byte>.Value, 0, 0);
temp = m_hmacsha1.HashValue;
for (int j = 0; j < BlockSize; j++) {
ret[j] ^= temp[j];
}
m_hmacsha1.Initialize();
}
// increment the block count.
m_block++;
return ret;
}
[System.Security.SecuritySafeCritical] // auto-generated
public byte[] CryptDeriveKey(string algname, string alghashname, int keySize, byte[] rgbIV)
{
if (keySize < 0)
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize"));
int algidhash = X509Utils.NameOrOidToAlgId(alghashname, OidGroup.HashAlgorithm);
if (algidhash == 0)
throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidAlgorithm"));
int algid = X509Utils.NameOrOidToAlgId(algname, OidGroup.AllGroups);
if (algid == 0)
throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidAlgorithm"));
// Validate the rgbIV array
if (rgbIV == null)
throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidIV"));
byte[] key = null;
DeriveKey(ProvHandle, algid, algidhash,
m_password, m_password.Length, keySize << 16, rgbIV, rgbIV.Length,
JitHelpers.GetObjectHandleOnStack(ref key));
return key;
}
[System.Security.SecurityCritical] // auto-generated
private SafeProvHandle _safeProvHandle = null;
private SafeProvHandle ProvHandle
{
[System.Security.SecurityCritical] // auto-generated
get
{
if (_safeProvHandle == null)
{
lock (this)
{
if (_safeProvHandle == null)
{
SafeProvHandle safeProvHandle = Utils.AcquireProvHandle(m_cspParams);
System.Threading.Thread.MemoryBarrier();
_safeProvHandle = safeProvHandle;
}
}
}
return _safeProvHandle;
}
}
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void DeriveKey(SafeProvHandle hProv, int algid, int algidHash,
byte[] password, int cbPassword, int dwFlags, byte[] IV, int cbIV,
ObjectHandleOnStack retKey);
}
}
| |
// 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,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.PythonTools.Django.Project {
/// <summary>
/// Merges the PTVS IVsCfg object with the Venus IVsCfg implementation redirecting
/// things appropriately to either one.
/// </summary>
class DjangoProjectConfig :
IVsCfg,
IVsProjectCfg,
IVsProjectCfg2,
IVsProjectFlavorCfg,
IVsDebuggableProjectCfg,
ISpecifyPropertyPages,
IVsSpecifyProjectDesignerPages,
IVsCfgBrowseObject
{
private readonly IVsCfg _pythonCfg;
private readonly IVsProjectFlavorCfg _webCfg;
public DjangoProjectConfig(IVsCfg pythonCfg, IVsProjectFlavorCfg webConfig) {
_pythonCfg = pythonCfg;
_webCfg = webConfig;
}
#region IVsCfg Members
public int get_DisplayName(out string pbstrDisplayName) {
return _pythonCfg.get_DisplayName(out pbstrDisplayName);
}
public int get_IsDebugOnly(out int pfIsDebugOnly) {
return _pythonCfg.get_IsDebugOnly(out pfIsDebugOnly);
}
public int get_IsReleaseOnly(out int pfIsReleaseOnly) {
return _pythonCfg.get_IsReleaseOnly(out pfIsReleaseOnly);
}
#endregion
#region IVsProjectCfg Members
public int EnumOutputs(out IVsEnumOutputs ppIVsEnumOutputs) {
IVsProjectCfg projCfg = _webCfg as IVsProjectCfg;
if (projCfg != null) {
return projCfg.EnumOutputs(out ppIVsEnumOutputs);
}
ppIVsEnumOutputs = null;
return VSConstants.E_NOTIMPL;
}
public int OpenOutput(string szOutputCanonicalName, out IVsOutput ppIVsOutput) {
IVsProjectCfg projCfg = _webCfg as IVsProjectCfg;
if (projCfg != null) {
return projCfg.OpenOutput(szOutputCanonicalName, out ppIVsOutput);
}
ppIVsOutput = null;
return VSConstants.E_NOTIMPL;
}
public int get_BuildableProjectCfg(out IVsBuildableProjectCfg ppIVsBuildableProjectCfg) {
IVsProjectCfg projCfg = _webCfg as IVsProjectCfg;
if (projCfg != null) {
return projCfg.get_BuildableProjectCfg(out ppIVsBuildableProjectCfg);
}
ppIVsBuildableProjectCfg = null;
return VSConstants.E_NOTIMPL;
}
public int get_CanonicalName(out string pbstrCanonicalName) {
IVsProjectCfg projCfg = _webCfg as IVsProjectCfg;
if (projCfg != null) {
return projCfg.get_CanonicalName(out pbstrCanonicalName);
}
pbstrCanonicalName = null;
return VSConstants.E_NOTIMPL;
}
public int get_IsPackaged(out int pfIsPackaged) {
IVsProjectCfg projCfg = _webCfg as IVsProjectCfg;
if (projCfg != null) {
return projCfg.get_IsPackaged(out pfIsPackaged);
}
pfIsPackaged = 0;
return VSConstants.E_NOTIMPL;
}
public int get_IsSpecifyingOutputSupported(out int pfIsSpecifyingOutputSupported) {
IVsProjectCfg projCfg = _webCfg as IVsProjectCfg;
if (projCfg != null) {
return projCfg.get_IsSpecifyingOutputSupported(out pfIsSpecifyingOutputSupported);
}
pfIsSpecifyingOutputSupported = 0;
return VSConstants.E_NOTIMPL;
}
public int get_Platform(out Guid pguidPlatform) {
IVsProjectCfg projCfg = _webCfg as IVsProjectCfg;
if (projCfg != null) {
return projCfg.get_Platform(out pguidPlatform);
}
pguidPlatform = Guid.Empty;
return VSConstants.E_NOTIMPL;
}
public int get_ProjectCfgProvider(out IVsProjectCfgProvider ppIVsProjectCfgProvider) {
IVsProjectCfg projCfg = _webCfg as IVsProjectCfg;
if (projCfg != null) {
return projCfg.get_ProjectCfgProvider(out ppIVsProjectCfgProvider);
}
ppIVsProjectCfgProvider = null;
return VSConstants.E_NOTIMPL;
}
public int get_RootURL(out string pbstrRootURL) {
IVsProjectCfg projCfg = _webCfg as IVsProjectCfg;
if (projCfg != null) {
return projCfg.get_RootURL(out pbstrRootURL);
}
pbstrRootURL = null;
return VSConstants.E_NOTIMPL;
}
public int get_TargetCodePage(out uint puiTargetCodePage) {
IVsProjectCfg projCfg = _webCfg as IVsProjectCfg;
if (projCfg != null) {
return projCfg.get_TargetCodePage(out puiTargetCodePage);
}
puiTargetCodePage = 0;
return VSConstants.E_NOTIMPL;
}
public int get_UpdateSequenceNumber(ULARGE_INTEGER[] puliUSN) {
IVsProjectCfg projCfg = _webCfg as IVsProjectCfg;
if (projCfg != null) {
return projCfg.get_UpdateSequenceNumber(puliUSN);
}
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsProjectCfg2 Members
public int OpenOutputGroup(string szCanonicalName, out IVsOutputGroup ppIVsOutputGroup) {
IVsProjectCfg2 projCfg = _pythonCfg as IVsProjectCfg2;
if (projCfg != null) {
return projCfg.OpenOutputGroup(szCanonicalName, out ppIVsOutputGroup);
}
ppIVsOutputGroup = null;
return VSConstants.E_NOTIMPL;
}
public int OutputsRequireAppRoot(out int pfRequiresAppRoot) {
IVsProjectCfg2 projCfg = _pythonCfg as IVsProjectCfg2;
if (projCfg != null) {
return projCfg.OutputsRequireAppRoot(out pfRequiresAppRoot);
}
pfRequiresAppRoot = 1;
return VSConstants.E_NOTIMPL;
}
public int get_CfgType(ref Guid iidCfg, out IntPtr ppCfg) {
if (iidCfg == typeof(IVsDebuggableProjectCfg).GUID)
{
var pyCfg = _pythonCfg as IVsProjectFlavorCfg;
if (pyCfg != null) {
return pyCfg.get_CfgType(ref iidCfg, out ppCfg);
}
}
var projCfg = _webCfg as IVsProjectFlavorCfg;
if (projCfg != null) {
return projCfg.get_CfgType(ref iidCfg, out ppCfg);
}
ppCfg = IntPtr.Zero;
return VSConstants.E_NOTIMPL;
}
public int get_IsPrivate(out int pfPrivate) {
IVsProjectCfg2 projCfg = _pythonCfg as IVsProjectCfg2;
if (projCfg != null) {
return projCfg.get_IsPrivate(out pfPrivate);
}
pfPrivate = 0;
return VSConstants.E_NOTIMPL;
}
public int get_OutputGroups(uint celt, IVsOutputGroup[] rgpcfg, uint[] pcActual = null) {
IVsProjectCfg2 projCfg = _pythonCfg as IVsProjectCfg2;
if (projCfg != null) {
return projCfg.get_OutputGroups(celt, rgpcfg, pcActual);
}
return VSConstants.E_NOTIMPL;
}
public int get_VirtualRoot(out string pbstrVRoot) {
IVsProjectCfg2 projCfg = _pythonCfg as IVsProjectCfg2;
if (projCfg != null) {
return projCfg.get_VirtualRoot(out pbstrVRoot);
}
pbstrVRoot = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsProjectFlavorCfg Members
public int Close() {
IVsProjectFlavorCfg cfg = _webCfg as IVsProjectFlavorCfg;
if (cfg != null) {
return cfg.Close();
}
return VSConstants.S_OK;
}
#endregion
#region IVsDebuggableProjectCfg Members
public int DebugLaunch(uint grfLaunch) {
IVsDebuggableProjectCfg cfg = _pythonCfg as IVsDebuggableProjectCfg;
if (cfg != null) {
return cfg.DebugLaunch(grfLaunch);
}
return VSConstants.E_NOTIMPL;
}
public int QueryDebugLaunch(uint grfLaunch, out int pfCanLaunch) {
IVsDebuggableProjectCfg cfg = _pythonCfg as IVsDebuggableProjectCfg;
if (cfg != null) {
return cfg.QueryDebugLaunch(grfLaunch, out pfCanLaunch);
}
pfCanLaunch = 0;
return VSConstants.E_NOTIMPL;
}
#endregion
#region ISpecifyPropertyPages Members
public void GetPages(CAUUID[] pPages) {
var cfg = _pythonCfg as ISpecifyPropertyPages;
if (cfg != null) {
cfg.GetPages(pPages);
}
}
#endregion
#region IVsSpecifyProjectDesignerPages Members
public int GetProjectDesignerPages(CAUUID[] pPages) {
var cfg = _pythonCfg as IVsSpecifyProjectDesignerPages;
if (cfg != null) {
return cfg.GetProjectDesignerPages(pPages);
}
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsCfgBrowseObject Members
public int GetCfg(out IVsCfg ppCfg) {
ppCfg = this;
return VSConstants.S_OK;
}
public int GetProjectItem(out IVsHierarchy pHier, out uint pItemid) {
var cfg = _pythonCfg as IVsCfgBrowseObject;
if (cfg != null) {
return cfg.GetProjectItem(out pHier, out pItemid);
}
pHier = null;
pItemid = 0;
return VSConstants.E_NOTIMPL;
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using log4net;
using Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenMetaverse.Assets;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Avatar.AvatarFactory;
using OpenSim.Region.OptionalModules.World.NPC;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.Instance;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;
using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
namespace OpenSim.Region.ScriptEngine.Shared.Tests
{
[TestFixture]
public class LSL_ApiObjectTests : OpenSimTestCase
{
private const double VECTOR_COMPONENT_ACCURACY = 0.0000005d;
private const float FLOAT_ACCURACY = 0.00005f;
protected Scene m_scene;
protected XEngine.XEngine m_engine;
[SetUp]
public override void SetUp()
{
base.SetUp();
IConfigSource initConfigSource = new IniConfigSource();
IConfig config = initConfigSource.AddConfig("XEngine");
config.Set("Enabled", "true");
m_scene = new SceneHelpers().SetupScene();
SceneHelpers.SetupSceneModules(m_scene, initConfigSource);
m_engine = new XEngine.XEngine();
m_engine.Initialise(initConfigSource);
m_engine.AddRegion(m_scene);
}
[Test]
public void TestllGetLinkPrimitiveParams()
{
TestHelpers.InMethod();
TestHelpers.EnableLogging();
UUID ownerId = TestHelpers.ParseTail(0x1);
SceneObjectGroup grp1 = SceneHelpers.CreateSceneObject(2, ownerId, "grp1-", 0x10);
grp1.AbsolutePosition = new Vector3(10, 11, 12);
m_scene.AddSceneObject(grp1);
LSL_Api apiGrp1 = new LSL_Api();
apiGrp1.Initialize(m_engine, grp1.RootPart, null, null);
// Check simple 1 prim case
{
LSL_List resList
= apiGrp1.llGetLinkPrimitiveParams(1, new LSL_List(new LSL_Integer(ScriptBaseClass.PRIM_ROTATION)));
Assert.That(resList.Length, Is.EqualTo(1));
}
// Check 2 prim case
{
LSL_List resList
= apiGrp1.llGetLinkPrimitiveParams(
1,
new LSL_List(
new LSL_Integer(ScriptBaseClass.PRIM_ROTATION),
new LSL_Integer(ScriptBaseClass.PRIM_LINK_TARGET),
new LSL_Integer(2),
new LSL_Integer(ScriptBaseClass.PRIM_ROTATION)));
Assert.That(resList.Length, Is.EqualTo(2));
}
// Check invalid parameters are ignored
{
LSL_List resList
= apiGrp1.llGetLinkPrimitiveParams(3, new LSL_List(new LSL_Integer(ScriptBaseClass.PRIM_ROTATION)));
Assert.That(resList.Length, Is.EqualTo(0));
}
// Check all parameters are ignored if an initial bad link is given
{
LSL_List resList
= apiGrp1.llGetLinkPrimitiveParams(
3,
new LSL_List(
new LSL_Integer(ScriptBaseClass.PRIM_ROTATION),
new LSL_Integer(ScriptBaseClass.PRIM_LINK_TARGET),
new LSL_Integer(1),
new LSL_Integer(ScriptBaseClass.PRIM_ROTATION)));
Assert.That(resList.Length, Is.EqualTo(0));
}
// Check only subsequent parameters are ignored when we hit the first bad link number
{
LSL_List resList
= apiGrp1.llGetLinkPrimitiveParams(
1,
new LSL_List(
new LSL_Integer(ScriptBaseClass.PRIM_ROTATION),
new LSL_Integer(ScriptBaseClass.PRIM_LINK_TARGET),
new LSL_Integer(3),
new LSL_Integer(ScriptBaseClass.PRIM_ROTATION)));
Assert.That(resList.Length, Is.EqualTo(1));
}
}
[Test]
// llSetPrimitiveParams and llGetPrimitiveParams test.
public void TestllSetPrimitiveParams()
{
TestHelpers.InMethod();
// Create Prim1.
Scene scene = new SceneHelpers().SetupScene();
string obj1Name = "Prim1";
UUID objUuid = new UUID("00000000-0000-0000-0000-000000000001");
SceneObjectPart part1 =
new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default,
Vector3.Zero, Quaternion.Identity,
Vector3.Zero) { Name = obj1Name, UUID = objUuid };
Assert.That(scene.AddNewSceneObject(new SceneObjectGroup(part1), false), Is.True);
LSL_Api apiGrp1 = new LSL_Api();
apiGrp1.Initialize(m_engine, part1, null, null);
// Note that prim hollow check is passed with the other prim params in order to allow the
// specification of a different check value from the prim param. A cylinder, prism, sphere,
// torus or ring, with a hole shape of square, is limited to a hollow of 70%. Test 5 below
// specifies a value of 95% and checks to see if 70% was properly returned.
// Test a sphere.
CheckllSetPrimitiveParams(
apiGrp1,
"test 1", // Prim test identification string
new LSL_Types.Vector3(6.0d, 9.9d, 9.9d), // Prim size
ScriptBaseClass.PRIM_TYPE_SPHERE, // Prim type
ScriptBaseClass.PRIM_HOLE_DEFAULT, // Prim hole type
new LSL_Types.Vector3(0.0d, 0.075d, 0.0d), // Prim cut
0.80f, // Prim hollow
new LSL_Types.Vector3(0.0d, 0.0d, 0.0d), // Prim twist
new LSL_Types.Vector3(0.32d, 0.76d, 0.0d), // Prim dimple
0.80f); // Prim hollow check
// Test a prism.
CheckllSetPrimitiveParams(
apiGrp1,
"test 2", // Prim test identification string
new LSL_Types.Vector3(3.5d, 3.5d, 3.5d), // Prim size
ScriptBaseClass.PRIM_TYPE_PRISM, // Prim type
ScriptBaseClass.PRIM_HOLE_CIRCLE, // Prim hole type
new LSL_Types.Vector3(0.0d, 1.0d, 0.0d), // Prim cut
0.90f, // Prim hollow
new LSL_Types.Vector3(0.0d, 0.0d, 0.0d), // Prim twist
new LSL_Types.Vector3(2.0d, 1.0d, 0.0d), // Prim taper
new LSL_Types.Vector3(0.0d, 0.0d, 0.0d), // Prim shear
0.90f); // Prim hollow check
// Test a box.
CheckllSetPrimitiveParams(
apiGrp1,
"test 3", // Prim test identification string
new LSL_Types.Vector3(3.5d, 3.5d, 3.5d), // Prim size
ScriptBaseClass.PRIM_TYPE_BOX, // Prim type
ScriptBaseClass.PRIM_HOLE_TRIANGLE, // Prim hole type
new LSL_Types.Vector3(0.0d, 1.0d, 0.0d), // Prim cut
0.99f, // Prim hollow
new LSL_Types.Vector3(1.0d, 0.0d, 0.0d), // Prim twist
new LSL_Types.Vector3(1.0d, 1.0d, 0.0d), // Prim taper
new LSL_Types.Vector3(0.0d, 0.0d, 0.0d), // Prim shear
0.99f); // Prim hollow check
// Test a tube.
CheckllSetPrimitiveParams(
apiGrp1,
"test 4", // Prim test identification string
new LSL_Types.Vector3(4.2d, 4.2d, 4.2d), // Prim size
ScriptBaseClass.PRIM_TYPE_TUBE, // Prim type
ScriptBaseClass.PRIM_HOLE_SQUARE, // Prim hole type
new LSL_Types.Vector3(0.0d, 1.0d, 0.0d), // Prim cut
0.00f, // Prim hollow
new LSL_Types.Vector3(1.0d, -1.0d, 0.0d), // Prim twist
new LSL_Types.Vector3(1.0d, 0.05d, 0.0d), // Prim hole size
// Expression for y selected to test precision problems during byte
// cast in SetPrimitiveShapeParams.
new LSL_Types.Vector3(0.0d, 0.35d + 0.1d, 0.0d), // Prim shear
new LSL_Types.Vector3(0.0d, 1.0d, 0.0d), // Prim profile cut
// Expression for y selected to test precision problems during sbyte
// cast in SetPrimitiveShapeParams.
new LSL_Types.Vector3(-1.0d, 0.70d + 0.1d + 0.1d, 0.0d), // Prim taper
1.11f, // Prim revolutions
0.88f, // Prim radius
0.95f, // Prim skew
0.00f); // Prim hollow check
// Test a prism.
CheckllSetPrimitiveParams(
apiGrp1,
"test 5", // Prim test identification string
new LSL_Types.Vector3(3.5d, 3.5d, 3.5d), // Prim size
ScriptBaseClass.PRIM_TYPE_PRISM, // Prim type
ScriptBaseClass.PRIM_HOLE_SQUARE, // Prim hole type
new LSL_Types.Vector3(0.0d, 1.0d, 0.0d), // Prim cut
0.99f, // Prim hollow
// Expression for x selected to test precision problems during sbyte
// cast in SetPrimitiveShapeBlockParams.
new LSL_Types.Vector3(0.7d + 0.2d, 0.0d, 0.0d), // Prim twist
// Expression for y selected to test precision problems during sbyte
// cast in SetPrimitiveShapeParams.
new LSL_Types.Vector3(2.0d, (1.3d + 0.1d), 0.0d), // Prim taper
new LSL_Types.Vector3(0.0d, 0.0d, 0.0d), // Prim shear
0.70f); // Prim hollow check
// Test a sculpted prim.
CheckllSetPrimitiveParams(
apiGrp1,
"test 6", // Prim test identification string
new LSL_Types.Vector3(2.0d, 2.0d, 2.0d), // Prim size
ScriptBaseClass.PRIM_TYPE_SCULPT, // Prim type
"be293869-d0d9-0a69-5989-ad27f1946fd4", // Prim map
ScriptBaseClass.PRIM_SCULPT_TYPE_SPHERE); // Prim sculpt type
}
// Set prim params for a box, cylinder or prism and check results.
public void CheckllSetPrimitiveParams(LSL_Api api, string primTest,
LSL_Types.Vector3 primSize, int primType, int primHoleType, LSL_Types.Vector3 primCut,
float primHollow, LSL_Types.Vector3 primTwist, LSL_Types.Vector3 primTaper, LSL_Types.Vector3 primShear,
float primHollowCheck)
{
// Set the prim params.
api.llSetPrimitiveParams(new LSL_Types.list(ScriptBaseClass.PRIM_SIZE, primSize,
ScriptBaseClass.PRIM_TYPE, primType, primHoleType,
primCut, primHollow, primTwist, primTaper, primShear));
// Get params for prim to validate settings.
LSL_Types.list primParams =
api.llGetPrimitiveParams(new LSL_Types.list(ScriptBaseClass.PRIM_SIZE, ScriptBaseClass.PRIM_TYPE));
// Validate settings.
CheckllSetPrimitiveParamsVector(primSize, api.llList2Vector(primParams, 0), primTest + " prim size");
Assert.AreEqual(primType, api.llList2Integer(primParams, 1),
"TestllSetPrimitiveParams " + primTest + " prim type check fail");
Assert.AreEqual(primHoleType, api.llList2Integer(primParams, 2),
"TestllSetPrimitiveParams " + primTest + " prim hole default check fail");
CheckllSetPrimitiveParamsVector(primCut, api.llList2Vector(primParams, 3), primTest + " prim cut");
Assert.AreEqual(primHollowCheck, api.llList2Float(primParams, 4), FLOAT_ACCURACY,
"TestllSetPrimitiveParams " + primTest + " prim hollow check fail");
CheckllSetPrimitiveParamsVector(primTwist, api.llList2Vector(primParams, 5), primTest + " prim twist");
CheckllSetPrimitiveParamsVector(primTaper, api.llList2Vector(primParams, 6), primTest + " prim taper");
CheckllSetPrimitiveParamsVector(primShear, api.llList2Vector(primParams, 7), primTest + " prim shear");
}
// Set prim params for a sphere and check results.
public void CheckllSetPrimitiveParams(LSL_Api api, string primTest,
LSL_Types.Vector3 primSize, int primType, int primHoleType, LSL_Types.Vector3 primCut,
float primHollow, LSL_Types.Vector3 primTwist, LSL_Types.Vector3 primDimple, float primHollowCheck)
{
// Set the prim params.
api.llSetPrimitiveParams(new LSL_Types.list(ScriptBaseClass.PRIM_SIZE, primSize,
ScriptBaseClass.PRIM_TYPE, primType, primHoleType,
primCut, primHollow, primTwist, primDimple));
// Get params for prim to validate settings.
LSL_Types.list primParams =
api.llGetPrimitiveParams(new LSL_Types.list(ScriptBaseClass.PRIM_SIZE, ScriptBaseClass.PRIM_TYPE));
// Validate settings.
CheckllSetPrimitiveParamsVector(primSize, api.llList2Vector(primParams, 0), primTest + " prim size");
Assert.AreEqual(primType, api.llList2Integer(primParams, 1),
"TestllSetPrimitiveParams " + primTest + " prim type check fail");
Assert.AreEqual(primHoleType, api.llList2Integer(primParams, 2),
"TestllSetPrimitiveParams " + primTest + " prim hole default check fail");
CheckllSetPrimitiveParamsVector(primCut, api.llList2Vector(primParams, 3), primTest + " prim cut");
Assert.AreEqual(primHollowCheck, api.llList2Float(primParams, 4), FLOAT_ACCURACY,
"TestllSetPrimitiveParams " + primTest + " prim hollow check fail");
CheckllSetPrimitiveParamsVector(primTwist, api.llList2Vector(primParams, 5), primTest + " prim twist");
CheckllSetPrimitiveParamsVector(primDimple, api.llList2Vector(primParams, 6), primTest + " prim dimple");
}
// Set prim params for a torus, tube or ring and check results.
public void CheckllSetPrimitiveParams(LSL_Api api, string primTest,
LSL_Types.Vector3 primSize, int primType, int primHoleType, LSL_Types.Vector3 primCut,
float primHollow, LSL_Types.Vector3 primTwist, LSL_Types.Vector3 primHoleSize,
LSL_Types.Vector3 primShear, LSL_Types.Vector3 primProfCut, LSL_Types.Vector3 primTaper,
float primRev, float primRadius, float primSkew, float primHollowCheck)
{
// Set the prim params.
api.llSetPrimitiveParams(new LSL_Types.list(ScriptBaseClass.PRIM_SIZE, primSize,
ScriptBaseClass.PRIM_TYPE, primType, primHoleType,
primCut, primHollow, primTwist, primHoleSize, primShear, primProfCut,
primTaper, primRev, primRadius, primSkew));
// Get params for prim to validate settings.
LSL_Types.list primParams =
api.llGetPrimitiveParams(new LSL_Types.list(ScriptBaseClass.PRIM_SIZE, ScriptBaseClass.PRIM_TYPE));
// Valdate settings.
CheckllSetPrimitiveParamsVector(primSize, api.llList2Vector(primParams, 0), primTest + " prim size");
Assert.AreEqual(primType, api.llList2Integer(primParams, 1),
"TestllSetPrimitiveParams " + primTest + " prim type check fail");
Assert.AreEqual(primHoleType, api.llList2Integer(primParams, 2),
"TestllSetPrimitiveParams " + primTest + " prim hole default check fail");
CheckllSetPrimitiveParamsVector(primCut, api.llList2Vector(primParams, 3), primTest + " prim cut");
Assert.AreEqual(primHollowCheck, api.llList2Float(primParams, 4), FLOAT_ACCURACY,
"TestllSetPrimitiveParams " + primTest + " prim hollow check fail");
CheckllSetPrimitiveParamsVector(primTwist, api.llList2Vector(primParams, 5), primTest + " prim twist");
CheckllSetPrimitiveParamsVector(primHoleSize, api.llList2Vector(primParams, 6), primTest + " prim hole size");
CheckllSetPrimitiveParamsVector(primShear, api.llList2Vector(primParams, 7), primTest + " prim shear");
CheckllSetPrimitiveParamsVector(primProfCut, api.llList2Vector(primParams, 8), primTest + " prim profile cut");
CheckllSetPrimitiveParamsVector(primTaper, api.llList2Vector(primParams, 9), primTest + " prim taper");
Assert.AreEqual(primRev, api.llList2Float(primParams, 10), FLOAT_ACCURACY,
"TestllSetPrimitiveParams " + primTest + " prim revolutions fail");
Assert.AreEqual(primRadius, api.llList2Float(primParams, 11), FLOAT_ACCURACY,
"TestllSetPrimitiveParams " + primTest + " prim radius fail");
Assert.AreEqual(primSkew, api.llList2Float(primParams, 12), FLOAT_ACCURACY,
"TestllSetPrimitiveParams " + primTest + " prim skew fail");
}
// Set prim params for a sculpted prim and check results.
public void CheckllSetPrimitiveParams(LSL_Api api, string primTest,
LSL_Types.Vector3 primSize, int primType, string primMap, int primSculptType)
{
// Set the prim params.
api.llSetPrimitiveParams(new LSL_Types.list(ScriptBaseClass.PRIM_SIZE, primSize,
ScriptBaseClass.PRIM_TYPE, primType, primMap, primSculptType));
// Get params for prim to validate settings.
LSL_Types.list primParams =
api.llGetPrimitiveParams(new LSL_Types.list(ScriptBaseClass.PRIM_SIZE, ScriptBaseClass.PRIM_TYPE));
// Validate settings.
CheckllSetPrimitiveParamsVector(primSize, api.llList2Vector(primParams, 0), primTest + " prim size");
Assert.AreEqual(primType, api.llList2Integer(primParams, 1),
"TestllSetPrimitiveParams " + primTest + " prim type check fail");
Assert.AreEqual(primMap, (string)api.llList2String(primParams, 2),
"TestllSetPrimitiveParams " + primTest + " prim map check fail");
Assert.AreEqual(primSculptType, api.llList2Integer(primParams, 3),
"TestllSetPrimitiveParams " + primTest + " prim type scuplt check fail");
}
public void CheckllSetPrimitiveParamsVector(LSL_Types.Vector3 vecCheck, LSL_Types.Vector3 vecReturned, string msg)
{
// Check each vector component against expected result.
Assert.AreEqual(vecCheck.x, vecReturned.x, VECTOR_COMPONENT_ACCURACY,
"TestllSetPrimitiveParams " + msg + " vector check fail on x component");
Assert.AreEqual(vecCheck.y, vecReturned.y, VECTOR_COMPONENT_ACCURACY,
"TestllSetPrimitiveParams " + msg + " vector check fail on y component");
Assert.AreEqual(vecCheck.z, vecReturned.z, VECTOR_COMPONENT_ACCURACY,
"TestllSetPrimitiveParams " + msg + " vector check fail on z component");
}
}
}
| |
/*
*
* (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.Configuration;
using System.Linq;
using ASC.Common.Data.Sql;
using ASC.Common.Data.Sql.Expressions;
using ASC.Core.Tenants;
using ASC.Core.Users;
using ASC.Security.Cryptography;
namespace ASC.Core.Data
{
public class DbUserService : DbBaseService, IUserService
{
public DbUserService(ConnectionStringSettings connectionString)
: base(connectionString, "tenant")
{
}
public IDictionary<Guid, UserInfo> GetUsers(int tenant, DateTime from)
{
var q = GetUserQuery(tenant, from);
return ExecList(q).ConvertAll(ToUser).ToDictionary(u => u.ID);
}
public UserInfo GetUser(int tenant, Guid id)
{
var q = GetUserQuery(tenant, default(DateTime)).Where("id", id);
return ExecList(q).ConvertAll(ToUser).SingleOrDefault();
}
public UserInfo GetUser(int tenant, string email)
{
var q = GetUserQuery(tenant, default(DateTime))
.Where("email", email)
.Where("removed", false);
return ExecList(q).ConvertAll(ToUser).SingleOrDefault();
}
public UserInfo GetUserByUserName(int tenant, string userName)
{
var q = GetUserQuery(tenant, default(DateTime))
.Where("userName", userName)
.Where("removed", false);
return ExecList(q).ConvertAll(ToUser).SingleOrDefault();
}
public UserInfo GetUserByPasswordHash(int tenant, string login, string passwordHash)
{
if (string.IsNullOrEmpty(login)) throw new ArgumentNullException("login");
Guid userId;
if (Guid.TryParse(login, out userId))
{
RegeneratePassword(tenant, userId);
var q = GetUserQuery()
.InnerJoin("core_usersecurity s", Exp.EqColumns("u.id", "s.userid"))
.Where("u.id", userId)
.Where(Exp.Or(
Exp.Eq("s.pwdhash", GetPasswordHash(userId, passwordHash)),
Exp.Eq("s.pwdhash", Hasher.Base64Hash(passwordHash, HashAlg.SHA256)) //todo: remove old scheme
))
.Where("u.removed", false);
if (tenant != Tenant.DEFAULT_TENANT)
{
q.Where("u.tenant", tenant);
}
return ExecList(q).ConvertAll(ToUser).FirstOrDefault();
}
else
{
var q = GetUserQuery()
.Where("u.email", login)
.Where("u.removed", false);
if (tenant != Tenant.DEFAULT_TENANT)
{
q.Where("u.tenant", tenant);
}
var users = ExecList(q).ConvertAll(ToUser);
UserInfo result = null;
foreach (var user in users)
{
RegeneratePassword(tenant, user.ID);
q = new SqlQuery("core_usersecurity s")
.SelectCount()
.Where("s.userid", user.ID)
.Where(Exp.Or(
Exp.Eq("s.pwdhash", GetPasswordHash(user.ID, passwordHash)),
Exp.Eq("s.pwdhash", Hasher.Base64Hash(passwordHash, HashAlg.SHA256)) //todo: remove old scheme
));
var count = ExecScalar<int>(q);
if (count > 0)
{
if (tenant != Tenant.DEFAULT_TENANT) return user;
//need for regenerate all passwords only
//todo: remove with old scheme
result = user;
}
}
return result;
}
}
public IEnumerable<UserInfo> GetUsersAllTenants(IEnumerable<string> userIds)
{
var q = GetUserQuery()
.Where(Exp.In("id", userIds.ToArray()))
.Where("removed", false);
return ExecList(q).ConvertAll(ToUser);
}
//todo: remove
private void RegeneratePassword(int tenant, Guid userId)
{
var q = new SqlQuery("core_usersecurity")
.Select("tenant", "pwdhashsha512")
.Where("userid", userId.ToString());
if (tenant != Tenant.DEFAULT_TENANT)
{
q.Where("tenant", tenant);
}
var result = ExecList(q)
.ConvertAll(r => new Tuple<int, string>(Convert.ToInt32(r[0]), (string)r[1]))
.FirstOrDefault();
if (result == null || string.IsNullOrEmpty(result.Item2)) return;
var password = Crypto.GetV(result.Item2, 1, false);
var passwordHash = PasswordHasher.GetClientPassword(password);
SetUserPasswordHash(result.Item1, userId, passwordHash);
}
public UserInfo SaveUser(int tenant, UserInfo user)
{
if (user == null) throw new ArgumentNullException("user");
if (string.IsNullOrEmpty(user.UserName)) throw new ArgumentOutOfRangeException("Empty username.");
if (user.ID == default(Guid)) user.ID = Guid.NewGuid();
if (user.CreateDate == default(DateTime)) user.CreateDate = DateTime.UtcNow;
user.LastModified = DateTime.UtcNow;
user.Tenant = tenant;
using (var db = GetDb())
using (var tx = db.BeginTransaction())
{
user.UserName = user.UserName.Trim();
var q = Query("core_user", tenant)
.SelectCount()
.Where("username", user.UserName)
.Where(!Exp.Eq("id", user.ID.ToString()))
.Where("removed", false);
var count = db.ExecuteScalar<int>(q);
if (count != 0)
{
throw new ArgumentOutOfRangeException("Duplicate username.");
}
user.Email = user.Email.Trim();
q = Query("core_user", tenant)
.SelectCount()
.Where("email", user.Email)
.Where(!Exp.Eq("id", user.ID.ToString()))
.Where("removed", false);
count = db.ExecuteScalar<int>(q);
if (count != 0)
{
throw new ArgumentOutOfRangeException("Duplicate email.");
}
var i = Insert("core_user", tenant)
.InColumnValue("id", user.ID.ToString())
.InColumnValue("username", user.UserName)
.InColumnValue("firstname", user.FirstName)
.InColumnValue("lastname", user.LastName)
.InColumnValue("sex", user.Sex)
.InColumnValue("bithdate", user.BirthDate)
.InColumnValue("status", user.Status)
.InColumnValue("title", user.Title)
.InColumnValue("workfromdate", user.WorkFromDate)
.InColumnValue("terminateddate", user.TerminatedDate)
.InColumnValue("contacts", user.ContactsToString())
.InColumnValue("email", string.IsNullOrEmpty(user.Email) ? user.Email : user.Email.Trim())
.InColumnValue("location", user.Location)
.InColumnValue("notes", user.Notes)
.InColumnValue("removed", user.Removed)
.InColumnValue("last_modified", user.LastModified)
.InColumnValue("activation_status", user.ActivationStatus)
.InColumnValue("culture", user.CultureName)
.InColumnValue("phone", user.MobilePhone)
.InColumnValue("phone_activation", user.MobilePhoneActivationStatus)
.InColumnValue("sid", user.Sid)
.InColumnValue("sso_name_id", user.SsoNameId)
.InColumnValue("sso_session_id", user.SsoSessionId)
.InColumnValue("create_on", user.CreateDate);
db.ExecuteNonQuery(i);
tx.Commit();
}
return user;
}
public void RemoveUser(int tenant, Guid id)
{
RemoveUser(tenant, id, false);
}
public void RemoveUser(int tenant, Guid id, bool immediate)
{
var stringId = id.ToString();
var batch = new List<ISqlInstruction>
{
Delete("core_acl", tenant).Where("subject", stringId),
Delete("core_subscription", tenant).Where("recipient", stringId),
Delete("core_subscriptionmethod", tenant).Where("recipient", stringId),
Delete("core_userphoto", tenant).Where("userid", stringId)
};
if (immediate)
{
batch.Add(Delete("core_usergroup", tenant).Where("userid", stringId));
batch.Add(Delete("core_user", tenant).Where("id", stringId));
batch.Add(Delete("core_usersecurity", tenant).Where("userid", stringId));
}
else
{
batch.Add(Update("core_usergroup", tenant).Set("removed", true).Set("last_modified", DateTime.UtcNow).Where("userid", stringId));
batch.Add(Update("core_user", tenant)
.Set("removed", true)
.Set("status", (int)EmployeeStatus.Terminated)
.Set("terminateddate", DateTime.UtcNow)
.Set("last_modified", DateTime.UtcNow)
.Where("id", stringId));
}
ExecBatch(batch);
}
public void SetUserPhoto(int tenant, Guid id, byte[] photo)
{
var sql = photo != null && photo.Length != 0 ?
Insert("core_userphoto", tenant).InColumns("userid", "photo").Values(id.ToString(), photo) :
(ISqlInstruction)Delete("core_userphoto", tenant).Where("userid", id.ToString());
ExecNonQuery(sql);
}
public byte[] GetUserPhoto(int tenant, Guid id)
{
var photo = ExecScalar<byte[]>(Query("core_userphoto", tenant).Select("photo").Where("userid", id.ToString()));
return photo ?? new byte[0];
}
public DateTime GetUserPasswordStamp(int tenant, Guid id)
{
var q = Query("core_usersecurity", tenant).Select("LastModified").Where("userid", id.ToString());
var stamp = ExecScalar<string>(q);
return !string.IsNullOrEmpty(stamp) ? Convert.ToDateTime(stamp) : DateTime.MinValue;
}
public void SetUserPasswordHash(int tenant, Guid id, string passwordHash)
{
var h1 = GetPasswordHash(id, passwordHash);
var i = Insert("core_usersecurity", tenant)
.InColumnValue("userid", id.ToString())
.InColumnValue("pwdhash", h1)
.InColumnValue("pwdhashsha512", null) //todo: remove
;
ExecNonQuery(i);
}
public IDictionary<Guid, Group> GetGroups(int tenant, DateTime from)
{
var q = GetGroupQuery(tenant, from);
return ExecList(q)
.ConvertAll(ToGroup)
.ToDictionary(g => g.Id);
}
public Group GetGroup(int tenant, Guid id)
{
var q = GetGroupQuery(tenant, default(DateTime)).Where("id", id);
return ExecList(q).ConvertAll(ToGroup).SingleOrDefault();
}
public Group SaveGroup(int tenant, Group group)
{
if (group == null) throw new ArgumentNullException("user");
if (group.Id == default(Guid)) group.Id = Guid.NewGuid();
group.LastModified = DateTime.UtcNow;
group.Tenant = tenant;
var i = Insert("core_group", tenant)
.InColumnValue("id", group.Id.ToString())
.InColumnValue("name", group.Name)
.InColumnValue("parentid", group.ParentId.ToString())
.InColumnValue("categoryid", group.CategoryId.ToString())
.InColumnValue("removed", group.Removed)
.InColumnValue("last_modified", group.LastModified)
.InColumnValue("sid", group.Sid);
ExecNonQuery(i);
return group;
}
public void RemoveGroup(int tenant, Guid id)
{
RemoveGroup(tenant, id, false);
}
public void RemoveGroup(int tenant, Guid id, bool immediate)
{
var batch = new List<ISqlInstruction>();
var ids = CollectGroupChilds(tenant, id.ToString());
batch.Add(Delete("core_acl", tenant).Where(Exp.In("subject", ids)));
batch.Add(Delete("core_subscription", tenant).Where(Exp.In("recipient", ids)));
batch.Add(Delete("core_subscriptionmethod", tenant).Where(Exp.In("recipient", ids)));
if (immediate)
{
batch.Add(Delete("core_usergroup", tenant).Where(Exp.In("groupid", ids)));
batch.Add(Delete("core_group", tenant).Where(Exp.In("id", ids)));
}
else
{
batch.Add(Update("core_usergroup", tenant).Set("removed", true).Set("last_modified", DateTime.UtcNow).Where(Exp.In("groupid", ids)));
batch.Add(Update("core_group", tenant).Set("removed", true).Set("last_modified", DateTime.UtcNow).Where(Exp.In("id", ids)));
}
ExecBatch(batch);
}
public IDictionary<string, UserGroupRef> GetUserGroupRefs(int tenant, DateTime from)
{
var q = GetUserGroupRefQuery(tenant, from);
return ExecList(q).ConvertAll(ToUserGroupRef).ToDictionary(r => r.CreateKey());
}
public UserGroupRef SaveUserGroupRef(int tenant, UserGroupRef r)
{
if (r == null) throw new ArgumentNullException("userGroupRef");
r.LastModified = DateTime.UtcNow;
r.Tenant = tenant;
var i = Insert("core_usergroup", tenant)
.InColumnValue("userid", r.UserId.ToString())
.InColumnValue("groupid", r.GroupId.ToString())
.InColumnValue("ref_type", (int)r.RefType)
.InColumnValue("removed", r.Removed)
.InColumnValue("last_modified", r.LastModified);
var u = Update("core_user", tenant).Set("last_modified", r.LastModified).Where("id", r.UserId.ToString());
ExecBatch(i, u);
return r;
}
public void RemoveUserGroupRef(int tenant, Guid userId, Guid groupId, UserGroupRefType refType)
{
RemoveUserGroupRef(tenant, userId, groupId, refType, false);
}
public void RemoveUserGroupRef(int tenant, Guid userId, Guid groupId, UserGroupRefType refType, bool immediate)
{
var where = Exp.Eq("userid", userId.ToString()) & Exp.Eq("groupid", groupId.ToString()) & Exp.Eq("ref_type", (int)refType);
var i = immediate ?
Delete("core_usergroup", tenant).Where(where) :
(ISqlInstruction)Update("core_usergroup", tenant).Where(where).Set("removed", true).Set("last_modified", DateTime.UtcNow);
var u = Update("core_user", tenant).Set("last_modified", DateTime.UtcNow).Where("id", userId.ToString());
ExecBatch(i, u);
}
private static SqlQuery GetUserQuery()
{
return new SqlQuery("core_user u")
.Select("u.id", "u.username", "u.firstname", "u.lastname", "u.sex", "u.bithdate", "u.status", "u.title")
.Select("u.workfromdate", "u.terminateddate", "u.contacts", "u.email", "u.location", "u.notes", "u.removed")
.Select("u.last_modified", "u.tenant", "u.activation_status", "u.culture", "u.phone", "u.phone_activation", "u.sid", "u.sso_name_id", "u.sso_session_id", "u.create_on");
}
private static SqlQuery GetUserQuery(int tenant, DateTime from)
{
var q = GetUserQuery();
var where = Exp.Empty;
if (tenant != Tenant.DEFAULT_TENANT)
{
where &= Exp.Eq("tenant", tenant);
}
if (from != default(DateTime))
{
where &= Exp.Ge("last_modified", from);
}
if (where != Exp.Empty)
{
q.Where(where);
}
else
{
q.Where(Exp.False);
}
return q;
}
private static UserInfo ToUser(object[] r)
{
var u = new UserInfo
{
ID = new Guid((string)r[0]),
UserName = (string)r[1],
FirstName = (string)r[2],
LastName = (string)r[3],
Sex = r[4] != null ? Convert.ToBoolean(r[4]) : (bool?)null,
BirthDate = (DateTime?)r[5],
Status = (EmployeeStatus)Convert.ToInt32(r[6]),
Title = (string)r[7],
WorkFromDate = (DateTime?)r[8],
TerminatedDate = (DateTime?)r[9],
Email = (string)r[11],
Location = (string)r[12],
Notes = (string)r[13],
Removed = Convert.ToBoolean(r[14]),
LastModified = Convert.ToDateTime(r[15]),
Tenant = Convert.ToInt32(r[16]),
ActivationStatus = (EmployeeActivationStatus)Convert.ToInt32(r[17]),
CultureName = (string)r[18],
MobilePhone = (string)r[19],
MobilePhoneActivationStatus = (MobilePhoneActivationStatus)Convert.ToInt32(r[20]),
Sid = (string)r[21],
SsoNameId = (string)r[22],
SsoSessionId = (string)r[23],
CreateDate = Convert.ToDateTime(r[24])
};
u.ContactsFromString((string)r[10]);
return u;
}
private static SqlQuery GetGroupQuery(int tenant, DateTime from)
{
var q = new SqlQuery("core_group").Select("id", "name", "parentid", "categoryid", "removed", "last_modified", "tenant", "sid");
var where = Exp.Empty;
if (tenant != Tenant.DEFAULT_TENANT)
{
where &= Exp.Eq("tenant", tenant);
}
if (from != default(DateTime))
{
where &= Exp.Ge("last_modified", from);
}
if (where != Exp.Empty)
{
q.Where(where);
}
else
{
q.Where(Exp.False);
}
return q;
}
private Group ToGroup(object[] r)
{
return new Group
{
Id = new Guid((string)r[0]),
Name = (string)r[1],
ParentId = r[2] != null ? new Guid((string)r[2]) : Guid.Empty,
CategoryId = r[3] != null ? new Guid((string)r[3]) : Guid.Empty,
Removed = Convert.ToBoolean(r[4]),
LastModified = Convert.ToDateTime(r[5]),
Tenant = Convert.ToInt32(r[6]),
Sid = (string)r[7]
};
}
private List<string> CollectGroupChilds(int tenant, string id)
{
var result = new List<string>();
var childs = ExecList(Query("core_group", tenant).Select("id").Where("parentid", id)).ConvertAll(r => (string)r[0]);
foreach (var child in childs)
{
result.Add(child);
result.AddRange(CollectGroupChilds(tenant, child));
}
result.Add(id);
return result.Distinct().ToList();
}
private static SqlQuery GetUserGroupRefQuery(int tenant, DateTime from)
{
var q = new SqlQuery("core_usergroup").Select("userid", "groupid", "ref_type", "removed", "last_modified", "tenant");
var where = Exp.Empty;
if (tenant != Tenant.DEFAULT_TENANT)
{
where &= Exp.Eq("tenant", tenant);
}
if (from != default(DateTime))
{
where &= Exp.Ge("last_modified", from);
}
if (where != Exp.Empty)
{
q.Where(where);
}
else
{
q.Where(Exp.False);
}
return q;
}
private static UserGroupRef ToUserGroupRef(object[] r)
{
return new UserGroupRef(new Guid((string)r[0]), new Guid((string)r[1]), (UserGroupRefType)Convert.ToInt32(r[2]))
{
Removed = Convert.ToBoolean(r[3]),
LastModified = Convert.ToDateTime(r[4]),
Tenant = Convert.ToInt32(r[5])
};
}
}
}
| |
namespace dotless.Core.Parser
{
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Exceptions;
using Infrastructure.Nodes;
using Utils;
public class Tokenizer
{
public int Optimization { get; set; }
private string _input; // LeSS input string
private List<string> _chunks; // chunkified input
private int _i; // current index in `input`
private int _j; // current chunk
private int _current; // index of current chunk, in `input`
private int _inputLength;
//Increasing throughput through tracing of Regex
private IDictionary<string, Regex> regexCache = new Dictionary<string, Regex>();
public Tokenizer(int optimization)
{
Optimization = optimization;
}
public void SetupInput(string input)
{
_i = _j = _current = 0;
_chunks = new List<string>();
_input = input.Replace("\r\n", "\n");
_inputLength = _input.Length;
// Split the input into chunks,
// Either delimited by /\n\n/ or
// delmited by '\n}' (see rationale above),
// depending on the level of optimization.
if (Optimization == 0)
_chunks.Add(_input);
else
{
var chunkParts = new List<StringBuilder> { new StringBuilder() };
var chunkPart = chunkParts.Last();
var skip = new Regex(@"\G[^\""'{}/\\`]+");
var comment = new Regex(@"\G\/\*(?:[^*\n]|\*+[^\/\n]|\*?(\n))*\*+\/");
var level = 0;
var lastBlock = 0;
var lastQuote = 0;
char? inString = null;
for (int i = 0; i < _inputLength; i++)
{
var match = skip.Match(_input, i);
if(match.Success)
{
chunkPart.Append(match.Value);
i += match.Length;
if (i == _inputLength)
break;
}
if(i < _inputLength - 1 && _input[i] == '/')
{
var cc = _input[i + 1];
if(cc == '/' || cc=='*')
{
match = comment.Match(_input, i);
if (match.Success)
{
i += match.Length;
chunkPart.Append(match.Value);
if (i == _inputLength)
break;
}
}
}
var c = _input[i];
if (c == '"' || c == '\'' || c == '`')
{
if (inString == null)
{
inString = c;
lastQuote = i;
}
else
inString = inString == c ? null : inString;
}
else if (inString != null && c == '\\' && i < _inputLength - 1)
{
chunkPart.Append(_input, i, 2);
i++;
continue;
}
else if (inString == null && c == '{')
{
level++;
lastBlock = i;
}
else if (inString == null && c == '}')
{
level--;
if (level < 0)
throw new ParsingException("Unexpected '}'", i);
chunkPart.Append(c);
chunkPart = new StringBuilder();
chunkParts.Add(chunkPart);
continue;
}
chunkPart.Append(c);
}
if(inString != null)
throw new ParsingException(string.Format("Missing closing quote ({0})", inString), lastQuote);
if(level > 0)
throw new ParsingException("Missing closing '}'", lastBlock);
_chunks = chunkParts.SelectList(p => p.ToString());
_input = _chunks.JoinStrings("");
_inputLength = _input.Length;
}
Advance(0); // skip any whitespace characters at the start.
}
public string MatchString(char tok)
{
var c = Match(tok);
return c == null ? null : c.Value;
}
public string MatchString(string tok)
{
var match = Match(tok);
return match == null ? null : match.Value;
}
//
// Parse from a token, regexp or string, and move forward if match
//
public CharMatchResult Match(char tok)
{
if (_i == _inputLength)
return null;
if (_input[_i] == tok)
{
Advance(1);
return new CharMatchResult(tok);
}
return null;
}
/// <summary>
/// A faster alternative to Match for when you don't need any Regex magic.
/// </summary>
public bool MatchSimple(string tok, bool caseInsensitive = false)
{
var chunk = _chunks[_j];
var offset = _i - _current;
int i;
for (i = 0; i < tok.Length && (i + offset) < chunk.Length; i++)
{
var c1 = tok[i];
var c2 = chunk[offset + i];
if (caseInsensitive)
{
c1 = char.ToLowerInvariant(c1);
c2 = char.ToLowerInvariant(c2);
}
if (c1 != c2) return false;
}
var ret = i == tok.Length;
if (!ret) return false;
Advance(tok.Length);
return true;
}
public RegexMatchResult Match(string tok, bool caseInsensitive = false)
{
var options = RegexOptions.None;
if (caseInsensitive)
options |= RegexOptions.IgnoreCase;
var regex = GetRegex(tok, options);
var match = regex.Match(_chunks[_j], _i - _current);
if (!match.Success)
return null;
Advance(match.Length);
return new RegexMatchResult(match);
}
public void Advance(int length)
{
// The match is confirmed, add the match length to `i`,
// and consume any extra white-space characters (' ' || '\n')
// which come after that. The reason for this is that LeSS's
// grammar is mostly white-space insensitive.
_i += length;
var endIndex = _current + _chunks[_j].Length;
while (true)
{
if(_i == _inputLength)
break;
if (_i == endIndex)
{
if (_j < _chunks.Count - 1)
{
_current = endIndex;
endIndex += _chunks[++_j].Length;
}
else
break;
}
if (!char.IsWhiteSpace(_input[_i]))
break;
_i++;
}
}
// Same as Match, but don't change the state of the parser,
// just return the match.
public bool Peek(char tok)
{
if (_i == _inputLength)
return false;
return _input[_i] == tok;
}
/// <summary>
/// Version of Peek that only accepts an exact string match, doesn't do any Regex stuff.
/// Use it for speed.
/// </summary>
public bool PeekSimple(string tok)
{
int i;
for (i = 0; i < tok.Length && (i + _i) < _input.Length; i++)
{
if (tok[i] != _input[_i + i]) return false;
}
return i == tok.Length;
}
public bool Peek(string tok)
{
var regex = GetRegex(tok, RegexOptions.None);
var match = regex.Match(_input, _i);
return match.Success;
}
private Regex GetRegex(string pattern, RegexOptions options)
{
if (!regexCache.ContainsKey(pattern))
regexCache.Add(pattern, new Regex(@"\G" + pattern, options));
return regexCache[pattern];
}
public char PreviousChar
{
get { return _i == 0 ? '\0' : _input[_i - 1]; }
}
public char CurrentChar
{
get { return _i == _inputLength ? '\0' : _input[_i]; }
}
public bool HasCompletedParsing()
{
return _i == _inputLength;
}
public Location Location
{
get
{
return new Location
{
Index = _i,
CurrentChunk = _j,
CurrentChunkIndex = _current
};
}
set
{
_i = value.Index;
_j = value.CurrentChunk;
_current = value.CurrentChunkIndex;
}
}
public Zone GetZone(string error, int position, int call, string fileName)
{
var first = _input.Substring(0, System.Math.Min(position, _input.Length));
var start = first.LastIndexOf('\n') + 1;
var line = first.Count(c => c == '\n');
var lines = _input.Split('\n');
var callLine = _input.Substring(0, call).Count(c => c == '\n');
return new Zone
{
FileName = fileName,
Message = error,
CallLine = callLine + 1,
CallExtract = callLine <= 0 ? null : new Extract(lines, callLine),
LineNumber = line + 1,
Position = position - start,
Extract = new Extract(lines, line),
};
}
}
public class Zone
{
public int LineNumber { get; set; }
public int Position { get; set; }
public Extract Extract { get; set; }
public string Message { get; set; }
public string FileName { get; set; }
public int CallLine { get; set; }
public Extract CallExtract { get; set; }
}
public class Extract
{
public Extract(string[] lines, int line)
{
Before = line > 0 ? lines[line - 1] : "/beginning of file";
Line = lines[line];
After = line + 1 < lines.Length ? lines[line + 1] : "/end of file";
}
public string After { get; set; }
public string Before { get; set; }
public string Line { get; set; }
}
public class Location
{
public int Index { get; set; }
public int CurrentChunk { get; set; }
public int CurrentChunkIndex { get; set; }
}
}
| |
/********************************************************
* ADO.NET 2.0 Data Provider for SQLite Version 3.X
* Written by Robert Simpson ([email protected])
*
* Released to the public domain, use at your own risk!
********************************************************/
namespace Mono.Data.Sqlite
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
#if !PLATFORM_COMPACTFRAMEWORK
using System.Runtime.Serialization;
#endif
/// <summary>
/// SQLite exception class.
/// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
[Serializable]
public sealed class SqliteException : DbException
#else
public sealed class SqliteException : Exception
#endif
{
private SQLiteErrorCode _errorCode;
#if !PLATFORM_COMPACTFRAMEWORK
private SqliteException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
/// <summary>
/// Public constructor for generating a SQLite error given the base error code
/// </summary>
/// <param name="errorCode">The SQLite error code to report</param>
/// <param name="extendedInformation">Extra text to go along with the error message text</param>
public SqliteException(int errorCode, string extendedInformation)
: base(GetStockErrorMessage(errorCode, extendedInformation))
{
_errorCode = (SQLiteErrorCode)errorCode;
}
/// <summary>
/// Various public constructors that just pass along to the base Exception
/// </summary>
/// <param name="message">Passed verbatim to Exception</param>
public SqliteException(string message)
: base(message)
{
}
/// <summary>
/// Various public constructors that just pass along to the base Exception
/// </summary>
public SqliteException()
{
}
/// <summary>
/// Various public constructors that just pass along to the base Exception
/// <param name="message">Passed to Exception</param>
/// <param name="innerException">Passed to Exception</param>
/// </summary>
public SqliteException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Retrieves the underlying SQLite error code for this exception
/// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
public new SQLiteErrorCode ErrorCode
#else
public SQLiteErrorCode ErrorCode
#endif
{
get { return _errorCode; }
}
/// <summary>
/// Initializes the exception class with the SQLite error code.
/// </summary>
/// <param name="errorCode">The SQLite error code</param>
/// <param name="errorMessage">A detailed error message</param>
/// <returns>An error message string</returns>
private static string GetStockErrorMessage(int errorCode, string errorMessage)
{
if (errorMessage == null) errorMessage = "";
if (errorMessage.Length > 0)
errorMessage = "\r\n" + errorMessage;
if (errorCode < 0 || errorCode >= _errorMessages.Length)
errorCode = 1;
return _errorMessages[errorCode] + errorMessage;
}
private static string[] _errorMessages = {
"SQLite OK",
"SQLite error",
"An internal logic error in SQLite",
"Access permission denied",
"Callback routine requested an abort",
"The database file is locked",
"A table in the database is locked",
"malloc() failed",
"Attempt to write a read-only database",
"Operation terminated by sqlite3_interrupt()",
"Some kind of disk I/O error occurred",
"The database disk image is malformed",
"Table or record not found",
"Insertion failed because the database is full",
"Unable to open the database file",
"Database lock protocol error",
"Database is empty",
"The database schema changed",
"Too much data for one row of a table",
"Abort due to constraint violation",
"Data type mismatch",
"Library used incorrectly",
"Uses OS features not supported on host",
"Authorization denied",
"Auxiliary database format error",
"2nd parameter to sqlite3_bind() out of range",
"File opened that is not a database file",
};
}
/// <summary>
/// SQLite error codes
/// </summary>
public enum SQLiteErrorCode
{
/// <summary>
/// Success
/// </summary>
Ok = 0,
/// <summary>
/// SQL error or missing database
/// </summary>
Error,
/// <summary>
/// Internal logic error in SQLite
/// </summary>
Internal,
/// <summary>
/// Access permission denied
/// </summary>
Perm,
/// <summary>
/// Callback routine requested an abort
/// </summary>
Abort,
/// <summary>
/// The database file is locked
/// </summary>
Busy,
/// <summary>
/// A table in the database is locked
/// </summary>
Locked,
/// <summary>
/// malloc() failed
/// </summary>
NoMem,
/// <summary>
/// Attempt to write a read-only database
/// </summary>
ReadOnly,
/// <summary>
/// Operation terminated by sqlite3_interrupt()
/// </summary>
Interrupt,
/// <summary>
/// Some kind of disk I/O error occurred
/// </summary>
IOErr,
/// <summary>
/// The database disk image is malformed
/// </summary>
Corrupt,
/// <summary>
/// Table or record not found
/// </summary>
NotFound,
/// <summary>
/// Insertion failed because database is full
/// </summary>
Full,
/// <summary>
/// Unable to open the database file
/// </summary>
CantOpen,
/// <summary>
/// Database lock protocol error
/// </summary>
Protocol,
/// <summary>
/// Database is empty
/// </summary>
Empty,
/// <summary>
/// The database schema changed
/// </summary>
Schema,
/// <summary>
/// Too much data for one row of a table
/// </summary>
TooBig,
/// <summary>
/// Abort due to constraint violation
/// </summary>
Constraint,
/// <summary>
/// Data type mismatch
/// </summary>
Mismatch,
/// <summary>
/// Library used incorrectly
/// </summary>
Misuse,
/// <summary>
/// Uses OS features not supported on host
/// </summary>
NOLFS,
/// <summary>
/// Authorization denied
/// </summary>
Auth,
/// <summary>
/// Auxiliary database format error
/// </summary>
Format,
/// <summary>
/// 2nd parameter to sqlite3_bind out of range
/// </summary>
Range,
/// <summary>
/// File opened that is not a database file
/// </summary>
NotADatabase,
/// <summary>
/// sqlite3_step() has another row ready
/// </summary>
Row = 100,
/// <summary>
/// sqlite3_step() has finished executing
/// </summary>
Done = 101,
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 0.13.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Bot.Connector
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
/// <summary>
/// Conversations operations.
/// </summary>
public partial class Conversations : IServiceOperations<ConnectorClient>, IConversations
{
/// <summary>
/// Initializes a new instance of the Conversations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public Conversations(ConnectorClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the ConnectorClient
/// </summary>
public ConnectorClient Client { get; private set; }
/// <summary>
/// CreateConversation
/// </summary>
/// Create a new Conversation.
///
/// POST to this method with a
/// * Bot being the bot creating the conversation
/// * IsGroup set to true if this is not a direct message (default is false)
/// * Members array contining the members you want to have be in the
/// conversation.
///
/// The return value is a ResourceResponse which contains a conversation id
/// which is suitable for use
/// in the message payload and REST API uris.
///
/// Most channels only support the semantics of bots initiating a direct
/// message conversation. An example of how to do that would be:
///
/// ```
/// var resource = await connector.conversations.CreateConversation(new
/// ConversationParameters(){ Bot = bot, members = new ChannelAccount[] { new
/// ChannelAccount("user1") } );
/// await connect.Conversations.SendToConversationAsync(resource.Id, new
/// Activity() ... ) ;
///
/// ```
/// <param name='parameters'>
/// Parameters to create the conversation from
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<object>> CreateConversationWithHttpMessagesAsync(ConversationParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateConversation", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v3/conversations").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200 && (int)_statusCode != 201 && (int)_statusCode != 202 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 403 && (int)_statusCode != 404 && (int)_statusCode != 500 && (int)_statusCode != 503)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<object>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<ResourceResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<ResourceResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 202)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<ResourceResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 400)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 401)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 403)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 404)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 500)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 503)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// SendToConversation
/// </summary>
/// This method allows you to send an activity to a conversation regardless of
/// previous posts to a conversation.
///
/// This is slightly different then ReplyToConversation().
/// * SendToConverstion(conversationId) - will simply append a message to the
/// end of the conversation according to the timestamp or semantics of the
/// channel
/// * ReplyToConversation(conversationId,ActivityId) - models the semantics of
/// threaded conversations, meaning it has the information necessary for the
/// channel to reply to the actual message being responded to.
///
/// SendToConversation is appropriate for the first message which initiates a
/// conversation, or if you don't have a particular activity you are
/// responding to.
///
/// ReplyToConversation is preferable to SendToConversation() because it
/// maintains threaded conversations.
/// <param name='activity'>
/// Activity to send
/// </param>
/// <param name='conversationId'>
/// Conversation ID
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<APIResponse>> SendToConversationWithHttpMessagesAsync(Activity activity, string conversationId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (activity == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "activity");
}
if (conversationId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "conversationId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("activity", activity);
tracingParameters.Add("conversationId", conversationId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "SendToConversation", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v3/conversations/{conversationId}/activities").ToString();
_url = _url.Replace("{conversationId}", Uri.EscapeDataString(conversationId));
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = SafeJsonConvert.SerializeObject(activity, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200 && (int)_statusCode != 201 && (int)_statusCode != 202 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 403 && (int)_statusCode != 404 && (int)_statusCode != 500 && (int)_statusCode != 503)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<APIResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 400)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 401)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 403)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 404)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 500)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 503)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// ReplyToActivity
/// </summary>
/// This method allows you to reply to an activity.
///
/// This is slightly different then SendToConversation().
/// * SendToConverstion(conversationId) - will simply append a message to the
/// end of the conversation according to the timestamp or semantics of the
/// channel
/// * ReplyToConversation(conversationId,ActivityId) - models the semantics of
/// threaded conversations, meaning it has the information necessary for the
/// channel to reply to the actual message being responded to.
///
/// ReplyToConversation is almost always preferable to SendToConversation()
/// because it maintains threaded conversations.
///
/// SendToConversation is appropriate for the first message which initiates a
/// conversation, or if you don't have a particular activity you are
/// responding to.
/// <param name='conversationId'>
/// Conversation ID
/// </param>
/// <param name='activityId'>
/// activityId the reply is to (OPTIONAL)
/// </param>
/// <param name='activity'>
/// Activity to send
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<APIResponse>> ReplyToActivityWithHttpMessagesAsync(string conversationId, string activityId, Activity activity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (conversationId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "conversationId");
}
if (activityId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "activityId");
}
if (activity == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "activity");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("conversationId", conversationId);
tracingParameters.Add("activityId", activityId);
tracingParameters.Add("activity", activity);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ReplyToActivity", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v3/conversations/{conversationId}/activities/{activityId}").ToString();
_url = _url.Replace("{conversationId}", Uri.EscapeDataString(conversationId));
_url = _url.Replace("{activityId}", Uri.EscapeDataString(activityId));
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = SafeJsonConvert.SerializeObject(activity, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200 && (int)_statusCode != 201 && (int)_statusCode != 202 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 403 && (int)_statusCode != 404 && (int)_statusCode != 500 && (int)_statusCode != 503)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<APIResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 400)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 401)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 403)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 404)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 500)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 503)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// GetConversationMembers
/// </summary>
/// Call this method to enumerate the members of a converstion.
///
/// This REST API takes a ConversationId and returns an array of
/// ChannelAccount[] objects
/// which are the members of the conversation.
/// <param name='conversationId'>
/// Conversation ID
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<object>> GetConversationMembersWithHttpMessagesAsync(string conversationId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (conversationId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "conversationId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("conversationId", conversationId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetConversationMembers", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v3/conversations/{conversationId}/members").ToString();
_url = _url.Replace("{conversationId}", Uri.EscapeDataString(conversationId));
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 403 && (int)_statusCode != 404 && (int)_statusCode != 500 && (int)_statusCode != 503)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<object>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<IList<ChannelAccount>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 400)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 401)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 403)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 404)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 500)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 503)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// GetActivityMembers
/// </summary>
/// Call this method to enumerate the members of an activity.
///
/// This REST API takes a ConversationId and a ActivityId, returning an array
/// of ChannelAccount[] objects
/// which are the members of the particular activity in the conversation.
/// <param name='conversationId'>
/// Conversation ID
/// </param>
/// <param name='activityId'>
/// Activity ID
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<object>> GetActivityMembersWithHttpMessagesAsync(string conversationId, string activityId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (conversationId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "conversationId");
}
if (activityId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "activityId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("conversationId", conversationId);
tracingParameters.Add("activityId", activityId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetActivityMembers", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v3/conversations/{conversationId}/activities/{activityId}/members").ToString();
_url = _url.Replace("{conversationId}", Uri.EscapeDataString(conversationId));
_url = _url.Replace("{activityId}", Uri.EscapeDataString(activityId));
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 403 && (int)_statusCode != 404 && (int)_statusCode != 500 && (int)_statusCode != 503)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<object>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<IList<ChannelAccount>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 400)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 401)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 403)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 404)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 500)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 503)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// UploadAttachment
/// </summary>
/// This method allows you to upload an attachment directly into a channels
/// blob storage.
///
/// This is useful because it allows you to store data in a compliant store
/// when dealing with enterprises.
///
/// The response is a ResourceResponse which contains an AttachmentId which is
/// suitable for using with the attachments api.
/// <param name='conversationId'>
/// Conversation ID
/// </param>
/// <param name='attachmentUpload'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<object>> UploadAttachmentWithHttpMessagesAsync(string conversationId, AttachmentData attachmentUpload, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (conversationId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "conversationId");
}
if (attachmentUpload == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "attachmentUpload");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("conversationId", conversationId);
tracingParameters.Add("attachmentUpload", attachmentUpload);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "UploadAttachment", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v3/conversations/{conversationId}/attachments").ToString();
_url = _url.Replace("{conversationId}", Uri.EscapeDataString(conversationId));
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = SafeJsonConvert.SerializeObject(attachmentUpload, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200 && (int)_statusCode != 201 && (int)_statusCode != 202 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 403 && (int)_statusCode != 404 && (int)_statusCode != 500 && (int)_statusCode != 503)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<object>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<ResourceResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<ResourceResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 202)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 400)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 401)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 403)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 404)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 500)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
// Deserialize Response
if ((int)_statusCode == 503)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<APIResponse>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using Dbg = System.Management.Automation.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Management.Automation;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Defines the implementation of the get-pfxcertificate cmdlet
/// </summary>
[Cmdlet(VerbsCommon.Get, "PfxCertificate", DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113323")]
[OutputType(typeof(X509Certificate2))]
public sealed class GetPfxCertificateCommand : PSCmdlet
{
/// <summary>
/// Gets or sets the path of the item for which to obtain the
/// certificate.
/// </summary>
[Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, Mandatory = true, ParameterSetName = "ByPath")]
public string[] FilePath
{
get
{
return _path;
}
set
{
_path = value;
}
}
private string[] _path;
/// <summary>
/// Gets or sets the literal path of the item for which to obtain the
/// certificate.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true, ParameterSetName = "ByLiteralPath")]
[Alias("PSPath")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] LiteralPath
{
get
{
return _path;
}
set
{
_path = value;
_isLiteralPath = true;
}
}
private bool _isLiteralPath = false;
//
// list of files that were not found
//
private ArrayList _filesNotFound = new ArrayList();
/// <summary>
/// Initializes a new instance of the GetPfxCertificateCommand
/// class
/// </summary>
public GetPfxCertificateCommand() : base()
{
}
/// <summary>
/// Processes records from the input pipeline.
/// For each input file, the command retrieves its
/// corresponding certificate.
/// </summary>
protected override void ProcessRecord()
{
//
// this cannot happen as we have specified the Path
// property to be a mandatory parameter
//
Dbg.Assert((FilePath != null) && (FilePath.Length > 0),
"GetCertificateCommand: Param binder did not bind path");
X509Certificate2 cert = null;
foreach (string p in FilePath)
{
List<string> paths = new List<string>();
// Expand wildcard characters
if (_isLiteralPath)
{
paths.Add(SessionState.Path.GetUnresolvedProviderPathFromPSPath(p));
}
else
{
try
{
foreach (PathInfo tempPath in SessionState.Path.GetResolvedPSPathFromPSPath(p))
{
paths.Add(tempPath.ProviderPath);
}
}
catch (ItemNotFoundException)
{
_filesNotFound.Add(p);
}
}
foreach (string resolvedPath in paths)
{
string resolvedProviderPath =
SecurityUtils.GetFilePathOfExistingFile(this, resolvedPath);
if (resolvedProviderPath == null)
{
_filesNotFound.Add(p);
}
else
{
try
{
cert = GetCertFromPfxFile(resolvedProviderPath);
}
catch (CryptographicException)
{
//
// CryptographicException is thrown when any error
// occurs inside the crypto class library. It has a
// protected member HResult that indicates the exact
// error but it is not available outside the class.
// Thus we have to assume that the above exception
// was thrown because the pfx file is password
// protected.
//
SecureString password = null;
string prompt = null;
prompt = CertificateCommands.GetPfxCertPasswordPrompt;
password = SecurityUtils.PromptForSecureString(Host.UI, prompt);
try
{
cert = GetCertFromPfxFile(resolvedProviderPath,
password);
}
catch (CryptographicException e)
{
//
// since we cannot really figure out the
// meaning of a given CryptographicException
// we have to use NotSpecified category here
//
ErrorRecord er =
new ErrorRecord(e,
"GetPfxCertificateUnknownCryptoError",
ErrorCategory.NotSpecified,
null);
WriteError(er);
continue;
}
}
WriteObject(cert);
}
}
}
if (_filesNotFound.Count > 0)
{
if (_filesNotFound.Count == FilePath.Length)
{
ErrorRecord er =
SecurityUtils.CreateFileNotFoundErrorRecord(
CertificateCommands.NoneOfTheFilesFound,
"GetPfxCertCommandNoneOfTheFilesFound");
ThrowTerminatingError(er);
}
else
{
//
// we found some files but not others.
// Write error for each missing file
//
foreach (string f in _filesNotFound)
{
ErrorRecord er =
SecurityUtils.CreateFileNotFoundErrorRecord(
CertificateCommands.FileNotFound,
"GetPfxCertCommandFileNotFound",
f
);
WriteError(er);
}
}
}
}
private static X509Certificate2 GetCertFromPfxFile(string path)
{
X509Certificate2 cert = new X509Certificate2();
cert.Import(path);
return cert;
}
private static X509Certificate2 GetCertFromPfxFile(string path, SecureString password)
{
X509Certificate2 cert = new X509Certificate2();
//
// NTRAID#DevDiv Bugs-33007-2004/7/08-kumarp
// the following will not be required once X509Certificate2.Import()
// accepts a SecureString
//
string clearTextPassword = SecurityUtils.GetStringFromSecureString(password);
cert.Import(path, clearTextPassword, X509KeyStorageFlags.DefaultKeySet);
return cert;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace System.IO
{
/// <summary>
/// Wrapper to help with path normalization.
/// </summary>
internal class PathHelper
{
/// <summary>
/// Normalize the given path.
/// </summary>
/// <remarks>
/// Normalizes via Win32 GetFullPathName().
/// </remarks>
/// <param name="path">Path to normalize</param>
/// <exception cref="PathTooLongException">Thrown if we have a string that is too large to fit into a UNICODE_STRING.</exception>
/// <exception cref="IOException">Thrown if the path is empty.</exception>
/// <returns>Normalized path</returns>
internal static string Normalize(string path)
{
Span<char> initialBuffer = stackalloc char[PathInternal.MaxShortPath];
var builder = new ValueStringBuilder(initialBuffer);
// Get the full path
GetFullPathName(path.AsSpan(), ref builder);
// If we have the exact same string we were passed in, don't allocate another string.
// TryExpandShortName does this input identity check.
string result = builder.AsSpan().IndexOf('~') >= 0
? TryExpandShortFileName(ref builder, originalPath: path)
: builder.AsSpan().Equals(path.AsSpan(), StringComparison.Ordinal) ? path : builder.ToString();
// Clear the buffer
builder.Dispose();
return result;
}
/// <summary>
/// Normalize the given path.
/// </summary>
/// <remarks>
/// Exceptions are the same as the string overload.
/// </remarks>
internal static string Normalize(ref ValueStringBuilder path)
{
Span<char> initialBuffer = stackalloc char[PathInternal.MaxShortPath];
var builder = new ValueStringBuilder(initialBuffer);
// Get the full path
GetFullPathName(path.AsSpan(terminate: true), ref builder);
string result = builder.AsSpan().IndexOf('~') >= 0
? TryExpandShortFileName(ref builder, originalPath: null)
: builder.ToString();
// Clear the buffer
builder.Dispose();
return result;
}
/// <summary>
/// Calls GetFullPathName on the given path.
/// </summary>
/// <param name="path">The path name. MUST be null terminated after the span.</param>
private static void GetFullPathName(ReadOnlySpan<char> path, ref ValueStringBuilder builder)
{
// If the string starts with an extended prefix we would need to remove it from the path before we call GetFullPathName as
// it doesn't root extended paths correctly. We don't currently resolve extended paths, so we'll just assert here.
Debug.Assert(PathInternal.IsPartiallyQualified(path) || !PathInternal.IsExtended(path));
uint result = 0;
while ((result = Interop.Kernel32.GetFullPathNameW(ref MemoryMarshal.GetReference(path), (uint)builder.Capacity, ref builder.GetPinnableReference(), IntPtr.Zero)) > builder.Capacity)
{
// Reported size is greater than the buffer size. Increase the capacity.
builder.EnsureCapacity(checked((int)result));
}
if (result == 0)
{
// Failure, get the error and throw
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == 0)
errorCode = Interop.Errors.ERROR_BAD_PATHNAME;
throw Win32Marshal.GetExceptionForWin32Error(errorCode, path.ToString());
}
builder.Length = (int)result;
}
internal static int PrependDevicePathChars(ref ValueStringBuilder content, bool isDosUnc, ref ValueStringBuilder buffer)
{
int length = content.Length;
length += isDosUnc
? PathInternal.UncExtendedPrefixLength - PathInternal.UncPrefixLength
: PathInternal.DevicePrefixLength;
buffer.EnsureCapacity(length + 1);
buffer.Length = 0;
if (isDosUnc)
{
// Is a \\Server\Share, put \\?\UNC\ in the front
buffer.Append(PathInternal.UncExtendedPathPrefix);
// Copy Server\Share\... over to the buffer
buffer.Append(content.AsSpan(PathInternal.UncPrefixLength));
// Return the prefix difference
return PathInternal.UncExtendedPrefixLength - PathInternal.UncPrefixLength;
}
else
{
// Not an UNC, put the \\?\ prefix in front, then the original string
buffer.Append(PathInternal.ExtendedPathPrefix);
buffer.Append(content.AsSpan());
return PathInternal.DevicePrefixLength;
}
}
internal static string TryExpandShortFileName(ref ValueStringBuilder outputBuilder, string originalPath)
{
// We guarantee we'll expand short names for paths that only partially exist. As such, we need to find the part of the path that actually does exist. To
// avoid allocating like crazy we'll create only one input array and modify the contents with embedded nulls.
Debug.Assert(!PathInternal.IsPartiallyQualified(outputBuilder.AsSpan()), "should have resolved by now");
// We'll have one of a few cases by now (the normalized path will have already:
//
// 1. Dos path (C:\)
// 2. Dos UNC (\\Server\Share)
// 3. Dos device path (\\.\C:\, \\?\C:\)
//
// We want to put the extended syntax on the front if it doesn't already have it (for long path support and speed), which may mean switching from \\.\.
//
// Note that we will never get \??\ here as GetFullPathName() does not recognize \??\ and will return it as C:\??\ (or whatever the current drive is).
int rootLength = PathInternal.GetRootLength(outputBuilder.AsSpan());
bool isDevice = PathInternal.IsDevice(outputBuilder.AsSpan());
// As this is a corner case we're not going to add a stackalloc here to keep the stack pressure down.
var inputBuilder = new ValueStringBuilder();
bool isDosUnc = false;
int rootDifference = 0;
bool wasDotDevice = false;
// Add the extended prefix before expanding to allow growth over MAX_PATH
if (isDevice)
{
// We have one of the following (\\?\ or \\.\)
inputBuilder.Append(outputBuilder.AsSpan());
if (outputBuilder[2] == '.')
{
wasDotDevice = true;
inputBuilder[2] = '?';
}
}
else
{
isDosUnc = !PathInternal.IsDevice(outputBuilder.AsSpan()) && outputBuilder.Length > 1 && outputBuilder[0] == '\\' && outputBuilder[1] == '\\';
rootDifference = PrependDevicePathChars(ref outputBuilder, isDosUnc, ref inputBuilder);
}
rootLength += rootDifference;
int inputLength = inputBuilder.Length;
bool success = false;
int foundIndex = inputBuilder.Length - 1;
while (!success)
{
uint result = Interop.Kernel32.GetLongPathNameW(
ref inputBuilder.GetPinnableReference(terminate: true), ref outputBuilder.GetPinnableReference(), (uint)outputBuilder.Capacity);
// Replace any temporary null we added
if (inputBuilder[foundIndex] == '\0') inputBuilder[foundIndex] = '\\';
if (result == 0)
{
// Look to see if we couldn't find the file
int error = Marshal.GetLastWin32Error();
if (error != Interop.Errors.ERROR_FILE_NOT_FOUND && error != Interop.Errors.ERROR_PATH_NOT_FOUND)
{
// Some other failure, give up
break;
}
// We couldn't find the path at the given index, start looking further back in the string.
foundIndex--;
for (; foundIndex > rootLength && inputBuilder[foundIndex] != '\\'; foundIndex--) ;
if (foundIndex == rootLength)
{
// Can't trim the path back any further
break;
}
else
{
// Temporarily set a null in the string to get Windows to look further up the path
inputBuilder[foundIndex] = '\0';
}
}
else if (result > outputBuilder.Capacity)
{
// Not enough space. The result count for this API does not include the null terminator.
outputBuilder.EnsureCapacity(checked((int)result));
result = Interop.Kernel32.GetLongPathNameW(ref inputBuilder.GetPinnableReference(), ref outputBuilder.GetPinnableReference(), (uint)outputBuilder.Capacity);
}
else
{
// Found the path
success = true;
outputBuilder.Length = checked((int)result);
if (foundIndex < inputLength - 1)
{
// It was a partial find, put the non-existent part of the path back
outputBuilder.Append(inputBuilder.AsSpan(foundIndex, inputBuilder.Length - foundIndex));
}
}
}
// If we were able to expand the path, use it, otherwise use the original full path result
ref ValueStringBuilder builderToUse = ref (success ? ref outputBuilder : ref inputBuilder);
// Switch back from \\?\ to \\.\ if necessary
if (wasDotDevice)
builderToUse[2] = '.';
// Change from \\?\UNC\ to \\?\UN\\ if needed
if (isDosUnc)
builderToUse[PathInternal.UncExtendedPrefixLength - PathInternal.UncPrefixLength] = '\\';
// Strip out any added characters at the front of the string
ReadOnlySpan<char> output = builderToUse.AsSpan(rootDifference);
string returnValue = ((originalPath != null) && output.Equals(originalPath.AsSpan(), StringComparison.Ordinal))
? originalPath : new string(output);
inputBuilder.Dispose();
return returnValue;
}
}
}
| |
//
// System.Web.UI.WebControls.BulletedList.cs
//
// Authors:
// Ben Maurer ([email protected])
//
// (C) 2003 Ben Maurer
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_2_0
using System.IO;
using System.Collections;
using System.Globalization;
using System.Text;
using System.Drawing;
using System.ComponentModel;
using System.ComponentModel.Design;
namespace System.Web.UI.WebControls {
[DesignerAttribute ("System.Web.UI.Design.WebControls.BulletedListDesigner, System.Design, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.ComponentModel.Design.IDesigner")]
[DefaultEventAttribute ("Click")]
[DefaultPropertyAttribute ("BulletStyle")]
public class BulletedList : ListControl, IPostBackEventHandler {
[MonoTODO ("we are missing a new style enum, we should be using it")]
protected override void AddAttributesToRender (HtmlTextWriter writer)
{
const string ListStyleType = "list-style-type";
const string ListStyleImage = "list-style-image";
bool isNumeric = false;
switch (BulletStyle)
{
case BulletStyle.NotSet:
break;
case BulletStyle.Numbered:
writer.AddStyleAttribute (ListStyleType, "decimal");
isNumeric = true;
break;
case BulletStyle.LowerAlpha:
writer.AddStyleAttribute (ListStyleType, "lower-alpha");
isNumeric = true;
break;
case BulletStyle.UpperAlpha:
writer.AddStyleAttribute (ListStyleType, "upper-alpha");
isNumeric = true;
break;
case BulletStyle.LowerRoman:
writer.AddStyleAttribute (ListStyleType, "lower-roman");
isNumeric = true;
break;
case BulletStyle.UpperRoman:
writer.AddStyleAttribute (ListStyleType, "lower-roman");
isNumeric = true;
break;
case BulletStyle.Disc:
writer.AddStyleAttribute (ListStyleType, "disc");
break;
case BulletStyle.Circle:
writer.AddStyleAttribute (ListStyleType, "circle");
break;
case BulletStyle.Square:
writer.AddStyleAttribute (ListStyleType, "square");
break;
case BulletStyle.CustomImage:
writer.AddStyleAttribute (ListStyleImage, "url(" + BulletImageUrl+ ")");
break;
}
if (isNumeric && FirstBulletNumber != 1)
writer.AddAttribute ("start", FirstBulletNumber.ToString ());
base.AddAttributesToRender (writer);
}
bool cacheIsEnabled;
[MonoTODO ("new bool prop on ListItem: Enabled")]
protected virtual void RenderBulletText (ListItem item, int index, HtmlTextWriter writer)
{
switch (DisplayMode) {
case BulletedListDisplayMode.Text:
//if (!item.Enabled) {
// writer.AddAttribute (HtmlTextWriterAttribute.Disabled, "disabled");
// writer.RenderBeginTag (HtmlTextWriterTag.Span);
//}
writer.Write (item.Text);
//if (!item.Enabled)
// writer.RenderEndTag ();
break;
case BulletedListDisplayMode.HyperLink:
//if (cacheIsEnabled && item.Enabled) {
// writer.AddAttribute (HtmlTextWriterAttribute.Href, item.Value);
// if (Target != "")
// writer.AddAttribute(HtmlTextWriterAttribute.Target, this.Target);
//
//}
//else
writer.AddAttribute (HtmlTextWriterAttribute.Disabled, "disabled");
writer.RenderBeginTag (HtmlTextWriterTag.A);
writer.Write (item.Text);
writer.RenderEndTag ();
break;
case BulletedListDisplayMode.LinkButton:
//if (cacheIsEnabled && item.Enabled)
writer.AddAttribute (HtmlTextWriterAttribute.Href, Page.ClientScript.GetPostBackClientHyperlink (this, (index.ToString (CultureInfo.InvariantCulture))));
//else
// writer.AddAttribute (HtmlTextWriterAttribute.Disabled, "disabled");
writer.RenderBeginTag (HtmlTextWriterTag.A);
writer.Write (item.Text);
writer.RenderEndTag ();
break;
}
}
protected override void RenderContents (HtmlTextWriter writer)
{
cacheIsEnabled = this.Enabled;
int idx = 0;
foreach (ListItem i in Items) {
writer.RenderBeginTag (HtmlTextWriterTag.Li);
this.RenderBulletText (i, idx ++, writer);
writer.RenderEndTag ();
}
}
void IPostBackEventHandler.RaisePostBackEvent (string eventArgument)
{
RaisePostBackEvent (eventArgument);
}
[MonoTODO ("ListControl has a CausesValidation prop in v1.2, we need to use it")]
protected virtual void RaisePostBackEvent (string eventArgument)
{
//if (CausesValidation)
// Page.Validate ();
this.OnClick (new BulletedListEventArgs (int.Parse (eventArgument, CultureInfo.InvariantCulture)));
}
[BrowsableAttribute (false)]
[EditorBrowsableAttribute (EditorBrowsableState.Never)]
public override bool AutoPostBack {
get { return base.AutoPostBack; }
set { throw new NotSupportedException (String.Format ("This property is not supported in {0}", GetType ())); }
}
[EditorBrowsableAttribute (EditorBrowsableState.Never)]
public override int SelectedIndex {
get { return base.SelectedIndex; }
set { throw new NotSupportedException (String.Format ("This property is not supported in {0}", GetType ())); }
}
[EditorBrowsableAttribute (EditorBrowsableState.Never)]
public override ListItem SelectedItem {
get { return base.SelectedItem; }
}
[DefaultValueAttribute ("")]
[EditorAttribute ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[UrlPropertyAttribute]
public virtual string BulletImageUrl {
get {
object ret = ViewState ["BulletImageUrl"];
if (ret != null)
return (string) ret;
return "";
}
set {
ViewState ["BulletImageUrl"] = value;
}
}
[DefaultValueAttribute (BulletStyle.NotSet)]
public virtual BulletStyle BulletStyle {
get {
object ret = ViewState ["BulletStyle"];
if (ret != null)
return (BulletStyle) ret;
return BulletStyle.NotSet;
}
set {
if ((int) value < 0 || (int) value > 9)
throw new ArgumentOutOfRangeException ("value");
ViewState ["BulletStyle"] = value;
}
}
public override ControlCollection Controls { get { return new EmptyControlCollection (this); } }
[DefaultValueAttribute (BulletedListDisplayMode.Text)]
public virtual BulletedListDisplayMode DisplayMode {
get {
object ret = ViewState ["DisplayMode"];
if (ret != null)
return (BulletedListDisplayMode) ret;
return BulletedListDisplayMode.Text;
}
set {
if ((int) value < 0 || (int) value > 2)
throw new ArgumentOutOfRangeException ("value");
ViewState ["DisplayMode"] = value;
}
}
[DefaultValueAttribute (1)]
public virtual int FirstBulletNumber {
get {
object ret = ViewState ["FirstBulletNumber"];
if (ret != null)
return (int) ret;
return 1;
}
set {
ViewState ["FirstBulletNumber"] = value;
}
}
protected override HtmlTextWriterTag TagKey {
get {
switch (BulletStyle) {
case BulletStyle.Numbered:
case BulletStyle.LowerAlpha:
case BulletStyle.UpperAlpha:
case BulletStyle.LowerRoman:
case BulletStyle.UpperRoman:
return HtmlTextWriterTag.Ol;
case BulletStyle.NotSet:
case BulletStyle.Disc:
case BulletStyle.Circle:
case BulletStyle.Square:
case BulletStyle.CustomImage:
default:
return HtmlTextWriterTag.Ul;
}
}
}
[DefaultValueAttribute ("")]
public virtual string Target {
get {
object ret = ViewState ["Target"];
if (ret != null)
return (string) ret;
return "";
}
set {
ViewState ["Target"] = value;
}
}
static readonly object ClickEvent = new object ();
public event BulletedListEventHandler Click
{
add {
Events.AddHandler (ClickEvent, value);
}
remove {
Events.RemoveHandler (ClickEvent, value);
}
}
protected virtual void OnClick (BulletedListEventArgs e)
{
if (Events != null) {
BulletedListEventHandler eh = (BulletedListEventHandler) (Events [ClickEvent]);
if (eh != null)
eh (this, e);
}
}
}
}
#endif
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmSupplierStatement
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmSupplierStatement() : base()
{
KeyPress += frmSupplierStatement_KeyPress;
FormClosed += frmSupplierStatement_FormClosed;
Load += frmSupplierStatement_Load;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.TextBox withEventsField_txtSearch;
public System.Windows.Forms.TextBox txtSearch {
get { return withEventsField_txtSearch; }
set {
if (withEventsField_txtSearch != null) {
withEventsField_txtSearch.Enter -= txtSearch_Enter;
withEventsField_txtSearch.KeyDown -= txtSearch_KeyDown;
withEventsField_txtSearch.KeyPress -= txtSearch_KeyPress;
}
withEventsField_txtSearch = value;
if (withEventsField_txtSearch != null) {
withEventsField_txtSearch.Enter += txtSearch_Enter;
withEventsField_txtSearch.KeyDown += txtSearch_KeyDown;
withEventsField_txtSearch.KeyPress += txtSearch_KeyPress;
}
}
}
public System.Windows.Forms.ComboBox cmbMonth;
private System.Windows.Forms.Button withEventsField_cmdPrint;
public System.Windows.Forms.Button cmdPrint {
get { return withEventsField_cmdPrint; }
set {
if (withEventsField_cmdPrint != null) {
withEventsField_cmdPrint.Click -= cmdPrint_Click;
}
withEventsField_cmdPrint = value;
if (withEventsField_cmdPrint != null) {
withEventsField_cmdPrint.Click += cmdPrint_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdExit;
public System.Windows.Forms.Button cmdExit {
get { return withEventsField_cmdExit; }
set {
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click -= cmdExit_Click;
}
withEventsField_cmdExit = value;
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click += cmdExit_Click;
}
}
}
public System.Windows.Forms.Panel picButtons;
private myDataGridView withEventsField_DataList1;
public myDataGridView DataList1 {
get { return withEventsField_DataList1; }
set {
if (withEventsField_DataList1 != null) {
withEventsField_DataList1.DoubleClick -= DataList1_DblClick;
withEventsField_DataList1.KeyPress -= DataList1_KeyPress;
}
withEventsField_DataList1 = value;
if (withEventsField_DataList1 != null) {
withEventsField_DataList1.DoubleClick += DataList1_DblClick;
withEventsField_DataList1.KeyPress += DataList1_KeyPress;
}
}
}
public System.Windows.Forms.Label lbl;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmSupplierStatement));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.txtSearch = new System.Windows.Forms.TextBox();
this.picButtons = new System.Windows.Forms.Panel();
this.cmbMonth = new System.Windows.Forms.ComboBox();
this.cmdPrint = new System.Windows.Forms.Button();
this.cmdExit = new System.Windows.Forms.Button();
this.DataList1 = new myDataGridView();
this.lbl = new System.Windows.Forms.Label();
this.picButtons.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
((System.ComponentModel.ISupportInitialize)this.DataList1).BeginInit();
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Supplier Previous Statements";
this.ClientSize = new System.Drawing.Size(263, 425);
this.Location = new System.Drawing.Point(3, 22);
this.ControlBox = false;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.Enabled = true;
this.KeyPreview = false;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmSupplierStatement";
this.txtSearch.AutoSize = false;
this.txtSearch.Size = new System.Drawing.Size(199, 19);
this.txtSearch.Location = new System.Drawing.Point(54, 48);
this.txtSearch.TabIndex = 1;
this.txtSearch.AcceptsReturn = true;
this.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.txtSearch.BackColor = System.Drawing.SystemColors.Window;
this.txtSearch.CausesValidation = true;
this.txtSearch.Enabled = true;
this.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtSearch.HideSelection = true;
this.txtSearch.ReadOnly = false;
this.txtSearch.MaxLength = 0;
this.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtSearch.Multiline = false;
this.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtSearch.TabStop = true;
this.txtSearch.Visible = true;
this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.txtSearch.Name = "txtSearch";
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.Size = new System.Drawing.Size(263, 39);
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.TabIndex = 4;
this.picButtons.TabStop = false;
this.picButtons.CausesValidation = true;
this.picButtons.Enabled = true;
this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText;
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Visible = true;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picButtons.Name = "picButtons";
this.cmbMonth.Size = new System.Drawing.Size(88, 21);
this.cmbMonth.Location = new System.Drawing.Point(84, 6);
this.cmbMonth.Items.AddRange(new object[] {
"Last Month",
"2 Months Ago",
"3 Months Ago",
"4 Months Ago",
"5 Months Ago",
"6 Months Ago"
});
this.cmbMonth.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbMonth.TabIndex = 3;
this.cmbMonth.BackColor = System.Drawing.SystemColors.Window;
this.cmbMonth.CausesValidation = true;
this.cmbMonth.Enabled = true;
this.cmbMonth.ForeColor = System.Drawing.SystemColors.WindowText;
this.cmbMonth.IntegralHeight = true;
this.cmbMonth.Cursor = System.Windows.Forms.Cursors.Default;
this.cmbMonth.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmbMonth.Sorted = false;
this.cmbMonth.TabStop = true;
this.cmbMonth.Visible = true;
this.cmbMonth.Name = "cmbMonth";
this.cmdPrint.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdPrint.Text = "&Print";
this.cmdPrint.Size = new System.Drawing.Size(73, 29);
this.cmdPrint.Location = new System.Drawing.Point(5, 3);
this.cmdPrint.TabIndex = 6;
this.cmdPrint.TabStop = false;
this.cmdPrint.BackColor = System.Drawing.SystemColors.Control;
this.cmdPrint.CausesValidation = true;
this.cmdPrint.Enabled = true;
this.cmdPrint.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdPrint.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdPrint.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdPrint.Name = "cmdPrint";
this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdExit.Text = "E&xit";
this.cmdExit.Size = new System.Drawing.Size(73, 29);
this.cmdExit.Location = new System.Drawing.Point(177, 3);
this.cmdExit.TabIndex = 5;
this.cmdExit.TabStop = false;
this.cmdExit.BackColor = System.Drawing.SystemColors.Control;
this.cmdExit.CausesValidation = true;
this.cmdExit.Enabled = true;
this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdExit.Name = "cmdExit";
//DataList1.OcxState = CType(resources.GetObject("'DataList1.OcxState"), System.Windows.Forms.AxHost.State)
this.DataList1.Size = new System.Drawing.Size(244, 342);
this.DataList1.Location = new System.Drawing.Point(9, 72);
this.DataList1.TabIndex = 2;
this.DataList1.Name = "DataList1";
this.lbl.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.lbl.Text = "&Search :";
this.lbl.Size = new System.Drawing.Size(40, 13);
this.lbl.Location = new System.Drawing.Point(11, 51);
this.lbl.TabIndex = 0;
this.lbl.BackColor = System.Drawing.Color.Transparent;
this.lbl.Enabled = true;
this.lbl.ForeColor = System.Drawing.SystemColors.ControlText;
this.lbl.Cursor = System.Windows.Forms.Cursors.Default;
this.lbl.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lbl.UseMnemonic = true;
this.lbl.Visible = true;
this.lbl.AutoSize = true;
this.lbl.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lbl.Name = "lbl";
this.Controls.Add(txtSearch);
this.Controls.Add(picButtons);
this.Controls.Add(DataList1);
this.Controls.Add(lbl);
this.picButtons.Controls.Add(cmbMonth);
this.picButtons.Controls.Add(cmdPrint);
this.picButtons.Controls.Add(cmdExit);
((System.ComponentModel.ISupportInitialize)this.DataList1).EndInit();
this.picButtons.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Runtime
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
// AsyncResult starts acquired; Complete releases.
[Fx.Tag.SynchronizationPrimitive(Fx.Tag.BlocksUsing.ManualResetEvent, SupportsAsync = true, ReleaseMethod = "Complete")]
abstract class AsyncResult : IAsyncResult
{
static AsyncCallback asyncCompletionWrapperCallback;
AsyncCallback callback;
bool completedSynchronously;
bool endCalled;
Exception exception;
bool isCompleted;
AsyncCompletion nextAsyncCompletion;
object state;
Action beforePrepareAsyncCompletionAction;
Func<IAsyncResult, bool> checkSyncValidationFunc;
[Fx.Tag.SynchronizationObject]
ManualResetEvent manualResetEvent;
[Fx.Tag.SynchronizationObject(Blocking = false)]
object thisLock;
#if DEBUG
StackTrace endStack;
StackTrace completeStack;
UncompletedAsyncResultMarker marker;
#endif
protected AsyncResult(AsyncCallback callback, object state)
{
this.callback = callback;
this.state = state;
this.thisLock = new object();
#if DEBUG
this.marker = new UncompletedAsyncResultMarker(this);
#endif
}
public object AsyncState
{
get
{
return state;
}
}
public WaitHandle AsyncWaitHandle
{
get
{
if (manualResetEvent != null)
{
return manualResetEvent;
}
lock (ThisLock)
{
if (manualResetEvent == null)
{
manualResetEvent = new ManualResetEvent(isCompleted);
}
}
return manualResetEvent;
}
}
public bool CompletedSynchronously
{
get
{
return completedSynchronously;
}
}
public bool HasCallback
{
get
{
return this.callback != null;
}
}
public bool IsCompleted
{
get
{
return isCompleted;
}
}
// used in conjunction with PrepareAsyncCompletion to allow for finally blocks
protected Action<AsyncResult, Exception> OnCompleting { get; set; }
object ThisLock
{
get
{
return this.thisLock;
}
}
// subclasses like TraceAsyncResult can use this to wrap the callback functionality in a scope
protected Action<AsyncCallback, IAsyncResult> VirtualCallback
{
get;
set;
}
protected void Complete(bool completedSynchronously)
{
if (this.isCompleted)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.AsyncResultCompletedTwice(GetType())));
}
#if DEBUG
this.marker.AsyncResult = null;
this.marker = null;
if (!Fx.FastDebug && completeStack == null)
{
completeStack = new StackTrace();
}
#endif
this.completedSynchronously = completedSynchronously;
if (OnCompleting != null)
{
// Allow exception replacement, like a catch/throw pattern.
try
{
OnCompleting(this, this.exception);
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
this.exception = exception;
}
}
if (completedSynchronously)
{
// If we completedSynchronously, then there's no chance that the manualResetEvent was created so
// we don't need to worry about a ----
Fx.Assert(this.manualResetEvent == null, "No ManualResetEvent should be created for a synchronous AsyncResult.");
this.isCompleted = true;
}
else
{
lock (ThisLock)
{
this.isCompleted = true;
if (this.manualResetEvent != null)
{
this.manualResetEvent.Set();
}
}
}
if (this.callback != null)
{
try
{
if (VirtualCallback != null)
{
VirtualCallback(this.callback, this);
}
else
{
this.callback(this);
}
}
#pragma warning disable 1634
#pragma warning suppress 56500 // transferring exception to another thread
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
throw Fx.Exception.AsError(new CallbackException(InternalSR.AsyncCallbackThrewException, e));
}
#pragma warning restore 1634
}
}
protected void Complete(bool completedSynchronously, Exception exception)
{
this.exception = exception;
Complete(completedSynchronously);
}
static void AsyncCompletionWrapperCallback(IAsyncResult result)
{
if (result == null)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.InvalidNullAsyncResult));
}
if (result.CompletedSynchronously)
{
return;
}
AsyncResult thisPtr = (AsyncResult)result.AsyncState;
if (!thisPtr.OnContinueAsyncCompletion(result))
{
return;
}
AsyncCompletion callback = thisPtr.GetNextCompletion();
if (callback == null)
{
ThrowInvalidAsyncResult(result);
}
bool completeSelf = false;
Exception completionException = null;
try
{
completeSelf = callback(result);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completeSelf = true;
completionException = e;
}
if (completeSelf)
{
thisPtr.Complete(false, completionException);
}
}
// Note: this should be only derived by the TransactedAsyncResult
protected virtual bool OnContinueAsyncCompletion(IAsyncResult result)
{
return true;
}
// Note: this should be used only by the TransactedAsyncResult
protected void SetBeforePrepareAsyncCompletionAction(Action beforePrepareAsyncCompletionAction)
{
this.beforePrepareAsyncCompletionAction = beforePrepareAsyncCompletionAction;
}
// Note: this should be used only by the TransactedAsyncResult
protected void SetCheckSyncValidationFunc(Func<IAsyncResult, bool> checkSyncValidationFunc)
{
this.checkSyncValidationFunc = checkSyncValidationFunc;
}
protected AsyncCallback PrepareAsyncCompletion(AsyncCompletion callback)
{
if (this.beforePrepareAsyncCompletionAction != null)
{
this.beforePrepareAsyncCompletionAction();
}
this.nextAsyncCompletion = callback;
if (AsyncResult.asyncCompletionWrapperCallback == null)
{
AsyncResult.asyncCompletionWrapperCallback = Fx.ThunkCallback(new AsyncCallback(AsyncCompletionWrapperCallback));
}
return AsyncResult.asyncCompletionWrapperCallback;
}
protected bool CheckSyncContinue(IAsyncResult result)
{
AsyncCompletion dummy;
return TryContinueHelper(result, out dummy);
}
protected bool SyncContinue(IAsyncResult result)
{
AsyncCompletion callback;
if (TryContinueHelper(result, out callback))
{
return callback(result);
}
else
{
return false;
}
}
bool TryContinueHelper(IAsyncResult result, out AsyncCompletion callback)
{
if (result == null)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.InvalidNullAsyncResult));
}
callback = null;
if (this.checkSyncValidationFunc != null)
{
if (!this.checkSyncValidationFunc(result))
{
return false;
}
}
else if (!result.CompletedSynchronously)
{
return false;
}
callback = GetNextCompletion();
if (callback == null)
{
ThrowInvalidAsyncResult("Only call Check/SyncContinue once per async operation (once per PrepareAsyncCompletion).");
}
return true;
}
AsyncCompletion GetNextCompletion()
{
AsyncCompletion result = this.nextAsyncCompletion;
this.nextAsyncCompletion = null;
return result;
}
protected static void ThrowInvalidAsyncResult(IAsyncResult result)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.InvalidAsyncResultImplementation(result.GetType())));
}
protected static void ThrowInvalidAsyncResult(string debugText)
{
string message = InternalSR.InvalidAsyncResultImplementationGeneric;
if (debugText != null)
{
#if DEBUG
message += " " + debugText;
#endif
}
throw Fx.Exception.AsError(new InvalidOperationException(message));
}
[Fx.Tag.Blocking(Conditional = "!asyncResult.isCompleted")]
protected static TAsyncResult End<TAsyncResult>(IAsyncResult result)
where TAsyncResult : AsyncResult
{
if (result == null)
{
throw Fx.Exception.ArgumentNull("result");
}
TAsyncResult asyncResult = result as TAsyncResult;
if (asyncResult == null)
{
throw Fx.Exception.Argument("result", InternalSR.InvalidAsyncResult);
}
if (asyncResult.endCalled)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.AsyncResultAlreadyEnded));
}
#if DEBUG
if (!Fx.FastDebug && asyncResult.endStack == null)
{
asyncResult.endStack = new StackTrace();
}
#endif
asyncResult.endCalled = true;
if (!asyncResult.isCompleted)
{
asyncResult.AsyncWaitHandle.WaitOne();
}
if (asyncResult.manualResetEvent != null)
{
asyncResult.manualResetEvent.Close();
}
if (asyncResult.exception != null)
{
throw Fx.Exception.AsError(asyncResult.exception);
}
return asyncResult;
}
// can be utilized by subclasses to write core completion code for both the [....] and async paths
// in one location, signalling chainable synchronous completion with the boolean result,
// and leveraging PrepareAsyncCompletion for conversion to an AsyncCallback.
// NOTE: requires that "this" is passed in as the state object to the asynchronous sub-call being used with a completion routine.
protected delegate bool AsyncCompletion(IAsyncResult result);
#if DEBUG
class UncompletedAsyncResultMarker
{
public UncompletedAsyncResultMarker(AsyncResult result)
{
AsyncResult = result;
}
[SuppressMessage(FxCop.Category.Performance, FxCop.Rule.AvoidUncalledPrivateCode,
Justification = "Debug-only facility")]
public AsyncResult AsyncResult { get; set; }
}
#endif
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\TextRenderComponent.h:44
namespace UnrealEngine
{
[ManageType("ManageTextRenderComponent")]
public partial class ManageTextRenderComponent : UTextRenderComponent, IManageWrapper
{
public ManageTextRenderComponent(IntPtr adress)
: base(adress)
{
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_OnComponentCollisionSettingsChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_PutAllRigidBodiesToSleep(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_SetAllMassScale(IntPtr self, float inMassScale);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_SetAllUseCCD(IntPtr self, bool inUseCCD);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_SetAngularDamping(IntPtr self, float inDamping);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_SetEnableGravity(IntPtr self, bool bGravityEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_SetLinearDamping(IntPtr self, float inDamping);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_SetNotifyRigidBodyCollision(IntPtr self, bool bNewNotifyRigidBodyCollision);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_SetSimulatePhysics(IntPtr self, bool bSimulate);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_UnWeldChildren(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_UnWeldFromParent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_UpdatePhysicsToRBChannels(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_WakeAllRigidBodies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_DetachFromParent(IntPtr self, bool bMaintainWorldPosition, bool bCallModify);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_OnAttachmentChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_OnHiddenInGameChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_OnVisibilityChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_PropagateLightingScenarioChange(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_UpdateBounds(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_UpdatePhysicsVolume(IntPtr self, bool bTriggerNotifiers);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_Activate(IntPtr self, bool bReset);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_BeginPlay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_CreateRenderState_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_Deactivate(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_DestroyComponent(IntPtr self, bool bPromoteChildren);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_DestroyRenderState_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_InitializeComponent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_InvalidateLightingCacheDetailed(IntPtr self, bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_OnActorEnableCollisionChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_OnComponentCreated(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_OnComponentDestroyed(IntPtr self, bool bDestroyingHierarchy);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_OnCreatePhysicsState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_OnDestroyPhysicsState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_OnRegister(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_OnRep_IsActive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_OnUnregister(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_RegisterComponentTickFunctions(IntPtr self, bool bRegister);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_SendRenderDynamicData_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_SendRenderTransform_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_SetActive(IntPtr self, bool bNewActive, bool bReset);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_SetAutoActivate(IntPtr self, bool bNewAutoActivate);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_SetComponentTickEnabled(IntPtr self, bool bEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_SetComponentTickEnabledAsync(IntPtr self, bool bEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_ToggleActive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_UninitializeComponent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_BeginDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_FinishDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_MarkAsEditorOnlySubobject(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_PostCDOContruct(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_PostEditImport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_PostInitProperties(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_PostLoad(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_PostNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_PostRepNotifies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_PostSaveRoot(IntPtr self, bool bCleanupIsRequired);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_PreDestroyFromReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_PreNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_ShutdownAfterError(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_CreateCluster(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UTextRenderComponent_OnClusterMarkedAsPendingKill(IntPtr self);
#endregion
#region Methods
/// <summary>
/// Called when the BodyInstance ResponseToChannels, CollisionEnabled or bNotifyRigidBodyCollision changes, in case subclasses want to use that information.
/// </summary>
protected override void OnComponentCollisionSettingsChanged()
=> E__Supper__UTextRenderComponent_OnComponentCollisionSettingsChanged(this);
/// <summary>
/// Force all bodies in this component to sleep.
/// </summary>
public override void PutAllRigidBodiesToSleep()
=> E__Supper__UTextRenderComponent_PutAllRigidBodiesToSleep(this);
/// <summary>
/// Change the mass scale used fo all bodies in this component
/// </summary>
public override void SetAllMassScale(float inMassScale)
=> E__Supper__UTextRenderComponent_SetAllMassScale(this, inMassScale);
/// <summary>
/// Set whether all bodies in this component should use Continuous Collision Detection
/// </summary>
public override void SetAllUseCCD(bool inUseCCD)
=> E__Supper__UTextRenderComponent_SetAllUseCCD(this, inUseCCD);
/// <summary>
/// Sets the angular damping of this component.
/// </summary>
public override void SetAngularDamping(float inDamping)
=> E__Supper__UTextRenderComponent_SetAngularDamping(this, inDamping);
/// <summary>
/// Enables/disables whether this component is affected by gravity. This applies only to components with bSimulatePhysics set to true.
/// </summary>
public override void SetEnableGravity(bool bGravityEnabled)
=> E__Supper__UTextRenderComponent_SetEnableGravity(this, bGravityEnabled);
/// <summary>
/// Sets the linear damping of this component.
/// </summary>
public override void SetLinearDamping(float inDamping)
=> E__Supper__UTextRenderComponent_SetLinearDamping(this, inDamping);
/// <summary>
/// Changes the value of bNotifyRigidBodyCollision
/// </summary>
public override void SetNotifyRigidBodyCollision(bool bNewNotifyRigidBodyCollision)
=> E__Supper__UTextRenderComponent_SetNotifyRigidBodyCollision(this, bNewNotifyRigidBodyCollision);
/// <summary>
/// Sets whether or not a single body should use physics simulation, or should be 'fixed' (kinematic).
/// <para>Note that if this component is currently attached to something, beginning simulation will detach it. </para>
/// </summary>
/// <param name="bSimulate">New simulation state for single body</param>
public override void SetSimulatePhysics(bool bSimulate)
=> E__Supper__UTextRenderComponent_SetSimulatePhysics(this, bSimulate);
/// <summary>
/// Unwelds the children of this component. Attachment is maintained
/// </summary>
public override void UnWeldChildren()
=> E__Supper__UTextRenderComponent_UnWeldChildren(this);
/// <summary>
/// UnWelds this component from its parent component. Attachment is maintained (DetachFromParent automatically unwelds)
/// </summary>
public override void UnWeldFromParent()
=> E__Supper__UTextRenderComponent_UnWeldFromParent(this);
/// <summary>
/// Internal function that updates physics objects to match the component collision settings.
/// </summary>
protected override void UpdatePhysicsToRBChannels()
=> E__Supper__UTextRenderComponent_UpdatePhysicsToRBChannels(this);
/// <summary>
/// Ensure simulation is running for all bodies in this component.
/// </summary>
public override void WakeAllRigidBodies()
=> E__Supper__UTextRenderComponent_WakeAllRigidBodies(this);
/// <summary>
/// DEPRECATED - Use DetachFromComponent() instead
/// </summary>
public override void DetachFromParentDeprecated(bool bMaintainWorldPosition, bool bCallModify)
=> E__Supper__UTextRenderComponent_DetachFromParent(this, bMaintainWorldPosition, bCallModify);
/// <summary>
/// Called when AttachParent changes, to allow the scene to update its attachment state.
/// </summary>
public override void OnAttachmentChanged()
=> E__Supper__UTextRenderComponent_OnAttachmentChanged(this);
/// <summary>
/// Overridable internal function to respond to changes in the hidden in game value of the component.
/// </summary>
protected override void OnHiddenInGameChanged()
=> E__Supper__UTextRenderComponent_OnHiddenInGameChanged(this);
/// <summary>
/// Overridable internal function to respond to changes in the visibility of the component.
/// </summary>
protected override void OnVisibilityChanged()
=> E__Supper__UTextRenderComponent_OnVisibilityChanged(this);
/// <summary>
/// Updates any visuals after the lighting has changed
/// </summary>
public override void PropagateLightingScenarioChange()
=> E__Supper__UTextRenderComponent_PropagateLightingScenarioChange(this);
/// <summary>
/// Update the Bounds of the component.
/// </summary>
public override void UpdateBounds()
=> E__Supper__UTextRenderComponent_UpdateBounds(this);
/// <summary>
/// Updates the PhysicsVolume of this SceneComponent, if bShouldUpdatePhysicsVolume is true.
/// </summary>
/// <param name="bTriggerNotifiers">if true, send zone/volume change events</param>
public override void UpdatePhysicsVolume(bool bTriggerNotifiers)
=> E__Supper__UTextRenderComponent_UpdatePhysicsVolume(this, bTriggerNotifiers);
/// <summary>
/// Activates the SceneComponent, should be overridden by native child classes.
/// </summary>
/// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param>
public override void Activate(bool bReset)
=> E__Supper__UTextRenderComponent_Activate(this, bReset);
/// <summary>
/// BeginsPlay for the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component).
/// <para>All Components (that want initialization) in the level will be Initialized on load before any </para>
/// Actor/Component gets BeginPlay.
/// <para>Requires component to be registered and initialized. </para>
/// </summary>
public override void BeginPlay()
=> E__Supper__UTextRenderComponent_BeginPlay(this);
/// <summary>
/// Used to create any rendering thread information for this component
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void CreateRenderState_Concurrent()
=> E__Supper__UTextRenderComponent_CreateRenderState_Concurrent(this);
/// <summary>
/// Deactivates the SceneComponent.
/// </summary>
public override void Deactivate()
=> E__Supper__UTextRenderComponent_Deactivate(this);
/// <summary>
/// Unregister the component, remove it from its outer Actor's Components array and mark for pending kill.
/// </summary>
public override void DestroyComponent(bool bPromoteChildren)
=> E__Supper__UTextRenderComponent_DestroyComponent(this, bPromoteChildren);
/// <summary>
/// Used to shut down any rendering thread structure for this component
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void DestroyRenderState_Concurrent()
=> E__Supper__UTextRenderComponent_DestroyRenderState_Concurrent(this);
/// <summary>
/// Initializes the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component).
/// <para>All Components in the level will be Initialized on load before any Actor/Component gets BeginPlay </para>
/// Requires component to be registered, and bWantsInitializeComponent to be true.
/// </summary>
public override void InitializeComponent()
=> E__Supper__UTextRenderComponent_InitializeComponent(this);
/// <summary>
/// Called when this actor component has moved, allowing it to discard statically cached lighting information.
/// </summary>
public override void InvalidateLightingCacheDetailed(bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly)
=> E__Supper__UTextRenderComponent_InvalidateLightingCacheDetailed(this, bInvalidateBuildEnqueuedLighting, bTranslationOnly);
/// <summary>
/// Called on each component when the Actor's bEnableCollisionChanged flag changes
/// </summary>
public override void OnActorEnableCollisionChanged()
=> E__Supper__UTextRenderComponent_OnActorEnableCollisionChanged(this);
/// <summary>
/// Called when a component is created (not loaded). This can happen in the editor or during gameplay
/// </summary>
public override void OnComponentCreated()
=> E__Supper__UTextRenderComponent_OnComponentCreated(this);
/// <summary>
/// Called when a component is destroyed
/// </summary>
/// <param name="bDestroyingHierarchy">True if the entire component hierarchy is being torn down, allows avoiding expensive operations</param>
public override void OnComponentDestroyed(bool bDestroyingHierarchy)
=> E__Supper__UTextRenderComponent_OnComponentDestroyed(this, bDestroyingHierarchy);
/// <summary>
/// Used to create any physics engine information for this component
/// </summary>
protected override void OnCreatePhysicsState()
=> E__Supper__UTextRenderComponent_OnCreatePhysicsState(this);
/// <summary>
/// Used to shut down and physics engine structure for this component
/// </summary>
protected override void OnDestroyPhysicsState()
=> E__Supper__UTextRenderComponent_OnDestroyPhysicsState(this);
/// <summary>
/// Called when a component is registered, after Scene is set, but before CreateRenderState_Concurrent or OnCreatePhysicsState are called.
/// </summary>
protected override void OnRegister()
=> E__Supper__UTextRenderComponent_OnRegister(this);
public override void OnRep_IsActive()
=> E__Supper__UTextRenderComponent_OnRep_IsActive(this);
/// <summary>
/// Called when a component is unregistered. Called after DestroyRenderState_Concurrent and OnDestroyPhysicsState are called.
/// </summary>
protected override void OnUnregister()
=> E__Supper__UTextRenderComponent_OnUnregister(this);
/// <summary>
/// Virtual call chain to register all tick functions
/// </summary>
/// <param name="bRegister">true to register, false, to unregister</param>
protected override void RegisterComponentTickFunctions(bool bRegister)
=> E__Supper__UTextRenderComponent_RegisterComponentTickFunctions(this, bRegister);
/// <summary>
/// Called to send dynamic data for this component to the rendering thread
/// </summary>
protected override void SendRenderDynamicData_Concurrent()
=> E__Supper__UTextRenderComponent_SendRenderDynamicData_Concurrent(this);
/// <summary>
/// Called to send a transform update for this component to the rendering thread
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void SendRenderTransform_Concurrent()
=> E__Supper__UTextRenderComponent_SendRenderTransform_Concurrent(this);
/// <summary>
/// Sets whether the component is active or not
/// </summary>
/// <param name="bNewActive">The new active state of the component</param>
/// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param>
public override void SetActive(bool bNewActive, bool bReset)
=> E__Supper__UTextRenderComponent_SetActive(this, bNewActive, bReset);
/// <summary>
/// Sets whether the component should be auto activate or not. Only safe during construction scripts.
/// </summary>
/// <param name="bNewAutoActivate">The new auto activate state of the component</param>
public override void SetAutoActivate(bool bNewAutoActivate)
=> E__Supper__UTextRenderComponent_SetAutoActivate(this, bNewAutoActivate);
/// <summary>
/// Set this component's tick functions to be enabled or disabled. Only has an effect if the function is registered
/// </summary>
/// <param name="bEnabled">Whether it should be enabled or not</param>
public override void SetComponentTickEnabled(bool bEnabled)
=> E__Supper__UTextRenderComponent_SetComponentTickEnabled(this, bEnabled);
/// <summary>
/// Spawns a task on GameThread that will call SetComponentTickEnabled
/// </summary>
/// <param name="bEnabled">Whether it should be enabled or not</param>
public override void SetComponentTickEnabledAsync(bool bEnabled)
=> E__Supper__UTextRenderComponent_SetComponentTickEnabledAsync(this, bEnabled);
/// <summary>
/// Toggles the active state of the component
/// </summary>
public override void ToggleActive()
=> E__Supper__UTextRenderComponent_ToggleActive(this);
/// <summary>
/// Handle this component being Uninitialized.
/// <para>Called from AActor::EndPlay only if bHasBeenInitialized is true </para>
/// </summary>
public override void UninitializeComponent()
=> E__Supper__UTextRenderComponent_UninitializeComponent(this);
/// <summary>
/// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an
/// <para>asynchronous cleanup process. </para>
/// </summary>
public override void BeginDestroy()
=> E__Supper__UTextRenderComponent_BeginDestroy(this);
/// <summary>
/// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed.
/// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para>
/// </summary>
public override void FinishDestroy()
=> E__Supper__UTextRenderComponent_FinishDestroy(this);
/// <summary>
/// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds
/// </summary>
public override void MarkAsEditorOnlySubobject()
=> E__Supper__UTextRenderComponent_MarkAsEditorOnlySubobject(this);
/// <summary>
/// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion
/// <para>in the construction of the default materials </para>
/// </summary>
public override void PostCDOContruct()
=> E__Supper__UTextRenderComponent_PostCDOContruct(this);
/// <summary>
/// Called after importing property values for this object (paste, duplicate or .t3d import)
/// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para>
/// are unsupported by the script serialization
/// </summary>
public override void PostEditImport()
=> E__Supper__UTextRenderComponent_PostEditImport(this);
/// <summary>
/// Called after the C++ constructor and after the properties have been initialized, including those loaded from config.
/// <para>This is called before any serialization or other setup has happened. </para>
/// </summary>
public override void PostInitProperties()
=> E__Supper__UTextRenderComponent_PostInitProperties(this);
/// <summary>
/// Do any object-specific cleanup required immediately after loading an object.
/// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para>
/// </summary>
public override void PostLoad()
=> E__Supper__UTextRenderComponent_PostLoad(this);
/// <summary>
/// Called right after receiving a bunch
/// </summary>
public override void PostNetReceive()
=> E__Supper__UTextRenderComponent_PostNetReceive(this);
/// <summary>
/// Called right after calling all OnRep notifies (called even when there are no notifies)
/// </summary>
public override void PostRepNotifies()
=> E__Supper__UTextRenderComponent_PostRepNotifies(this);
/// <summary>
/// Called from within SavePackage on the passed in base/root object.
/// <para>This function is called after the package has been saved and can perform cleanup. </para>
/// </summary>
/// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param>
public override void PostSaveRoot(bool bCleanupIsRequired)
=> E__Supper__UTextRenderComponent_PostSaveRoot(this, bCleanupIsRequired);
/// <summary>
/// Called right before being marked for destruction due to network replication
/// </summary>
public override void PreDestroyFromReplication()
=> E__Supper__UTextRenderComponent_PreDestroyFromReplication(this);
/// <summary>
/// Called right before receiving a bunch
/// </summary>
public override void PreNetReceive()
=> E__Supper__UTextRenderComponent_PreNetReceive(this);
/// <summary>
/// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources.
/// </summary>
public override void ShutdownAfterError()
=> E__Supper__UTextRenderComponent_ShutdownAfterError(this);
/// <summary>
/// Called after PostLoad to create UObject cluster
/// </summary>
public override void CreateCluster()
=> E__Supper__UTextRenderComponent_CreateCluster(this);
/// <summary>
/// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it.
/// </summary>
public override void OnClusterMarkedAsPendingKill()
=> E__Supper__UTextRenderComponent_OnClusterMarkedAsPendingKill(this);
#endregion
public static implicit operator IntPtr(ManageTextRenderComponent self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator ManageTextRenderComponent(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<ManageTextRenderComponent>(PtrDesc);
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using i16 = System.Int16;
using u8 = System.Byte;
using u16 = System.UInt16;
namespace Community.CsharpSqlite
{
using sqlite3_value = Sqlite3.Mem;
public partial class Sqlite3
{
/*
** 2005 May 23
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains functions used to access the internal hash tables
** of user defined functions and collation sequences.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
**
*************************************************************************
*/
//#include "sqliteInt.h"
/*
** Invoke the 'collation needed' callback to request a collation sequence
** in the encoding enc of name zName, length nName.
*/
static void callCollNeeded( sqlite3 db, int enc, string zName )
{
Debug.Assert( db.xCollNeeded == null || db.xCollNeeded16 == null );
if ( db.xCollNeeded != null )
{
string zExternal = zName;// sqlite3DbStrDup(db, zName);
if ( zExternal == null )
return;
db.xCollNeeded( db.pCollNeededArg, db, enc, zExternal );
sqlite3DbFree( db, ref zExternal );
}
#if !SQLITE_OMIT_UTF16
if( db.xCollNeeded16!=null ){
string zExternal;
sqlite3_value pTmp = sqlite3ValueNew(db);
sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
if( zExternal!="" ){
db.xCollNeeded16( db.pCollNeededArg, db, db.aDbStatic[0].pSchema.enc, zExternal );//(int)ENC(db), zExternal);
}
sqlite3ValueFree(ref pTmp);
}
#endif
}
/*
** This routine is called if the collation factory fails to deliver a
** collation function in the best encoding but there may be other versions
** of this collation function (for other text encodings) available. Use one
** of these instead if they exist. Avoid a UTF-8 <. UTF-16 conversion if
** possible.
*/
static int synthCollSeq( sqlite3 db, CollSeq pColl )
{
CollSeq pColl2;
string z = pColl.zName;
int i;
byte[] aEnc = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
for ( i = 0; i < 3; i++ )
{
pColl2 = sqlite3FindCollSeq( db, aEnc[i], z, 0 );
if ( pColl2.xCmp != null )
{
pColl = pColl2.Copy(); //memcpy(pColl, pColl2, sizeof(CollSeq));
pColl.xDel = null; /* Do not copy the destructor */
return SQLITE_OK;
}
}
return SQLITE_ERROR;
}
/*
** This function is responsible for invoking the collation factory callback
** or substituting a collation sequence of a different encoding when the
** requested collation sequence is not available in the desired encoding.
**
** If it is not NULL, then pColl must point to the database native encoding
** collation sequence with name zName, length nName.
**
** The return value is either the collation sequence to be used in database
** db for collation type name zName, length nName, or NULL, if no collation
** sequence can be found.
**
** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
*/
static CollSeq sqlite3GetCollSeq(
sqlite3 db, /* The database connection */
u8 enc, /* The desired encoding for the collating sequence */
CollSeq pColl, /* Collating sequence with native encoding, or NULL */
string zName /* Collating sequence name */
)
{
CollSeq p;
p = pColl;
if ( p == null )
{
p = sqlite3FindCollSeq( db, enc, zName, 0 );
}
if ( p == null || p.xCmp == null )
{
/* No collation sequence of this type for this encoding is registered.
** Call the collation factory to see if it can supply us with one.
*/
callCollNeeded( db, enc, zName );
p = sqlite3FindCollSeq( db, enc, zName, 0 );
}
if ( p != null && p.xCmp == null && synthCollSeq( db, p ) != 0 )
{
p = null;
}
Debug.Assert( p == null || p.xCmp != null );
return p;
}
/*
** This routine is called on a collation sequence before it is used to
** check that it is defined. An undefined collation sequence exists when
** a database is loaded that contains references to collation sequences
** that have not been defined by sqlite3_create_collation() etc.
**
** If required, this routine calls the 'collation needed' callback to
** request a definition of the collating sequence. If this doesn't work,
** an equivalent collating sequence that uses a text encoding different
** from the main database is substituted, if one is available.
*/
static int sqlite3CheckCollSeq( Parse pParse, CollSeq pColl )
{
if ( pColl != null )
{
string zName = pColl.zName;
sqlite3 db = pParse.db;
CollSeq p = sqlite3GetCollSeq( db, ENC( db ), pColl, zName );
if ( null == p )
{
sqlite3ErrorMsg( pParse, "no such collation sequence: %s", zName );
pParse.nErr++;
return SQLITE_ERROR;
}
//
//Debug.Assert(p == pColl);
if ( p != pColl ) // Had to lookup appropriate sequence
{
pColl.enc = p.enc;
pColl.pUser = p.pUser;
pColl.type = p.type;
pColl.xCmp = p.xCmp;
pColl.xDel = p.xDel;
}
}
return SQLITE_OK;
}
/*
** Locate and return an entry from the db.aCollSeq hash table. If the entry
** specified by zName and nName is not found and parameter 'create' is
** true, then create a new entry. Otherwise return NULL.
**
** Each pointer stored in the sqlite3.aCollSeq hash table contains an
** array of three CollSeq structures. The first is the collation sequence
** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
**
** Stored immediately after the three collation sequences is a copy of
** the collation sequence name. A pointer to this string is stored in
** each collation sequence structure.
*/
static CollSeq[] findCollSeqEntry(
sqlite3 db, /* Database connection */
string zName, /* Name of the collating sequence */
int create /* Create a new entry if true */
)
{
CollSeq[] pColl;
int nName = sqlite3Strlen30( zName );
pColl = sqlite3HashFind( db.aCollSeq, zName, nName, (CollSeq[])null );
if ( ( null == pColl ) && create != 0 )
{
pColl = new CollSeq[3]; //sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
if ( pColl != null )
{
CollSeq pDel = null;
pColl[0] = new CollSeq();
pColl[0].zName = zName;
pColl[0].enc = SQLITE_UTF8;
pColl[1] = new CollSeq();
pColl[1].zName = zName;
pColl[1].enc = SQLITE_UTF16LE;
pColl[2] = new CollSeq();
pColl[2].zName = zName;
pColl[2].enc = SQLITE_UTF16BE;
//memcpy(pColl[0].zName, zName, nName);
//pColl[0].zName[nName] = 0;
CollSeq[] pDelArray = sqlite3HashInsert( ref db.aCollSeq, pColl[0].zName, nName, pColl );
if ( pDelArray != null )
pDel = pDelArray[0];
/* If a malloc() failure occurred in sqlite3HashInsert(), it will
** return the pColl pointer to be deleted (because it wasn't added
** to the hash table).
*/
Debug.Assert( pDel == null || pDel == pColl[0] );
if ( pDel != null )
{
//// db.mallocFailed = 1;
pDel = null; //was sqlite3DbFree(db,ref pDel);
pColl = null;
}
}
}
return pColl;
}
/*
** Parameter zName points to a UTF-8 encoded string nName bytes long.
** Return the CollSeq* pointer for the collation sequence named zName
** for the encoding 'enc' from the database 'db'.
**
** If the entry specified is not found and 'create' is true, then create a
** new entry. Otherwise return NULL.
**
** A separate function sqlite3LocateCollSeq() is a wrapper around
** this routine. sqlite3LocateCollSeq() invokes the collation factory
** if necessary and generates an error message if the collating sequence
** cannot be found.
**
** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
*/
static CollSeq sqlite3FindCollSeq(
sqlite3 db,
u8 enc,
string zName,
u8 create
)
{
CollSeq[] pColl;
if ( zName != null )
{
pColl = findCollSeqEntry( db, zName, create );
}
else
{
pColl = new CollSeq[enc];
pColl[enc - 1] = db.pDfltColl;
}
Debug.Assert( SQLITE_UTF8 == 1 && SQLITE_UTF16LE == 2 && SQLITE_UTF16BE == 3 );
Debug.Assert( enc >= SQLITE_UTF8 && enc <= SQLITE_UTF16BE );
if ( pColl != null )
{
enc -= 1; // if (pColl != null) pColl += enc - 1;
return pColl[enc];
}
else
return null;
}
/* During the search for the best function definition, this procedure
** is called to test how well the function passed as the first argument
** matches the request for a function with nArg arguments in a system
** that uses encoding enc. The value returned indicates how well the
** request is matched. A higher value indicates a better match.
**
** The returned value is always between 0 and 6, as follows:
**
** 0: Not a match, or if nArg<0 and the function is has no implementation.
** 1: A variable arguments function that prefers UTF-8 when a UTF-16
** encoding is requested, or vice versa.
** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
** requested, or vice versa.
** 3: A variable arguments function using the same text encoding.
** 4: A function with the exact number of arguments requested that
** prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
** 5: A function with the exact number of arguments requested that
** prefers UTF-16LE when UTF-16BE is requested, or vice versa.
** 6: An exact match.
**
*/
static int matchQuality( FuncDef p, int nArg, int enc )
{
int match = 0;
if ( p.nArg == -1 || p.nArg == nArg
|| ( nArg == -1 && ( p.xFunc != null || p.xStep != null ) )
)
{
match = 1;
if ( p.nArg == nArg || nArg == -1 )
{
match = 4;
}
if ( enc == p.iPrefEnc )
{
match += 2;
}
else if ( ( enc == SQLITE_UTF16LE && p.iPrefEnc == SQLITE_UTF16BE ) ||
( enc == SQLITE_UTF16BE && p.iPrefEnc == SQLITE_UTF16LE ) )
{
match += 1;
}
}
return match;
}
/*
** Search a FuncDefHash for a function with the given name. Return
** a pointer to the matching FuncDef if found, or 0 if there is no match.
*/
static FuncDef functionSearch(
FuncDefHash pHash, /* Hash table to search */
int h, /* Hash of the name */
string zFunc, /* Name of function */
int nFunc /* Number of bytes in zFunc */
)
{
FuncDef p;
for ( p = pHash.a[h]; p != null; p = p.pHash )
{
if ( p.zName.Length == nFunc && p.zName.StartsWith( zFunc, StringComparison.OrdinalIgnoreCase ) )
{
return p;
}
}
return null;
}
/*
** Insert a new FuncDef into a FuncDefHash hash table.
*/
static void sqlite3FuncDefInsert(
FuncDefHash pHash, /* The hash table into which to insert */
FuncDef pDef /* The function definition to insert */
)
{
FuncDef pOther;
int nName = sqlite3Strlen30( pDef.zName );
u8 c1 = (u8)pDef.zName[0];
int h = ( sqlite3UpperToLower[c1] + nName ) % ArraySize( pHash.a );
pOther = functionSearch( pHash, h, pDef.zName, nName );
if ( pOther != null )
{
Debug.Assert( pOther != pDef && pOther.pNext != pDef );
pDef.pNext = pOther.pNext;
pOther.pNext = pDef;
}
else
{
pDef.pNext = null;
pDef.pHash = pHash.a[h];
pHash.a[h] = pDef;
}
}
/*
** Locate a user function given a name, a number of arguments and a flag
** indicating whether the function prefers UTF-16 over UTF-8. Return a
** pointer to the FuncDef structure that defines that function, or return
** NULL if the function does not exist.
**
** If the createFlag argument is true, then a new (blank) FuncDef
** structure is created and liked into the "db" structure if a
** no matching function previously existed. When createFlag is true
** and the nArg parameter is -1, then only a function that accepts
** any number of arguments will be returned.
**
** If createFlag is false and nArg is -1, then the first valid
** function found is returned. A function is valid if either xFunc
** or xStep is non-zero.
**
** If createFlag is false, then a function with the required name and
** number of arguments may be returned even if the eTextRep flag does not
** match that requested.
*/
static FuncDef sqlite3FindFunction(
sqlite3 db, /* An open database */
string zName, /* Name of the function. Not null-terminated */
int nName, /* Number of characters in the name */
int nArg, /* Number of arguments. -1 means any number */
u8 enc, /* Preferred text encoding */
u8 createFlag /* Create new entry if true and does not otherwise exist */
)
{
FuncDef p; /* Iterator variable */
FuncDef pBest = null; /* Best match found so far */
int bestScore = 0;
int h; /* Hash value */
Debug.Assert( enc == SQLITE_UTF8 || enc == SQLITE_UTF16LE || enc == SQLITE_UTF16BE );
h = ( sqlite3UpperToLower[(u8)zName[0]] + nName ) % ArraySize( db.aFunc.a );
/* First search for a match amongst the application-defined functions.
*/
p = functionSearch( db.aFunc, h, zName, nName );
while ( p != null )
{
int score = matchQuality( p, nArg, enc );
if ( score > bestScore )
{
pBest = p;
bestScore = score;
}
p = p.pNext;
}
/* If no match is found, search the built-in functions.
**
** If the SQLITE_PreferBuiltin flag is set, then search the built-in
** functions even if a prior app-defined function was found. And give
** priority to built-in functions.
**
** Except, if createFlag is true, that means that we are trying to
** install a new function. Whatever FuncDef structure is returned it will
** have fields overwritten with new information appropriate for the
** new function. But the FuncDefs for built-in functions are read-only.
** So we must not search for built-ins when creating a new function.
*/
if ( 0 == createFlag && ( pBest == null || ( db.flags & SQLITE_PreferBuiltin ) != 0 ) )
{
#if SQLITE_OMIT_WSD
FuncDefHash pHash = GLOBAL( FuncDefHash, sqlite3GlobalFunctions );
#else
FuncDefHash pHash = sqlite3GlobalFunctions;
#endif
bestScore = 0;
p = functionSearch( pHash, h, zName, nName );
while ( p != null )
{
int score = matchQuality( p, nArg, enc );
if ( score > bestScore )
{
pBest = p;
bestScore = score;
}
p = p.pNext;
}
}
/* If the createFlag parameter is true and the search did not reveal an
** exact match for the name, number of arguments and encoding, then add a
** new entry to the hash table and return it.
*/
if ( createFlag != 0 && ( bestScore < 6 || pBest.nArg != nArg ) &&
( pBest = new FuncDef() ) != null )
{ //sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
//pBest.zName = (char *)&pBest[1];
pBest.nArg = (i16)nArg;
pBest.iPrefEnc = enc;
pBest.zName = zName; //memcpy(pBest.zName, zName, nName);
//pBest.zName[nName] = 0;
sqlite3FuncDefInsert( db.aFunc, pBest );
}
if ( pBest != null && ( pBest.xStep != null || pBest.xFunc != null || createFlag != 0 ) )
{
return pBest;
}
return null;
}
/*
** Free all resources held by the schema structure. The void* argument points
** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
** pointer itself, it just cleans up subsidiary resources (i.e. the contents
** of the schema hash tables).
**
** The Schema.cache_size variable is not cleared.
*/
static void sqlite3SchemaClear( Schema p )
{
Hash temp1;
Hash temp2;
HashElem pElem;
Schema pSchema = p;
temp1 = pSchema.tblHash;
temp2 = pSchema.trigHash;
sqlite3HashInit( pSchema.trigHash );
sqlite3HashClear( pSchema.idxHash );
for ( pElem = sqliteHashFirst( temp2 ); pElem != null; pElem = sqliteHashNext( pElem ) )
{
Trigger pTrigger = (Trigger)sqliteHashData( pElem );
sqlite3DeleteTrigger( null, ref pTrigger );
}
sqlite3HashClear( temp2 );
sqlite3HashInit( pSchema.trigHash );
for ( pElem = temp1.first; pElem != null; pElem = pElem.next )//sqliteHashFirst(&temp1); pElem; pElem = sqliteHashNext(pElem))
{
Table pTab = (Table)pElem.data; //sqliteHashData(pElem);
sqlite3DeleteTable( null, ref pTab );
}
sqlite3HashClear( temp1 );
sqlite3HashClear( pSchema.fkeyHash );
pSchema.pSeqTab = null;
if ( ( pSchema.flags & DB_SchemaLoaded ) != 0 )
{
pSchema.iGeneration++;
pSchema.flags = (u16)( pSchema.flags & ( ~DB_SchemaLoaded ) );
}
p.Clear();
}
/*
** Find and return the schema associated with a BTree. Create
** a new one if necessary.
*/
static Schema sqlite3SchemaGet( sqlite3 db, Btree pBt )
{
Schema p;
if ( pBt != null )
{
p = sqlite3BtreeSchema( pBt, -1, (dxFreeSchema)sqlite3SchemaClear );//Schema.Length, sqlite3SchemaFree);
}
else
{
p = new Schema(); // (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
}
if ( p == null )
{
//// db.mallocFailed = 1;
}
else if ( 0 == p.file_format )
{
sqlite3HashInit( p.tblHash );
sqlite3HashInit( p.idxHash );
sqlite3HashInit( p.trigHash );
sqlite3HashInit( p.fkeyHash );
p.enc = SQLITE_UTF8;
}
return p;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
using Microsoft.Win32;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// This enum is used to distinguish two sets of parameters on some of the remoting cmdlets.
/// </summary>
internal enum RunspaceParameterSet
{
/// <summary>
/// Use ComputerName parameter set.
/// </summary>
ComputerName,
/// <summary>
/// Use Runspace Parameter set.
/// </summary>
Runspace
}
/// <summary>
/// This is a static utility class that performs some of the common chore work for the
/// the remoting cmdlets.
/// </summary>
internal static class RemotingCommandUtil
{
internal static bool HasRepeatingRunspaces(PSSession[] runspaceInfos)
{
if (runspaceInfos == null)
{
throw PSTraceSource.NewArgumentNullException("runspaceInfos");
}
if (runspaceInfos.GetLength(0) == 0)
{
throw PSTraceSource.NewArgumentException("runspaceInfos");
}
for (int i = 0; i < runspaceInfos.GetLength(0); i++)
{
for (int k = 0; k < runspaceInfos.GetLength(0); k++)
{
if (i != k)
{
if (runspaceInfos[i].Runspace.InstanceId == runspaceInfos[k].Runspace.InstanceId)
{
return true;
}
}
}
}
return false;
}
internal static bool ExceedMaximumAllowableRunspaces(PSSession[] runspaceInfos)
{
if (runspaceInfos == null)
{
throw PSTraceSource.NewArgumentNullException("runspaceInfos");
}
if (runspaceInfos.GetLength(0) == 0)
{
throw PSTraceSource.NewArgumentException("runspaceInfos");
}
return false;
}
/// <summary>
/// Checks the prerequisites for a cmdlet and terminates if the cmdlet
/// is not valid.
/// </summary>
internal static void CheckRemotingCmdletPrerequisites()
{
#if UNIX
// TODO: check that PSRP requirements are installed
return;
#else
bool notSupported = true;
string WSManKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\WSMAN\\";
CheckHostRemotingPrerequisites();
try
{
// the following registry key defines WSMan compatability
// HKLM\Software\Microsoft\Windows\CurrentVersion\WSMAN\ServiceStackVersion
string wsManStackValue = null;
RegistryKey wsManKey = Registry.LocalMachine.OpenSubKey(WSManKeyPath);
if (wsManKey != null)
{
wsManStackValue = (string)wsManKey.GetValue("ServiceStackVersion");
}
Version wsManStackVersion = !string.IsNullOrEmpty(wsManStackValue) ?
new Version(wsManStackValue.Trim()) :
System.Management.Automation.Remoting.Client.WSManNativeApi.WSMAN_STACK_VERSION;
// WSMan stack version must be 2.0 or later.
if (wsManStackVersion >= new Version(2, 0))
{
notSupported = false;
}
}
catch (FormatException)
{
notSupported = true;
}
catch (OverflowException)
{
notSupported = true;
}
catch (ArgumentException)
{
notSupported = true;
}
catch (System.Security.SecurityException)
{
notSupported = true;
}
catch (ObjectDisposedException)
{
notSupported = true;
}
if (notSupported)
{
// WSMan is not supported on this platform
throw new InvalidOperationException(
"Windows PowerShell remoting features are not enabled or not supported on this machine.\nThis may be because you do not have the correct version of WS-Management installed or this version of Windows does not support remoting currently.\n For more information, type 'get-help about_remote_requirements'.");
}
#endif
}
/// <summary>
/// Facilitates to check if remoting is supported on the host machine.
/// PowerShell remoting is supported on all Windows SQU's except WinPE.
/// </summary>
/// <exception cref="InvalidOperationException">
/// When PowerShell is hosted on a WinPE machine, the execution
/// of this API would result in an InvalidOperationException being
/// thrown, indicating that remoting is not supported on a WinPE machine.
/// </exception>
internal static void CheckHostRemotingPrerequisites()
{
// A registry key indicates if the SKU is WINPE. If this turns out to be true,
// then an InValidOperation exception is thrown.
bool isWinPEHost = Utils.IsWinPEHost();
if (isWinPEHost)
{
// WSMan is not supported on this platform
// throw new InvalidOperationException(
// "WinPE does not support Windows PowerShell remoting");
ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.WinPERemotingNotSupported)), null, ErrorCategory.InvalidOperation, null);
throw new InvalidOperationException(errorRecord.ToString());
}
}
internal static void CheckPSVersion(Version version)
{
// PSVersion value can only be 2.0, 3.0, 4.0, 5.0, or 5.1
if (version != null)
{
// PSVersion value can only be 2.0, 3.0, 4.0, 5.0, or 5.1
if (!(version.Major >= 2 && version.Major <= 4 && version.Minor == 0) &&
!(version.Major == 5 && version.Minor <= 1))
{
throw new ArgumentException(
StringUtil.Format(RemotingErrorIdStrings.PSVersionParameterOutOfRange, version, "PSVersion"));
}
}
}
/// <summary>
/// Checks if the specified version of PowerShell is installed.
/// </summary>
/// <param name="version"></param>
internal static void CheckIfPowerShellVersionIsInstalled(Version version)
{
// Check if PowerShell 2.0 is installed
if (version != null && version.Major == 2)
{
#if CORECLR
// PowerShell 2.0 is not available for CoreCLR
throw new ArgumentException(
PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.PowerShellNotInstalled,
version, "PSVersion"));
#else
// Because of app-compat issues, in Win8, we will have PS 2.0 installed by default but not .NET 2.0
// In such a case, it is not enough if we check just PowerShell registry keys. We also need to check if .NET 2.0 is installed.
try
{
RegistryKey engineKey = PSSnapInReader.GetPSEngineKey(PSVersionInfo.RegistryVersion1Key);
// Also check for .NET 2.0 installation
if (!PsUtils.FrameworkRegistryInstallation.IsFrameworkInstalled(2, 0, 0))
{
throw new ArgumentException(
PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.NetFrameWorkV2NotInstalled));
}
}
catch (PSArgumentException)
{
throw new ArgumentException(
PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.PowerShellNotInstalled,
version, "PSVersion"));
}
#endif
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ExpressRouteCircuitAuthorizationsOperations operations.
/// </summary>
internal partial class ExpressRouteCircuitAuthorizationsOperations : IServiceOperations<NetworkManagementClient>, IExpressRouteCircuitAuthorizationsOperations
{
/// <summary>
/// Initializes a new instance of the ExpressRouteCircuitAuthorizationsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ExpressRouteCircuitAuthorizationsOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Deletes the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified authorization from the specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> GetWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (authorizationName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("authorizationName", authorizationName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{authorizationName}", System.Uri.EscapeDataString(authorizationName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ExpressRouteCircuitAuthorization>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitAuthorization>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates an authorization in the specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create or update express route circuit
/// authorization operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<ExpressRouteCircuitAuthorization> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the circuit.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>> ListWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ExpressRouteCircuitAuthorization>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (authorizationName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("authorizationName", authorizationName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{authorizationName}", System.Uri.EscapeDataString(authorizationName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates an authorization in the specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create or update express route circuit
/// authorization operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (authorizationName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationName");
}
if (authorizationParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationParameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("authorizationName", authorizationName);
tracingParameters.Add("authorizationParameters", authorizationParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{authorizationName}", System.Uri.EscapeDataString(authorizationName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(authorizationParameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(authorizationParameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ExpressRouteCircuitAuthorization>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitAuthorization>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitAuthorization>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ExpressRouteCircuitAuthorization>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Studio.Core.CorePublic
File: StrategyContainer.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Studio.Core
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Ecng.Collections;
using Ecng.Common;
using Ecng.ComponentModel;
using Ecng.Configuration;
using Ecng.Serialization;
using MoreLinq;
using StockSharp.Algo;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Logging;
using StockSharp.Messages;
using StockSharp.Xaml.PropertyGrid;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;
using StockSharp.Localization;
[DisplayNameLoc(LocalizedStrings.Str3169Key)]
[DescriptionLoc(LocalizedStrings.Str3170Key)]
public class StrategyContainer : Strategy, IStrategyContainer, INotifyPropertiesChanged
{
private const int _defaultHistoryDaysCount = 30;
private readonly HashSet<string> _additionalProperties = new HashSet<string>
{
"HistoryDaysCount"
};
private readonly HashSet<string> _skippedParameters = new HashSet<string>
{
"Id", "Name"
};
private SettingsStorage _storage;
private bool _needRestart;
public StrategyInfo StrategyInfo { get; set; }
public override string Name
{
get { return Strategy != null ? Strategy.Name : base.Name; }
set
{
base.Name = value;
if (Strategy != null)
Strategy.Name = value;
}
}
private Strategy _strategy;
private MarketDataSettings _marketDataSettings;
private SessionType _sessionType;
[Browsable(false)]
public Strategy Strategy
{
get { return _strategy; }
set
{
if (_strategy != null)
{
ChildStrategies.Remove(_strategy);
_strategy.Log -= OnLog;
_strategy.PropertyChanged -= OnPropertyChanged;
_strategy.ProcessStateChanged -= OnProcessStateChanged;
//new ChartClearAreasCommand().Process(Strategy);
StrategyRemoved.SafeInvoke(_strategy);
}
_strategy = value;
if (_strategy == null)
return;
if (_storage != null)
_strategy.Id = _storage.GetValue<Guid>("StrategyContainerId");
var storage = new SettingsStorage
{
{ "Settings", _storage },
{ "Statistics", GetStatistics() },
{ "Orders", GetActiveOrders() },
{ "Positions", PositionManager.Positions.ToArray() },
};
_strategy.NameGenerator.AutoGenerateStrategyName = false;
_strategy.Connector = Connector;
_strategy.SafeLoadState(storage);
ChildStrategies.Add(_strategy);
_strategy.Parent = null;
_strategy.Log += OnLog;
_strategy.PropertyChanged += OnPropertyChanged;
_strategy.ProcessStateChanged += OnProcessStateChanged;
_strategy.ParametersChanged += OnParametersChanged;
_strategy.UnrealizedPnLInterval = UnrealizedPnLInterval;
StrategyAssigned.SafeInvoke(_strategy);
RaiseParametersChanged("Name");
RaisePropertiesChanged();
}
}
public event Action<Strategy> StrategyRemoved;
public event Action<Strategy> StrategyAssigned;
public override Security Security
{
get { return base.Security; }
set
{
base.Security = value;
if (Strategy != null)
Strategy.Security = value;
}
}
public override Portfolio Portfolio
{
get { return base.Portfolio; }
set
{
base.Portfolio = value;
if (Strategy != null)
Strategy.Portfolio = value;
}
}
public override IConnector Connector
{
get { return base.Connector; }
set
{
base.Connector = value;
if (Strategy != null)
Strategy.Connector = value;
}
}
public override ProcessStates ProcessState => Strategy == null ? ProcessStates.Stopped : Strategy.ProcessState;
public override TimeSpan UnrealizedPnLInterval
{
get { return base.UnrealizedPnLInterval; }
set
{
base.UnrealizedPnLInterval = value;
if (Strategy != null)
Strategy.UnrealizedPnLInterval = value;
}
}
public bool NeedRestart
{
get { return _needRestart; }
set
{
_needRestart = value;
this.Notify("NeedRestart");
}
}
public SessionType SessionType
{
get { return _sessionType; }
set
{
_sessionType = value;
if (_sessionType == SessionType.Emulation)
NameGenerator.Pattern += LocalizedStrings.Str3171;
else
NameGenerator.Pattern.TrimEnd(LocalizedStrings.Str3171);
}
}
[CategoryLoc(LocalizedStrings.GeneralKey)]
[DisplayNameLoc(LocalizedStrings.Str3172Key)]
[DescriptionLoc(LocalizedStrings.Str3173Key)]
[PropertyOrder(0)]
public int HistoryDaysCount { get; set; }
public MarketDataSettings MarketDataSettings
{
get { return _marketDataSettings; }
set
{
_marketDataSettings = value;
RaiseParametersChanged("MarketDataSettings");
}
}
public StrategyContainer()
{
HistoryDaysCount = _defaultHistoryDaysCount;
}
private IDictionary<Order, IEnumerable<MyTrade>> GetActiveOrders()
{
return Orders
.Filter(OrderStates.Active)
.ToDictionary(o => o, o => MyTrades.Where(t => t.Order == o));
}
private SettingsStorage GetStatistics()
{
var statistics = new SettingsStorage();
foreach (var parameter in StatisticManager.Parameters)
statistics.SetValue(parameter.Name, parameter.Save());
return statistics;
}
private void OnLog(LogMessage message)
{
if(message.Source == Strategy)
RaiseLog(message);
}
protected override void RaiseLog(LogMessage message)
{
if (message.Source == this && Strategy != null)
return;
base.RaiseLog(message);
}
private void OnProcessStateChanged(Strategy strategy)
{
RaiseProcessStateChanged(strategy);
if (strategy == Strategy)
this.Notify("ProcessState");
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "Security":
Security = Strategy.Security;
break;
case "Portfolio":
Portfolio = Strategy.Portfolio;
break;
case "Name":
RaiseParametersChanged("Name");
break;
}
}
private void OnParametersChanged()
{
RaiseParametersChanged("Strategy");
}
public override void Load(SettingsStorage storage)
{
_storage = storage;
var strategyInfoId = storage.GetValue<long?>("StrategyInfoId");
if (Strategy == null && strategyInfoId != null)
{
StrategyInfo = ConfigManager
.GetService<IStudioEntityRegistry>()
.Strategies.ReadById(strategyInfoId);
this.InitStrategy();
}
if (Strategy != null)
{
Strategy.Id = storage.GetValue<Guid>("StrategyContainerId");
Strategy.Load(storage);
}
var marketDataSettings = storage.GetValue<string>("MarketDataSettings");
if (marketDataSettings != null)
{
var id = marketDataSettings.To<Guid>();
var settings = ConfigManager.GetService<MarketDataSettingsCache>().Settings.FirstOrDefault(s => s.Id == id);
if (settings != null)
MarketDataSettings = settings;
}
HistoryDaysCount = storage.GetValue("HistoryDaysCount", _defaultHistoryDaysCount);
}
public override void Save(SettingsStorage storage)
{
if (Strategy != null)
{
storage.SetValue("StrategyContainerId", Strategy.Id);
storage.SetValue("StrategyInfoId", StrategyInfo.Id);
if (Strategy.Security != null)
storage.SetValue("security", _strategy.Security.Id);
if (Strategy.Portfolio != null)
storage.SetValue("portfolio", _strategy.Portfolio.Name);
Strategy.Save(storage);
}
else if (_storage != null)
{
_storage.ForEach(pair => storage.SetValue(pair.Key, pair.Value));
}
if (MarketDataSettings != null)
storage.SetValue("MarketDataSettings", MarketDataSettings.Id.To<string>());
storage.SetValue("HistoryDaysCount", HistoryDaysCount);
}
public override void Start()
{
if (Strategy == null)
{
this.AddErrorLog(LocalizedStrings.Str3174);
return;
}
Strategy.Environment.Clear();
Strategy.Environment.AddRange(Environment);
var parameters = Parameters.ToDictionary(p => p.Name);
foreach (var strategyParam in Strategy.Parameters)
{
if (_skippedParameters.Contains(strategyParam.Name))
continue;
var tmp = parameters.TryGetValue(strategyParam.Name);
if (tmp != null)
strategyParam.Value = tmp.Value;
}
Strategy.Start();
}
public override void Stop()
{
if (Strategy == null)
{
this.AddErrorLog(LocalizedStrings.Str3174);
return;
}
Strategy.Stop();
if (!NeedRestart)
return;
this.InitStrategy();
NeedRestart = false;
}
public override Strategy Clone()
{
var strategy = (StrategyContainer)base.Clone();
strategy.StrategyInfo = StrategyInfo;
strategy.MarketDataSettings = MarketDataSettings;
strategy.SessionType = SessionType;
if (Strategy != null)
{
strategy.Strategy = Strategy.Clone();
strategy.Strategy.Id = Guid.NewGuid();
}
return strategy;
}
public override void AttachOrder(Order order, IEnumerable<MyTrade> myTrades)
{
Strategy.AttachOrder(order, myTrades);
}
protected override void AssignOrderStrategyId(Order order)
{
order.UserOrderId = this.GetStrategyId().To<string>();
}
#region Implementation of ICustomTypeDescriptor
public String GetClassName()
{
return TypeDescriptor.GetClassName(Strategy, true);
}
public AttributeCollection GetAttributes()
{
return TypeDescriptor.GetAttributes(Strategy, true);
}
public String GetComponentName()
{
return TypeDescriptor.GetComponentName(Strategy, true);
}
public TypeConverter GetConverter()
{
return TypeDescriptor.GetConverter(Strategy ?? this, true);
}
public EventDescriptor GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(Strategy, true);
}
public PropertyDescriptor GetDefaultProperty()
{
return TypeDescriptor.GetDefaultProperty(Strategy, true);
}
public object GetEditor(Type editorBaseType)
{
return TypeDescriptor.GetEditor(Strategy, editorBaseType, true);
}
public EventDescriptorCollection GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(Strategy, attributes, true);
}
public PropertyDescriptorCollection GetProperties()
{
var props = TypeDescriptor
.GetProperties(Strategy)
.OfType<PropertyDescriptor>()
.Where(NeedShowProperty);
var additionalProps = TypeDescriptor
.GetProperties(this, true)
.OfType<PropertyDescriptor>()
.Where(pd => _additionalProperties.Contains(pd.Name));
return new PropertyDescriptorCollection(props.Concat(additionalProps).ToArray());
}
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
return TypeDescriptor.GetProperties(Strategy, attributes);
}
public EventDescriptorCollection GetEvents()
{
return TypeDescriptor.GetEvents(Strategy, true);
}
public object GetPropertyOwner(PropertyDescriptor pd)
{
return _additionalProperties.Contains(pd.Name) ? this : Strategy;
}
private bool NeedShowProperty(PropertyDescriptor pd)
{
if (pd.Category == LocalizedStrings.Str436 || pd.Category == LocalizedStrings.Str1559 || pd.Category == LocalizedStrings.Str3050)
return false;
return true;
}
#endregion
#region INotifyPropertiesChanged
public event Action PropertiesChanged;
protected virtual void RaisePropertiesChanged()
{
PropertiesChanged.SafeInvoke();
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="BlockBasedBlobReader.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.Azure.Storage.DataMovement.TransferControllers
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Storage.Blob;
internal sealed class BlockBasedBlobReader : TransferReaderWriterBase
{
/// <summary>
/// Instance to represent source location.
/// </summary>
private readonly AzureBlobLocation sourceLocation;
/// <summary>
/// Block/append blob instance to be downloaded from.
/// </summary>
private readonly CloudBlob sourceBlob;
/// <summary>
/// Window to record unfinished chunks to be retransferred again.
/// </summary>
private Queue<long> lastTransferWindow;
private readonly TransferJob transferJob;
/// <summary>
/// Value to indicate whether the transfer is finished.
/// This is to tell the caller that the reader can be disposed,
/// Both error happened or completed will be treated to be finished.
/// </summary>
private volatile bool isFinished = false;
/// <summary>
/// Work token indicates whether this reader has work, could be 0(no work) or 1(has work).
/// </summary>
private volatile int workToken;
private volatile bool isStateSwitchedInternal;
private CountdownEvent downloadCountdownEvent;
public BlockBasedBlobReader(
TransferScheduler scheduler,
SyncTransferController controller,
CancellationToken cancellationToken)
: base(scheduler, controller, cancellationToken)
{
this.transferJob = this.SharedTransferData.TransferJob;
this.sourceLocation = this.transferJob.Source as AzureBlobLocation;
this.sourceBlob = this.sourceLocation?.Blob;
Debug.Assert(
(this.sourceBlob is CloudBlockBlob) || (this.sourceBlob is CloudAppendBlob),
"Initializing BlockBlobReader while source location is not a block blob or an append blob.");
this.workToken = 1;
}
public override bool IsFinished
{
get
{
return this.isFinished;
}
}
public override bool HasWork
{
get
{
return this.workToken == 1;
}
}
public override async Task DoWorkInternalAsync()
{
try
{
if (!this.PreProcessed)
{
await this.FetchAttributeAsync();
}
else
{
await this.DownloadBlockBlobAsync();
}
}
catch (Exception)
{
this.isFinished = true;
throw;
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
if (null != this.downloadCountdownEvent)
{
this.downloadCountdownEvent.Dispose();
this.downloadCountdownEvent = null;
}
}
}
private async Task FetchAttributeAsync()
{
if (Interlocked.CompareExchange(ref workToken, 0, 1) == 0)
{
return;
}
await Task.Yield();
this.NotifyStarting();
if (this.sourceLocation.IsInstanceInfoFetched != true)
{
AccessCondition accessCondition = Utils.GenerateIfMatchConditionWithCustomerCondition(
this.sourceLocation.ETag,
this.sourceLocation.AccessCondition,
this.sourceLocation.CheckedAccessCondition);
try
{
await this.sourceBlob.FetchAttributesAsync(
accessCondition,
Utils.GenerateBlobRequestOptions(this.sourceLocation.BlobRequestOptions),
Utils.GenerateOperationContext(this.Controller.TransferContext),
this.CancellationToken).ConfigureAwait(false);
}
#if EXPECT_INTERNAL_WRAPPEDSTORAGEEXCEPTION
catch (Exception ex) when (ex is StorageException || (ex is AggregateException && ex.InnerException is StorageException))
{
var e = ex as StorageException ?? ex.InnerException as StorageException;
#else
catch (StorageException e)
{
#endif
if (null != e.RequestInformation &&
e.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound)
{
throw new InvalidOperationException(Resources.SourceBlobDoesNotExistException, e);
}
else
{
throw;
}
}
}
// Note: If the transfer job's dispatch root is directory transfer, no need to check access condition for source location.
// If the transfer job's dispatch root is single transfer, access condition has been checked if logic reach here.
this.sourceLocation.CheckedAccessCondition = true;
if (this.sourceBlob.Properties.BlobType == BlobType.Unspecified)
{
throw new InvalidOperationException(Resources.FailedToGetBlobTypeException);
}
if (string.IsNullOrEmpty(this.sourceLocation.ETag))
{
if (0 != this.SharedTransferData.TransferJob.CheckPoint.EntryTransferOffset)
{
throw new InvalidOperationException(Resources.RestartableInfoCorruptedException);
}
this.sourceLocation.ETag = this.sourceBlob.Properties.ETag;
}
else if ((this.SharedTransferData.TransferJob.CheckPoint.EntryTransferOffset > this.sourceBlob.Properties.Length)
|| (this.SharedTransferData.TransferJob.CheckPoint.EntryTransferOffset < 0))
{
throw new InvalidOperationException(Resources.RestartableInfoCorruptedException);
}
this.SharedTransferData.DisableContentMD5Validation =
null != this.sourceLocation.BlobRequestOptions ?
this.sourceLocation.BlobRequestOptions.DisableContentMD5Validation.HasValue ?
this.sourceLocation.BlobRequestOptions.DisableContentMD5Validation.Value : false : false;
this.SharedTransferData.TotalLength = this.sourceBlob.Properties.Length;
this.SharedTransferData.Attributes = Utils.GenerateAttributes(this.sourceBlob);
if ((0 == this.SharedTransferData.TransferJob.CheckPoint.EntryTransferOffset)
&& (null != this.SharedTransferData.TransferJob.CheckPoint.TransferWindow)
&& (0 != this.SharedTransferData.TransferJob.CheckPoint.TransferWindow.Count))
{
throw new InvalidOperationException(Resources.RestartableInfoCorruptedException);
}
// Only initialize private queue when TransferWindow is necessary.
if (!this.EnableOneChunkFileOptimization)
{
this.lastTransferWindow = new Queue<long>(this.SharedTransferData.TransferJob.CheckPoint.TransferWindow);
}
int downloadCount = (this.lastTransferWindow == null ? 0 : this.lastTransferWindow.Count) +
(int)Math.Ceiling((double)(this.sourceBlob.Properties.Length - this.SharedTransferData.TransferJob.CheckPoint.EntryTransferOffset) / this.SharedTransferData.BlockSize);
if (0 == downloadCount)
{
this.isFinished = true;
this.PreProcessed = true;
this.workToken = 1;
return;
}
if (this.EnableOneChunkFileOptimization)
{
this.isStateSwitchedInternal = true;
await this.DownloadBlockBlobAsync().ConfigureAwait(false);
this.PreProcessed = true;
}
else
{
this.downloadCountdownEvent = new CountdownEvent(downloadCount);
this.PreProcessed = true; // Note: PreProcessed should be set before workToken, otherwise SyncTransferController would schedule reader again before writer PreProcess
this.workToken = 1;
}
}
private async Task DownloadBlockBlobAsync()
{
if (!this.isStateSwitchedInternal && Interlocked.CompareExchange(ref this.workToken, 0, 1) == 0)
{
return;
}
byte[][] memoryBuffer = this.Scheduler.MemoryManager.RequireBuffers(this.SharedTransferData.MemoryChunksRequiredEachTime);
if (null != memoryBuffer)
{
long startOffset = 0;
// Only multi-chunk file need transfer window calculation.
if (!this.EnableOneChunkFileOptimization)
{
if (!this.IsTransferWindowEmpty())
{
startOffset = this.lastTransferWindow.Dequeue();
}
else
{
bool canUpload = false;
lock (this.transferJob.CheckPoint.TransferWindowLock)
{
if (this.transferJob.CheckPoint.TransferWindow.Count < Constants.MaxCountInTransferWindow)
{
startOffset = this.transferJob.CheckPoint.EntryTransferOffset;
if (this.transferJob.CheckPoint.EntryTransferOffset < this.SharedTransferData.TotalLength)
{
this.transferJob.CheckPoint.TransferWindow.Add(startOffset);
this.transferJob.CheckPoint.EntryTransferOffset = Math.Min(
this.transferJob.CheckPoint.EntryTransferOffset + this.SharedTransferData.BlockSize,
this.SharedTransferData.TotalLength);
canUpload = true;
}
}
}
if (!canUpload)
{
this.workToken = 1;
this.Scheduler.MemoryManager.ReleaseBuffers(memoryBuffer);
return;
}
}
if ((startOffset > this.SharedTransferData.TotalLength)
|| (startOffset < 0))
{
this.Scheduler.MemoryManager.ReleaseBuffers(memoryBuffer);
throw new InvalidOperationException(Resources.RestartableInfoCorruptedException);
}
this.SetBlockDownloadHasWork();
}
ReadDataState asyncState = new ReadDataState
{
MemoryBuffer = memoryBuffer,
BytesRead = 0,
StartOffset = startOffset,
Length = (int)Math.Min(this.SharedTransferData.BlockSize, this.SharedTransferData.TotalLength - startOffset),
MemoryManager = this.Scheduler.MemoryManager,
};
using (asyncState)
{
await this.DownloadChunkAsync(asyncState).ConfigureAwait(false);
}
return;
}
this.SetBlockDownloadHasWork();
}
private async Task DownloadChunkAsync(ReadDataState asyncState)
{
Debug.Assert(null != asyncState, "asyncState object expected");
// Use Yield to return to scheduling main logic immediately, and to improve scheduling efficiency.
if (!this.isStateSwitchedInternal)
{
await Task.Yield();
}
// If a parallel operation caused the controller to be placed in
// error state exit early to avoid unnecessary I/O.
if (this.Controller.ErrorOccurred)
{
return;
}
AccessCondition accessCondition = Utils.GenerateIfMatchConditionWithCustomerCondition(
this.sourceBlob.Properties.ETag,
this.sourceLocation.AccessCondition);
if (asyncState.MemoryBuffer.Length == 1)
{
// We're to download this block.
asyncState.MemoryStream =
new MemoryStream(
asyncState.MemoryBuffer[0],
0,
asyncState.Length);
await this.sourceBlob.DownloadRangeToStreamAsync(
asyncState.MemoryStream,
asyncState.StartOffset,
asyncState.Length,
accessCondition,
Utils.GenerateBlobRequestOptions(this.sourceLocation.BlobRequestOptions),
Utils.GenerateOperationContext(this.Controller.TransferContext),
this.CancellationToken).ConfigureAwait(false);
}
else
{
var blockSize = Constants.DefaultTransferChunkSize; // 4MB
var startOffset = asyncState.StartOffset;
var remainingLength = asyncState.Length;
var index = 0;
do
{
var length = Math.Min(blockSize, remainingLength);
var memoryStream = new MemoryStream(asyncState.MemoryBuffer[index], 0, length);
await this.sourceBlob.DownloadRangeToStreamAsync(
memoryStream,
startOffset,
length,
accessCondition,
Utils.GenerateBlobRequestOptions(this.sourceLocation.BlobRequestOptions),
Utils.GenerateOperationContext(this.Controller.TransferContext),
this.CancellationToken);
index++;
startOffset += length;
remainingLength -= length;
} while (remainingLength > 0);
}
TransferData transferData = new TransferData(this.Scheduler.MemoryManager)
{
StartOffset = asyncState.StartOffset,
Length = asyncState.Length,
MemoryBuffer = asyncState.MemoryBuffer
};
this.SharedTransferData.AvailableData.TryAdd(transferData.StartOffset, transferData);
// Set memory buffer to null. We don't want its dispose method to
// be called once our asyncState is disposed. The memory should
// not be reused yet, we still need to write it to disk.
asyncState.MemoryBuffer = null;
// When there is only one chunk, after read the only chunk, reader's work has finished, no more work to do.
if (this.EnableOneChunkFileOptimization)
{
this.isFinished = true;
}
else
{
this.SetFinish();
this.SetBlockDownloadHasWork();
}
}
private void SetFinish()
{
if (this.downloadCountdownEvent.Signal())
{
this.isFinished = true;
}
}
private void SetBlockDownloadHasWork()
{
if (this.HasWork)
{
return;
}
// Check if we have blocks available to download.
if (!this.IsTransferWindowEmpty()
|| this.transferJob.CheckPoint.EntryTransferOffset < this.SharedTransferData.TotalLength)
{
this.workToken = 1;
return;
}
}
private bool IsTransferWindowEmpty()
{
return null == this.lastTransferWindow || this.lastTransferWindow.Count == 0;
}
}
}
| |
#pragma warning disable 1591
using AjaxControlToolkit.Design;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AjaxControlToolkit {
/// <summary>
/// The Accordion control represents a series of panes that can be viewed
/// one at a time. The control is used to create "strongly typed" access
/// to the AccordionBehavior. Its major purpose is to structure the content
/// in a way that the AccordionBehavior can understand it.
/// </summary>
[Designer(typeof(AccordionDesigner))]
[ToolboxData("<{0}:Accordion runat=server></{0}:Accordion>")]
[ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.AccordionName + Constants.IconPostfix)]
public class Accordion : WebControl {
// ViewState key for tracking the number of panes in the Accordion
internal const string ItemCountViewStateKey = "_!ItemCount";
/// <summary>
/// An event to raise when an item (i.e. Pane's Header or Content) is created during data binding
/// </summary>
public event EventHandler<AccordionItemEventArgs> ItemCreated;
/// <summary>
/// An event to raise when an item (i.e. Pane's Header or Content) is data bound
/// </summary>
public event EventHandler<AccordionItemEventArgs> ItemDataBound;
/// <summary>
/// An event to raise when a command is fired
/// </summary>
public event CommandEventHandler ItemCommand;
// AccordionExtender to attach
AccordionExtender _extender;
// The Accordion's child panes
AccordionPaneCollection _panes;
#region DataBinding Fields
// DataSource to bind the Accordion to
object _dataSource;
// DataBinding template for the header
ITemplate _headerTemplate;
// DataBinding template for the content
ITemplate _contentTemplate;
// Whether or not the control has been initialized
bool _initialized;
// Whether the page's PreLoad event has already fired
bool _pagePreLoadFired;
// Whether or not the Accordion needs to be databound but hasn't been yet
bool _requiresDataBinding;
// Flag to determine if we should throw an exception when a data property
// (i.e. DataSource, DataSourceID, DataMember) is changed
bool _throwOnDataPropertyChange;
// View of the the data provided by the data property
DataSourceView _currentView;
// Whether the current DataSourceView was loaded from a DataSourceID
bool _currentViewIsFromDataSourceID;
// Whether the current DataSourceView contains valid data
bool _currentViewValid;
// Arguments used to sort, filter, etc., the data when creating
// the DataSourceView (although we will use the default whenever possible)
DataSourceSelectArguments _arguments;
// Enumerable list of data items obtained from the DataSource
IEnumerable _selectResult;
// Thread synchronization event used for obtaining data from the DataSource
EventWaitHandle _selectWait;
#endregion
// Default constructor that tells ASP.NET to render it as a DIV
public Accordion()
: base(HtmlTextWriterTag.Div) {
}
// Reference to the AccordionExtender wrapped by the Accordion control.
// This will be referenced in CreateChildControls so that the extender
// will always be created by any calls to EnsureChildControls.
AccordionExtender AccordionExtender {
get {
if(_extender == null) {
// Create the extender
_extender = new AccordionExtender();
_extender.ID = ID + "_AccordionExtender";
_extender.TargetControlID = ID;
Controls.AddAt(0, _extender);
}
return _extender;
}
}
/// <summary>
/// Length of the transition animation in milliseconds. The default is 500
/// </summary>
[Browsable(true)]
[Category("Behavior")]
[Description("Length of the transition animation in milliseconds")]
[DefaultValue(500)]
public int TransitionDuration {
get { return AccordionExtender.TransitionDuration; }
set { AccordionExtender.TransitionDuration = value; }
}
/// <summary>
/// The number of frames per second used in animation effects' transition.
/// This is used to tune performance when using FadeTransition,
/// a large number of Accordion Panes, etc.
/// The default is 30.
/// </summary>
[Browsable(true)]
[Category("Behavior")]
[Description("Number of frames per second used in the transition animation")]
[DefaultValue(30)]
public int FramesPerSecond {
get { return AccordionExtender.FramesPerSecond; }
set { AccordionExtender.FramesPerSecond = value; }
}
/// <summary>
/// Whether or not to use a fade effect when transitioning between selected
/// Accordion Panes. The default is false
/// </summary>
[Browsable(true)]
[Category("Behavior")]
[Description("Whether or not to use a fade effect in the transition animations")]
[DefaultValue(false)]
public bool FadeTransitions {
get { return AccordionExtender.FadeTransitions; }
set { AccordionExtender.FadeTransitions = value; }
}
/// <summary>
/// The default Header CSS class
/// </summary>
[Browsable(true)]
[Category("Appearance")]
[Description("Default CSS class for Accordion Pane Headers")]
public string HeaderCssClass {
get { return AccordionExtender.HeaderCssClass; }
set { AccordionExtender.HeaderCssClass = value; }
}
/// <summary>
/// The default selected Header CSS Class
/// </summary>
[Browsable(true)]
[Category("Appearance")]
[Description("Default CSS class for the selected Accordion Pane Headers")]
public string HeaderSelectedCssClass {
get { return AccordionExtender.HeaderSelectedCssClass; }
set { AccordionExtender.HeaderSelectedCssClass = value; }
}
/// <summary>
/// The default Content CSS class
/// </summary>
[Browsable(true)]
[Category("Appearance")]
[Description("Default CSS class for Accordion Pane Content")]
public string ContentCssClass {
get { return AccordionExtender.ContentCssClass; }
set { AccordionExtender.ContentCssClass = value; }
}
/// <summary>
/// Determines how to controll resizing of the Accordion.
/// If it is set to None, then the Accordion can grow as large or as small as necessary.
/// If it is set to Limit, then the Accordion will always be less than or equal to its Height.
/// If it is set to Fill then it will always be equal to its height.
/// The default is None.
/// </summary>
[Browsable(true)]
[Category("Behavior")]
[Description("Determine how the growth of the Accordion will be controlled")]
[DefaultValue(AutoSize.None)]
public AutoSize AutoSize {
get { return AccordionExtender.AutoSize; }
set { AccordionExtender.AutoSize = value; }
}
/// <summary>
/// Index of the AccordionPane to be displayed
/// (this property must be set before OnPreRender). The default is 0
/// </summary>
[Browsable(true)]
[Category("Behavior")]
[Description("Index of the AccordionPane to be displayed")]
[DefaultValue(0)]
public int SelectedIndex {
get { return AccordionExtender.SelectedIndex; }
set { AccordionExtender.SelectedIndex = value; }
}
/// <summary>
/// Whether or not clicking the header will close the currently opened pane (leaving
/// all the Accordion's panes closed). The default is true
/// </summary>
[Browsable(true)]
[Category("Behavior")]
[Description("Whether or not clicking the header will close the currently opened pane (leaving all the Accordion's panes closed)")]
[DefaultValue(true)]
public bool RequireOpenedPane {
get { return AccordionExtender.RequireOpenedPane; }
set { AccordionExtender.RequireOpenedPane = value; }
}
/// <summary>
/// Whether or not we suppress the client-side click handlers of any elements (including server
/// controls like Button or HTML elements like anchor) in the header sections of the Accordion.
/// The default is false
/// </summary>
[Browsable(true)]
[Category("Behavior")]
[Description("Whether or not we suppress the client-side click handlers of any elements in the header sections")]
[DefaultValue(false)]
public bool SuppressHeaderPostbacks {
get { return AccordionExtender.SuppressHeaderPostbacks; }
set { AccordionExtender.SuppressHeaderPostbacks = value; }
}
/// <summary>
/// A collection of child panes in the Accordion
/// </summary>
[PersistenceMode(PersistenceMode.InnerProperty)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public AccordionPaneCollection Panes {
get {
if(_panes == null)
_panes = new AccordionPaneCollection(this);
return _panes;
}
}
/// <summary>
/// Prevent the Controls property from appearing in the editor (so
/// that people will use the Panes collection instead)
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override ControlCollection Controls {
get { return base.Controls; }
}
#region DataBinding Properties
/// <summary>
/// A template for the Header of databound panes
/// </summary>
[Browsable(false)]
[DefaultValue(null)]
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateContainer(typeof(AccordionContentPanel))]
public virtual ITemplate HeaderTemplate {
get { return _headerTemplate; }
set { _headerTemplate = value; }
}
/// <summary>
/// A template for the content of databound panes
/// </summary>
[Browsable(false)]
[DefaultValue(null)]
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateContainer(typeof(AccordionContentPanel))]
public virtual ITemplate ContentTemplate {
get { return _contentTemplate; }
set { _contentTemplate = value; }
}
/// <summary>
/// The data source that provides data for populating
/// the list of AccordionPanes
/// </summary>
[Bindable(true)]
[Category("Data")]
[DefaultValue(null)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual object DataSource {
get { return _dataSource; }
set {
if((value == null) || (value is IListSource) || (value is IEnumerable)) {
_dataSource = value;
OnDataPropertyChanged();
} else {
throw new ArgumentException("Can't bind to value that is not an IListSource or an IEnumerable.");
}
}
}
/// <summary>
/// The ID of the DataControl that this control should use to retrieve its data source.
/// When the control is bound to a DataControl, it can retrieve a data source instance on demand,
/// and thereby attempt to work in auto-DataBind mode.
/// </summary>
[DefaultValue("")]
[IDReferenceProperty(typeof(DataSourceControl))]
[Category("Data")]
public virtual string DataSourceID {
get { return ViewState["DataSourceID"] as string ?? String.Empty; }
set {
ViewState["DataSourceID"] = value;
OnDataPropertyChanged();
}
}
/// <summary>
/// A member in the DataSource to bind to
/// </summary>
[DefaultValue("")]
[Category("Data")]
public virtual string DataMember {
get { return ViewState["DataMember"] as string ?? String.Empty; }
set {
ViewState["DataMember"] = value;
OnDataPropertyChanged();
}
}
// Whether or not the Accordion was databound using the DataSourceID
// property rather than setting the DataSource directly
protected bool IsBoundUsingDataSourceID {
get { return !String.IsNullOrEmpty(DataSourceID); }
}
// Whether or not the control has already been databound, or still needs
// to be databound
protected bool RequiresDataBinding {
get { return _requiresDataBinding; }
set { _requiresDataBinding = value; }
}
// Arguments used to request data-related operations from
// data source controls when data is retrieved
protected DataSourceSelectArguments SelectArguments {
get {
if(_arguments == null)
_arguments = CreateDataSourceSelectArguments();
return _arguments;
}
}
#endregion
//OnInit handler to wireup the Page's PreLoad event
protected override void OnInit(EventArgs e) {
base.OnInit(e);
if(Page != null) {
Page.PreLoad += new EventHandler(this.OnPagePreLoad);
if(!IsViewStateEnabled && Page.IsPostBack)
RequiresDataBinding = true;
}
}
// OnPreLoad is used to determine whether or not we still need to databind the Accordion
void OnPagePreLoad(object sender, EventArgs e) {
_initialized = true;
if(Page != null) {
Page.PreLoad -= new EventHandler(this.OnPagePreLoad);
// Setting RequiresDataBinding to true in OnLoad is too late because the OnLoad page event
// happens before the control.OnLoad method gets called. So a page_load handler on the page
// that calls DataBind won't prevent DataBind from getting called again in PreRender.
if(!Page.IsPostBack)
RequiresDataBinding = true;
// If this is a postback and viewstate is enabled, but we have never bound the control
// before, it is probably because its visibility was changed in the postback. In this
// case, we need to bind the control or it will never appear. This is a common scenario
// for Wizard and MultiView.
if(Page.IsPostBack && IsViewStateEnabled && ViewState[ItemCountViewStateKey] == null)
RequiresDataBinding = true;
_pagePreLoadFired = true;
}
EnsureChildControls();
}
// Connect to the DataSourceView and determine if we still need to
// do databinding
protected override void OnLoad(EventArgs e) {
_initialized = true; // just in case we were added to the page after PreLoad
ConnectToDataSourceView();
if(Page != null && !_pagePreLoadFired && ViewState[ItemCountViewStateKey] == null) {
// If the control was added after PagePreLoad, we still need to databind it because it missed its
// first change in PagePreLoad. If this control was created by a call to a parent control's DataBind
// in Page_Load (with is relatively common), this control will already have been databound even
// though pagePreLoad never fired and the page isn't a postback.
if(!Page.IsPostBack) {
RequiresDataBinding = true;
}
// If the control was added to the page after page.PreLoad, we'll never get the event and we'll
// never databind the control. So if we're catching up and Load happens but PreLoad never happened,
// call DataBind. This may make the control get databound twice if the user called DataBind on the control
// directly in Page.OnLoad, but better to bind twice than never to bind at all.
else if(IsViewStateEnabled) {
RequiresDataBinding = true;
}
}
base.OnLoad(e);
}
// Create the AccordionExtender and attach it to the div
// that will be generated for this control
protected override void CreateChildControls() {
base.CreateChildControls();
// If we already have items in the ViewState, create the control
// hierarchy using the view state (and not the datasource)
if(AccordionExtender != null && ViewState[ItemCountViewStateKey] != null)
CreateControlHierarchy(false);
ClearChildViewState();
// Ensure creation of child controls
foreach(var pane in Panes) {
ControlCollection controls = pane.Controls;
}
}
// Mark the selected AccordionPane so it does not appear collapsed
protected override void OnPreRender(EventArgs e) {
EnsureDataBound();
base.OnPreRender(e);
// Set the overflow to hidden to prevent any growth from
// showing initially before it is hidden by the script if
// we are controlling the height
if(AutoSize != AutoSize.None) {
Style[HtmlTextWriterStyle.Overflow] = "hidden";
Style[HtmlTextWriterStyle.OverflowX] = "auto";
}
// Apply the standard header/content styles, but allow the
// pane's styles to take precedent
foreach(var pane in Panes) {
if(pane.HeaderCssClass == HeaderSelectedCssClass)
pane.HeaderCssClass = String.Empty;
if(!String.IsNullOrEmpty(HeaderCssClass) && String.IsNullOrEmpty(pane.HeaderCssClass))
pane.HeaderCssClass = HeaderCssClass;
if(!String.IsNullOrEmpty(ContentCssClass) && String.IsNullOrEmpty(pane.ContentCssClass))
pane.ContentCssClass = ContentCssClass;
}
// Get the index of the selected pane, or use the first pane if we don't
// have a valid index and require one. (Note: We don't reset the SelectedIndex
// property because it may refer to a pane that will be added dynamically on the
// client. If we need to start with a pane visible, then we'll open the first
// pane because that's the default value used on the client as the SelectedIndex
// in this scenario.)
var index = AccordionExtender.SelectedIndex;
index = ((index < 0 || index >= Panes.Count) && AccordionExtender.RequireOpenedPane) ? 0 : index;
// Make sure the selected pane is displayed
if(index >= 0 && index < Panes.Count) {
var content = Panes[index].ContentContainer;
if(content != null)
content.Collapsed = false;
// Set the CSS class for the open panes header
if(!String.IsNullOrEmpty(HeaderSelectedCssClass))
Panes[index].HeaderCssClass = HeaderSelectedCssClass;
}
}
/// <summary>
/// Override FindControl to look first at this control, then check each
/// of its child AccordionPanes for the control
/// </summary>
/// <param name="id" type="String">ID of the control to find</param>
/// <returns></returns>
public override Control FindControl(string id) {
var ctrl = base.FindControl(id);
if(ctrl == null)
foreach(var pane in Panes) {
ctrl = pane.FindControl(id);
if(ctrl != null)
break;
}
return ctrl;
}
//Empty out the child Pane's collection
internal void ClearPanes() {
for(var i = Controls.Count - 1; i >= 0; i--)
if(Controls[i] is AccordionPane)
Controls.RemoveAt(i);
}
#region DataBinding
// Connects this data bound control to the appropriate DataSourceView
// and hooks up the appropriate event listener for the
// DataSourceViewChanged event. The return value is the new view (if
// any) that was connected to. An exception is thrown if there is
// a problem finding the requested view or data source.
DataSourceView ConnectToDataSourceView() {
// If the current view is correct, there is no need to reconnect
if(_currentViewValid && !DesignMode)
return _currentView;
// Disconnect from old view, if necessary
if((_currentView != null) && (_currentViewIsFromDataSourceID)) {
// We only care about this event if we are bound through the DataSourceID property
_currentView.DataSourceViewChanged -= new EventHandler(OnDataSourceViewChanged);
}
// Connect to new view
IDataSource ds = null;
var dataSourceID = DataSourceID;
if(!String.IsNullOrEmpty(dataSourceID)) {
// Try to find a DataSource control with the ID specified in DataSourceID
var control = NamingContainer.FindControl(dataSourceID);
if(control == null)
throw new HttpException(String.Format(CultureInfo.CurrentCulture, "DataSource '{1}' for control '{0}' doesn't exist", ID, dataSourceID));
ds = control as IDataSource;
if(ds == null)
throw new HttpException(String.Format(CultureInfo.CurrentCulture, "'{1}' is not a data source for control '{0}'.", ID, dataSourceID));
}
if(ds == null)
// DataSource control was not found, construct a temporary data source to wrap the data
return null;
else
// Ensure that both DataSourceID as well as DataSource are not set at the same time
if(DataSource != null)
throw new InvalidOperationException("DataSourceID and DataSource can't be set at the same time.");
// IDataSource was found, extract the appropriate view and return it
var newView = ds.GetView(DataMember);
if(newView == null)
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, "DataSourceView not found for control '{0}'", ID));
_currentViewIsFromDataSourceID = IsBoundUsingDataSourceID;
_currentView = newView;
// If we're bound through the DataSourceID proeprty, then we care about this event
if((_currentView != null) && (_currentViewIsFromDataSourceID))
_currentView.DataSourceViewChanged += new EventHandler(OnDataSourceViewChanged);
_currentViewValid = true;
return _currentView;
}
/// <summary>
/// Bind the Accordion to its DataSource
/// </summary>
public override void DataBind() {
// Don't databind to a data source control when the control is in the designer but not top-level
if(IsBoundUsingDataSourceID && DesignMode && (Site == null))
return;
// do our own databinding
RequiresDataBinding = false;
OnDataBinding(EventArgs.Empty);
}
// DataBind the Accordion to its panes
protected override void OnDataBinding(EventArgs e) {
base.OnDataBinding(e);
//Only bind if the control has the DataSource or DataSourceID set
if(this.DataSource != null || IsBoundUsingDataSourceID) {
// reset the control state
ClearPanes();
ClearChildViewState();
// and then create the control hierarchy using the datasource
CreateControlHierarchy(true);
ChildControlsCreated = true;
}
}
// Create the new control hierarchy of AccordionPanes
// (using the DataSource if specificed)
protected virtual void CreateControlHierarchy(bool useDataSource) {
var count = -1;
IEnumerable dataSource = null;
var itemsArray = new List<AccordionPane>();
if(!useDataSource) {
var viewCount = ViewState[ItemCountViewStateKey];
// ViewState must have a non-null value for ItemCount because we check for
// this in CreateChildControls
if(viewCount != null) {
count = (int)viewCount;
if(count != -1) {
var dummyList = new List<object>(count);
for(var i = 0; i < count; i++)
dummyList.Add(null);
dataSource = dummyList;
itemsArray.Capacity = count;
}
}
} else {
dataSource = GetData();
count = 0;
var collection = dataSource as ICollection;
if(collection != null)
itemsArray.Capacity = collection.Count;
}
if(dataSource != null) {
var index = 0;
foreach(var dataItem in dataSource) {
var ap = new AccordionPane();
ap.ID = String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}_Pane_{1}", ID, index.ToString(CultureInfo.InvariantCulture));
Controls.Add(ap);
CreateItem(dataItem, index, AccordionItemType.Header, ap.HeaderContainer, HeaderTemplate, useDataSource);
CreateItem(dataItem, index, AccordionItemType.Content, ap.ContentContainer, ContentTemplate, useDataSource);
itemsArray.Add(ap);
count++;
index++;
}
}
// If we're binding, save the number of items contained in the repeater for use in round-trips
if(useDataSource)
ViewState[ItemCountViewStateKey] = ((dataSource != null) ? count : -1);
}
// Create an AccordionPane's item (either Header or Content) and raise the ItemCreated event
void CreateItem(object dataItem, int index, AccordionItemType itemType, AccordionContentPanel container, ITemplate template, bool dataBind) {
if(template == null)
return;
var itemArgs = new AccordionItemEventArgs(container, itemType);
OnItemCreated(itemArgs);
container.SetDataItemProperties(dataItem, index, itemType);
template.InstantiateIn(container);
if(dataBind) {
container.DataBind();
OnItemDataBound(itemArgs);
}
}
// Ensure that the Accordion has been databound if it needed to be
protected void EnsureDataBound() {
try {
_throwOnDataPropertyChange = true;
if(RequiresDataBinding && !String.IsNullOrEmpty(DataSourceID))
DataBind();
} finally {
_throwOnDataPropertyChange = false;
}
}
// Returns an IEnumerable that is the DataSource, which either came
// from the DataSource property or from the control bound via the
// DataSourceID property.
protected virtual IEnumerable GetData() {
_selectResult = null;
var view = ConnectToDataSourceView();
if(view != null) {
Debug.Assert(_currentViewValid);
// create a handle here to make sure this is a synchronous operation.
_selectWait = new EventWaitHandle(false, EventResetMode.AutoReset);
view.Select(SelectArguments, new DataSourceViewSelectCallback(DoSelect));
_selectWait.WaitOne();
} else if(DataSource != null)
_selectResult = DataSource as IEnumerable;
return _selectResult;
}
// Create the DataSourceSelectArguments (which just defaults to the Empty value
// because we don't want to sort, filter, etc.)
protected virtual DataSourceSelectArguments CreateDataSourceSelectArguments() {
return DataSourceSelectArguments.Empty;
}
// Select the data
void DoSelect(IEnumerable data) {
_selectResult = data;
_selectWait.Set();
}
// Wrap the CommandArgs of an ItemCommand event with AccordionCommandEventArgs
// returns whether the event was handled
protected override bool OnBubbleEvent(object source, EventArgs args) {
var handled = false;
var accordionArgs = args as AccordionCommandEventArgs;
if(accordionArgs != null) {
OnItemCommand(accordionArgs);
handled = true;
}
return handled;
}
// This method is called when DataMember, DataSource, or DataSourceID is changed.
protected virtual void OnDataPropertyChanged() {
if(_throwOnDataPropertyChange)
throw new HttpException("Invalid data property change");
if(_initialized)
RequiresDataBinding = true;
_currentViewValid = false;
}
// Indicate that we need to be databound whenever the DataSourceView changes
protected virtual void OnDataSourceViewChanged(object sender, EventArgs args) {
RequiresDataBinding = true;
}
protected virtual void OnItemCommand(AccordionCommandEventArgs args) {
if(ItemCommand != null)
ItemCommand(this, args);
}
protected virtual void OnItemCreated(AccordionItemEventArgs args) {
if(ItemCreated != null)
ItemCreated(this, args);
}
protected virtual void OnItemDataBound(AccordionItemEventArgs args) {
if(ItemDataBound != null)
ItemDataBound(this, args);
}
#endregion
}
}
#pragma warning restore 1591
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Net.Http.Headers;
using System.ServiceModel.Diagnostics;
using System.Runtime;
using System.Threading;
using System.Threading.Tasks;
namespace System.ServiceModel.Channels
{
public abstract class MessageEncoder
{
public abstract string ContentType { get; }
public abstract string MediaType { get; }
public abstract MessageVersion MessageVersion { get; }
public virtual T GetProperty<T>() where T : class
{
if (typeof(T) == typeof(FaultConverter))
{
return (T)(object)FaultConverter.GetDefaultFaultConverter(this.MessageVersion);
}
return null;
}
public Message ReadMessage(Stream stream, int maxSizeOfHeaders)
{
return ReadMessage(stream, maxSizeOfHeaders, null);
}
public virtual Task<Message> ReadMessageAsync(Stream stream, int maxSizeOfHeaders, string contentType)
{
return Task.FromResult(ReadMessage(stream, maxSizeOfHeaders, contentType));
}
public virtual Task<Message> ReadMessageAsync(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType)
{
return Task.FromResult(ReadMessage(buffer, bufferManager, contentType));
}
public abstract Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType);
public Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager)
{
Message message = ReadMessage(buffer, bufferManager, null);
return message;
}
public abstract Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType);
// used for buffered streaming
internal async Task<ArraySegment<byte>> BufferMessageStreamAsync(Stream stream, BufferManager bufferManager, int maxBufferSize)
{
byte[] buffer = bufferManager.TakeBuffer(ConnectionOrientedTransportDefaults.ConnectionBufferSize);
int offset = 0;
int currentBufferSize = Math.Min(buffer.Length, maxBufferSize);
while (offset < currentBufferSize)
{
int count = await stream.ReadAsync(buffer, offset, currentBufferSize - offset, CancellationToken.None);
if (count == 0)
{
stream.Dispose();
break;
}
offset += count;
if (offset == currentBufferSize)
{
if (currentBufferSize >= maxBufferSize)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(MaxMessageSizeStream.CreateMaxReceivedMessageSizeExceededException(maxBufferSize));
}
currentBufferSize = Math.Min(currentBufferSize * 2, maxBufferSize);
byte[] temp = bufferManager.TakeBuffer(currentBufferSize);
Buffer.BlockCopy(buffer, 0, temp, 0, offset);
bufferManager.ReturnBuffer(buffer);
buffer = temp;
}
}
return new ArraySegment<byte>(buffer, 0, offset);
}
// used for buffered streaming
internal virtual async Task<Message> ReadMessageAsync(Stream stream, BufferManager bufferManager, int maxBufferSize, string contentType)
{
return ReadMessage(await BufferMessageStreamAsync(stream, bufferManager, maxBufferSize), bufferManager, contentType);
}
public override string ToString()
{
return ContentType;
}
public abstract void WriteMessage(Message message, Stream stream);
public virtual IAsyncResult BeginWriteMessage(Message message, Stream stream, AsyncCallback callback, object state)
{
return this.WriteMessageAsync(message, stream).ToApm(callback, state);
}
public virtual void EndWriteMessage(IAsyncResult result)
{
result.ToApmEnd();
}
public ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager)
{
ArraySegment<byte> arraySegment = WriteMessage(message, maxMessageSize, bufferManager, 0);
return arraySegment;
}
public abstract ArraySegment<byte> WriteMessage(Message message, int maxMessageSize,
BufferManager bufferManager, int messageOffset);
public virtual Task WriteMessageAsync(Message message, Stream stream)
{
WriteMessage(message, stream);
return TaskHelpers.CompletedTask();
}
public virtual Task<ArraySegment<byte>> WriteMessageAsync(Message message, int maxMessageSize,
BufferManager bufferManager, int messageOffset)
{
return Task.FromResult(WriteMessage(message, maxMessageSize, bufferManager, messageOffset));
}
public virtual bool IsContentTypeSupported(string contentType)
{
if (contentType == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("contentType"));
return IsContentTypeSupported(contentType, this.ContentType, this.MediaType);
}
internal bool IsContentTypeSupported(string contentType, string supportedContentType, string supportedMediaType)
{
if (supportedContentType == contentType)
return true;
if (contentType.Length > supportedContentType.Length &&
contentType.StartsWith(supportedContentType, StringComparison.Ordinal) &&
contentType[supportedContentType.Length] == ';')
return true;
// now check case-insensitively
if (contentType.StartsWith(supportedContentType, StringComparison.OrdinalIgnoreCase))
{
if (contentType.Length == supportedContentType.Length)
{
return true;
}
else if (contentType.Length > supportedContentType.Length)
{
char ch = contentType[supportedContentType.Length];
// Linear Whitespace is allowed to appear between the end of one property and the semicolon.
// LWS = [CRLF]? (SP | HT)+
if (ch == ';')
{
return true;
}
// Consume the [CRLF]?
int i = supportedContentType.Length;
if (ch == '\r' && contentType.Length > supportedContentType.Length + 1 && contentType[i + 1] == '\n')
{
i += 2;
ch = contentType[i];
}
// Look for a ';' or nothing after (SP | HT)+
if (ch == ' ' || ch == '\t')
{
i++;
while (i < contentType.Length)
{
ch = contentType[i];
if (ch != ' ' && ch != '\t')
break;
++i;
}
}
if (ch == ';' || i == contentType.Length)
return true;
}
}
// sometimes we get a contentType that has parameters, but our encoders
// merely expose the base content-type, so we will check a stripped version
try
{
MediaTypeHeaderValue parsedContentType = MediaTypeHeaderValue.Parse(contentType);
if (supportedMediaType.Length > 0 && !supportedMediaType.Equals(parsedContentType.MediaType, StringComparison.OrdinalIgnoreCase))
return false;
if (!IsCharSetSupported(parsedContentType.CharSet))
return false;
}
catch (FormatException)
{
// bad content type, so we definitely don't support it!
return false;
}
return true;
}
internal virtual bool IsCharSetSupported(string charset)
{
return false;
}
internal void ThrowIfMismatchedMessageVersion(Message message)
{
if (message.Version != MessageVersion)
{
throw TraceUtility.ThrowHelperError(
new ProtocolException(string.Format(SRServiceModel.EncoderMessageVersionMismatch, message.Version, MessageVersion)),
message);
}
}
}
}
| |
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
#if UNITY_EDITOR
using System.Reflection;
public class RXWatcher
{
private static RXWatcher _instance;
private GameObject _gameObject;
private List<RXWatcherLink> _watcherLinks = new List<RXWatcherLink>();
private RXWatcher ()
{
_gameObject = new GameObject("RXWatcher");
}
static public void Watch(object target)
{
if(target == null) return;
Watch (target, false, null);
}
static public void Watch(object target, bool shouldShowNonPublic)
{
if(target == null) return;
Watch (target, shouldShowNonPublic, null);
}
static public void Watch(object target, bool shouldShowNonPublic, string targetName)
{
if(target == null) return;
if(targetName == null)
{
if(target is Type)
{
targetName = (target as Type).Name;
}
else
{
targetName = target.GetType().Name;
}
}
if(_instance == null)
{
_instance = new RXWatcher();
}
_instance.DoWatch(target, targetName, shouldShowNonPublic);
}
public void DoWatch(object target, string targetName, bool shouldShowNonPublic)
{
int watcherLinkCount = _watcherLinks.Count;
for(int w = 0; w<watcherLinkCount; w++)
{
if(_watcherLinks[w].GetTarget() == target)
{
return; //we already have a watcher for this target!
}
}
GameObject linkGO = new GameObject(targetName);
linkGO.transform.parent = _gameObject.transform;
RXWatcherLink link = linkGO.AddComponent<RXWatcherLink>();
link.Init(target, shouldShowNonPublic);
_watcherLinks.Add(link);
}
static public void RemoveWatcherLink(RXWatcherLink watcherLink)
{
_instance.DoRemoveWatcherLink(watcherLink);
}
public void DoRemoveWatcherLink(RXWatcherLink watcherLink)
{
int watcherLinkCount = _watcherLinks.Count;
for(int w = 0; w<watcherLinkCount; w++)
{
if(_watcherLinks[w] == watcherLink)
{
_watcherLinks.RemoveAt(w);
return;
}
}
}
}
public class RXWatcherLink : MonoBehaviour
{
private WeakReference _targetRef;
private bool _hasSetup = false;
private bool _shouldShowNonPublicMembers = false;
private List<RXWatcherLinkMember> _members = new List<RXWatcherLinkMember>();
public void Init(object target, bool shouldShowNonPublic)
{
_targetRef = new WeakReference(target);
_shouldShowNonPublicMembers = shouldShowNonPublic;
}
private void SetupTarget()
{
object target = _targetRef.Target;
Type targetType = _targetRef.Target.GetType();
BindingFlags bindingFlags = BindingFlags.Public;
if(target is Type)
{
bindingFlags |= BindingFlags.Static;
targetType = target as Type;
}
else
{
bindingFlags |= BindingFlags.Instance;
}
if(_shouldShowNonPublicMembers)
{
bindingFlags |= BindingFlags.NonPublic;
}
FieldInfo[] fieldInfos = targetType.GetFields(bindingFlags);
PropertyInfo[] propertyInfos = targetType.GetProperties(bindingFlags);
for(int f = 0; f<fieldInfos.Length; f++)
{
RXWatcherLinkMember member = new RXWatcherLinkMember(this, fieldInfos[f]);
if(member.CheckIfValid())
{
_members.Add(member);
}
}
for(int p = 0; p<propertyInfos.Length; p++)
{
RXWatcherLinkMember member = new RXWatcherLinkMember(this, propertyInfos[p]);
if(member.CheckIfValid())
{
_members.Add(member);
}
}
}
public void Update()
{
if(_targetRef.Target == null)
{
Destroy();
}
else
{
if(!_hasSetup)
{
_hasSetup = true;
SetupTarget();
}
}
}
public object GetTarget()
{
return _targetRef.Target;
}
public List<RXWatcherLinkMember> members
{
get {return _members;}
}
private void Destroy()
{
UnityEngine.Object.Destroy(gameObject);
RXWatcher.RemoveWatcherLink(this);
}
}
//this is used to wrap FieldInfo+PropertyInfo so they can be treated the exact same way
public class RXWatcherLinkMember
{
public string name;
public Type memberType;
public MemberInfo memberInfo;
private RXWatcherLink _link;
private PropertyInfo _propertyInfo = null;
private FieldInfo _fieldInfo = null;
public RXWatcherLinkMember(RXWatcherLink link, MemberInfo memberInfo)
{
_link = link;
this.memberInfo = memberInfo;
_propertyInfo = memberInfo as PropertyInfo;
if(_propertyInfo != null)
{
name = _propertyInfo.Name;
memberType = _propertyInfo.PropertyType;
}
else //check if it's a field instead
{
_fieldInfo = memberInfo as FieldInfo;
if(_fieldInfo != null)
{
name = _fieldInfo.Name;
memberType = _fieldInfo.FieldType;
}
}
}
public bool CheckIfValid()
{
if(_propertyInfo != null)
{
if(_propertyInfo.CanWrite)
{
return true;
}
}
else if(_fieldInfo != null)
{
return true;
}
return false;
}
public object GetValue()
{
if(_propertyInfo != null)
{
return _propertyInfo.GetValue(_link.GetTarget(), null);
}
else if(_fieldInfo != null)
{
return _fieldInfo.GetValue(_link.GetTarget());
}
return null;
}
public void SetValue(object newValue)
{
if(_propertyInfo != null)
{
_propertyInfo.SetValue(_link.GetTarget(), newValue, null);
}
else if(_fieldInfo != null)
{
_fieldInfo.SetValue(_link.GetTarget(), newValue);
}
}
}
#else
//do nothing if we're not in the editor
public class RXWatcher
{
static public void Watch(object target)
{
}
static public void Watch(object target, bool shouldShowNonPublic)
{
}
static public void Watch(object target, bool shouldShowNonPublic, string targetName)
{
}
}
public class RXWatcherLink : MonoBehaviour
{
}
#endif
| |
using System.Reflection;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
namespace Prism.Interactivity
{
/// <summary>
/// Trigger action that executes a command when invoked.
/// It also maintains the Enabled state of the target control based on the CanExecute method of the command.
/// </summary>
public class InvokeCommandAction : TriggerAction<UIElement>
{
private ExecutableCommandBehavior _commandBehavior;
/// <summary>
/// Dependency property identifying if the associated element should automaticlaly be enabled or disabled based on the result of the Command's CanExecute
/// </summary>
public static readonly DependencyProperty AutoEnableProperty =
DependencyProperty.Register("AutoEnable", typeof(bool), typeof(InvokeCommandAction),
new PropertyMetadata(true, (d, e) => ((InvokeCommandAction)d).OnAllowDisableChanged((bool)e.NewValue)));
/// <summary>
/// Gets or sets whther or not the associated element will automatically be enabled or disabled based on the result of the commands CanExecute
/// </summary>
public bool AutoEnable
{
get { return (bool)GetValue(AutoEnableProperty); }
set { SetValue(AutoEnableProperty, value); }
}
private void OnAllowDisableChanged(bool newValue)
{
var behavior = GetOrCreateBehavior();
if (behavior != null)
behavior.AutoEnable = newValue;
}
/// <summary>
/// Dependency property identifying the command to execute when invoked.
/// </summary>
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(ICommand), typeof(InvokeCommandAction),
new PropertyMetadata(null, (d, e) => ((InvokeCommandAction)d).OnCommandChanged((ICommand)e.NewValue)));
/// <summary>
/// Gets or sets the command to execute when invoked.
/// </summary>
public ICommand Command
{
get { return GetValue(CommandProperty) as ICommand; }
set { SetValue(CommandProperty, value); }
}
private void OnCommandChanged(ICommand newValue)
{
var behavior = GetOrCreateBehavior();
if (behavior != null)
behavior.Command = newValue;
}
/// <summary>
/// Dependency property identifying the command parameter to supply on command execution.
/// </summary>
public static readonly DependencyProperty CommandParameterProperty =
DependencyProperty.Register("CommandParameter", typeof(object), typeof(InvokeCommandAction),
new PropertyMetadata(null, (d, e) => ((InvokeCommandAction)d).OnCommandParameterChanged(e.NewValue)));
/// <summary>
/// Gets or sets the command parameter to supply on command execution.
/// </summary>
public object CommandParameter
{
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
private void OnCommandParameterChanged(object newValue)
{
var behavior = GetOrCreateBehavior();
if (behavior != null)
behavior.CommandParameter = newValue;
}
/// <summary>
/// Dependency property identifying the TriggerParameterPath to be parsed to identify the child property of the trigger parameter to be used as the command parameter.
/// </summary>
public static readonly DependencyProperty TriggerParameterPathProperty =
DependencyProperty.Register("TriggerParameterPath", typeof(string), typeof(InvokeCommandAction),
new PropertyMetadata(null, (d, e) => { }));
/// <summary>
/// Gets or sets the TriggerParameterPath value.
/// </summary>
public string TriggerParameterPath
{
get { return GetValue(TriggerParameterPathProperty) as string; }
set { SetValue(TriggerParameterPathProperty, value); }
}
/// <summary>
/// Public wrapper of the Invoke method.
/// </summary>
public void InvokeAction(object parameter)
{
Invoke(parameter);
}
/// <summary>
/// Executes the command
/// </summary>
/// <param name="parameter">This parameter is passed to the command; the CommandParameter specified in the CommandParameterProperty is used for command invocation if not null.</param>
protected override void Invoke(object parameter)
{
if (!string.IsNullOrEmpty(TriggerParameterPath))
{
//Walk the ParameterPath for nested properties.
var propertyPathParts = TriggerParameterPath.Split('.');
object propertyValue = parameter;
foreach (var propertyPathPart in propertyPathParts)
{
var propInfo = propertyValue.GetType().GetTypeInfo().GetProperty(propertyPathPart);
propertyValue = propInfo.GetValue(propertyValue);
}
parameter = propertyValue;
}
var behavior = GetOrCreateBehavior();
if (behavior != null)
{
behavior.ExecuteCommand(parameter);
}
}
/// <summary>
/// Sets the Command and CommandParameter properties to null.
/// </summary>
protected override void OnDetaching()
{
base.OnDetaching();
Command = null;
CommandParameter = null;
_commandBehavior = null;
}
/// <summary>
/// This method is called after the behavior is attached.
/// It updates the command behavior's Command and CommandParameter properties if necessary.
/// </summary>
protected override void OnAttached()
{
base.OnAttached();
// In case this action is attached to a target object after the Command and/or CommandParameter properties are set,
// the command behavior would be created without a value for these properties.
// To cover this scenario, the Command and CommandParameter properties of the behavior are updated here.
var behavior = GetOrCreateBehavior();
behavior.AutoEnable = AutoEnable;
if (behavior.Command != Command)
behavior.Command = Command;
if (behavior.CommandParameter != CommandParameter)
behavior.CommandParameter = CommandParameter;
}
private ExecutableCommandBehavior GetOrCreateBehavior()
{
// In case this method is called prior to this action being attached,
// the CommandBehavior would always keep a null target object (which isn't changeable afterwards).
// Therefore, in that case the behavior shouldn't be created and this method should return null.
if (_commandBehavior == null && AssociatedObject != null)
{
_commandBehavior = new ExecutableCommandBehavior(AssociatedObject);
}
return _commandBehavior;
}
/// <summary>
/// A CommandBehavior that exposes a public ExecuteCommand method. It provides the functionality to invoke commands and update Enabled state of the target control.
/// It is not possible to make the <see cref="InvokeCommandAction"/> inherit from <see cref="CommandBehaviorBase{T}"/>, since the <see cref="InvokeCommandAction"/>
/// must already inherit from <see cref="TriggerAction{T}"/>, so we chose to follow the aggregation approach.
/// </summary>
private class ExecutableCommandBehavior : CommandBehaviorBase<UIElement>
{
/// <summary>
/// Constructor specifying the target object.
/// </summary>
/// <param name="target">The target object the behavior is attached to.</param>
public ExecutableCommandBehavior(UIElement target)
: base(target)
{
}
/// <summary>
/// Executes the command, if it's set.
/// </summary>
public new void ExecuteCommand(object parameter)
{
base.ExecuteCommand(parameter);
}
}
}
}
| |
namespace PokerTell.Plugins.PlayerPeeker
{
using System;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using log4net;
/// <summary>
/// Description of PeekerStats.
/// </summary>
public class PeekerStats
{
public MonStruct AvgBuyin;
public AvgStruct AvgEntrants;
public TextStruct AvgFinish;
public MonStruct AvgProfit;
public AvgStruct GamesPlayed;
public TextStruct Name;
public PercStruct PercFinalTables;
public PercStruct PercITM;
public PercStruct PercROI;
public PercStruct PercWins;
public MonStruct Profit;
public TextStruct Site;
static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public PeekerStats(string htmlTagText)
{
Name = new TextStruct(@"StatsName: (?<Q>.+) Average", htmlTagText);
Site = new TextStruct(@"Site: (?<Q>\w+) Average", htmlTagText);
AvgFinish = new TextStruct(@"Average Finish: (?<Q>\d+/\d+)", htmlTagText);
AvgEntrants = new AvgStruct(@"Average Entrants: *(?<Q>[0-9,.]+)", htmlTagText);
AvgBuyin = new MonStruct(@"Average Buyin: *\$(?<Q>[0-9,.]+)", htmlTagText);
AvgProfit = new MonStruct(@"Average Profit: *(?<Q>[-$0-9,.]+)", htmlTagText);
Profit = new MonStruct(@"Est\. Profit: *(?<Q>[-$0-9,.]+)", htmlTagText);
PercROI = new PercStruct(@"ROI: *(?<Q>[-0-9,.]+)%", htmlTagText);
PercITM = new PercStruct(@"ITM: *(?<Q>[-0-9,.]+)%", htmlTagText);
PercFinalTables = new PercStruct(@"Final Tables: *\d+ *\((?<Q>[-0-9,.]+)%\)", htmlTagText);
PercWins = new PercStruct(@"Wins: *\d+ *\((?<Q>[-0-9,.]+)%\)", htmlTagText);
GamesPlayed = new AvgStruct(@"Games Played: *(?<Q>[0-9,.]+)", htmlTagText);
}
public struct AvgStruct
{
public readonly string Pattern;
public readonly int Value;
readonly Match _match;
public AvgStruct(string pattern, string toParse)
{
Pattern = pattern;
_match = Regex.Match(toParse, pattern, RegexOptions.IgnoreCase);
try
{
if (_match.Success)
{
if (!int.TryParse(_match.Groups["Q"].Value.Replace(",", string.Empty), out Value))
{
Value = -1;
}
}
else
{
Value = -1;
}
}
catch (Exception excep)
{
Log.Error("Unexpected", excep);
Value = -1;
}
}
public override string ToString()
{
return string.Format("{0:0,0}", Value);
}
}
public struct MonStruct
{
public readonly string Pattern;
public readonly double Value;
readonly Match _match;
public MonStruct(string pattern, string toParse)
{
string temp;
Pattern = pattern;
_match = Regex.Match(toParse, pattern, RegexOptions.IgnoreCase);
try
{
if (_match.Success)
{
temp = _match.Groups["Q"].Value.Replace("$", string.Empty);
temp = temp.Replace(",", string.Empty);
if (!double.TryParse(temp, out Value))
{
Value = -1;
}
}
else
{
Value = -1;
}
}
catch (Exception excep)
{
Log.Error("Unexpected", excep);
Value = -1;
}
}
public override string ToString()
{
return string.Format("{00:#,0.00}$", Value);
}
}
public struct PercStruct
{
public readonly string Pattern;
public readonly int Value;
readonly Match _match;
public PercStruct(string pattern, string toParse)
{
Pattern = pattern;
_match = Regex.Match(toParse, pattern, RegexOptions.IgnoreCase);
try
{
if (_match.Success)
{
if (!int.TryParse(_match.Groups["Q"].Value, out Value))
{
Value = -1;
}
}
else
{
Value = -1;
}
}
catch (Exception excep)
{
Log.Error("Unexpected", excep);
Value = -1;
}
}
public override string ToString()
{
return string.Format("{00}%", Value);
}
}
public struct TextStruct
{
public readonly string Pattern;
public readonly string Value;
readonly Match _match;
public TextStruct(string pattern, string toParse)
{
Pattern = pattern;
_match = Regex.Match(toParse, pattern, RegexOptions.IgnoreCase);
Value = _match.Groups["Q"].Value;
}
public override string ToString()
{
return Value;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using ADBannerView = UnityEngine.iOS.ADBannerView;
public class BombMessageResponder : MessageResponder
{
public TwitchBombHandle twitchBombHandlePrefab = null;
public TwitchComponentHandle twitchComponentHandlePrefab = null;
public ModuleCameras moduleCamerasPrefab = null;
public Leaderboard leaderboard = null;
public TwitchPlaysService parentService = null;
private List<BombCommander> _bombCommanders = new List<BombCommander>();
private List<TwitchBombHandle> _bombHandles = new List<TwitchBombHandle>();
private List<TwitchComponentHandle> _componentHandles = new List<TwitchComponentHandle>();
private int _currentBomb = -1;
public static ModuleCameras moduleCameras = null;
private float specialNameProbability = 0.25f;
private string[] singleNames = new string[]
{
"Bomblebee",
"Big Bomb",
"Big Bomb Man",
"Explodicus",
"Little Boy",
"Fat Man",
"Bombadillo",
"The Dud",
"Molotov",
"Sergeant Cluster",
"La Bomba",
"Bombchu",
"Bomboleo"
};
private string[,] doubleNames = new string[,]
{
{ null, "The Bomb 2: Bomb Harder" },
{ null, "The Bomb 2: The Second Bombing" },
{ "Bomb", "Bomber" },
{ null, "The Bomb Reloaded" },
{ "Bombic", "& Knuckles" },
{ null, "The River Kwai" },
{ "Bomboleo", "Bombolea" }
};
#region Unity Lifecycle
private void OnEnable()
{
if (!TwitchPlaysService.DebugMode)
{
InputInterceptor.DisableInput();
}
leaderboard.ClearSolo();
TwitchPlaysService.logUploader.Clear();
StartCoroutine(CheckForBomb());
}
private void OnDisable()
{
StopAllCoroutines();
leaderboard.BombsAttempted++;
string bombMessage = null;
bool HasDetonated = false;
var timeStarting = float.MaxValue;
var timeRemaining = float.MaxValue;
var timeRemainingFormatted = "";
TwitchPlaysService.logUploader.Post();
foreach (var commander in _bombCommanders)
{
HasDetonated |= (bool) CommonReflectedTypeInfo.HasDetonatedProperty.GetValue(commander.Bomb, null);
if (timeRemaining > commander.CurrentTimer)
{
timeStarting = commander._bombStartingTimer;
timeRemaining = commander.CurrentTimer;
}
if (!string.IsNullOrEmpty(timeRemainingFormatted))
{
timeRemainingFormatted += ", " + commander.GetFullFormattedTime;
}
else
{
timeRemainingFormatted = commander.GetFullFormattedTime;
}
}
if (HasDetonated)
{
bombMessage = string.Format("KAPOW KAPOW The bomb has exploded, with {0} remaining! KAPOW KAPOW", timeRemainingFormatted);
leaderboard.BombsExploded+=_bombCommanders.Count;
leaderboard.Success = false;
}
else
{
bombMessage = string.Format("PraiseIt PraiseIt The bomb has been defused, with {0} remaining! PraiseIt PraiseIt", timeRemainingFormatted);
leaderboard.BombsCleared+=_bombCommanders.Count;
leaderboard.Success = true;
if (leaderboard.CurrentSolvers.Count == 1)
{
float previousRecord = 0.0f;
float elapsedTime = timeStarting - timeRemaining;
string userName = "";
foreach (string uName in leaderboard.CurrentSolvers.Keys)
{
userName = uName;
break;
}
if (leaderboard.CurrentSolvers[userName] == (Leaderboard.RequiredSoloSolves * _bombCommanders.Count))
{
leaderboard.AddSoloClear(userName, elapsedTime, out previousRecord);
TimeSpan elapsedTimeSpan = TimeSpan.FromSeconds(elapsedTime);
bombMessage = string.Format("PraiseIt PraiseIt {0} completed a solo defusal in {1}:{2:00}!", leaderboard.SoloSolver.UserName, (int)elapsedTimeSpan.TotalMinutes, elapsedTimeSpan.Seconds);
if (elapsedTime < previousRecord)
{
TimeSpan previousTimeSpan = TimeSpan.FromSeconds(previousRecord);
bombMessage += string.Format(" It's a new record! (Previous record: {0}:{1:00})", (int)previousTimeSpan.TotalMinutes, previousTimeSpan.Seconds);
}
bombMessage += " PraiseIt PraiseIt";
}
else
{
leaderboard.ClearSolo();
}
}
}
parentService.StartCoroutine(SendDelayedMessage(1.0f, bombMessage, SendAnalysisLink));
if (moduleCameras != null)
{
moduleCameras.gameObject.SetActive(false);
}
foreach (var handle in _bombHandles)
{
if (handle != null)
{
Destroy(handle.gameObject, 2.0f);
}
}
_bombHandles.Clear();
_bombCommanders.Clear();
if (_componentHandles != null)
{
foreach (TwitchComponentHandle handle in _componentHandles)
{
Destroy(handle.gameObject, 2.0f);
}
}
_componentHandles.Clear();
MusicPlayer.StopAllMusic();
}
#endregion
#region Protected/Private Methods
private IEnumerator CheckForBomb()
{
TwitchComponentHandle.ResetId();
UnityEngine.Object[] bombs;
do
{
yield return null;
bombs = FindObjectsOfType(CommonReflectedTypeInfo.BombType);
if (bombs.Length > 0)
{
yield return new WaitForSeconds(0.1f);
bombs = FindObjectsOfType(CommonReflectedTypeInfo.BombType);
}
System.Random rand = new System.Random();
if (bombs.Length == 1)
{
_currentBomb = -1;
SetBomb((MonoBehaviour) bombs[0], -1);
if (rand.NextDouble() < specialNameProbability)
{
_bombHandles[0].nameText.text = singleNames[rand.Next(0, singleNames.Length - 1)];
}
_coroutineQueue.AddToQueue(_bombHandles[0].OnMessageReceived(_bombHandles[0].nameText.text, "red", "!bomb hold"), -1);
}
else
{
_currentBomb = 0;
int id = 0;
for (var i = bombs.Length - 1; i >= 0; i--)
{
SetBomb((MonoBehaviour) bombs[i], id++);
}
if (rand.NextDouble() < specialNameProbability)
{
int nameIndex = rand.Next(0, doubleNames.Length - 1);
string nameText = null;
for (int i = 0; i < 2; i++)
{
nameText = doubleNames[nameIndex, i];
if (nameText != null)
{
_bombHandles[i].nameText.text = nameText;
}
}
}
else
{
_bombHandles[1].nameText.text = "The Other Bomb";
}
_coroutineQueue.AddToQueue(_bombHandles[0].OnMessageReceived(_bombHandles[0].nameText.text, "red", "!bomb hold"), 0);
}
} while (bombs == null || bombs.Length == 0);
moduleCameras = Instantiate<ModuleCameras>(moduleCamerasPrefab);
}
private void SetBomb(MonoBehaviour bomb, int id)
{
_bombCommanders.Add(new BombCommander(bomb));
CreateBombHandleForBomb(bomb, id);
CreateComponentHandlesForBomb(bomb);
if (id == -1)
{
_ircConnection.SendMessage("The next bomb is now live! Start sending your commands! MrDestructoid");
}
else if (id == 0)
{
_ircConnection.SendMessage("The next set of bombs are now live! Start sending your commands! MrDestructoid");
}
}
protected override void OnMessageReceived(string userNickName, string userColorCode, string text)
{
if (text.Equals("!stop", StringComparison.InvariantCultureIgnoreCase))
{
_currentBomb = _coroutineQueue.CurrentBombID;
return;
}
if (text.Equals("!modules", StringComparison.InvariantCultureIgnoreCase))
{
moduleCameras.AttachToModules(_componentHandles);
return;
}
if (_currentBomb > -1)
{
//Check for !bomb messages, and pass them off to the currently held bomb.
Match match = Regex.Match(text, "^!bomb (.+)", RegexOptions.IgnoreCase);
if (match.Success)
{
string internalCommand = match.Groups[1].Value;
text = string.Format("!bomb{0} {1}", _currentBomb + 1, internalCommand);
}
}
foreach (var handle in _bombHandles)
{
if (handle != null)
{
IEnumerator onMessageReceived = handle.OnMessageReceived(userNickName, userColorCode, text);
if (onMessageReceived == null) continue;
if (_currentBomb != handle.bombID)
{
_coroutineQueue.AddToQueue(_bombCommanders[_currentBomb].LetGoBomb(), handle.bombID);
_currentBomb = handle.bombID;
}
_coroutineQueue.AddToQueue(onMessageReceived, handle.bombID);
}
}
foreach (TwitchComponentHandle componentHandle in _componentHandles)
{
IEnumerator onMessageReceived = componentHandle.OnMessageReceived(userNickName, userColorCode, text);
if (onMessageReceived != null)
{
if (_currentBomb != componentHandle.bombID)
{
_coroutineQueue.AddToQueue(_bombCommanders[_currentBomb].LetGoBomb(),componentHandle.bombID);
_currentBomb = componentHandle.bombID;
}
_coroutineQueue.AddToQueue(onMessageReceived,componentHandle.bombID);
}
}
}
private void CreateBombHandleForBomb(MonoBehaviour bomb, int id)
{
TwitchBombHandle _bombHandle = Instantiate<TwitchBombHandle>(twitchBombHandlePrefab);
_bombHandle.bombID = id;
_bombHandle.ircConnection = _ircConnection;
_bombHandle.bombCommander = _bombCommanders[_bombCommanders.Count-1];
_bombHandle.coroutineQueue = _coroutineQueue;
_bombHandle.coroutineCanceller = _coroutineCanceller;
_bombHandles.Add(_bombHandle);
}
private bool CreateComponentHandlesForBomb(MonoBehaviour bomb)
{
bool foundComponents = false;
IList bombComponents = (IList)CommonReflectedTypeInfo.BombComponentsField.GetValue(bomb);
if (bombComponents.Count > 12)
{
_bombCommanders[_bombCommanders.Count - 1]._multiDecker = true;
}
foreach (MonoBehaviour bombComponent in bombComponents)
{
object componentType = CommonReflectedTypeInfo.ComponentTypeField.GetValue(bombComponent);
int componentTypeInt = (int)Convert.ChangeType(componentType, typeof(int));
ComponentTypeEnum componentTypeEnum = (ComponentTypeEnum)componentTypeInt;
switch (componentTypeEnum)
{
case ComponentTypeEnum.Empty:
continue;
case ComponentTypeEnum.Timer:
_bombCommanders[_bombCommanders.Count - 1]._timerComponent = bombComponent;
continue;
default:
foundComponents = true;
break;
}
TwitchComponentHandle handle = (TwitchComponentHandle)Instantiate(twitchComponentHandlePrefab, bombComponent.transform, false);
handle.ircConnection = _ircConnection;
handle.bombCommander = _bombCommanders[_bombCommanders.Count - 1];
handle.bombComponent = bombComponent;
handle.componentType = componentTypeEnum;
handle.coroutineQueue = _coroutineQueue;
handle.coroutineCanceller = _coroutineCanceller;
handle.leaderboard = leaderboard;
handle.bombID = _currentBomb == -1 ? -1 : _bombCommanders.Count - 1;
Vector3 idealOffset = handle.transform.TransformDirection(GetIdealPositionForHandle(handle, bombComponents, out handle.direction));
handle.transform.SetParent(bombComponent.transform.parent, true);
handle.basePosition = handle.transform.localPosition;
handle.idealHandlePositionOffset = bombComponent.transform.parent.InverseTransformDirection(idealOffset);
handle.bombCommander._bombSolvableModules++;
_componentHandles.Add(handle);
}
return foundComponents;
}
private Vector3 GetIdealPositionForHandle(TwitchComponentHandle thisHandle, IList bombComponents, out TwitchComponentHandle.Direction direction)
{
Rect handleBasicRect = new Rect(-0.155f, -0.1f, 0.31f, 0.2f);
Rect bombComponentBasicRect = new Rect(-0.1f, -0.1f, 0.2f, 0.2f);
float baseUp = (handleBasicRect.height + bombComponentBasicRect.height) * 0.55f;
float baseRight = (handleBasicRect.width + bombComponentBasicRect.width) * 0.55f;
Vector2 extentUp = new Vector2(0.0f, baseUp * 0.1f);
Vector2 extentRight = new Vector2(baseRight * 0.2f, 0.0f);
Vector2 extentResult = Vector2.zero;
while (true)
{
Rect handleRect = handleBasicRect;
handleRect.position += extentRight;
if (!HasOverlap(thisHandle, handleRect, bombComponentBasicRect, bombComponents))
{
extentResult = extentRight;
direction = TwitchComponentHandle.Direction.Left;
break;
}
handleRect = handleBasicRect;
handleRect.position -= extentRight;
if (!HasOverlap(thisHandle, handleRect, bombComponentBasicRect, bombComponents))
{
extentResult = -extentRight;
direction = TwitchComponentHandle.Direction.Right;
break;
}
handleRect = handleBasicRect;
handleRect.position += extentUp;
if (!HasOverlap(thisHandle, handleRect, bombComponentBasicRect, bombComponents))
{
extentResult = extentUp;
direction = TwitchComponentHandle.Direction.Down;
break;
}
handleRect = handleBasicRect;
handleRect.position -= extentUp;
if (!HasOverlap(thisHandle, handleRect, bombComponentBasicRect, bombComponents))
{
extentResult = -extentUp;
direction = TwitchComponentHandle.Direction.Up;
break;
}
extentUp.y += baseUp * 0.1f;
extentRight.x += baseRight * 0.1f;
}
return new Vector3(extentResult.x, 0.0f, extentResult.y);
}
private bool HasOverlap(TwitchComponentHandle thisHandle, Rect handleRect, Rect bombComponentBasicRect, IList bombComponents)
{
foreach (MonoBehaviour bombComponent in bombComponents)
{
Vector3 bombComponentCenter = thisHandle.transform.InverseTransformPoint(bombComponent.transform.position);
Rect bombComponentRect = bombComponentBasicRect;
bombComponentRect.position += new Vector2(bombComponentCenter.x, bombComponentCenter.z);
if (bombComponentRect.Overlaps(handleRect))
{
return true;
}
}
return false;
}
private IEnumerator SendDelayedMessage(float delay, string message, Action callback = null)
{
yield return new WaitForSeconds(delay);
_ircConnection.SendMessage(message);
if (callback != null)
{
callback();
}
}
private void SendAnalysisLink()
{
if (!TwitchPlaysService.logUploader.PostToChat())
{
Debug.Log("[BombMessageResponder] Analysis URL not found, instructing LogUploader to post when it's ready");
TwitchPlaysService.logUploader.postOnComplete = true;
}
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
internal static class IOInputs
{
public static bool SupportsSettingCreationTime { get { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); } }
public static bool SupportsGettingCreationTime { get { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) | RuntimeInformation.IsOSPlatform(OSPlatform.OSX); } }
// Max path length (minus trailing \0). Unix values vary system to system; just using really long values here likely to be more than on the average system.
public static readonly int MaxPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? 259 : 10000;
// Windows specific, this is the maximum length that can be passed using extended syntax. Does not include the trailing \0.
public static readonly int MaxExtendedPath = short.MaxValue - 1;
// Same as MaxPath on Unix
public static readonly int MaxLongPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? MaxExtendedPath : MaxPath;
// Windows specific, this is the maximum length that can be passed to APIs taking directory names, such as Directory.CreateDirectory & Directory.Move.
// Does not include the trailing \0.
// We now do the appropriate wrapping to allow creating longer directories. Like MaxPath, this is a legacy restriction.
public static readonly int MaxDirectory = 247;
public const int MaxComponent = 255;
public const string ExtendedPrefix = @"\\?\";
public const string ExtendedUncPrefix = @"\\?\UNC\";
public static IEnumerable<string> GetValidPathComponentNames()
{
yield return Path.GetRandomFileName();
yield return "!@#$%^&";
yield return "\x65e5\x672c\x8a9e";
yield return "A";
yield return " A";
yield return " A";
yield return "FileName";
yield return "FileName.txt";
yield return " FileName";
yield return " FileName.txt";
yield return " FileName";
yield return " FileName.txt";
yield return "This is a valid component name";
yield return "This is a valid component name.txt";
yield return "V1.0.0.0000";
}
// These are the WhiteSpace characters we used to trim for paths:
//
// (char)0x9, // Horizontal tab '\t'
// (char)0xA, // Line feed '\n'
// (char)0xB, // Vertical tab '\v'
// (char)0xC, // Form feed '\f'
// (char)0xD, // Carriage return '\r'
// (char)0x20, // Space ' '
// (char)0x85, // Next line '\u0085'
// (char)0xA0 // Non breaking space '\u00A0'
public static IEnumerable<string> GetControlWhiteSpace()
{
yield return "\t";
yield return "\t\t";
yield return "\t\t\t";
yield return "\n";
yield return "\n\n";
yield return "\n\n\n";
yield return "\t\n";
yield return "\t\n\t\n";
yield return "\n\t\n";
yield return "\n\t\n\t";
// Add other control chars
yield return "\v\f\r";
}
public static IEnumerable<string> GetSimpleWhiteSpace()
{
yield return " ";
yield return " ";
yield return " ";
yield return " ";
yield return " ";
}
/// <summary>
/// Whitespace characters that arent in the traditional control set (e.g. less than 0x20)
/// and aren't space (e.g. 0x20).
/// </summary>
public static IEnumerable<string> GetNonControlWhiteSpace()
{
yield return "\u0085"; // Next Line (.NET used to trim)
yield return "\u00A0"; // Non breaking space (.NET used to trim)
yield return "\u2028"; // Line separator
yield return "\u2029"; // Paragraph separator
yield return "\u2003"; // EM space
yield return "\u2008"; // Punctuation space
}
/// <summary>
/// Whitespace characters other than space (includes some Unicode whitespace characters we
/// did not traditionally trim.
/// </summary>
public static IEnumerable<string> GetNonSpaceWhiteSpace()
{
return GetControlWhiteSpace().Concat(GetNonControlWhiteSpace());
}
/// <summary>
/// This is the Whitespace we used to trim from paths
/// </summary>
public static IEnumerable<string> GetWhiteSpace()
{
return GetControlWhiteSpace().Concat(GetSimpleWhiteSpace());
}
public static IEnumerable<string> GetUncPathsWithoutShareName()
{
foreach (char slash in new[] { Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar })
{
if (!PlatformDetection.IsWindows && slash == '/') // Unc paths must start with '\' on Unix
{
continue;
}
string slashes = new string(slash, 2);
yield return slashes;
yield return slashes + " ";
yield return slashes + new string(slash, 5);
yield return slashes + "S";
yield return slashes + "S ";
yield return slashes + "LOCALHOST";
yield return slashes + "LOCALHOST " + slash;
yield return slashes + "LOCALHOST " + new string(slash, 2);
yield return slashes + "LOCALHOST" + slash + " ";
yield return slashes + "LOCALHOST" + slash + slash + " ";
}
}
public static IEnumerable<string> GetPathsWithReservedDeviceNames()
{
string root = Path.GetPathRoot(Directory.GetCurrentDirectory());
foreach (string deviceName in GetReservedDeviceNames())
{
yield return deviceName;
yield return Path.Combine(root, deviceName);
yield return Path.Combine(root, "Directory", deviceName);
yield return Path.Combine(new string(Path.DirectorySeparatorChar, 2), "LOCALHOST", deviceName);
}
}
public static IEnumerable<string> GetPathsWithAlternativeDataStreams()
{
yield return @"AA:";
yield return @"AAA:";
yield return @"AA:A";
yield return @"AAA:A";
yield return @"AA:AA";
yield return @"AAA:AA";
yield return @"AA:AAA";
yield return @"AAA:AAA";
yield return @"AA:FileName";
yield return @"AAA:FileName";
yield return @"AA:FileName.txt";
yield return @"AAA:FileName.txt";
yield return @"A:FileName.txt:";
yield return @"AA:FileName.txt:AA";
yield return @"AAA:FileName.txt:AAA";
yield return @"C:\:";
yield return @"C:\:FileName";
yield return @"C:\:FileName.txt";
yield return @"C:\fileName:";
yield return @"C:\fileName:FileName.txt";
yield return @"C:\fileName:FileName.txt:";
yield return @"C:\fileName:FileName.txt:AA";
yield return @"C:\fileName:FileName.txt:AAA";
yield return @"ftp://fileName:FileName.txt:AAA";
}
public static IEnumerable<string> GetPathsWithComponentLongerThanMaxComponent()
{
// While paths themselves can be up to and including 32,000 characters, most volumes
// limit each component of the path to a total of 255 characters.
string component = new string('s', MaxComponent + 1);
yield return string.Format(@"C:\{0}", component);
yield return string.Format(@"C:\{0}\Filename.txt", component);
yield return string.Format(@"C:\{0}\Filename.txt\", component);
yield return string.Format(@"\\{0}\Share", component);
yield return string.Format(@"\\LOCALHOST\{0}", component);
yield return string.Format(@"\\LOCALHOST\{0}\FileName.txt", component);
yield return string.Format(@"\\LOCALHOST\Share\{0}", component);
}
public static IEnumerable<string> GetPathsLongerThanMaxDirectory(string rootPath)
{
yield return GetLongPath(rootPath, MaxDirectory + 1);
yield return GetLongPath(rootPath, MaxDirectory + 2);
yield return GetLongPath(rootPath, MaxDirectory + 3);
}
public static IEnumerable<string> GetPathsLongerThanMaxPath(string rootPath, bool useExtendedSyntax = false)
{
yield return GetLongPath(rootPath, MaxPath + 1, useExtendedSyntax);
yield return GetLongPath(rootPath, MaxPath + 2, useExtendedSyntax);
yield return GetLongPath(rootPath, MaxPath + 3, useExtendedSyntax);
}
public static IEnumerable<string> GetPathsLongerThanMaxLongPath(string rootPath, bool useExtendedSyntax = false)
{
yield return GetLongPath(rootPath, MaxExtendedPath + 1, useExtendedSyntax);
yield return GetLongPath(rootPath, MaxExtendedPath + 2, useExtendedSyntax);
}
private static string GetLongPath(string rootPath, int characterCount, bool extended = false)
{
return IOServices.GetPath(rootPath, characterCount, extended).FullPath;
}
public static IEnumerable<string> GetReservedDeviceNames()
{ // See: http://msdn.microsoft.com/en-us/library/aa365247.aspx
yield return "CON";
yield return "AUX";
yield return "NUL";
yield return "PRN";
yield return "COM1";
yield return "COM2";
yield return "COM3";
yield return "COM4";
yield return "COM5";
yield return "COM6";
yield return "COM7";
yield return "COM8";
yield return "COM9";
yield return "LPT1";
yield return "LPT2";
yield return "LPT3";
yield return "LPT4";
yield return "LPT5";
yield return "LPT6";
yield return "LPT7";
yield return "LPT8";
yield return "LPT9";
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Text;
namespace System.IO
{
/// <summary>Contains internal path helpers that are shared between many projects.</summary>
internal static partial class PathInternal
{
/// <summary>
/// Returns true if the path starts in a directory separator.
/// </summary>
internal static bool StartsWithDirectorySeparator(ReadOnlySpan<char> path) => path.Length > 0 && IsDirectorySeparator(path[0]);
#if MS_IO_REDIST
internal static string EnsureTrailingSeparator(string path)
=> EndsInDirectorySeparator(path) ? path : path + DirectorySeparatorCharAsString;
internal static bool EndsInDirectorySeparator(string path)
=> !string.IsNullOrEmpty(path) && IsDirectorySeparator(path[path.Length - 1]);
#else
internal static string EnsureTrailingSeparator(string path)
=> Path.EndsInDirectorySeparator(path.AsSpan()) ? path : path + DirectorySeparatorCharAsString;
#endif
internal static bool IsRoot(ReadOnlySpan<char> path)
=> path.Length == GetRootLength(path);
/// <summary>
/// Get the common path length from the start of the string.
/// </summary>
internal static int GetCommonPathLength(string first, string second, bool ignoreCase)
{
int commonChars = EqualStartingCharacterCount(first, second, ignoreCase: ignoreCase);
// If nothing matches
if (commonChars == 0)
return commonChars;
// Or we're a full string and equal length or match to a separator
if (commonChars == first.Length
&& (commonChars == second.Length || IsDirectorySeparator(second[commonChars])))
return commonChars;
if (commonChars == second.Length && IsDirectorySeparator(first[commonChars]))
return commonChars;
// It's possible we matched somewhere in the middle of a segment e.g. C:\Foodie and C:\Foobar.
while (commonChars > 0 && !IsDirectorySeparator(first[commonChars - 1]))
commonChars--;
return commonChars;
}
/// <summary>
/// Gets the count of common characters from the left optionally ignoring case
/// </summary>
internal static unsafe int EqualStartingCharacterCount(string first, string second, bool ignoreCase)
{
if (string.IsNullOrEmpty(first) || string.IsNullOrEmpty(second)) return 0;
int commonChars = 0;
fixed (char* f = first)
fixed (char* s = second)
{
char* l = f;
char* r = s;
char* leftEnd = l + first.Length;
char* rightEnd = r + second.Length;
while (l != leftEnd && r != rightEnd
&& (*l == *r || (ignoreCase && char.ToUpperInvariant(*l) == char.ToUpperInvariant(*r))))
{
commonChars++;
l++;
r++;
}
}
return commonChars;
}
/// <summary>
/// Returns true if the two paths have the same root
/// </summary>
internal static bool AreRootsEqual(string first, string second, StringComparison comparisonType)
{
int firstRootLength = GetRootLength(first.AsSpan());
int secondRootLength = GetRootLength(second.AsSpan());
return firstRootLength == secondRootLength
&& string.Compare(
strA: first,
indexA: 0,
strB: second,
indexB: 0,
length: firstRootLength,
comparisonType: comparisonType) == 0;
}
/// <summary>
/// Try to remove relative segments from the given path (without combining with a root).
/// </summary>
/// <param name="path">Input path</param>
/// <param name="rootLength">The length of the root of the given path</param>
internal static string RemoveRelativeSegments(string path, int rootLength)
{
Span<char> initialBuffer = stackalloc char[260 /* PathInternal.MaxShortPath */];
ValueStringBuilder sb = new ValueStringBuilder(initialBuffer);
if (RemoveRelativeSegments(path.AsSpan(), rootLength, ref sb))
{
path = sb.ToString();
}
sb.Dispose();
return path;
}
/// <summary>
/// Try to remove relative segments from the given path (without combining with a root).
/// </summary>
/// <param name="path">Input path</param>
/// <param name="rootLength">The length of the root of the given path</param>
/// <param name="sb">String builder that will store the result</param>
/// <returns>"true" if the path was modified</returns>
internal static bool RemoveRelativeSegments(ReadOnlySpan<char> path, int rootLength, ref ValueStringBuilder sb)
{
Debug.Assert(rootLength > 0);
bool flippedSeparator = false;
int skip = rootLength;
// We treat "\.." , "\." and "\\" as a relative segment. We want to collapse the first separator past the root presuming
// the root actually ends in a separator. Otherwise the first segment for RemoveRelativeSegments
// in cases like "\\?\C:\.\" and "\\?\C:\..\", the first segment after the root will be ".\" and "..\" which is not considered as a relative segment and hence not be removed.
if (PathInternal.IsDirectorySeparator(path[skip - 1]))
skip--;
// Remove "//", "/./", and "/../" from the path by copying each character to the output,
// except the ones we're removing, such that the builder contains the normalized path
// at the end.
if (skip > 0)
{
sb.Append(path.Slice(0, skip));
}
for (int i = skip; i < path.Length; i++)
{
char c = path[i];
if (PathInternal.IsDirectorySeparator(c) && i + 1 < path.Length)
{
// Skip this character if it's a directory separator and if the next character is, too,
// e.g. "parent//child" => "parent/child"
if (PathInternal.IsDirectorySeparator(path[i + 1]))
{
continue;
}
// Skip this character and the next if it's referring to the current directory,
// e.g. "parent/./child" => "parent/child"
if ((i + 2 == path.Length || PathInternal.IsDirectorySeparator(path[i + 2])) &&
path[i + 1] == '.')
{
i++;
continue;
}
// Skip this character and the next two if it's referring to the parent directory,
// e.g. "parent/child/../grandchild" => "parent/grandchild"
if (i + 2 < path.Length &&
(i + 3 == path.Length || PathInternal.IsDirectorySeparator(path[i + 3])) &&
path[i + 1] == '.' && path[i + 2] == '.')
{
// Unwind back to the last slash (and if there isn't one, clear out everything).
int s;
for (s = sb.Length - 1; s >= skip; s--)
{
if (PathInternal.IsDirectorySeparator(sb[s]))
{
sb.Length = (i + 3 >= path.Length && s == skip) ? s + 1 : s; // to avoid removing the complete "\tmp\" segment in cases like \\?\C:\tmp\..\, C:\tmp\..
break;
}
}
if (s < skip)
{
sb.Length = skip;
}
i += 2;
continue;
}
}
// Normalize the directory separator if needed
if (c != PathInternal.DirectorySeparatorChar && c == PathInternal.AltDirectorySeparatorChar)
{
c = PathInternal.DirectorySeparatorChar;
flippedSeparator = true;
}
sb.Append(c);
}
// If we haven't changed the source path, return the original
if (!flippedSeparator && sb.Length == path.Length)
{
return false;
}
// We may have eaten the trailing separator from the root when we started and not replaced it
if (skip != rootLength && sb.Length < rootLength)
{
sb.Append(path[rootLength - 1]);
}
return true;
}
}
}
| |
// 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.Runtime;
using System.ServiceModel.Channels;
using System.ServiceModel.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace System.ServiceModel.Dispatcher
{
public sealed class DispatchRuntime
{
private ConcurrencyMode _concurrencyMode;
private bool _ensureOrderedDispatch;
private bool _automaticInputSessionShutdown;
private ChannelDispatcher _channelDispatcher;
private IInstanceProvider _instanceProvider;
private IInstanceContextProvider _instanceContextProvider;
private SynchronizedCollection<IDispatchMessageInspector> _messageInspectors;
private OperationCollection _operations;
private ImmutableDispatchRuntime _runtime;
private SynchronizationContext _synchronizationContext;
private Type _type;
private DispatchOperation _unhandled;
private SharedRuntimeState _shared;
internal DispatchRuntime(ClientRuntime proxyRuntime, SharedRuntimeState shared)
: this(shared)
{
ClientRuntime = proxyRuntime ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(proxyRuntime));
_instanceProvider = new CallbackInstanceProvider();
_channelDispatcher = new ChannelDispatcher(shared);
_instanceContextProvider = InstanceContextProviderBase.GetProviderForMode(InstanceContextMode.PerSession, this);
Fx.Assert(!shared.IsOnServer, "Client constructor called on server?");
}
private DispatchRuntime(SharedRuntimeState shared)
{
_shared = shared;
_operations = new OperationCollection(this);
_messageInspectors = NewBehaviorCollection<IDispatchMessageInspector>();
_synchronizationContext = ThreadBehavior.GetCurrentSynchronizationContext();
_automaticInputSessionShutdown = true;
_unhandled = new DispatchOperation(this, "*", MessageHeaders.WildcardAction, MessageHeaders.WildcardAction);
_unhandled.InternalFormatter = MessageOperationFormatter.Instance;
_unhandled.InternalInvoker = new UnhandledActionInvoker(this);
}
public IInstanceContextProvider InstanceContextProvider
{
get
{
return _instanceContextProvider;
}
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value)));
}
lock (ThisLock)
{
InvalidateRuntime();
_instanceContextProvider = value;
}
}
}
public ConcurrencyMode ConcurrencyMode
{
get
{
return _concurrencyMode;
}
set
{
lock (ThisLock)
{
InvalidateRuntime();
_concurrencyMode = value;
}
}
}
public bool EnsureOrderedDispatch
{
get
{
return _ensureOrderedDispatch;
}
set
{
lock (ThisLock)
{
InvalidateRuntime();
_ensureOrderedDispatch = value;
}
}
}
public bool AutomaticInputSessionShutdown
{
get { return _automaticInputSessionShutdown; }
set
{
lock (ThisLock)
{
InvalidateRuntime();
_automaticInputSessionShutdown = value;
}
}
}
public ChannelDispatcher ChannelDispatcher
{
get { return _channelDispatcher ?? EndpointDispatcher.ChannelDispatcher; }
}
public ClientRuntime CallbackClientRuntime
{
get
{
if (ClientRuntime == null)
{
lock (ThisLock)
{
if (ClientRuntime == null)
{
ClientRuntime = new ClientRuntime(this, _shared);
}
}
}
return ClientRuntime;
}
}
public EndpointDispatcher EndpointDispatcher { get; } = null;
public IInstanceProvider InstanceProvider
{
get { return _instanceProvider; }
set
{
lock (ThisLock)
{
InvalidateRuntime();
_instanceProvider = value;
}
}
}
public SynchronizedCollection<IDispatchMessageInspector> MessageInspectors
{
get { return _messageInspectors; }
}
public SynchronizedKeyedCollection<string, DispatchOperation> Operations
{
get { return _operations; }
}
public SynchronizationContext SynchronizationContext
{
get { return _synchronizationContext; }
set
{
lock (ThisLock)
{
InvalidateRuntime();
_synchronizationContext = value;
}
}
}
public Type Type
{
get { return _type; }
set
{
lock (ThisLock)
{
InvalidateRuntime();
_type = value;
}
}
}
public DispatchOperation UnhandledDispatchOperation
{
get { return _unhandled; }
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value));
}
lock (ThisLock)
{
InvalidateRuntime();
_unhandled = value;
}
}
}
internal bool HasMatchAllOperation
{
get
{
return false;
}
}
internal bool EnableFaults
{
get
{
if (IsOnServer)
{
ChannelDispatcher channelDispatcher = ChannelDispatcher;
return (channelDispatcher != null) && channelDispatcher.EnableFaults;
}
else
{
return _shared.EnableFaults;
}
}
}
internal bool IsOnServer
{
get { return _shared.IsOnServer; }
}
internal bool ManualAddressing
{
get
{
if (IsOnServer)
{
ChannelDispatcher channelDispatcher = ChannelDispatcher;
return (channelDispatcher != null) && channelDispatcher.ManualAddressing;
}
else
{
return _shared.ManualAddressing;
}
}
}
internal int MaxParameterInspectors
{
get
{
lock (ThisLock)
{
int max = 0;
for (int i = 0; i < _operations.Count; i++)
{
max = System.Math.Max(max, _operations[i].ParameterInspectors.Count);
}
max = System.Math.Max(max, _unhandled.ParameterInspectors.Count);
return max;
}
}
}
// Internal access to CallbackClientRuntime, but this one doesn't create on demand
internal ClientRuntime ClientRuntime { get; private set; }
internal object ThisLock
{
get { return _shared; }
}
internal DispatchOperationRuntime GetOperation(ref Message message)
{
ImmutableDispatchRuntime runtime = GetRuntime();
return runtime.GetOperation(ref message);
}
internal ImmutableDispatchRuntime GetRuntime()
{
ImmutableDispatchRuntime runtime = _runtime;
if (runtime != null)
{
return runtime;
}
else
{
return GetRuntimeCore();
}
}
private ImmutableDispatchRuntime GetRuntimeCore()
{
lock (ThisLock)
{
if (_runtime == null)
{
_runtime = new ImmutableDispatchRuntime(this);
}
return _runtime;
}
}
internal void InvalidateRuntime()
{
lock (ThisLock)
{
_shared.ThrowIfImmutable();
_runtime = null;
}
}
internal void LockDownProperties()
{
_shared.LockDownProperties();
}
internal SynchronizedCollection<T> NewBehaviorCollection<T>()
{
return new DispatchBehaviorCollection<T>(this);
}
internal class UnhandledActionInvoker : IOperationInvoker
{
private readonly DispatchRuntime _dispatchRuntime;
public UnhandledActionInvoker(DispatchRuntime dispatchRuntime)
{
_dispatchRuntime = dispatchRuntime;
}
public object[] AllocateInputs()
{
return new object[1];
}
public Task<object> InvokeAsync(object instance, object[] inputs, out object[] outputs)
{
outputs = EmptyArray<object>.Allocate(0);
Message message = inputs[0] as Message;
if (message == null)
{
return null;
}
string action = message.Headers.Action;
FaultCode code = FaultCode.CreateSenderFaultCode(AddressingStrings.ActionNotSupported,
message.Version.Addressing.Namespace);
string reasonText = SR.Format(SR.SFxNoEndpointMatchingContract, action);
FaultReason reason = new FaultReason(reasonText);
FaultException exception = new FaultException(reason, code);
ErrorBehavior.ThrowAndCatch(exception);
ServiceChannel serviceChannel = OperationContext.Current.InternalServiceChannel;
OperationContext.Current.OperationCompleted +=
delegate (object sender, EventArgs e)
{
ChannelDispatcher channelDispatcher = _dispatchRuntime.ChannelDispatcher;
if (!channelDispatcher.HandleError(exception) && serviceChannel.HasSession)
{
try
{
serviceChannel.Close(ChannelHandler.CloseAfterFaultTimeout);
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
channelDispatcher.HandleError(ex);
}
}
};
if (_dispatchRuntime._shared.EnableFaults)
{
MessageFault fault = MessageFault.CreateFault(code, reason, action);
return Task.FromResult((object)Message.CreateMessage(message.Version, fault, message.Version.Addressing.DefaultFaultAction));
}
else
{
OperationContext.Current.RequestContext.Close();
OperationContext.Current.RequestContext = null;
return Task.FromResult((object)null);
}
}
public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException());
}
public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException());
}
}
internal class DispatchBehaviorCollection<T> : SynchronizedCollection<T>
{
private DispatchRuntime _outer;
internal DispatchBehaviorCollection(DispatchRuntime outer)
: base(outer.ThisLock)
{
_outer = outer;
}
protected override void ClearItems()
{
_outer.InvalidateRuntime();
base.ClearItems();
}
protected override void InsertItem(int index, T item)
{
if (item == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(item));
}
_outer.InvalidateRuntime();
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
_outer.InvalidateRuntime();
base.RemoveItem(index);
}
protected override void SetItem(int index, T item)
{
if (item == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(item));
}
_outer.InvalidateRuntime();
base.SetItem(index, item);
}
}
internal class OperationCollection : SynchronizedKeyedCollection<string, DispatchOperation>
{
private DispatchRuntime _outer;
internal OperationCollection(DispatchRuntime outer)
: base(outer.ThisLock)
{
_outer = outer;
}
protected override void ClearItems()
{
_outer.InvalidateRuntime();
base.ClearItems();
}
protected override string GetKeyForItem(DispatchOperation item)
{
return item.Name;
}
protected override void InsertItem(int index, DispatchOperation item)
{
if (item == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(item));
}
if (item.Parent != _outer)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.SFxMismatchedOperationParent);
}
_outer.InvalidateRuntime();
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
_outer.InvalidateRuntime();
base.RemoveItem(index);
}
protected override void SetItem(int index, DispatchOperation item)
{
if (item == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(item));
}
if (item.Parent != _outer)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.SFxMismatchedOperationParent);
}
_outer.InvalidateRuntime();
base.SetItem(index, item);
}
}
private class CallbackInstanceProvider : IInstanceProvider
{
object IInstanceProvider.GetInstance(InstanceContext instanceContext)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxCannotActivateCallbackInstace));
}
object IInstanceProvider.GetInstance(InstanceContext instanceContext, Message message)
{
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.SFxCannotActivateCallbackInstace), message);
}
void IInstanceProvider.ReleaseInstance(InstanceContext instanceContext, object instance)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxCannotActivateCallbackInstace));
}
}
}
}
| |
/*
MIT License
Copyright (c) 2017 Saied Zarrinmehr
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using SpatialAnalysis.FieldUtility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using SpatialAnalysis.CellularEnvironment;
using SpatialAnalysis.Data;
namespace SpatialAnalysis.Data.Visualization
{
/// <summary>
/// Interaction logic for SpatialDataFieldSelection.xaml
/// </summary>
public partial class SpatialDataFieldSelection : Window
{
#region Hiding the close button
private const int GWL_STYLE = -16;
private const int WS_SYSMENU = 0x80000;
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
void dataSelection_Loaded(object sender, RoutedEventArgs e)
{
var hwnd = new WindowInteropHelper(this).Handle;
SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);
}
#endregion
private OSMDocument _host { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="SpatialDataFieldSelection"/> is result.
/// </summary>
/// <value><c>true</c> if the data is assigned correctly; otherwise, <c>false</c>.</value>
public bool Result { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to visualize data cost or data
/// </summary>
/// <value><c>true</c> if visualize cost; otherwise, <c>false</c>.</value>
public bool VisualizeCost { get; set; }
TextBlock cellularDataNames { get; set; }
TextBlock fieldNames { get; set; }
TextBlock _eventNames { get; set; }
/// <summary>
/// Gets or sets all selected spatial data.
/// </summary>
/// <value>All selected spatial data.</value>
public List<ISpatialData> AllSelectedSpatialData { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="SpatialDataFieldSelection"/> class.
/// </summary>
/// <param name="host">The main document to which this class belongs.</param>
/// <param name="title">The title.</param>
/// <param name="allowForMultipleSelections">if set to <c>true</c> multiple selections is allowed.</param>
public SpatialDataFieldSelection(OSMDocument host, string title, bool allowForMultipleSelections)
{
InitializeComponent();
this._host = host;
this._title.Text = title;
if (allowForMultipleSelections)
{
this.dataNames.SelectionMode = SelectionMode.Multiple;
}
else
{
this.dataNames.SelectionMode = SelectionMode.Single;
}
this.cellularDataNames = new TextBlock()
{
Text = "Data".ToUpper(),
FontSize = 14,
FontWeight = FontWeights.Bold,
Foreground = new SolidColorBrush(Colors.DarkGray)
};
this.dataNames.Items.Add(this.cellularDataNames);
foreach (Function item in this._host.cellularFloor.AllSpatialDataFields.Values)
{
SpatialDataField data = item as SpatialDataField;
if (data != null)
{
this.dataNames.Items.Add(data);
}
}
this.fieldNames = new TextBlock()
{
Text = "Activity".ToUpper(),
FontSize = 14,
FontWeight = FontWeights.Bold,
Foreground = new SolidColorBrush(Colors.DarkGray)
};
if (this._host.AllActivities.Count > 0)
{
this.dataNames.Items.Add(this.fieldNames);
foreach (KeyValuePair<string, Activity> item in this._host.AllActivities)
{
this.dataNames.Items.Add(item.Value);
}
}
this._eventNames = new TextBlock
{
Text = "Occupancy Events".ToUpper(),
FontSize = 14,
FontWeight = FontWeights.Bold,
Foreground = new SolidColorBrush(Colors.DarkGray)
};
if (this._host.AllOccupancyEvent.Count > 0)
{
this.dataNames.Items.Add(this._eventNames);
foreach (SpatialAnalysis.Events.EvaluationEvent item in this._host.AllOccupancyEvent.Values)
{
this.dataNames.Items.Add(item);
}
}
this.dataNames.SelectionChanged += dataNames_SelectionChanged;
this.Result = false;
this.AllSelectedSpatialData = new List<ISpatialData>();
this.Loaded += dataSelection_Loaded;
this.KeyDown += new KeyEventHandler(_dataSelection_KeyDown);
}
void dataNames_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
this.dataNames.SelectionChanged -= dataNames_SelectionChanged;
try
{
if (this.dataNames.SelectionMode == SelectionMode.Single)
{
var obj = this.dataNames.SelectedItem;
TextBlock selected = obj as TextBlock;
if (selected != null)
{
this.dataNames.SelectedIndex = -1;
}
}
else if (this.dataNames.SelectionMode == SelectionMode.Multiple)
{
List<object> data = new List<object>();
foreach (var item in this.dataNames.SelectedItems)
{
TextBlock selected = item as TextBlock;
if (selected == null)
{
data.Add(item);
}
}
this.dataNames.SelectedItems.Clear();
foreach (var item in data)
{
this.dataNames.SelectedItems.Add(item);
}
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
this.dataNames.SelectionChanged += dataNames_SelectionChanged;
}
void _dataSelection_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
foreach (var item in this.dataNames.SelectedItems)
{
ISpatialData spatialData = item as ISpatialData;
if (spatialData != null)
{
this.AllSelectedSpatialData.Add(spatialData);
}
}
this.Result = true;
this.Close();
}
else if (e.Key == Key.Escape)
{
this.Result = false;
this.Close();
}
}
private void Okay_Click(object sender, RoutedEventArgs e)
{
foreach (var item in this.dataNames.SelectedItems)
{
ISpatialData spatialData = item as ISpatialData;
if (spatialData != null)
{
this.AllSelectedSpatialData.Add(spatialData);
}
}
this.Result = true;
this.Close();
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
this.Result = false;
this.Close();
}
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Text;
using OpenSource.UPnP.AV;
namespace OpenSource.UPnP.AV.CdsMetadata
{
/// <summary>
/// Represent the names of attributes applicable to resources.
/// The order of these attributes should match as in the ones
/// in <see cref="_ATTRIB"/>.
/// </summary>
public enum _RESATTRIB
{
/// <summary>
/// required for res
/// </summary>
protocolInfo = _ATTRIB.protocolInfo,
/// <summary>
/// optional for res
/// </summary>
importUri,
/// <summary>
/// optional for res
/// </summary>
size,
/// <summary>
/// optional for res
/// </summary>
duration,
/// <summary>
/// optional for res
/// </summary>
bitrate,
/// <summary>
/// optional for res
/// </summary>
sampleFrequency,
/// <summary>
/// optional for res
/// </summary>
bitsPerSample,
/// <summary>
/// optional for res
/// </summary>
nrAudioChannels,
/// <summary>
/// optional for res
/// </summary>
resolution,
/// <summary>
/// optional for res
/// </summary>
colorDepth,
/// <summary>
/// optional for res
/// </summary>
protection,
}
/// <summary>
/// Various attributes in all 3 (upnp:, dc:, DIDL-Lite) namespaces tags.
/// </summary>
public enum _ATTRIB
{
/// <summary>
/// required for item, container
/// </summary>
id,
/// <summary>
/// required for item, container
/// </summary>
restricted,
/// <summary>
/// optional for item, container
/// </summary>
parentID,
/// <summary>
/// optional for item, required by
/// item if the item is a reference
/// to another item
/// </summary>
refID,
/// <summary>
/// optional for container
/// </summary>
childCount,
/// <summary>
/// optional for container
/// </summary>
searchable,
/// <summary>
/// required for res
/// </summary>
protocolInfo,
/// <summary>
/// optional for res
/// </summary>
importUri,
/// <summary>
/// optional for res
/// </summary>
size,
/// <summary>
/// optional for res
/// </summary>
duration,
/// <summary>
/// optional for res
/// </summary>
bitrate,
/// <summary>
/// optional for res
/// </summary>
sampleFrequency,
/// <summary>
/// optional for res
/// </summary>
bitsPerSample,
/// <summary>
/// optional for res
/// </summary>
nrAudioChannels,
/// <summary>
/// optional for res
/// </summary>
resolution,
/// <summary>
/// optional for res
/// </summary>
colorDepth,
/// <summary>
/// optional for res
/// </summary>
protection,
/// <summary>
/// required for upnp:searchClass and upnp:createClass
/// </summary>
includeDerived,
/// <summary>
/// optional for upnp:class, upnp:searchClass, and upnp:createClass
/// </summary>
name,
/// <summary>
/// optional for upnp:person
/// </summary>
role,
}
/// <summary>
/// Enumerates the optional resource properties.
/// The declared order of the resources should match
/// the _RESATTRIB enumerator.
/// </summary>
public enum OptionalResourceProperties
{
size = _RESATTRIB.size,
duration,
bitrate,
sampleFrequency,
bitsPerSample,
nrAudioChannels,
resolution,
colorDepth,
protection,
}
/// <summary>
/// Enumeration of dublin-core tag names.
/// The declared order should match the
/// CommonPropertyNames enumerator.
/// </summary>
public enum _DC
{
title = CommonPropertyNames.title,
contributor,
publisher,
description,
date,
language,
relation,
rights,
creator,
}
/// <summary>
/// Enumeration of UPNP-AV defined tag names.
/// The declared order should match the
/// CommonPropertyNames enumerator.
/// </summary>
public enum _UPNP
{
/// <summary>
/// upnp namespace items
/// </summary>
artist = CommonPropertyNames.artist,
actor,
author,
role,
producer,
director,
genre,
album,
playlist,
albumArtURI,
artistDiscographyURI,
lyricsURI,
storageTotal,
storageUsed,
storageFree,
storageMaxPartition,
storageMedium,
longDescription,
icon,
region,
rating,
radioCallSign,
radioStationID,
radioBand,
channelNr,
channelName,
scheduledStartTime,
scheduledEndTime,
DVDRegionCode,
originalTrackNumber,
toc,
userAnnotation,
/// <summary>
/// This is a special case because it is an enumeration type.
/// </summary>
writeStatus,
/// <summary>
/// These are special cases of the _UPNP enumeration
/// because they are represented by classes and not
/// simple data types.
/// </summary>
Class,
searchClass,
createClass,
}
/// <summary>
/// Enumeration of DIDL-Lite tags
/// The declared order should match the
/// CommonPropertyNames enumerator.
/// </summary>
public enum _DIDL
{
DIDL_Lite,
Container,
Item,
Res,
Desc,
}
/// <summary>
/// Enumeration of standard metadata properties that
/// can be used with the
/// <see cref="Tags"/>
/// class's indexer. This aggregates the _UPNP and _DC
/// enumerations.
/// </summary>
public enum CommonPropertyNames
{
artist, // upnp namespace items order must be same as _UPNP
actor,
author,
role,
producer,
director,
genre,
album,
playlist,
albumArtURI,
artistDiscographyURI,
lyricsURI,
storageTotal,
storageUsed,
storageFree,
storageMaxPartition,
storageMedium,
longDescription,
icon,
region,
rating,
radioCallSign,
radioStationID,
radioBand,
channelNr,
channelName,
scheduledStartTime,
scheduledEndTime,
DVDRegionCode,
originalTrackNumber,
toc,
userAnnotation,
writeStatus,
Class,
searchClass,
createClass,
DoNotUse, //not used, reserved for implementation
title, //dublin-core tags must be same order as in _DC
contributor,
publisher,
description,
date,
language,
relation,
rights,
creator,
}
/// <summary>
/// Enumeration of the values indicating whether
/// an object's binary resources can be overwritten.
/// </summary>
public enum EnumWriteStatus
{
UNKNOWN,
/// <summary>
/// But the english language says to use this...
/// ... and we've seen people use this so
/// we'll allow both.
/// </summary>
WRITEABLE,
/// <summary>
/// The spec says to use this...
/// </summary>
WRITABLE,
PROTECTED,
NOT_WRITABLE,
MIXED
}
}
| |
namespace Fonlow.SyncML.Windows
{
partial class SyncMLForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
logMemoListerner.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SyncMLForm));
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.syncToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.syncToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.slowSyncToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.stopSyncToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.syncFromClientToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.refreshFromClientToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.syncFromServerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.refreshFromServerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.settingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.displayLogWindowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.testFormToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.contentToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.button1 = new System.Windows.Forms.Button();
this.edStatus = new System.Windows.Forms.TextBox();
this.btnSync = new System.Windows.Forms.Button();
this.progressBar = new System.Windows.Forms.ProgressBar();
this.lbProgress = new System.Windows.Forms.Label();
this.lbProgressReceiving = new System.Windows.Forms.Label();
this.progressBarReceiving = new System.Windows.Forms.ProgressBar();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.syncToolStripMenuItem,
this.toolsToolStripMenuItem,
this.helpToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(355, 24);
this.menuStrip1.TabIndex = 1;
this.menuStrip1.Text = "menuStrip1";
//
// syncToolStripMenuItem
//
this.syncToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.syncToolStripMenuItem1,
this.slowSyncToolStripMenuItem,
this.pingToolStripMenuItem,
this.stopSyncToolStripMenuItem,
this.syncFromClientToolStripMenuItem,
this.refreshFromClientToolStripMenuItem,
this.syncFromServerToolStripMenuItem,
this.refreshFromServerToolStripMenuItem});
this.syncToolStripMenuItem.Name = "syncToolStripMenuItem";
this.syncToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.syncToolStripMenuItem.Text = "Sync";
//
// syncToolStripMenuItem1
//
this.syncToolStripMenuItem1.Name = "syncToolStripMenuItem1";
this.syncToolStripMenuItem1.ShortcutKeys = System.Windows.Forms.Keys.F2;
this.syncToolStripMenuItem1.Size = new System.Drawing.Size(312, 22);
this.syncToolStripMenuItem1.Text = "Sync";
this.syncToolStripMenuItem1.Click += new System.EventHandler(this.syncToolStripMenuItem1_Click);
//
// slowSyncToolStripMenuItem
//
this.slowSyncToolStripMenuItem.Name = "slowSyncToolStripMenuItem";
this.slowSyncToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F3;
this.slowSyncToolStripMenuItem.Size = new System.Drawing.Size(312, 22);
this.slowSyncToolStripMenuItem.Text = "Slow Sync";
this.slowSyncToolStripMenuItem.Click += new System.EventHandler(this.slowSyncToolStripMenuItem_Click_1);
//
// pingToolStripMenuItem
//
this.pingToolStripMenuItem.Name = "pingToolStripMenuItem";
this.pingToolStripMenuItem.Size = new System.Drawing.Size(312, 22);
this.pingToolStripMenuItem.Text = "Reset Last Anchor";
this.pingToolStripMenuItem.Visible = false;
this.pingToolStripMenuItem.Click += new System.EventHandler(this.pingToolStripMenuItem_Click);
//
// stopSyncToolStripMenuItem
//
this.stopSyncToolStripMenuItem.Enabled = false;
this.stopSyncToolStripMenuItem.Name = "stopSyncToolStripMenuItem";
this.stopSyncToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Q)));
this.stopSyncToolStripMenuItem.Size = new System.Drawing.Size(312, 22);
this.stopSyncToolStripMenuItem.Text = "Stop Sync";
this.stopSyncToolStripMenuItem.Click += new System.EventHandler(this.stopSyncToolStripMenuItem_Click);
//
// syncFromClientToolStripMenuItem
//
this.syncFromClientToolStripMenuItem.Name = "syncFromClientToolStripMenuItem";
this.syncFromClientToolStripMenuItem.Size = new System.Drawing.Size(312, 22);
this.syncFromClientToolStripMenuItem.Text = "One-Way Sync from Client";
this.syncFromClientToolStripMenuItem.Click += new System.EventHandler(this.syncFromClientToolStripMenuItem_Click);
//
// refreshFromClientToolStripMenuItem
//
this.refreshFromClientToolStripMenuItem.Name = "refreshFromClientToolStripMenuItem";
this.refreshFromClientToolStripMenuItem.Size = new System.Drawing.Size(312, 22);
this.refreshFromClientToolStripMenuItem.Text = "Replace All of the Server Data with Local Data";
this.refreshFromClientToolStripMenuItem.Click += new System.EventHandler(this.refreshFromClientToolStripMenuItem_Click);
//
// syncFromServerToolStripMenuItem
//
this.syncFromServerToolStripMenuItem.Name = "syncFromServerToolStripMenuItem";
this.syncFromServerToolStripMenuItem.Size = new System.Drawing.Size(312, 22);
this.syncFromServerToolStripMenuItem.Text = "One-Way Sync from Server";
this.syncFromServerToolStripMenuItem.Click += new System.EventHandler(this.syncFromServerToolStripMenuItem_Click);
//
// refreshFromServerToolStripMenuItem
//
this.refreshFromServerToolStripMenuItem.Name = "refreshFromServerToolStripMenuItem";
this.refreshFromServerToolStripMenuItem.Size = new System.Drawing.Size(312, 22);
this.refreshFromServerToolStripMenuItem.Text = "Replace All Local Data with the Server Data";
this.refreshFromServerToolStripMenuItem.Click += new System.EventHandler(this.refreshFromServerToolStripMenuItem_Click);
//
// toolsToolStripMenuItem
//
this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.settingsToolStripMenuItem,
this.displayLogWindowToolStripMenuItem,
this.testFormToolStripMenuItem});
this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem";
this.toolsToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.toolsToolStripMenuItem.Text = "Tools";
this.toolsToolStripMenuItem.Click += new System.EventHandler(this.toolsToolStripMenuItem_Click);
//
// settingsToolStripMenuItem
//
this.settingsToolStripMenuItem.Name = "settingsToolStripMenuItem";
this.settingsToolStripMenuItem.Size = new System.Drawing.Size(182, 22);
this.settingsToolStripMenuItem.Text = "Preferences...";
this.settingsToolStripMenuItem.Click += new System.EventHandler(this.settingsToolStripMenuItem_Click);
//
// displayLogWindowToolStripMenuItem
//
this.displayLogWindowToolStripMenuItem.Name = "displayLogWindowToolStripMenuItem";
this.displayLogWindowToolStripMenuItem.Size = new System.Drawing.Size(182, 22);
this.displayLogWindowToolStripMenuItem.Text = "Display Log Window";
this.displayLogWindowToolStripMenuItem.Click += new System.EventHandler(this.displayLogWindowToolStripMenuItem_Click);
//
// testFormToolStripMenuItem
//
this.testFormToolStripMenuItem.Name = "testFormToolStripMenuItem";
this.testFormToolStripMenuItem.Size = new System.Drawing.Size(182, 22);
this.testFormToolStripMenuItem.Text = "TestForm";
this.testFormToolStripMenuItem.Visible = false;
this.testFormToolStripMenuItem.Click += new System.EventHandler(this.testFormToolStripMenuItem_Click);
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.contentToolStripMenuItem,
this.aboutToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.helpToolStripMenuItem.Text = "Help";
//
// contentToolStripMenuItem
//
this.contentToolStripMenuItem.Name = "contentToolStripMenuItem";
this.contentToolStripMenuItem.Size = new System.Drawing.Size(122, 22);
this.contentToolStripMenuItem.Text = "Contents";
this.contentToolStripMenuItem.Click += new System.EventHandler(this.contentToolStripMenuItem_Click);
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(122, 22);
this.aboutToolStripMenuItem.Text = "About...";
this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click);
//
// button1
//
this.button1.Image = ((System.Drawing.Image)(resources.GetObject("button1.Image")));
this.button1.ImageAlign = System.Drawing.ContentAlignment.TopCenter;
this.button1.Location = new System.Drawing.Point(89, 28);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(77, 58);
this.button1.TabIndex = 9;
this.button1.Text = "Preferences";
this.button1.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// edStatus
//
this.edStatus.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.edStatus.Location = new System.Drawing.Point(6, 92);
this.edStatus.Multiline = true;
this.edStatus.Name = "edStatus";
this.edStatus.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.edStatus.Size = new System.Drawing.Size(342, 198);
this.edStatus.TabIndex = 10;
//
// btnSync
//
this.btnSync.Image = ((System.Drawing.Image)(resources.GetObject("btnSync.Image")));
this.btnSync.ImageAlign = System.Drawing.ContentAlignment.TopCenter;
this.btnSync.Location = new System.Drawing.Point(6, 28);
this.btnSync.Name = "btnSync";
this.btnSync.Size = new System.Drawing.Size(77, 58);
this.btnSync.TabIndex = 6;
this.btnSync.Text = "Sync";
this.btnSync.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
this.btnSync.UseVisualStyleBackColor = true;
this.btnSync.Click += new System.EventHandler(this.btnSync_Click);
//
// progressBar
//
this.progressBar.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(128)))));
this.progressBar.Location = new System.Drawing.Point(172, 74);
this.progressBar.Name = "progressBar";
this.progressBar.Size = new System.Drawing.Size(171, 12);
this.progressBar.TabIndex = 11;
this.progressBar.Visible = false;
//
// lbProgress
//
this.lbProgress.AutoSize = true;
this.lbProgress.Location = new System.Drawing.Point(173, 58);
this.lbProgress.Name = "lbProgress";
this.lbProgress.Size = new System.Drawing.Size(34, 13);
this.lbProgress.TabIndex = 12;
this.lbProgress.Text = " ";
this.lbProgress.Visible = false;
//
// lbProgressReceiving
//
this.lbProgressReceiving.AutoSize = true;
this.lbProgressReceiving.Location = new System.Drawing.Point(173, 28);
this.lbProgressReceiving.Name = "lbProgressReceiving";
this.lbProgressReceiving.Size = new System.Drawing.Size(34, 13);
this.lbProgressReceiving.TabIndex = 14;
this.lbProgressReceiving.Text = " ";
this.lbProgressReceiving.Visible = false;
//
// progressBarReceiving
//
this.progressBarReceiving.ForeColor = System.Drawing.SystemColors.GradientActiveCaption;
this.progressBarReceiving.Location = new System.Drawing.Point(172, 44);
this.progressBarReceiving.Name = "progressBarReceiving";
this.progressBarReceiving.Size = new System.Drawing.Size(171, 12);
this.progressBarReceiving.TabIndex = 13;
this.progressBarReceiving.Visible = false;
//
// SyncMLForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(355, 297);
this.Controls.Add(this.lbProgressReceiving);
this.Controls.Add(this.progressBarReceiving);
this.Controls.Add(this.lbProgress);
this.Controls.Add(this.progressBar);
this.Controls.Add(this.button1);
this.Controls.Add(this.edStatus);
this.Controls.Add(this.btnSync);
this.Controls.Add(this.menuStrip1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "SyncMLForm";
this.Text = "SyncML Client for XXX";
this.Load += new System.EventHandler(this.FrmSyncML_Load);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FrmSyncML_FormClosing);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem syncToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pingToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem syncToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem settingsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem displayLogWindowToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem contentToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox edStatus;
private System.Windows.Forms.Button btnSync;
private System.Windows.Forms.ToolStripMenuItem testFormToolStripMenuItem;
private System.Windows.Forms.ProgressBar progressBar;
private System.Windows.Forms.Label lbProgress;
private System.Windows.Forms.Label lbProgressReceiving;
private System.Windows.Forms.ProgressBar progressBarReceiving;
private System.Windows.Forms.ToolStripMenuItem slowSyncToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem stopSyncToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem syncFromClientToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem refreshFromClientToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem syncFromServerToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem refreshFromServerToolStripMenuItem;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Reflection
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Threading;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_FieldInfo))]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class FieldInfo : MemberInfo, _FieldInfo
{
#region Static Members
public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle)
{
if (handle.IsNullHandle())
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"), nameof(handle));
FieldInfo f = RuntimeType.GetFieldInfo(handle.GetRuntimeFieldInfo());
Type declaringType = f.DeclaringType;
if (declaringType != null && declaringType.IsGenericType)
throw new ArgumentException(String.Format(
CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_FieldDeclaringTypeGeneric"),
f.Name, declaringType.GetGenericTypeDefinition()));
return f;
}
[System.Runtime.InteropServices.ComVisible(false)]
public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle, RuntimeTypeHandle declaringType)
{
if (handle.IsNullHandle())
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"));
return RuntimeType.GetFieldInfo(declaringType.GetRuntimeType(), handle.GetRuntimeFieldInfo());
}
#endregion
#region Constructor
protected FieldInfo() { }
#endregion
public static bool operator ==(FieldInfo left, FieldInfo right)
{
if (ReferenceEquals(left, right))
return true;
if ((object)left == null || (object)right == null ||
left is RuntimeFieldInfo || right is RuntimeFieldInfo)
{
return false;
}
return left.Equals(right);
}
public static bool operator !=(FieldInfo left, FieldInfo right)
{
return !(left == right);
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Field; } }
#endregion
#region Public Abstract\Virtual Members
public virtual Type[] GetRequiredCustomModifiers()
{
throw new NotImplementedException();
}
public virtual Type[] GetOptionalCustomModifiers()
{
throw new NotImplementedException();
}
[CLSCompliant(false)]
public virtual void SetValueDirect(TypedReference obj, Object value)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS"));
}
[CLSCompliant(false)]
public virtual Object GetValueDirect(TypedReference obj)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS"));
}
public abstract RuntimeFieldHandle FieldHandle { get; }
public abstract Type FieldType { get; }
public abstract Object GetValue(Object obj);
public virtual Object GetRawConstantValue() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS")); }
public abstract void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture);
public abstract FieldAttributes Attributes { get; }
#endregion
#region Public Members
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public void SetValue(Object obj, Object value)
{
// Theoretically we should set up a LookForMyCaller stack mark here and pass that along.
// But to maintain backward compatibility we can't switch to calling an
// internal overload that takes a stack mark.
// Fortunately the stack walker skips all the reflection invocation frames including this one.
// So this method will never be returned by the stack walker as the caller.
// See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp.
SetValue(obj, value, BindingFlags.Default, Type.DefaultBinder, null);
}
public bool IsPublic { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Public; } }
public bool IsPrivate { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Private; } }
public bool IsFamily { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Family; } }
public bool IsAssembly { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Assembly; } }
public bool IsFamilyAndAssembly { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamANDAssem; } }
public bool IsFamilyOrAssembly { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamORAssem; } }
public bool IsStatic { get { return(Attributes & FieldAttributes.Static) != 0; } }
public bool IsInitOnly { get { return(Attributes & FieldAttributes.InitOnly) != 0; } }
public bool IsLiteral { get { return(Attributes & FieldAttributes.Literal) != 0; } }
public bool IsNotSerialized { get { return(Attributes & FieldAttributes.NotSerialized) != 0; } }
public bool IsSpecialName { get { return(Attributes & FieldAttributes.SpecialName) != 0; } }
public bool IsPinvokeImpl { get { return(Attributes & FieldAttributes.PinvokeImpl) != 0; } }
public virtual bool IsSecurityCritical
{
get { return FieldHandle.IsSecurityCritical(); }
}
public virtual bool IsSecuritySafeCritical
{
get { return FieldHandle.IsSecuritySafeCritical(); }
}
public virtual bool IsSecurityTransparent
{
get { return FieldHandle.IsSecurityTransparent(); }
}
#endregion
}
[Serializable]
internal abstract class RuntimeFieldInfo : FieldInfo, ISerializable
{
#region Private Data Members
private BindingFlags m_bindingFlags;
protected RuntimeTypeCache m_reflectedTypeCache;
protected RuntimeType m_declaringType;
#endregion
#region Constructor
protected RuntimeFieldInfo()
{
// Used for dummy head node during population
}
protected RuntimeFieldInfo(RuntimeTypeCache reflectedTypeCache, RuntimeType declaringType, BindingFlags bindingFlags)
{
m_bindingFlags = bindingFlags;
m_declaringType = declaringType;
m_reflectedTypeCache = reflectedTypeCache;
}
#endregion
#region NonPublic Members
internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
private RuntimeType ReflectedTypeInternal
{
get
{
return m_reflectedTypeCache.GetRuntimeType();
}
}
internal RuntimeType GetDeclaringTypeInternal()
{
return m_declaringType;
}
internal RuntimeType GetRuntimeType() { return m_declaringType; }
internal abstract RuntimeModule GetRuntimeModule();
#endregion
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return MemberTypes.Field; } }
public override Type ReflectedType
{
get
{
return m_reflectedTypeCache.IsGlobal ? null : ReflectedTypeInternal;
}
}
public override Type DeclaringType
{
get
{
return m_reflectedTypeCache.IsGlobal ? null : m_declaringType;
}
}
public override Module Module { get { return GetRuntimeModule(); } }
#endregion
#region Object Overrides
public unsafe override String ToString()
{
return FieldType.FormatTypeName() + " " + Name;
}
#endregion
#region ICustomAttributeProvider
public override Object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
#region FieldInfo Overrides
// All implemented on derived classes
#endregion
#region ISerializable Implementation
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
MemberInfoSerializationHolder.GetSerializationInfo(
info,
Name,
ReflectedTypeInternal,
ToString(),
MemberTypes.Field);
}
#endregion
}
[Serializable]
internal unsafe sealed class RtFieldInfo : RuntimeFieldInfo, IRuntimeFieldInfo
{
#region FCalls
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static private extern void PerformVisibilityCheckOnField(IntPtr field, Object target, RuntimeType declaringType, FieldAttributes attr, uint invocationFlags);
#endregion
#region Private Data Members
// agressive caching
private IntPtr m_fieldHandle;
private FieldAttributes m_fieldAttributes;
// lazy caching
private string m_name;
private RuntimeType m_fieldType;
private INVOCATION_FLAGS m_invocationFlags;
#if FEATURE_APPX
private bool IsNonW8PFrameworkAPI()
{
if (GetRuntimeType().IsNonW8PFrameworkAPI())
return true;
// Allow "value__"
if (m_declaringType.IsEnum)
return false;
RuntimeAssembly rtAssembly = GetRuntimeAssembly();
if (rtAssembly.IsFrameworkAssembly())
{
int ctorToken = rtAssembly.InvocableAttributeCtorToken;
if (System.Reflection.MetadataToken.IsNullToken(ctorToken) ||
!CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken))
return true;
}
return false;
}
#endif
internal INVOCATION_FLAGS InvocationFlags
{
get
{
if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
{
Type declaringType = DeclaringType;
bool fIsReflectionOnlyType = (declaringType is ReflectionOnlyType);
INVOCATION_FLAGS invocationFlags = 0;
// first take care of all the NO_INVOKE cases
if (
(declaringType != null && declaringType.ContainsGenericParameters) ||
(declaringType == null && Module.Assembly.ReflectionOnly) ||
(fIsReflectionOnlyType)
)
{
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE;
}
// If the invocationFlags are still 0, then
// this should be an usable field, determine the other flags
if (invocationFlags == 0)
{
if ((m_fieldAttributes & FieldAttributes.InitOnly) != (FieldAttributes)0)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD;
if ((m_fieldAttributes & FieldAttributes.HasFieldRVA) != (FieldAttributes)0)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD;
// A public field is inaccesible to Transparent code if the field is Critical.
bool needsTransparencySecurityCheck = IsSecurityCritical && !IsSecuritySafeCritical;
bool needsVisibilitySecurityCheck = ((m_fieldAttributes & FieldAttributes.FieldAccessMask) != FieldAttributes.Public) ||
(declaringType != null && declaringType.NeedsReflectionSecurityCheck);
if (needsTransparencySecurityCheck || needsVisibilitySecurityCheck)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
// find out if the field type is one of the following: Primitive, Enum or Pointer
Type fieldType = FieldType;
if (fieldType.IsPointer || fieldType.IsEnum || fieldType.IsPrimitive)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_FIELD_SPECIAL_CAST;
}
#if FEATURE_APPX
if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI())
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API;
#endif // FEATURE_APPX
// must be last to avoid threading problems
m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;
}
return m_invocationFlags;
}
}
#endregion
private RuntimeAssembly GetRuntimeAssembly() { return m_declaringType.GetRuntimeAssembly(); }
#region Constructor
internal RtFieldInfo(
RuntimeFieldHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags)
: base(reflectedTypeCache, declaringType, bindingFlags)
{
m_fieldHandle = handle.Value;
m_fieldAttributes = RuntimeFieldHandle.GetAttributes(handle);
}
#endregion
#region Private Members
RuntimeFieldHandleInternal IRuntimeFieldInfo.Value
{
get
{
return new RuntimeFieldHandleInternal(m_fieldHandle);
}
}
#endregion
#region Internal Members
internal void CheckConsistency(Object target)
{
// only test instance fields
if ((m_fieldAttributes & FieldAttributes.Static) != FieldAttributes.Static)
{
if (!m_declaringType.IsInstanceOfType(target))
{
if (target == null)
{
throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatFldReqTarg"));
}
else
{
throw new ArgumentException(
String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Arg_FieldDeclTarget"),
Name, m_declaringType, target.GetType()));
}
}
}
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal override bool CacheEquals(object o)
{
RtFieldInfo m = o as RtFieldInfo;
if ((object)m == null)
return false;
return m.m_fieldHandle == m_fieldHandle;
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal void InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture, ref StackCrawlMark stackMark)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
RuntimeType declaringType = DeclaringType as RuntimeType;
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
{
if (declaringType != null && declaringType.ContainsGenericParameters)
throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenField"));
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyField"));
throw new FieldAccessException();
}
CheckConsistency(obj);
RuntimeType fieldType = (RuntimeType)FieldType;
value = fieldType.CheckValue(value, binder, culture, invokeAttr);
#region Security Check
#if FEATURE_APPX
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
{
RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
if (caller != null && !caller.IsSafeForReflection())
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
}
#endif
if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0)
PerformVisibilityCheckOnField(m_fieldHandle, obj, m_declaringType, m_fieldAttributes, (uint)m_invocationFlags);
#endregion
bool domainInitialized = false;
if (declaringType == null)
{
RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized);
}
else
{
domainInitialized = declaringType.DomainInitialized;
RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized);
declaringType.DomainInitialized = domainInitialized;
}
}
// UnsafeSetValue doesn't perform any consistency or visibility check.
// It is the caller's responsibility to ensure the operation is safe.
// When the caller needs to perform visibility checks they should call
// InternalSetValue() instead. When the caller needs to perform
// consistency checks they should call CheckConsistency() before
// calling this method.
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal void UnsafeSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
{
RuntimeType declaringType = DeclaringType as RuntimeType;
RuntimeType fieldType = (RuntimeType)FieldType;
value = fieldType.CheckValue(value, binder, culture, invokeAttr);
bool domainInitialized = false;
if (declaringType == null)
{
RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized);
}
else
{
domainInitialized = declaringType.DomainInitialized;
RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized);
declaringType.DomainInitialized = domainInitialized;
}
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal Object InternalGetValue(Object obj, ref StackCrawlMark stackMark)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
RuntimeType declaringType = DeclaringType as RuntimeType;
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
{
if (declaringType != null && DeclaringType.ContainsGenericParameters)
throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenField"));
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyField"));
throw new FieldAccessException();
}
CheckConsistency(obj);
#if FEATURE_APPX
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
{
RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
if (caller != null && !caller.IsSafeForReflection())
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
}
#endif
RuntimeType fieldType = (RuntimeType)FieldType;
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0)
PerformVisibilityCheckOnField(m_fieldHandle, obj, m_declaringType, m_fieldAttributes, (uint)(m_invocationFlags & ~INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD));
return UnsafeGetValue(obj);
}
// UnsafeGetValue doesn't perform any consistency or visibility check.
// It is the caller's responsibility to ensure the operation is safe.
// When the caller needs to perform visibility checks they should call
// InternalGetValue() instead. When the caller needs to perform
// consistency checks they should call CheckConsistency() before
// calling this method.
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal Object UnsafeGetValue(Object obj)
{
RuntimeType declaringType = DeclaringType as RuntimeType;
RuntimeType fieldType = (RuntimeType)FieldType;
bool domainInitialized = false;
if (declaringType == null)
{
return RuntimeFieldHandle.GetValue(this, obj, fieldType, null, ref domainInitialized);
}
else
{
domainInitialized = declaringType.DomainInitialized;
object retVal = RuntimeFieldHandle.GetValue(this, obj, fieldType, declaringType, ref domainInitialized);
declaringType.DomainInitialized = domainInitialized;
return retVal;
}
}
#endregion
#region MemberInfo Overrides
public override String Name
{
get
{
if (m_name == null)
m_name = RuntimeFieldHandle.GetName(this);
return m_name;
}
}
internal String FullName
{
get
{
return String.Format("{0}.{1}", DeclaringType.FullName, Name);
}
}
public override int MetadataToken
{
get { return RuntimeFieldHandle.GetToken(this); }
}
internal override RuntimeModule GetRuntimeModule()
{
return RuntimeTypeHandle.GetModule(RuntimeFieldHandle.GetApproxDeclaringType(this));
}
#endregion
#region FieldInfo Overrides
public override Object GetValue(Object obj)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return InternalGetValue(obj, ref stackMark);
}
public override object GetRawConstantValue() { throw new InvalidOperationException(); }
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override Object GetValueDirect(TypedReference obj)
{
if (obj.IsNull)
throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null"));
Contract.EndContractBlock();
unsafe
{
// Passing TypedReference by reference is easier to make correct in native code
return RuntimeFieldHandle.GetValueDirect(this, (RuntimeType)FieldType, &obj, (RuntimeType)DeclaringType);
}
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
InternalSetValue(obj, value, invokeAttr, binder, culture, ref stackMark);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValueDirect(TypedReference obj, Object value)
{
if (obj.IsNull)
throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null"));
Contract.EndContractBlock();
unsafe
{
// Passing TypedReference by reference is easier to make correct in native code
RuntimeFieldHandle.SetValueDirect(this, (RuntimeType)FieldType, &obj, value, (RuntimeType)DeclaringType);
}
}
public override RuntimeFieldHandle FieldHandle
{
get
{
Type declaringType = DeclaringType;
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly"));
return new RuntimeFieldHandle(this);
}
}
internal IntPtr GetFieldHandle()
{
return m_fieldHandle;
}
public override FieldAttributes Attributes
{
get
{
return m_fieldAttributes;
}
}
public override Type FieldType
{
get
{
if (m_fieldType == null)
m_fieldType = new Signature(this, m_declaringType).FieldType;
return m_fieldType;
}
}
public override Type[] GetRequiredCustomModifiers()
{
return new Signature(this, m_declaringType).GetCustomModifiers(1, true);
}
public override Type[] GetOptionalCustomModifiers()
{
return new Signature(this, m_declaringType).GetCustomModifiers(1, false);
}
#endregion
}
[Serializable]
internal sealed unsafe class MdFieldInfo : RuntimeFieldInfo, ISerializable
{
#region Private Data Members
private int m_tkField;
private string m_name;
private RuntimeType m_fieldType;
private FieldAttributes m_fieldAttributes;
#endregion
#region Constructor
internal MdFieldInfo(
int tkField, FieldAttributes fieldAttributes, RuntimeTypeHandle declaringTypeHandle, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags)
: base(reflectedTypeCache, declaringTypeHandle.GetRuntimeType(), bindingFlags)
{
m_tkField = tkField;
m_name = null;
m_fieldAttributes = fieldAttributes;
}
#endregion
#region Internal Members
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal override bool CacheEquals(object o)
{
MdFieldInfo m = o as MdFieldInfo;
if ((object)m == null)
return false;
return m.m_tkField == m_tkField &&
m_declaringType.GetTypeHandleInternal().GetModuleHandle().Equals(
m.m_declaringType.GetTypeHandleInternal().GetModuleHandle());
}
#endregion
#region MemberInfo Overrides
public override String Name
{
get
{
if (m_name == null)
m_name = GetRuntimeModule().MetadataImport.GetName(m_tkField).ToString();
return m_name;
}
}
public override int MetadataToken { get { return m_tkField; } }
internal override RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
#endregion
#region FieldInfo Overrides
public override RuntimeFieldHandle FieldHandle { get { throw new NotSupportedException(); } }
public override FieldAttributes Attributes { get { return m_fieldAttributes; } }
public override bool IsSecurityCritical { get { return DeclaringType.IsSecurityCritical; } }
public override bool IsSecuritySafeCritical { get { return DeclaringType.IsSecuritySafeCritical; } }
public override bool IsSecurityTransparent { get { return DeclaringType.IsSecurityTransparent; } }
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override Object GetValueDirect(TypedReference obj)
{
return GetValue(null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValueDirect(TypedReference obj,Object value)
{
throw new FieldAccessException(Environment.GetResourceString("Acc_ReadOnly"));
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public unsafe override Object GetValue(Object obj)
{
return GetValue(false);
}
public unsafe override Object GetRawConstantValue() { return GetValue(true); }
private unsafe Object GetValue(bool raw)
{
// Cannot cache these because they could be user defined non-agile enumerations
Object value = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_tkField, FieldType.GetTypeHandleInternal(), raw);
if (value == DBNull.Value)
throw new NotSupportedException(Environment.GetResourceString("Arg_EnumLitValueNotFound"));
return value;
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
{
throw new FieldAccessException(Environment.GetResourceString("Acc_ReadOnly"));
}
public override Type FieldType
{
get
{
if (m_fieldType == null)
{
ConstArray fieldMarshal = GetRuntimeModule().MetadataImport.GetSigOfFieldDef(m_tkField);
m_fieldType = new Signature(fieldMarshal.Signature.ToPointer(),
(int)fieldMarshal.Length, m_declaringType).FieldType;
}
return m_fieldType;
}
}
public override Type[] GetRequiredCustomModifiers()
{
return EmptyArray<Type>.Value;
}
public override Type[] GetOptionalCustomModifiers()
{
return EmptyArray<Type>.Value;
}
#endregion
}
}
| |
#pragma warning disable 1634, 1691
namespace System.Workflow.ComponentModel
{
#region Imports
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Reflection;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel.Design;
using System.Xml;
using System.IO;
#endregion
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public sealed class WorkflowChanges
{
#region Data members
public static readonly DependencyProperty ConditionProperty = DependencyProperty.RegisterAttached("Condition", typeof(ActivityCondition), typeof(WorkflowChanges), new PropertyMetadata(DependencyPropertyOptions.Metadata));
internal static DependencyProperty WorkflowChangeActionsProperty = DependencyProperty.RegisterAttached("WorkflowChangeActions", typeof(IList), typeof(WorkflowChanges), new PropertyMetadata(DependencyPropertyOptions.NonSerialized));
internal static DependencyProperty WorkflowChangeVersionProperty = DependencyProperty.RegisterAttached("WorkflowChangeVersion", typeof(Guid), typeof(WorkflowChanges), new PropertyMetadata(Guid.Empty, DependencyPropertyOptions.NonSerialized));
private Activity originalRootActivity = null;
private Activity clonedRootActivity = null;
private List<WorkflowChangeAction> modelChangeActions = new List<WorkflowChangeAction>();
private bool saved = false;
#endregion
#region Constuctor & Destructor
public WorkflowChanges(Activity rootActivity)
{
if (rootActivity == null)
throw new ArgumentNullException("rootActivity");
if (!(rootActivity is CompositeActivity) || rootActivity.Parent != null)
throw new ArgumentException(SR.GetString(SR.Error_RootActivityTypeInvalid2), "rootActivity");
#pragma warning suppress 56506
if (rootActivity.DesignMode)
throw new InvalidOperationException(SR.GetString(SR.Error_NoRuntimeAvailable));
// get the original activity
this.originalRootActivity = (Activity)((Activity)rootActivity).GetValue(Activity.WorkflowDefinitionProperty);
if (this.originalRootActivity == null)
this.originalRootActivity = rootActivity;
// Work around: for dynamic update create a clone, without calling initialize for runtime
this.clonedRootActivity = (Activity)CloneRootActivity(originalRootActivity);
// make the tree readonly
ApplyDynamicUpdateMode((Activity)this.clonedRootActivity);
}
#endregion
#region Public members
// WhenConditionProperty Get and Set Accessors
public static object GetCondition(object dependencyObject)
{
if (dependencyObject == null)
throw new ArgumentNullException("dependencyObject");
if (!(dependencyObject is DependencyObject))
throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(DependencyObject).FullName), "dependencyObject");
return (dependencyObject as DependencyObject).GetValue(ConditionProperty);
}
public static void SetCondition(object dependencyObject, object value)
{
if (dependencyObject == null)
throw new ArgumentNullException("dependencyObject");
if (!(dependencyObject is DependencyObject))
throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(DependencyObject).FullName), "dependencyObject");
(dependencyObject as DependencyObject).SetValue(ConditionProperty, value);
}
public CompositeActivity TransientWorkflow
{
get
{
return this.clonedRootActivity as CompositeActivity;
}
}
public ValidationErrorCollection Validate()
{
TypeProvider typeProvider = CreateTypeProvider(this.originalRootActivity);
// create service provider
ServiceContainer serviceContainer = new ServiceContainer();
serviceContainer.AddService(typeof(ITypeProvider), typeProvider);
ValidationManager validationManager = new ValidationManager(serviceContainer);
ValidationErrorCollection errors;
using (WorkflowCompilationContext.CreateScope(validationManager))
{
errors = ValidationHelpers.ValidateObject(validationManager, this.clonedRootActivity);
}
return XomlCompilerHelper.MorphIntoFriendlyValidationErrors(errors);
}
private void Save()
{
ValidationErrorCollection errors = Validate();
if (errors.HasErrors)
throw new WorkflowValidationFailedException(SR.GetString(SR.Error_CompilerValidationFailed), errors);
//work around !!!for conditions we do diff
object originalConditions = ((Activity)this.originalRootActivity).GetValue(ConditionTypeConverter.DeclarativeConditionDynamicProp);
object changedConditions = ((Activity)this.clonedRootActivity).GetValue(ConditionTypeConverter.DeclarativeConditionDynamicProp);
if (null != originalConditions)
this.modelChangeActions.AddRange(((IWorkflowChangeDiff)originalConditions).Diff(originalConditions, changedConditions));
else if (null != changedConditions)
this.modelChangeActions.AddRange(((IWorkflowChangeDiff)changedConditions).Diff(originalConditions, changedConditions));
// diff the process model
this.modelChangeActions.AddRange(DiffTrees(this.originalRootActivity as CompositeActivity, this.clonedRootActivity as CompositeActivity));
// always call it after diff tree, otherwise it turns on the Locked.
ReleaseDynamicUpdateMode((Activity)this.clonedRootActivity);
// cache the change actions into the new workflow definition
ArrayList workflowChanges = (ArrayList)((Activity)this.clonedRootActivity).GetValue(WorkflowChanges.WorkflowChangeActionsProperty);
if (workflowChanges == null)
{
workflowChanges = new ArrayList();
((Activity)this.clonedRootActivity).SetValue(WorkflowChanges.WorkflowChangeActionsProperty, workflowChanges);
}
workflowChanges.AddRange(this.modelChangeActions);
((Activity)this.clonedRootActivity).SetValue(WorkflowChanges.WorkflowChangeVersionProperty, Guid.NewGuid());
this.saved = true;
// now initialize for runtime
((IDependencyObjectAccessor)this.clonedRootActivity).InitializeDefinitionForRuntime(null);
}
internal void ApplyTo(Activity activity)
{
if (activity == null)
throw new ArgumentNullException("activity");
if (activity.Parent != null)
throw new ArgumentException(SR.GetString(SR.Error_RootActivityTypeInvalid), "activity");
if (activity.RootActivity == null)
throw new InvalidOperationException(SR.GetString(SR.Error_MissingRootActivity));
if (activity.WorkflowCoreRuntime == null)
throw new InvalidOperationException(SR.GetString(SR.Error_NoRuntimeAvailable));
if (this.saved)
throw new InvalidOperationException(SR.GetString(SR.Error_TransactionAlreadyApplied));
if (!CompareWorkflowDefinition((Activity)this.originalRootActivity, (Activity)activity.RootActivity.GetValue(Activity.WorkflowDefinitionProperty)))
throw new ArgumentException(SR.GetString(SR.Error_WorkflowDefinitionModified), "activity");
this.Save();
// go up in the chain and then apply changes
IWorkflowCoreRuntime workflowCoreRuntime = activity.WorkflowCoreRuntime;
if (workflowCoreRuntime.CurrentAtomicActivity != null)
throw new InvalidOperationException(SR.GetString(SR.Error_InsideAtomicScope));
bool suspended = workflowCoreRuntime.SuspendInstance(SR.GetString(SR.SuspendReason_WorkflowChange));
try
{
// collect all context Activities
List<Activity> contextActivities = new List<Activity>();
Queue<Activity> contextActivitiesQueue = new Queue<Activity>();
contextActivitiesQueue.Enqueue(workflowCoreRuntime.RootActivity);
while (contextActivitiesQueue.Count > 0)
{
Activity contextActivity = contextActivitiesQueue.Dequeue();
contextActivities.Add(contextActivity);
// enqueue child context Activities
IList<Activity> nestedContextActivities = (IList<Activity>)contextActivity.GetValue(Activity.ActiveExecutionContextsProperty);
if (nestedContextActivities != null)
{
foreach (Activity nestedContextActivity in nestedContextActivities)
contextActivitiesQueue.Enqueue(nestedContextActivity);
}
}
// run instance level validations
ValidationErrorCollection validationErrors = new ValidationErrorCollection();
foreach (WorkflowChangeAction changeAction in this.modelChangeActions)
{
if (changeAction is ActivityChangeAction)
{
foreach (Activity contextActivity in contextActivities)
{
// WinOE Bug 16903: Ask the contextActivity itself whether or not it can be removed.
// An activity can not be removed if it's in the executing mode.
if (changeAction is RemovedActivityAction &&
contextActivity.DottedPath == ((RemovedActivityAction)changeAction).OriginalRemovedActivity.DottedPath)
validationErrors.AddRange(changeAction.ValidateChanges(contextActivity));
// Ask the parent context activity whether or not this child activity can be added or removed.
// The call to TraverseDottedPathFromRoot here should return the parent context activity for this change action.
if (contextActivity.TraverseDottedPathFromRoot(((ActivityChangeAction)changeAction).OwnerActivityDottedPath) != null)
validationErrors.AddRange(changeAction.ValidateChanges(contextActivity));
}
}
}
// if errors then return
if (validationErrors.HasErrors)
throw new WorkflowValidationFailedException(SR.GetString(SR.Error_RuntimeValidationFailed), validationErrors);
// verify if workflow can be changed
VerifyWorkflowCanBeChanged(workflowCoreRuntime);
// inform workflow runtime
workflowCoreRuntime.OnBeforeDynamicChange(this.modelChangeActions);
// set the new Workflow Definition
workflowCoreRuntime.RootActivity.SetValue(Activity.WorkflowDefinitionProperty, this.clonedRootActivity);
// apply changes to all context Activities
foreach (Activity contextActivity in contextActivities)
{
// apply change to state reader
foreach (WorkflowChangeAction changeAction in this.modelChangeActions)
{
if (changeAction is ActivityChangeAction)
{
if (contextActivity.TraverseDottedPathFromRoot(((ActivityChangeAction)changeAction).OwnerActivityDottedPath) != null)
{
bool result = changeAction.ApplyTo(contextActivity);
Debug.Assert(result, "ApplyTo failed");
}
}
}
// fixup meta properties and notify changes
// if the context activity is the one that's being removed, we do not fixup the meta properties.
Activity clonedActivity = ((Activity)this.clonedRootActivity).GetActivityByName(contextActivity.QualifiedName);
if (clonedActivity != null)
contextActivity.FixUpMetaProperties(clonedActivity);
NotifyChangesToChildExecutors(workflowCoreRuntime, contextActivity, this.modelChangeActions);
NotifyChangesCompletedToChildExecutors(workflowCoreRuntime, contextActivity);
}
// inform workflow runtime
workflowCoreRuntime.OnAfterDynamicChange(true, this.modelChangeActions);
}
catch
{
workflowCoreRuntime.OnAfterDynamicChange(false, this.modelChangeActions);
throw;
}
finally
{
if (suspended)
workflowCoreRuntime.Resume();
}
}
#endregion
#region Internal Helpers
private void OnActivityListChanged(object sender, ActivityCollectionChangeEventArgs e)
{
if (e.RemovedItems != null)
{
foreach (Activity removedActivity in e.RemovedItems)
{
if (removedActivity.Readonly)
ReleaseDynamicUpdateMode(removedActivity);
}
}
}
private void ApplyDynamicUpdateMode(Activity seedActivity)
{
Queue<Activity> queue = new Queue<Activity>();
queue.Enqueue(seedActivity);
while (queue.Count > 0)
{
Activity activity = queue.Dequeue();
activity.Readonly = true;
activity.DynamicUpdateMode = true;
foreach (DependencyProperty dependencyProperty in activity.MetaDependencyProperties)
{
if (activity.IsBindingSet(dependencyProperty))
{
ActivityBind activityBind = activity.GetBinding(dependencyProperty);
if (activityBind != null)
activityBind.DynamicUpdateMode = true;
}
}
if (activity is CompositeActivity)
{
CompositeActivity compositeActivity = activity as CompositeActivity;
compositeActivity.Activities.ListChanged += new EventHandler<ActivityCollectionChangeEventArgs>(this.OnActivityListChanged);
foreach (Activity activity2 in ((CompositeActivity)activity).Activities)
queue.Enqueue(activity2);
}
}
}
private void ReleaseDynamicUpdateMode(Activity seedActivity)
{
Queue<Activity> queue = new Queue<Activity>();
queue.Enqueue(seedActivity);
while (queue.Count > 0)
{
Activity activity = queue.Dequeue() as Activity;
activity.Readonly = false;
activity.DynamicUpdateMode = false;
foreach (DependencyProperty dependencyProperty in activity.MetaDependencyProperties)
{
if (activity.IsBindingSet(dependencyProperty))
{
ActivityBind activityBind = activity.GetBinding(dependencyProperty);
if (activityBind != null)
activityBind.DynamicUpdateMode = false;
}
}
if (activity is CompositeActivity)
{
CompositeActivity compositeActivity = activity as CompositeActivity;
compositeActivity.Activities.ListChanged -= new EventHandler<ActivityCollectionChangeEventArgs>(this.OnActivityListChanged);
foreach (Activity activity2 in ((CompositeActivity)activity).Activities)
queue.Enqueue(activity2);
}
}
}
private void VerifyWorkflowCanBeChanged(IWorkflowCoreRuntime workflowCoreRuntime)
{
// check if the update is allowed on this root-activity.
ActivityCondition dynamicUpdateCondition = ((Activity)workflowCoreRuntime.RootActivity).GetValue(WorkflowChanges.ConditionProperty) as ActivityCondition;
if (dynamicUpdateCondition != null)
{
using (workflowCoreRuntime.SetCurrentActivity(workflowCoreRuntime.RootActivity))
{
if (!dynamicUpdateCondition.Evaluate(workflowCoreRuntime.RootActivity, workflowCoreRuntime))
throw new InvalidOperationException(SR.GetString(CultureInfo.CurrentCulture, SR.Error_DynamicUpdateEvaluation, new object[] { workflowCoreRuntime.InstanceID.ToString() }));
}
}
}
private void NotifyChangesCompletedToChildExecutors(IWorkflowCoreRuntime workflowCoreRuntime, Activity contextActivity)
{
Queue compositeActivities = new Queue();
compositeActivities.Enqueue(contextActivity);
while (compositeActivities.Count > 0)
{
CompositeActivity compositeActivity = compositeActivities.Dequeue() as CompositeActivity;
if (compositeActivity == null || !WorkflowChanges.IsActivityExecutable(compositeActivity))
continue;
ISupportWorkflowChanges compositeActivityExecutor = ActivityExecutors.GetActivityExecutor(compositeActivity) as ISupportWorkflowChanges;
if (compositeActivityExecutor != null)
{
using (workflowCoreRuntime.SetCurrentActivity(compositeActivity))
{
using (ActivityExecutionContext executionContext = new ActivityExecutionContext(compositeActivity))
compositeActivityExecutor.OnWorkflowChangesCompleted(executionContext);
}
}
foreach (Activity activity in compositeActivity.Activities)
{
if (activity is CompositeActivity)
compositeActivities.Enqueue(activity);
}
}
}
//
internal static bool IsActivityExecutable(Activity activity)
{
if (!activity.Enabled)
return false;
if (activity.Parent != null)
return IsActivityExecutable(activity.Parent);
return activity.Enabled;
}
private void NotifyChangesToChildExecutors(IWorkflowCoreRuntime workflowCoreRuntime, Activity contextActivity, IList<WorkflowChangeAction> changeActions)
{
foreach (WorkflowChangeAction action in changeActions)
{
if (!(action is ActivityChangeAction))
continue;
CompositeActivity ownerActivity = contextActivity.TraverseDottedPathFromRoot(((ActivityChangeAction)action).OwnerActivityDottedPath) as CompositeActivity;
if (ownerActivity == null || !WorkflowChanges.IsActivityExecutable(ownerActivity))
continue;
ISupportWorkflowChanges compositeActivityExecutor = ActivityExecutors.GetActivityExecutor(ownerActivity) as ISupportWorkflowChanges;
if (compositeActivityExecutor == null)
throw new ApplicationException(SR.GetString(SR.Error_WorkflowChangesNotSupported, ownerActivity.GetType().FullName));
using (workflowCoreRuntime.SetCurrentActivity(ownerActivity))
{
using (ActivityExecutionContext executionContext = new ActivityExecutionContext(ownerActivity))
{
if (action is AddedActivityAction)
{
Activity addedActivity = ownerActivity.Activities[((AddedActivityAction)action).Index];
if (WorkflowChanges.IsActivityExecutable(addedActivity))
{
addedActivity.OnActivityExecutionContextLoad(executionContext.Activity.RootActivity.WorkflowCoreRuntime);
executionContext.InitializeActivity(addedActivity);
compositeActivityExecutor.OnActivityAdded(executionContext, addedActivity);
}
}
else if (action is RemovedActivityAction)
{
RemovedActivityAction removedActivityAction = (RemovedActivityAction)action;
if (WorkflowChanges.IsActivityExecutable(removedActivityAction.OriginalRemovedActivity))
{
compositeActivityExecutor.OnActivityRemoved(executionContext, removedActivityAction.OriginalRemovedActivity);
if (removedActivityAction.OriginalRemovedActivity.ExecutionResult != ActivityExecutionResult.Uninitialized)
{
removedActivityAction.OriginalRemovedActivity.Uninitialize(executionContext.Activity.RootActivity.WorkflowCoreRuntime);
removedActivityAction.OriginalRemovedActivity.SetValue(Activity.ExecutionResultProperty, ActivityExecutionResult.Uninitialized);
}
removedActivityAction.OriginalRemovedActivity.OnActivityExecutionContextUnload(executionContext.Activity.RootActivity.WorkflowCoreRuntime);
removedActivityAction.OriginalRemovedActivity.Dispose();
}
}
}
}
}
}
#endregion
#region Static helpers
private static bool CompareWorkflowDefinition(Activity originalWorkflowDefinition, Activity currentWorkflowDefinition)
{
if (originalWorkflowDefinition == currentWorkflowDefinition)
return true;
if (originalWorkflowDefinition.GetType() != currentWorkflowDefinition.GetType())
return false;
Guid originalChangeVersion = (Guid)originalWorkflowDefinition.GetValue(WorkflowChanges.WorkflowChangeVersionProperty);
Guid currentChangeVersion = (Guid)currentWorkflowDefinition.GetValue(WorkflowChanges.WorkflowChangeVersionProperty);
return (originalChangeVersion == currentChangeVersion);
}
private static List<WorkflowChangeAction> DiffTrees(CompositeActivity originalCompositeActivity, CompositeActivity clonedCompositeActivity)
{
List<WorkflowChangeAction> listChanges = new List<WorkflowChangeAction>();
IEnumerator<Activity> clonedActivitiesEnum = clonedCompositeActivity.Activities.GetEnumerator();
IEnumerator<Activity> originalActivitiesEnum = originalCompositeActivity.Activities.GetEnumerator();
int currentRemoveIndex = 0;
while (originalActivitiesEnum.MoveNext())
{
bool foundMatching = false;
Activity originalActivity = originalActivitiesEnum.Current;
while (clonedActivitiesEnum.MoveNext())
{
Activity clonedActivity = clonedActivitiesEnum.Current;
if (clonedActivity.Readonly)
{
if (originalActivity.DottedPath == clonedActivity.CachedDottedPath)
{
currentRemoveIndex++;
foundMatching = true;
if (originalActivity is CompositeActivity)
listChanges.AddRange(DiffTrees(originalActivity as CompositeActivity, clonedActivity as CompositeActivity));
break;
}
else
{
listChanges.Add(new RemovedActivityAction(currentRemoveIndex, originalActivity, clonedCompositeActivity));
while (originalActivitiesEnum.MoveNext())
{
originalActivity = originalActivitiesEnum.Current;
if (originalActivity.DottedPath == clonedActivity.CachedDottedPath)
{
currentRemoveIndex++;
foundMatching = true;
if (originalActivity is CompositeActivity)
listChanges.AddRange(DiffTrees(originalActivity as CompositeActivity, clonedActivity as CompositeActivity));
break;
}
else
{
listChanges.Add(new RemovedActivityAction(currentRemoveIndex, originalActivity, clonedCompositeActivity));
}
}
}
break;
}
else
{
listChanges.Add(new AddedActivityAction(clonedCompositeActivity, clonedActivity));
currentRemoveIndex++;
}
}
if (!foundMatching)
{
listChanges.Add(new RemovedActivityAction(currentRemoveIndex, originalActivity, clonedCompositeActivity));
}
}
while (clonedActivitiesEnum.MoveNext())
listChanges.Add(new AddedActivityAction(clonedCompositeActivity, clonedActivitiesEnum.Current));
return listChanges;
}
private static Activity CloneRootActivity(Activity originalRootActivity)
{
// create new definition root
string xomlText = originalRootActivity.GetValue(Activity.WorkflowXamlMarkupProperty) as string;
string rulesText = null;
Activity clonedRootActivity = null;
IServiceProvider serviceProvider = originalRootActivity.GetValue(Activity.WorkflowRuntimeProperty) as IServiceProvider;
Debug.Assert(serviceProvider != null);
if (!string.IsNullOrEmpty(xomlText))
{
rulesText = originalRootActivity.GetValue(Activity.WorkflowRulesMarkupProperty) as string;
clonedRootActivity = Activity.OnResolveActivityDefinition(null, xomlText, rulesText, true, false, serviceProvider);
}
else
clonedRootActivity = Activity.OnResolveActivityDefinition(originalRootActivity.GetType(), null, null, true, false, serviceProvider);
if (clonedRootActivity == null)
throw new NullReferenceException(SR.GetString(SR.Error_InvalidRootForWorkflowChanges));
// deserialize change history and apply it to new definition tree
ArrayList workflowChanges = (ArrayList)((Activity)originalRootActivity).GetValue(WorkflowChanges.WorkflowChangeActionsProperty);
if (workflowChanges != null)
{
workflowChanges = CloneWorkflowChangeActions(workflowChanges, originalRootActivity);
if (workflowChanges != null)
{
// apply changes to the shared schedule Defn to get the instance specific copy
foreach (WorkflowChangeAction action in workflowChanges)
{
bool result = action.ApplyTo((Activity)clonedRootActivity);
Debug.Assert(result, "ApplyTo Failed");
}
((Activity)clonedRootActivity).SetValue(WorkflowChanges.WorkflowChangeActionsProperty, workflowChanges);
}
}
return clonedRootActivity;
}
private static ArrayList CloneWorkflowChangeActions(ArrayList workflowChanges, Activity rootActivity)
{
if (workflowChanges == null)
throw new ArgumentNullException("workflowChanges");
if (rootActivity == null)
throw new ArgumentNullException("rootActivity");
string dynamicUpdateHistory = null;
TypeProvider typeProvider = CreateTypeProvider(rootActivity);
ServiceContainer serviceContainer = new ServiceContainer();
serviceContainer.AddService(typeof(ITypeProvider), typeProvider);
DesignerSerializationManager manager = new DesignerSerializationManager(serviceContainer);
WorkflowMarkupSerializer xomlSerializer = new WorkflowMarkupSerializer();
ArrayList clonedWorkflowChanges = null;
// serialize dynamic updates
using (manager.CreateSession())
{
using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
{
using (XmlWriter xmlWriter = Helpers.CreateXmlWriter(sw))
{
WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager);
xomlSerializer.Serialize(xomlSerializationManager, xmlWriter, workflowChanges);
dynamicUpdateHistory = sw.ToString();
}
}
// deserialize those
using (StringReader sr = new StringReader(dynamicUpdateHistory))
{
using (XmlReader xmlReader = XmlReader.Create(sr))
{
WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager);
clonedWorkflowChanges = xomlSerializer.Deserialize(xomlSerializationManager, xmlReader) as ArrayList;
}
}
}
return clonedWorkflowChanges;
}
internal static TypeProvider CreateTypeProvider(Activity rootActivity)
{
TypeProvider typeProvider = new TypeProvider(null);
Type companionType = rootActivity.GetType();
typeProvider.SetLocalAssembly(companionType.Assembly);
typeProvider.AddAssembly(companionType.Assembly);
foreach (AssemblyName assemblyName in companionType.Assembly.GetReferencedAssemblies())
{
Assembly referencedAssembly = null;
try
{
referencedAssembly = Assembly.Load(assemblyName);
if (referencedAssembly != null)
typeProvider.AddAssembly(referencedAssembly);
}
catch
{
}
if (referencedAssembly == null && assemblyName.CodeBase != null)
typeProvider.AddAssemblyReference(assemblyName.CodeBase);
}
return typeProvider;
}
#endregion
}
#region WorkflowChangeAction classes
[DesignerSerializer(typeof(WorkflowMarkupSerializer), typeof(WorkflowMarkupSerializer))]
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public abstract class WorkflowChangeAction
{
protected internal abstract bool ApplyTo(Activity rootActivity);
protected internal abstract ValidationErrorCollection ValidateChanges(Activity activity);
}
[DesignerSerializer(typeof(ActivityChangeActionMarkupSerializer), typeof(WorkflowMarkupSerializer))]
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public abstract class ActivityChangeAction : WorkflowChangeAction
{
private string ownerActivityDottedPath = string.Empty;
protected ActivityChangeAction()
{
}
protected ActivityChangeAction(CompositeActivity compositeActivity)
{
if (compositeActivity == null)
throw new ArgumentNullException("compositeActivity");
this.ownerActivityDottedPath = compositeActivity.DottedPath;
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public string OwnerActivityDottedPath
{
get
{
return this.ownerActivityDottedPath;
}
internal set
{
this.ownerActivityDottedPath = value;
}
}
protected internal override ValidationErrorCollection ValidateChanges(Activity contextActivity)
{
if (contextActivity == null)
throw new ArgumentNullException("contextActivity");
ValidationErrorCollection errors = new ValidationErrorCollection();
CompositeActivity ownerActivity = contextActivity.TraverseDottedPathFromRoot(this.OwnerActivityDottedPath) as CompositeActivity;
if (ownerActivity != null && WorkflowChanges.IsActivityExecutable(ownerActivity))
{
foreach (Validator validator in ComponentDispenser.CreateComponents(ownerActivity.GetType(), typeof(ActivityValidatorAttribute)))
{
ValidationError error = validator.ValidateActivityChange(ownerActivity, this);
if (error != null)
errors.Add(error);
}
}
return errors;
}
}
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public sealed class AddedActivityAction : ActivityChangeAction
{
private int index = 0;
private Activity addedActivity = null;
public AddedActivityAction()
{
}
public AddedActivityAction(CompositeActivity compositeActivity, Activity activityAdded)
: base(compositeActivity)
{
if (compositeActivity == null)
throw new ArgumentNullException("compositeActivity");
if (activityAdded == null)
throw new ArgumentNullException("activityAdded");
this.index = (compositeActivity.Activities != null) ? compositeActivity.Activities.IndexOf(activityAdded) : -1;
this.addedActivity = activityAdded;
}
public int Index
{
get
{
return this.index;
}
internal set
{
this.index = value;
}
}
public Activity AddedActivity
{
get
{
return this.addedActivity;
}
internal set
{
this.addedActivity = value;
}
}
protected internal override bool ApplyTo(Activity rootActivity)
{
if (rootActivity == null)
throw new ArgumentNullException("rootActivity");
if (!(rootActivity is CompositeActivity))
throw new ArgumentException(SR.GetString(SR.Error_RootActivityTypeInvalid), "rootActivity");
CompositeActivity ownerActivity = rootActivity.TraverseDottedPathFromRoot(this.OwnerActivityDottedPath) as CompositeActivity;
if (ownerActivity == null)
return false;
// !!!work around:
ownerActivity.DynamicUpdateMode = true;
CompositeActivity addedActivityOwner = this.addedActivity.Parent;
try
{
this.addedActivity.SetParent(ownerActivity);
Activity clonedAddedActivity = this.addedActivity;
if (!this.addedActivity.DesignMode)
clonedAddedActivity = this.addedActivity.Clone();
// We need to serialize and deserialize in order to clone during design mode
else
{
TypeProvider typeProvider = WorkflowChanges.CreateTypeProvider(rootActivity);
ServiceContainer serviceContainer = new ServiceContainer();
serviceContainer.AddService(typeof(ITypeProvider), typeProvider);
DesignerSerializationManager manager = new DesignerSerializationManager(serviceContainer);
WorkflowMarkupSerializer xomlSerializer = new WorkflowMarkupSerializer();
string addedActivityText = string.Empty;
// serialize dynamic updates
using (manager.CreateSession())
{
using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
{
using (XmlWriter xmlWriter = Helpers.CreateXmlWriter(sw))
{
WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager);
xomlSerializer.Serialize(xomlSerializationManager, xmlWriter, this.addedActivity);
addedActivityText = sw.ToString();
}
}
// deserialize those
using (StringReader sr = new StringReader(addedActivityText))
{
using (XmlReader xmlReader = XmlReader.Create(sr))
{
WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager);
clonedAddedActivity = xomlSerializer.Deserialize(xomlSerializationManager, xmlReader) as Activity;
}
}
}
if (clonedAddedActivity == null)
throw new InvalidOperationException(SR.GetString(SR.Error_ApplyDynamicChangeFailed));
}
if (ownerActivity.WorkflowCoreRuntime != null)
((IDependencyObjectAccessor)clonedAddedActivity).InitializeInstanceForRuntime(ownerActivity.WorkflowCoreRuntime);
clonedAddedActivity.SetParent(null);
ownerActivity.Activities.Insert(this.index, clonedAddedActivity);
}
finally
{
this.addedActivity.SetParent(addedActivityOwner);
ownerActivity.DynamicUpdateMode = false;
}
return true;
}
}
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public sealed class RemovedActivityAction : ActivityChangeAction
{
private int removedActivityIndex = -1;
private Activity originalRemovedActivity = null;
public RemovedActivityAction()
{
}
public RemovedActivityAction(int removedActivityIndex, Activity originalActivity, CompositeActivity clonedParentActivity)
: base(clonedParentActivity)
{
if (originalActivity == null)
throw new ArgumentNullException("originalActivity");
if (clonedParentActivity == null)
throw new ArgumentNullException("clonedParentActivity");
this.originalRemovedActivity = originalActivity;
this.removedActivityIndex = removedActivityIndex;
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public int RemovedActivityIndex
{
get
{
return this.removedActivityIndex;
}
internal set
{
this.removedActivityIndex = value;
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Activity OriginalRemovedActivity
{
get
{
return this.originalRemovedActivity;
}
internal set
{
this.originalRemovedActivity = value;
}
}
protected internal override ValidationErrorCollection ValidateChanges(Activity contextActivity)
{
ValidationErrorCollection errors = base.ValidateChanges(contextActivity);
Activity removedActivityInContext = contextActivity.TraverseDottedPathFromRoot(this.originalRemovedActivity.DottedPath);
if (WorkflowChanges.IsActivityExecutable(removedActivityInContext) && removedActivityInContext.ExecutionStatus == ActivityExecutionStatus.Executing)
errors.Add(new ValidationError(SR.GetString(SR.Error_RemoveExecutingActivity, this.originalRemovedActivity.QualifiedName), ErrorNumbers.Error_RemoveExecutingActivity));
return errors;
}
protected internal override bool ApplyTo(Activity rootActivity)
{
if (rootActivity == null)
throw new ArgumentNullException("rootActivity");
if (!(rootActivity is CompositeActivity))
throw new ArgumentException(SR.GetString(SR.Error_RootActivityTypeInvalid), "rootActivity");
CompositeActivity ownerActivity = rootActivity.TraverseDottedPathFromRoot(this.OwnerActivityDottedPath) as CompositeActivity;
if (ownerActivity == null)
return false;
if (this.removedActivityIndex >= ownerActivity.Activities.Count)
return false;
// !!!work around:
ownerActivity.DynamicUpdateMode = true;
try
{
this.originalRemovedActivity = ownerActivity.Activities[this.removedActivityIndex];
ownerActivity.Activities.RemoveAt(this.removedActivityIndex);
}
finally
{
ownerActivity.DynamicUpdateMode = false;
}
return true;
}
}
#endregion
#region Class ActivityChangeActionMarkupSerializer
internal sealed class ActivityChangeActionMarkupSerializer : WorkflowMarkupSerializer
{
protected internal override PropertyInfo[] GetProperties(WorkflowMarkupSerializationManager serializationManager, object obj)
{
List<PropertyInfo> properties = new List<PropertyInfo>(base.GetProperties(serializationManager, obj));
//Collect the internal properties, we do this so that activity change action apis don't need to expose unnecessary setters
foreach (PropertyInfo property in obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy))
{
DesignerSerializationVisibility visibility = Helpers.GetSerializationVisibility(property);
if (visibility != DesignerSerializationVisibility.Hidden && property.GetSetMethod() == null && property.GetSetMethod(true) != null)
properties.Add(property);
}
return properties.ToArray();
}
}
#endregion
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using FluentAssertions;
using Microsoft.Build.Construction;
using Microsoft.DotNet.Tools.Test.Utilities;
using Msbuild.Tests.Utilities;
using System;
using System.IO;
using Xunit;
namespace Microsoft.DotNet.Cli.Remove.Reference.Tests
{
public class GivenDotnetRemoveReference : TestBase
{
private const string HelpText = @".NET Remove Project to Project reference Command
Usage: dotnet remove <PROJECT> reference [options] <args>
Arguments:
<PROJECT> The project file to operate on. If a file is not specified, the command will search the current directory for one.
<args> Project to project references to remove
Options:
-h, --help Show help information
-f, --framework <FRAMEWORK> Remove reference only when targeting a specific framework
";
const string FrameworkNet451Arg = "-f net451";
const string ConditionFrameworkNet451 = "== 'net451'";
const string FrameworkNetCoreApp10Arg = "-f netcoreapp1.0";
const string ConditionFrameworkNetCoreApp10 = "== 'netcoreapp1.0'";
static readonly string[] DefaultFrameworks = new string[] { "netcoreapp1.0", "net451" };
private TestSetup Setup([System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(Setup), string identifier = "")
{
return new TestSetup(
TestAssets.Get(TestSetup.TestGroup, TestSetup.ProjectName)
.CreateInstance(callingMethod: callingMethod, identifier: identifier)
.WithSourceFiles()
.Root
.FullName);
}
private ProjDir NewDir([System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "")
{
return new ProjDir(TestAssets.CreateTestDirectory(callingMethod: callingMethod, identifier: identifier).FullName);
}
private ProjDir NewLib(string dir = null, [System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "")
{
var projDir = dir == null ? NewDir(callingMethod: callingMethod, identifier: identifier) : new ProjDir(dir);
try
{
string newArgs = $"classlib -o \"{projDir.Path}\" --no-restore";
new NewCommandShim()
.WithWorkingDirectory(projDir.Path)
.ExecuteWithCapturedOutput(newArgs)
.Should().Pass();
}
catch (System.ComponentModel.Win32Exception e)
{
throw new Exception($"Intermittent error in `dotnet new` occurred when running it in dir `{projDir.Path}`\nException:\n{e}");
}
return projDir;
}
private static void SetTargetFrameworks(ProjDir proj, string[] frameworks)
{
var csproj = proj.CsProj();
csproj.AddProperty("TargetFrameworks", string.Join(";", frameworks));
csproj.Save();
}
private ProjDir NewLibWithFrameworks(string dir = null, [System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "")
{
var ret = NewLib(dir, callingMethod: callingMethod, identifier: identifier);
SetTargetFrameworks(ret, DefaultFrameworks);
return ret;
}
private ProjDir GetLibRef(TestSetup setup)
{
return new ProjDir(setup.LibDir);
}
private ProjDir AddLibRef(TestSetup setup, ProjDir proj, string additionalArgs = "")
{
var ret = GetLibRef(setup);
new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(proj.CsProjPath)
.Execute($"{additionalArgs} \"{ret.CsProjPath}\"")
.Should().Pass();
return ret;
}
private ProjDir AddValidRef(TestSetup setup, ProjDir proj, string frameworkArg = "")
{
var ret = new ProjDir(setup.ValidRefDir);
new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(proj.CsProjPath)
.Execute($"{frameworkArg} \"{ret.CsProjPath}\"")
.Should().Pass();
return ret;
}
[Theory]
[InlineData("--help")]
[InlineData("-h")]
public void WhenHelpOptionIsPassedItPrintsUsage(string helpArg)
{
var cmd = new RemoveReferenceCommand().Execute(helpArg);
cmd.Should().Pass();
cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText);
}
[Theory]
[InlineData("")]
[InlineData("unknownCommandName")]
public void WhenNoCommandIsPassedItPrintsError(string commandName)
{
var cmd = new DotnetCommand()
.ExecuteWithCapturedOutput($"remove {commandName}");
cmd.Should().Fail();
cmd.StdErr.Should().Be("Required command was not provided.");
}
[Fact]
public void WhenTooManyArgumentsArePassedItPrintsError()
{
var cmd = new AddReferenceCommand()
.WithProject("one two three")
.Execute("proj.csproj");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().BeVisuallyEquivalentTo("Unrecognized command or argument 'two'\r\nUnrecognized command or argument 'three'");
}
[Theory]
[InlineData("idontexist.csproj")]
[InlineData("ihave?inv@lid/char\\acters")]
public void WhenNonExistingProjectIsPassedItPrintsErrorAndUsage(string projName)
{
var setup = Setup();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(projName)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Be($"Could not find project or directory `{projName}`.");
cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText);
}
[Fact]
public void WhenBrokenProjectIsPassedItPrintsErrorAndUsage()
{
string projName = "Broken/Broken.csproj";
var setup = Setup();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(projName)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Be("Project `Broken/Broken.csproj` is invalid.");
cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText);
}
[Fact]
public void WhenMoreThanOneProjectExistsInTheDirectoryItPrintsErrorAndUsage()
{
var setup = Setup();
var workingDir = Path.Combine(setup.TestRoot, "MoreThanOne");
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(workingDir)
.Execute($"\"{setup.ValidRefCsprojRelToOtherProjPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Be($"Found more than one project in `{workingDir + Path.DirectorySeparatorChar}`. Please specify which one to use.");
cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText);
}
[Fact]
public void WhenNoProjectsExistsInTheDirectoryItPrintsErrorAndUsage()
{
var setup = Setup();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Be($"Could not find any project in `{setup.TestRoot + Path.DirectorySeparatorChar}`.");
cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText);
}
[Fact]
public void ItRemovesRefWithoutCondAndPrintsStatus()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var libref = AddLibRef(setup, lib);
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{libref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be($"Project reference `{Path.Combine("Lib", setup.LibCsprojName)}` removed.");
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0);
}
[Fact]
public void ItRemovesRefWithCondAndPrintsStatus()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var libref = AddLibRef(setup, lib, FrameworkNet451Arg);
int condBefore = lib.CsProj().NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{libref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be($"Project reference `{Path.Combine("Lib", setup.LibCsprojName)}` removed.");
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(libref.Name, ConditionFrameworkNet451).Should().Be(0);
}
[Fact]
public void WhenTwoDifferentRefsArePresentItDoesNotRemoveBoth()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var libref = AddLibRef(setup, lib);
var validref = AddValidRef(setup, lib);
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{libref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be($"Project reference `{Path.Combine("Lib", setup.LibCsprojName)}` removed.");
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore);
csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0);
}
[Fact]
public void WhenRefWithoutCondIsNotThereItPrintsMessage()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var libref = GetLibRef(setup);
string csprojContetntBefore = lib.CsProjContent();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{libref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be($"Project reference `{libref.CsProjPath}` could not be found.");
lib.CsProjContent().Should().BeEquivalentTo(csprojContetntBefore);
}
[Fact]
public void WhenRefWithCondIsNotThereItPrintsMessage()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var libref = GetLibRef(setup);
string csprojContetntBefore = lib.CsProjContent();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{libref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be($"Project reference `{libref.CsProjPath}` could not be found.");
lib.CsProjContent().Should().BeEquivalentTo(csprojContetntBefore);
}
[Fact]
public void WhenRefWithAndWithoutCondArePresentAndRemovingNoCondItDoesNotRemoveOther()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var librefCond = AddLibRef(setup, lib, FrameworkNet451Arg);
var librefNoCond = AddLibRef(setup, lib);
var csprojBefore = lib.CsProj();
int noCondBefore = csprojBefore.NumberOfItemGroupsWithoutCondition();
int condBefore = csprojBefore.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{librefNoCond.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be($"Project reference `{Path.Combine("Lib", setup.LibCsprojName)}` removed.");
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(librefNoCond.Name).Should().Be(0);
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(librefCond.Name, ConditionFrameworkNet451).Should().Be(1);
}
[Fact]
public void WhenRefWithAndWithoutCondArePresentAndRemovingCondItDoesNotRemoveOther()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var librefCond = AddLibRef(setup, lib, FrameworkNet451Arg);
var librefNoCond = AddLibRef(setup, lib);
var csprojBefore = lib.CsProj();
int noCondBefore = csprojBefore.NumberOfItemGroupsWithoutCondition();
int condBefore = csprojBefore.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{librefCond.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be($"Project reference `{Path.Combine("Lib", setup.LibCsprojName)}` removed.");
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore);
csproj.NumberOfProjectReferencesWithIncludeContaining(librefNoCond.Name).Should().Be(1);
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(librefCond.Name, ConditionFrameworkNet451).Should().Be(0);
}
[Fact]
public void WhenRefWithDifferentCondIsPresentItDoesNotRemoveIt()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var librefCondNet451 = AddLibRef(setup, lib, FrameworkNet451Arg);
var librefCondNetCoreApp10 = AddLibRef(setup, lib, FrameworkNetCoreApp10Arg);
var csprojBefore = lib.CsProj();
int condNet451Before = csprojBefore.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
int condNetCoreApp10Before = csprojBefore.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNetCoreApp10);
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{librefCondNet451.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be($"Project reference `{Path.Combine("Lib", setup.LibCsprojName)}` removed.");
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condNet451Before - 1);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(librefCondNet451.Name, ConditionFrameworkNet451).Should().Be(0);
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNetCoreApp10).Should().Be(condNetCoreApp10Before);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(librefCondNetCoreApp10.Name, ConditionFrameworkNetCoreApp10).Should().Be(1);
}
[Fact]
public void WhenDuplicateReferencesArePresentItRemovesThemAll()
{
var setup = Setup();
var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithDoubledRef"));
var libref = GetLibRef(setup);
string removedText = $@"Project reference `{setup.LibCsprojRelPath}` removed.
Project reference `{setup.LibCsprojRelPath}` removed.";
int noCondBefore = proj.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(proj.CsProjPath)
.Execute($"\"{libref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().BeVisuallyEquivalentTo(removedText);
var csproj = proj.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0);
}
[Fact]
public void WhenPassingRefWithRelPathItRemovesRefWithAbsolutePath()
{
var setup = Setup();
var lib = GetLibRef(setup);
var libref = AddValidRef(setup, lib);
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(lib.Path)
.WithProject(lib.CsProjPath)
.Execute($"\"{setup.ValidRefCsprojRelToOtherProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be($"Project reference `{setup.ValidRefCsprojRelToOtherProjPath}` removed.");
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0);
}
[Fact]
public void WhenPassingRefWithRelPathToProjectItRemovesRefWithPathRelToProject()
{
var setup = Setup();
var lib = GetLibRef(setup);
var libref = AddValidRef(setup, lib);
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{setup.ValidRefCsprojRelToOtherProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be($"Project reference `{setup.ValidRefCsprojRelToOtherProjPath}` removed.");
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0);
}
[Fact]
public void WhenPassingRefWithAbsolutePathItRemovesRefWithRelPath()
{
var setup = Setup();
var lib = GetLibRef(setup);
var libref = AddValidRef(setup, lib);
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be($"Project reference `{setup.ValidRefCsprojRelToOtherProjPath}` removed.");
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0);
}
[Fact]
public void WhenPassingMultipleReferencesItRemovesThemAll()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var libref = AddLibRef(setup, lib);
var validref = AddValidRef(setup, lib);
string outputText = $@"Project reference `{Path.Combine("Lib", setup.LibCsprojName)}` removed.
Project reference `{Path.Combine(setup.ValidRefCsprojRelPath)}` removed.";
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{libref.CsProjPath}\" \"{validref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().BeVisuallyEquivalentTo(outputText);
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0);
csproj.NumberOfProjectReferencesWithIncludeContaining(validref.Name).Should().Be(0);
}
[Fact]
public void WhenPassingMultipleReferencesAndOneOfThemDoesNotExistItRemovesOne()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var libref = GetLibRef(setup);
var validref = AddValidRef(setup, lib);
string OutputText = $@"Project reference `{setup.LibCsprojPath}` could not be found.
Project reference `{Path.Combine(setup.ValidRefCsprojRelPath)}` removed.";
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{libref.CsProjPath}\" \"{validref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().BeVisuallyEquivalentTo(OutputText);
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(validref.Name).Should().Be(0);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
// ----------------------------------------------------------------------------
//
// AggregateType
//
// Represents a generic constructed (or instantiated) type. Parent is the AggregateSymbol.
// ----------------------------------------------------------------------------
internal sealed class AggregateType : CType
{
private AggregateType _baseType; // This is the result of calling SubstTypeArray on the aggregate's baseClass.
private TypeArray _ifacesAll; // This is the result of calling SubstTypeArray on the aggregate's ifacesAll.
private TypeArray _winrtifacesAll; //This is the list of collection interfaces implemented by a WinRT object.
private Type _associatedSystemType;
public AggregateType(AggregateSymbol parent, TypeArray typeArgsThis, AggregateType outerType)
: base(TypeKind.TK_AggregateType)
{
Debug.Assert(typeArgsThis != null);
OuterType = outerType;
OwningAggregate = parent;
TypeArgsThis = typeArgsThis;
// Here we need to check our current type args. If we have an open placeholder,
// then we need to have all open placeholders, and we want to flush
// our outer type args so that they're open placeholders.
//
// This is because of the following scenario:
//
// class B<T>
// {
// class C<U>
// {
// }
// class D
// {
// void Foo()
// {
// Type T = typeof(C<>);
// }
// }
// }
//
// The outer type will be B<T>, but the inner type will be C<>. However,
// this will eventually be represented in IL as B<>.C<>. As such, we should
// keep our data structures clear - if we have one open type argument, then
// all of them must be open type arguments.
//
// Ensure that invariant here.
Debug.Assert(outerType == null || outerType.TypeArgsAll != null);
TypeArgsAll = outerType != null ? TypeArray.Concat(outerType.TypeArgsAll, typeArgsThis) : typeArgsThis;
}
public bool? ConstraintError; // Did the constraints check produce an error?
// These two flags are used to track hiding within interfaces.
// Their use and validity is always localized. See e.g. MemberLookup::LookupInInterfaces.
public bool AllHidden; // All members are hidden by a derived interface member.
public bool DiffHidden; // Members other than a specific kind are hidden by a derived interface member or class member.
public AggregateType OuterType { get; } // the outer type if this is a nested type
public AggregateSymbol OwningAggregate { get; }
public AggregateType BaseClass
{
get
{
if (_baseType == null)
{
Type baseSysType = AssociatedSystemType.BaseType;
if (baseSysType == null)
{
return null;
}
// If we have a generic type definition, then we need to set the
// base class to be our current base type, and use that to calculate
// our agg type and its base, then set it to be the generic version of the
// base type. This is because:
//
// Suppose we have Foo<T> : IFoo<T>
//
// Initially, the BaseType will be IFoo<Foo.T>, which gives us the substitution
// that we want to use for our agg type's base type. However, in the Symbol chain,
// we want the base type to be IFoo<IFoo.T>. So we need to substitute.
//
// If we don't have a generic type definition, then we just need to set our base
// class. This is so that if we have a base type that's generic, we'll be
// getting the correctly instantiated base type.
AggregateType baseClass = SymbolTable.GetCTypeFromType(baseSysType) as AggregateType;
Debug.Assert(baseClass != null);
_baseType = TypeManager.SubstType(baseClass, TypeArgsAll);
}
return _baseType;
}
}
public IEnumerable<AggregateType> TypeHierarchy
{
get
{
if (IsInterfaceType)
{
yield return this;
foreach (AggregateType iface in IfacesAll.Items)
{
yield return iface;
}
yield return PredefinedTypes.GetPredefinedAggregate(PredefinedType.PT_OBJECT).getThisType();
}
else
{
for (AggregateType agg = this; agg != null; agg = agg.BaseClass)
{
yield return agg;
}
}
}
}
public TypeArray TypeArgsThis { get; }
public TypeArray TypeArgsAll { get; }
public TypeArray IfacesAll => _ifacesAll ?? (_ifacesAll = TypeManager.SubstTypeArray(OwningAggregate.GetIfacesAll(), TypeArgsAll));
private bool IsCollectionType
{
get
{
Type sysType = AssociatedSystemType;
if (sysType.IsGenericType)
{
Type genType = sysType.GetGenericTypeDefinition();
return genType == typeof(IList<>)
|| genType == typeof(ICollection<>)
|| genType == typeof(IEnumerable<>)
|| genType == typeof(IReadOnlyList<>)
|| genType == typeof(IReadOnlyCollection<>)
|| genType == typeof(IDictionary<,>)
|| genType == typeof(IReadOnlyDictionary<,>);
}
return sysType == typeof(System.Collections.IList)
|| sysType == typeof(System.Collections.ICollection)
|| sysType == typeof(System.Collections.IEnumerable)
|| sysType == typeof(System.Collections.Specialized.INotifyCollectionChanged)
|| sysType == typeof(System.ComponentModel.INotifyPropertyChanged);
}
}
public TypeArray WinRTCollectionIfacesAll
{
get
{
if (_winrtifacesAll == null)
{
List<CType> typeList = new List<CType>();
foreach (AggregateType type in IfacesAll.Items)
{
Debug.Assert(type.IsInterfaceType);
if (type.IsCollectionType)
{
typeList.Add(type);
}
}
_winrtifacesAll = TypeArray.Allocate(typeList.ToArray());
}
return _winrtifacesAll;
}
}
public override bool IsReferenceType => OwningAggregate.IsRefType();
public override bool IsNonNullableValueType => IsValueType;
public override bool IsValueType => OwningAggregate.IsValueType();
public override bool IsStaticClass => OwningAggregate.IsStatic();
public override bool IsPredefined => OwningAggregate.IsPredefined();
public override PredefinedType PredefinedType
{
get
{
Debug.Assert(IsPredefined);
return OwningAggregate.GetPredefType();
}
}
public override bool IsPredefType(PredefinedType pt)
{
AggregateSymbol agg = OwningAggregate;
return agg.IsPredefined() && agg.GetPredefType() == pt;
}
public override bool IsDelegateType => OwningAggregate.IsDelegate();
public override bool IsSimpleType
{
get
{
AggregateSymbol agg = OwningAggregate;
return agg.IsPredefined() && PredefinedTypeFacts.IsSimpleType(agg.GetPredefType());
}
}
public override bool IsSimpleOrEnum
{
get
{
AggregateSymbol agg = OwningAggregate;
return agg.IsPredefined() ? PredefinedTypeFacts.IsSimpleType(agg.GetPredefType()) : agg.IsEnum();
}
}
public override bool IsSimpleOrEnumOrString
{
get
{
AggregateSymbol agg = OwningAggregate;
if (agg.IsPredefined())
{
PredefinedType pt = agg.GetPredefType();
return PredefinedTypeFacts.IsSimpleType(pt) || pt == PredefinedType.PT_STRING;
}
return agg.IsEnum();
}
}
public override bool IsNumericType
{
get
{
AggregateSymbol agg = OwningAggregate;
return agg.IsPredefined() && PredefinedTypeFacts.IsNumericType(agg.GetPredefType());
}
}
public override bool IsStructOrEnum
{
get
{
AggregateSymbol agg = OwningAggregate;
return agg.IsStruct() || agg.IsEnum();
}
}
public override bool IsStructType => OwningAggregate.IsStruct();
public override bool IsEnumType => OwningAggregate.IsEnum();
public override bool IsInterfaceType => OwningAggregate.IsInterface();
public override bool IsClassType => OwningAggregate.IsClass();
public override AggregateType UnderlyingEnumType
{
get
{
Debug.Assert(IsEnumType);
return OwningAggregate.GetUnderlyingType();
}
}
public override Type AssociatedSystemType => _associatedSystemType ?? (_associatedSystemType = CalculateAssociatedSystemType());
private Type CalculateAssociatedSystemType()
{
Type uninstantiatedType = OwningAggregate.AssociatedSystemType;
if (uninstantiatedType.IsGenericType)
{
// Get each type arg.
TypeArray typeArgs = TypeArgsAll;
Type[] systemTypeArgs = new Type[typeArgs.Count];
for (int i = 0; i < systemTypeArgs.Length; i++)
{
// Unnamed type parameter types are just placeholders.
CType typeArg = typeArgs[i];
if (typeArg is TypeParameterType typeParamArg && typeParamArg.Symbol.name == null)
{
return null;
}
systemTypeArgs[i] = typeArg.AssociatedSystemType;
}
try
{
return uninstantiatedType.MakeGenericType(systemTypeArgs);
}
catch (ArgumentException)
{
// If the constraints don't work, just return the type without substituting it.
}
}
return uninstantiatedType;
}
public override FUNDTYPE FundamentalType
{
get
{
AggregateSymbol sym = OwningAggregate;
// Treat enums like their underlying types.
if (sym.IsEnum())
{
sym = sym.GetUnderlyingType().OwningAggregate;
}
else if (!sym.IsStruct())
{
return FUNDTYPE.FT_REF; // Interfaces, classes, delegates are reference types.
}
// Struct type could be predefined (int, long, etc.) or some other struct.
return sym.IsPredefined() ? PredefinedTypeFacts.GetFundType(sym.GetPredefType()) : FUNDTYPE.FT_STRUCT;
}
}
public override ConstValKind ConstValKind
{
get
{
if (IsPredefType(PredefinedType.PT_INTPTR) || IsPredefType(PredefinedType.PT_UINTPTR))
{
return ConstValKind.IntPtr;
}
switch (FundamentalType)
{
case FUNDTYPE.FT_I8:
case FUNDTYPE.FT_U8:
return ConstValKind.Long;
case FUNDTYPE.FT_STRUCT:
// Here we can either have a decimal type, or an enum
// whose fundamental type is decimal.
Debug.Assert(
OwningAggregate.IsEnum() && OwningAggregate.GetUnderlyingType().PredefinedType == PredefinedType.PT_DECIMAL
|| IsPredefined && PredefinedType == PredefinedType.PT_DATETIME
|| IsPredefined && PredefinedType == PredefinedType.PT_DECIMAL);
return IsPredefined && PredefinedType == PredefinedType.PT_DATETIME
? ConstValKind.Long
: ConstValKind.Decimal;
case FUNDTYPE.FT_REF:
return IsPredefined && PredefinedType == PredefinedType.PT_STRING
? ConstValKind.String
: ConstValKind.IntPtr;
case FUNDTYPE.FT_R4:
return ConstValKind.Float;
case FUNDTYPE.FT_R8:
return ConstValKind.Double;
case FUNDTYPE.FT_I1:
return ConstValKind.Boolean;
default:
return ConstValKind.Int;
}
}
}
public override AggregateType GetAts() => this;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.