context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Copyright (C) Pash Contributors. License GPL/BSD. See https://github.com/Pash-Project/Pash/
using System;
using System.Management.Automation;
using Pash.Implementation;
namespace System.Management
{
/// <summary>
/// Imutable class that acts like a string, but provides many options around manipulating a powershell 'path'.
/// </summary>
public class Path
{
private readonly string _rawPath;
static readonly string _predeterminedCorrectSlash;
static readonly string _predeterminedWrongSlash;
static Path()
{
if (System.IO.Path.DirectorySeparatorChar.Equals('/'))
{
_predeterminedCorrectSlash = "/";
_predeterminedWrongSlash = "\\";
}
else
{
_predeterminedCorrectSlash = "\\";
_predeterminedWrongSlash = "/";
}
}
public Path(string rawPath)
: this(_predeterminedCorrectSlash, _predeterminedWrongSlash, rawPath)
{
}
public Path(string correctSlash, string wrongSlash, string rawPath)
{
_rawPath = rawPath ?? string.Empty;
CorrectSlash = correctSlash;
WrongSlash = wrongSlash;
}
public string CorrectSlash { get; set; }
public string WrongSlash { get; set; }
public static implicit operator string(Path path)
{
return path._rawPath;
}
public static implicit operator Path(string path)
{
return new Path(path);
}
public override bool Equals(object obj)
{
if (obj is string)
{
return _rawPath.Equals(obj);
}
var objPath = obj as Path;
if (objPath != null)
{
return _rawPath.Equals(objPath._rawPath);
}
return base.Equals(obj);
}
public override int GetHashCode()
{
return _rawPath.GetHashCode();
}
public Path NormalizeSlashes()
{
return new Path(CorrectSlash, WrongSlash, _rawPath.Replace(WrongSlash, CorrectSlash));
}
public Path TrimEnd(params char[] trimChars)
{
return new Path(CorrectSlash, WrongSlash, _rawPath.TrimEnd(trimChars));
}
public Path TrimEndSlash()
{
return new Path(CorrectSlash, WrongSlash, _rawPath.TrimEnd(char.Parse(CorrectSlash)));
}
public int LastIndexOf(char value)
{
return _rawPath.LastIndexOf(value);
}
public int IndexOf(char value)
{
return _rawPath.IndexOf(value);
}
public Path GetChildNameOrSelfIfNoChild()
{
Path path = this.NormalizeSlashes()
.TrimEndSlash();
int iLastSlash = path.LastIndexOf('\\');
if (iLastSlash == -1)
{
return path;
}
return new Path(CorrectSlash, WrongSlash, path._rawPath.Substring(iLastSlash + 1));
}
public Path GetParentPath(Path root)
{
var path = this;
path = path.NormalizeSlashes();
path = path.TrimEndSlash();
if (root != null)
{
if (string.Equals(path, root, StringComparison.CurrentCultureIgnoreCase))
{
return new Path(CorrectSlash, WrongSlash, string.Empty);
}
}
int iLastSlash = path._rawPath.LastIndexOf(CorrectSlash);
string newPath = root;
if (iLastSlash > 0)
{
newPath = path._rawPath.Substring(0, iLastSlash);
}
else if (iLastSlash == 1)
{
newPath = new Path(CorrectSlash, WrongSlash, CorrectSlash);
}
Path resultPath = new Path(CorrectSlash, WrongSlash, newPath);
return resultPath.ApplyDriveSlash();
}
public Path ApplyDriveSlash()
{
// append a slash to the end (if it's the root drive)
if (this.IsRootPath())
{
if (!this.EndsWithSlash())
{
return this.AppendSlashAtEnd();
}
return this;
}
var result = this.TrimEndSlash();
return result;
}
public Path Combine(Path child)
{
var parent = this;
if (string.IsNullOrEmpty(parent) && string.IsNullOrEmpty(child))
{
return child;
}
if (string.IsNullOrEmpty(parent) && !string.IsNullOrEmpty(child))
{
return child.NormalizeSlashes();
}
parent = parent.NormalizeSlashes();
if (!string.IsNullOrEmpty(parent) && string.IsNullOrEmpty(child))
{
if (parent.EndsWithSlash())
{
return parent;
}
else
{
return parent.AppendSlashAtEnd();
}
}
child = child.NormalizeSlashes();
var builder = new System.Text.StringBuilder(parent);
if (!parent.EndsWithSlash())
builder.Append(CorrectSlash);
// Make sure we do not add two \
if (child.StartsWithSlash())
{
builder.Append(child, 1, child.Length - 1);
}
else
{
builder.Append(child);
}
return new Path(CorrectSlash, WrongSlash, builder.ToString());
}
public Path GetFullPath(string driveName, string currentLocation, bool isFileSystemProvider)
{
if (this.IsRootPath())
{
return this.MakePath(driveName);
}
if (isFileSystemProvider)
{
Path combinedPath;
if (this.HasDrive())
{
combinedPath = this;
}
else
{
combinedPath = ((Path)currentLocation).Combine(this);
}
return new Path(CorrectSlash, WrongSlash, System.IO.Path.GetFullPath(combinedPath));
}
// TODO: this won't work with non-file-system paths that use "../" navigation or other "." navigation.
return (new Path(CorrectSlash, WrongSlash, currentLocation)).Combine(this);
}
public bool StartsWithSlash()
{
if (this.NormalizeSlashes()._rawPath.StartsWith(CorrectSlash))
{
return true;
}
return false;
}
public bool EndsWithSlash()
{
if (this.NormalizeSlashes()._rawPath.EndsWith(CorrectSlash))
{
return true;
}
return false;
}
public Path AppendSlashAtEnd()
{
if (this.EndsWithSlash())
{
return this;
}
return new Path(CorrectSlash, WrongSlash, this._rawPath + CorrectSlash);
}
public bool StartsWith(string value)
{
return _rawPath.StartsWith(value);
}
public bool IsRootPath()
{
// handle unix '/' path
if (this.Length == 1 && this == CorrectSlash)
{
return true;
}
// handle windows drive "C:" "C:\\"
var x = this.TrimEndSlash();
if (this.GetDrive() == x._rawPath.TrimEnd(':'))
{
return true;
}
return false;
}
public string GetDrive()
{
if (this.StartsWithSlash())
{
// return unix drive
return CorrectSlash;
}
int iDelimiter = _rawPath.IndexOf(':');
if (iDelimiter == -1)
return null;
return _rawPath.Substring(0, iDelimiter);
}
public bool TryGetDriveName(out string driveName)
{
driveName = GetDrive();
if (string.IsNullOrEmpty(driveName))
{
return false;
}
return true;
}
public bool HasDrive()
{
var drive = GetDrive();
if (string.IsNullOrEmpty(drive))
{
return false;
}
return true;
}
public Path RemoveDrive()
{
string drive;
if (this.TryGetDriveName(out drive))
{
var newPath = _rawPath.Substring(drive.Length);
if (newPath.StartsWith(":"))
return new Path(CorrectSlash, WrongSlash, newPath.Substring(1));
return new Path(CorrectSlash, WrongSlash, newPath);
}
return this;
}
public Path MakePath(string driveName)
{
Path fullPath;
if (driveName == CorrectSlash)
{
string preSlash = this.StartsWithSlash() ? string.Empty : CorrectSlash;
fullPath = new Path(CorrectSlash, WrongSlash, string.Format("{0}{1}", preSlash, this));
}
else
{
if (this.HasDrive())
{
return this;
}
//TODO: should this take a "current path" parameter? EX: {drive}:{currentPath??}/{this}
string preSlash = this.StartsWithSlash() ? string.Empty : CorrectSlash;
fullPath = new Path(CorrectSlash, WrongSlash, string.Format("{0}:{1}{2}", driveName, preSlash, this));
}
return fullPath.NormalizeSlashes();
}
public override string ToString()
{
return _rawPath;
}
public int Length { get { return _rawPath.Length; } }
}
public static partial class _
{
public static Path AsPath(this string value)
{
return (Path)value;
}
public static string NormalizeSlashes(this string value)
{
return ((Path)value).NormalizeSlashes();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace Rhino.Mocks.Constraints
{
internal class AllPropertiesMatchConstraint : AbstractConstraint
{
private object _expected; //object holding the expected property values.
private string _message; //the message that Rhino Mocks will show.
private Stack<string> _properties; //used to build the property name like Order.Product.Price for the message.
private List<object> _checkedObjects; //every object that is matched goes in this list to prevent recursive loops.
/// <summary>
/// Initializes a new constraint object.
/// </summary>
/// <param name="expected">The expected object, The actual object is passed in as a parameter to the <see cref="Eval"/> method</param>
public AllPropertiesMatchConstraint(object expected)
{
_expected = expected;
_properties = new Stack<string>();
_checkedObjects = new List<object>();
}
/// <summary>
/// Evaluate this constraint.
/// </summary>
/// <param name="obj">The actual object that was passed in the method call to the mock.</param>
/// <returns>True when the constraint is met, else false.</returns>
public override bool Eval(object obj)
{
_properties.Clear();
_checkedObjects.Clear();
_properties.Push(obj.GetType().Name);
bool result = CheckReferenceType(_expected, obj);
_properties.Pop();
_checkedObjects.Clear();
return result;
}
/// <summary>
/// Rhino.Mocks uses this property to generate an error message.
/// </summary>
/// <value>
/// A message telling the tester why the constraint failed.
/// </value>
public override string Message
{
get { return _message; }
}
/// <summary>
/// Checks if the properties of the <paramref name="actual"/> object
/// are the same as the properies of the <paramref name="expected"/> object.
/// </summary>
/// <param name="expected">The expected object</param>
/// <param name="actual">The actual object</param>
/// <returns>True when both objects have the same values, else False.</returns>
protected virtual bool CheckReferenceType(object expected, object actual)
{
Type tExpected = expected.GetType();
Type tActual = actual.GetType();
if (tExpected != tActual)
{
_message = string.Format("Expected type '{0}' doesn't match with actual type '{1}'", tExpected.Name, tActual.Name);
return false;
}
return CheckValue(expected, actual);
}
/// <summary>
///
/// </summary>
/// <param name="expected"></param>
/// <param name="actual"></param>
/// <returns></returns>
/// <remarks>This is the real heart of the beast.</remarks>
protected virtual bool CheckValue(object expected, object actual)
{
if (actual == null && expected != null)
{
_message = string.Format("Expected value of {0} is '{1}', actual value is null", BuildPropertyName(), expected);
return false;
}
if (expected == null)
{
if (actual != null)
{
_message = string.Format("Expected value of {0} is null, actual value is '{1}'", BuildPropertyName(), actual);
return false;
}
}
else
{
//if both objects are comparable Equals can be used to determine equality. (value types implement IComparable too when boxed)
if (expected is IComparable)
{
if (!expected.Equals(actual))
{
_message = string.Format("Expected value of {0} is '{1}', actual value is '{2}'", BuildPropertyName(), expected.ToString(), actual.ToString());
return false;
}
}
else if (expected is IEnumerable) //if both objects are lists we should tread them as such.
{
if (!CheckCollection((IEnumerable)expected, (IEnumerable)actual))
{
return false;
}
}
else if (!_checkedObjects.Contains(expected)) //prevent endless recursive loops.
{
_checkedObjects.Add(expected);
if (!CheckProperties(expected, actual))
{
return false;
}
if (!CheckFields(expected, actual))
{
return false;
}
}
}
return true;
}
/// <summary>
/// Used by CheckReferenceType to check all properties of the reference type.
/// </summary>
/// <param name="expected">The expected object</param>
/// <param name="actual">The actual object</param>
/// <returns>True when both objects have the same values, else False.</returns>
protected virtual bool CheckProperties(object expected, object actual)
{
Type tExpected = expected.GetType();
Type tActual = actual.GetType();
PropertyInfo[] properties = tExpected.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (PropertyInfo property in properties)
{
//TODO: deal with indexed properties
ParameterInfo[] indexParameters = property.GetIndexParameters();
if (indexParameters.Length == 0) //It's not an indexed property
{
_properties.Push(property.Name);
try
{
object expectedValue = property.GetValue(expected, null);
object actualValue = property.GetValue(actual, null);
//if (!CheckValue(expectedValue, actualValue)) return false;
if (!CheckValue(expectedValue, actualValue)) return false;
}
catch (System.Reflection.TargetInvocationException)
{
//the inner exception should give you a clou about why we couldn't invoke GetValue...
//do nothing
}
_properties.Pop();
}
}
return true;
}
/// <summary>
/// Used by CheckReferenceType to check all fields of the reference type.
/// </summary>
/// <param name="expected">The expected object</param>
/// <param name="actual">The actual object</param>
/// <returns>True when both objects have the same values, else False.</returns>
protected virtual bool CheckFields(object expected, object actual)
{
Type tExpected = expected.GetType();
Type tActual = actual.GetType();
_checkedObjects.Add(actual);
FieldInfo[] fields = tExpected.GetFields(BindingFlags.Instance | BindingFlags.Public);
foreach (FieldInfo field in fields)
{
_properties.Push(field.Name);
object expectedValue = field.GetValue(expected);
object actualValue = field.GetValue(actual);
bool result = CheckValue(expectedValue, actualValue);
_properties.Pop();
if (!result) return false;
}
return true;
}
/// <summary>
/// Checks the items of both collections
/// </summary>
/// <param name="expectedCollection">The expected collection</param>
/// <param name="actualCollection"></param>
/// <returns>True if both collections contain the same items in the same order.</returns>
private bool CheckCollection(IEnumerable expectedCollection, IEnumerable actualCollection)
{
if (expectedCollection != null) //only check the list if there is something in there.
{
IEnumerator expectedEnumerator = expectedCollection.GetEnumerator();
IEnumerator actualEnumerator = actualCollection.GetEnumerator();
bool expectedHasMore = expectedEnumerator.MoveNext();
bool actualHasMore = actualEnumerator.MoveNext();
int expectedCount = 0;
int actualCount = 0;
string name = _properties.Pop(); //pop the propertyname from the stack to be replaced by the same name with an index.
while (expectedHasMore && actualHasMore)
{
object expectedValue = expectedEnumerator.Current;
object actualValue = actualEnumerator.Current;
_properties.Push(name + string.Format("[{0}]", expectedCount)); //replace the earlier popped property name
expectedCount++;
actualCount++;
if (!CheckReferenceType(expectedValue, actualValue))
{
return false;
}
_properties.Pop(); //pop the old indexed property name to make place for a new one
expectedHasMore = expectedEnumerator.MoveNext();
actualHasMore = actualEnumerator.MoveNext();
}
_properties.Push(name); //push the original property name back on the stack.
//examine the expectedMoveNextResult and the actualMoveNextResult to see if one collection was bigger than the other.
if (expectedHasMore & !actualHasMore) //actual has less items than expected.
{
//find out how much items there are in the expected collection.
do expectedCount++; while (expectedEnumerator.MoveNext());
}
if (!expectedHasMore & actualHasMore) //actual has more items than expected.
{
//find out how much items there are in the actual collection.
do actualCount++; while (actualEnumerator.MoveNext());
}
if (expectedCount != actualCount)
{
_message = string.Format("expected number of items in collection {0} is '{1}', actual is '{2}'", BuildPropertyName(), expectedCount, actualCount);
return false;
}
}
return true;
}
/// <summary>
/// Builds a propertyname from the Stack _properties like 'Order.Product.Price'
/// to be used in the error message.
/// </summary>
/// <returns>A nested property name.</returns>
private string BuildPropertyName()
{
StringBuilder result = new StringBuilder();
string[] names = _properties.ToArray();
foreach(string name in names)
{
if (result.Length > 0)
{
result.Insert(0, '.');
}
result.Insert(0, name);
}
return result.ToString();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security;
using System.Timers;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using RegionFlags = OpenMetaverse.RegionFlags;
namespace OpenSim.Region.CoreModules.World.Estate
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "EstateManagementModule")]
public class EstateManagementModule : IEstateModule, INonSharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Timer m_regionChangeTimer = new Timer();
public Scene Scene { get; private set; }
public IUserManagement UserManager { get; private set; }
protected EstateManagementCommands m_commands;
/// <summary>
/// If false, region restart requests from the client are blocked even if they are otherwise legitimate.
/// </summary>
public bool AllowRegionRestartFromClient { get; set; }
private EstateTerrainXferHandler TerrainUploader;
public TelehubManager m_Telehub;
public event ChangeDelegate OnRegionInfoChange;
public event ChangeDelegate OnEstateInfoChange;
public event MessageDelegate OnEstateMessage;
private int m_delayCount = 0;
#region Region Module interface
public string Name { get { return "EstateManagementModule"; } }
public Type ReplaceableInterface { get { return null; } }
public void Initialise(IConfigSource source)
{
AllowRegionRestartFromClient = true;
IConfig config = source.Configs["EstateManagement"];
if (config != null)
AllowRegionRestartFromClient = config.GetBoolean("AllowRegionRestartFromClient", true);
}
public void AddRegion(Scene scene)
{
Scene = scene;
Scene.RegisterModuleInterface<IEstateModule>(this);
Scene.EventManager.OnNewClient += EventManager_OnNewClient;
Scene.EventManager.OnRequestChangeWaterHeight += changeWaterHeight;
m_Telehub = new TelehubManager(scene);
m_commands = new EstateManagementCommands(this);
m_commands.Initialise();
}
public void RemoveRegion(Scene scene) {}
public void RegionLoaded(Scene scene)
{
// Sets up the sun module based no the saved Estate and Region Settings
// DO NOT REMOVE or the sun will stop working
scene.TriggerEstateSunUpdate();
UserManager = scene.RequestModuleInterface<IUserManagement>();
}
public void Close()
{
m_commands.Close();
}
#endregion
#region Packet Data Responders
private void clientSendDetailedEstateData(IClientAPI remote_client, UUID invoice)
{
sendDetailedEstateData(remote_client, invoice);
sendEstateLists(remote_client, invoice);
}
private void sendDetailedEstateData(IClientAPI remote_client, UUID invoice)
{
uint sun = 0;
if (Scene.RegionInfo.EstateSettings.FixedSun)
sun = (uint)(Scene.RegionInfo.EstateSettings.SunPosition * 1024.0) + 0x1800;
UUID estateOwner;
estateOwner = Scene.RegionInfo.EstateSettings.EstateOwner;
if (Scene.Permissions.IsGod(remote_client.AgentId))
estateOwner = remote_client.AgentId;
remote_client.SendDetailedEstateData(invoice,
Scene.RegionInfo.EstateSettings.EstateName,
Scene.RegionInfo.EstateSettings.EstateID,
Scene.RegionInfo.EstateSettings.ParentEstateID,
GetEstateFlags(),
sun,
Scene.RegionInfo.RegionSettings.Covenant,
(uint) Scene.RegionInfo.RegionSettings.CovenantChangedDateTime,
Scene.RegionInfo.EstateSettings.AbuseEmail,
estateOwner);
}
private void sendEstateLists(IClientAPI remote_client, UUID invoice)
{
remote_client.SendEstateList(invoice,
(int)Constants.EstateAccessCodex.EstateManagers,
Scene.RegionInfo.EstateSettings.EstateManagers,
Scene.RegionInfo.EstateSettings.EstateID);
remote_client.SendEstateList(invoice,
(int)Constants.EstateAccessCodex.AccessOptions,
Scene.RegionInfo.EstateSettings.EstateAccess,
Scene.RegionInfo.EstateSettings.EstateID);
remote_client.SendEstateList(invoice,
(int)Constants.EstateAccessCodex.AllowedGroups,
Scene.RegionInfo.EstateSettings.EstateGroups,
Scene.RegionInfo.EstateSettings.EstateID);
remote_client.SendBannedUserList(invoice,
Scene.RegionInfo.EstateSettings.EstateBans,
Scene.RegionInfo.EstateSettings.EstateID);
}
private void estateSetRegionInfoHandler(bool blockTerraform, bool noFly, bool allowDamage, bool blockLandResell, int maxAgents, float objectBonusFactor,
int matureLevel, bool restrictPushObject, bool allowParcelChanges)
{
if (blockTerraform)
Scene.RegionInfo.RegionSettings.BlockTerraform = true;
else
Scene.RegionInfo.RegionSettings.BlockTerraform = false;
if (noFly)
Scene.RegionInfo.RegionSettings.BlockFly = true;
else
Scene.RegionInfo.RegionSettings.BlockFly = false;
if (allowDamage)
Scene.RegionInfo.RegionSettings.AllowDamage = true;
else
Scene.RegionInfo.RegionSettings.AllowDamage = false;
if (blockLandResell)
Scene.RegionInfo.RegionSettings.AllowLandResell = false;
else
Scene.RegionInfo.RegionSettings.AllowLandResell = true;
if((byte)maxAgents <= Scene.RegionInfo.AgentCapacity)
Scene.RegionInfo.RegionSettings.AgentLimit = (byte) maxAgents;
else
Scene.RegionInfo.RegionSettings.AgentLimit = Scene.RegionInfo.AgentCapacity;
Scene.RegionInfo.RegionSettings.ObjectBonus = objectBonusFactor;
if (matureLevel <= 13)
Scene.RegionInfo.RegionSettings.Maturity = 0;
else if (matureLevel <= 21)
Scene.RegionInfo.RegionSettings.Maturity = 1;
else
Scene.RegionInfo.RegionSettings.Maturity = 2;
if (restrictPushObject)
Scene.RegionInfo.RegionSettings.RestrictPushing = true;
else
Scene.RegionInfo.RegionSettings.RestrictPushing = false;
if (allowParcelChanges)
Scene.RegionInfo.RegionSettings.AllowLandJoinDivide = true;
else
Scene.RegionInfo.RegionSettings.AllowLandJoinDivide = false;
Scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
sendRegionInfoPacketToAll();
}
public void setEstateTerrainBaseTexture(int level, UUID texture)
{
setEstateTerrainBaseTexture(null, level, texture);
sendRegionHandshakeToAll();
}
public void setEstateTerrainBaseTexture(IClientAPI remoteClient, int level, UUID texture)
{
if (texture == UUID.Zero)
return;
switch (level)
{
case 0:
Scene.RegionInfo.RegionSettings.TerrainTexture1 = texture;
break;
case 1:
Scene.RegionInfo.RegionSettings.TerrainTexture2 = texture;
break;
case 2:
Scene.RegionInfo.RegionSettings.TerrainTexture3 = texture;
break;
case 3:
Scene.RegionInfo.RegionSettings.TerrainTexture4 = texture;
break;
}
Scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
sendRegionInfoPacketToAll();
}
public void setEstateTerrainTextureHeights(int corner, float lowValue, float highValue)
{
setEstateTerrainTextureHeights(null, corner, lowValue, highValue);
}
public void setEstateTerrainTextureHeights(IClientAPI client, int corner, float lowValue, float highValue)
{
switch (corner)
{
case 0:
Scene.RegionInfo.RegionSettings.Elevation1SW = lowValue;
Scene.RegionInfo.RegionSettings.Elevation2SW = highValue;
break;
case 1:
Scene.RegionInfo.RegionSettings.Elevation1NW = lowValue;
Scene.RegionInfo.RegionSettings.Elevation2NW = highValue;
break;
case 2:
Scene.RegionInfo.RegionSettings.Elevation1SE = lowValue;
Scene.RegionInfo.RegionSettings.Elevation2SE = highValue;
break;
case 3:
Scene.RegionInfo.RegionSettings.Elevation1NE = lowValue;
Scene.RegionInfo.RegionSettings.Elevation2NE = highValue;
break;
}
Scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
sendRegionHandshakeToAll();
sendRegionInfoPacketToAll();
}
private void handleCommitEstateTerrainTextureRequest(IClientAPI remoteClient)
{
// sendRegionHandshakeToAll();
}
public void setRegionTerrainSettings(float WaterHeight,
float TerrainRaiseLimit, float TerrainLowerLimit,
bool UseEstateSun, bool UseFixedSun, float SunHour,
bool UseGlobal, bool EstateFixedSun, float EstateSunHour)
{
// Water Height
Scene.RegionInfo.RegionSettings.WaterHeight = WaterHeight;
// Terraforming limits
Scene.RegionInfo.RegionSettings.TerrainRaiseLimit = TerrainRaiseLimit;
Scene.RegionInfo.RegionSettings.TerrainLowerLimit = TerrainLowerLimit;
// Time of day / fixed sun
Scene.RegionInfo.RegionSettings.UseEstateSun = UseEstateSun;
Scene.RegionInfo.RegionSettings.FixedSun = UseFixedSun;
Scene.RegionInfo.RegionSettings.SunPosition = SunHour;
Scene.TriggerEstateSunUpdate();
//m_log.Debug("[ESTATE]: UFS: " + UseFixedSun.ToString());
//m_log.Debug("[ESTATE]: SunHour: " + SunHour.ToString());
sendRegionInfoPacketToAll();
Scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
}
private void handleEstateRestartSimRequest(IClientAPI remoteClient, int timeInSeconds)
{
if (!AllowRegionRestartFromClient)
{
remoteClient.SendAlertMessage("Region restart has been disabled on this simulator.");
return;
}
IRestartModule restartModule = Scene.RequestModuleInterface<IRestartModule>();
if (restartModule != null)
{
List<int> times = new List<int>();
while (timeInSeconds > 0)
{
times.Add(timeInSeconds);
if (timeInSeconds > 300)
timeInSeconds -= 120;
else if (timeInSeconds > 30)
timeInSeconds -= 30;
else
timeInSeconds -= 15;
}
restartModule.ScheduleRestart(UUID.Zero, "Region will restart in {0}", times.ToArray(), false);
m_log.InfoFormat(
"User {0} requested restart of region {1} in {2} seconds",
remoteClient.Name, Scene.Name, times.Count != 0 ? times[0] : 0);
}
}
private void handleChangeEstateCovenantRequest(IClientAPI remoteClient, UUID estateCovenantID)
{
// m_log.DebugFormat(
// "[ESTATE MANAGEMENT MODULE]: Handling request from {0} to change estate covenant to {1}",
// remoteClient.Name, estateCovenantID);
Scene.RegionInfo.RegionSettings.Covenant = estateCovenantID;
Scene.RegionInfo.RegionSettings.CovenantChangedDateTime = Util.UnixTimeSinceEpoch();
Scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
}
private void handleEstateAccessDeltaRequest(IClientAPI remote_client, UUID invoice, int estateAccessType, UUID user)
{
// EstateAccessDelta handles Estate Managers, Sim Access, Sim Banlist, allowed Groups.. etc.
if (user == Scene.RegionInfo.EstateSettings.EstateOwner)
return; // never process EO
if ((estateAccessType & 4) != 0) // User add
{
if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true))
{
if ((estateAccessType & 1) != 0) // All estates
{
List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner);
EstateSettings estateSettings;
foreach (int estateID in estateIDs)
{
if (estateID != Scene.RegionInfo.EstateSettings.EstateID)
{
estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID);
estateSettings.AddEstateUser(user);
estateSettings.Save();
}
}
}
Scene.RegionInfo.EstateSettings.AddEstateUser(user);
Scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, Scene.RegionInfo.EstateSettings.EstateAccess, Scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & 8) != 0) // User remove
{
if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true))
{
if ((estateAccessType & 1) != 0) // All estates
{
List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner);
EstateSettings estateSettings;
foreach (int estateID in estateIDs)
{
if (estateID != Scene.RegionInfo.EstateSettings.EstateID)
{
estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID);
estateSettings.RemoveEstateUser(user);
estateSettings.Save();
}
}
}
Scene.RegionInfo.EstateSettings.RemoveEstateUser(user);
Scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, Scene.RegionInfo.EstateSettings.EstateAccess, Scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & 16) != 0) // Group add
{
if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true))
{
if ((estateAccessType & 1) != 0) // All estates
{
List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner);
EstateSettings estateSettings;
foreach (int estateID in estateIDs)
{
if (estateID != Scene.RegionInfo.EstateSettings.EstateID)
{
estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID);
estateSettings.AddEstateGroup(user);
estateSettings.Save();
}
}
}
Scene.RegionInfo.EstateSettings.AddEstateGroup(user);
Scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, Scene.RegionInfo.EstateSettings.EstateGroups, Scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & 32) != 0) // Group remove
{
if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true))
{
if ((estateAccessType & 1) != 0) // All estates
{
List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner);
EstateSettings estateSettings;
foreach (int estateID in estateIDs)
{
if (estateID != Scene.RegionInfo.EstateSettings.EstateID)
{
estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID);
estateSettings.RemoveEstateGroup(user);
estateSettings.Save();
}
}
}
Scene.RegionInfo.EstateSettings.RemoveEstateGroup(user);
Scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, Scene.RegionInfo.EstateSettings.EstateGroups, Scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & 64) != 0) // Ban add
{
if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, false))
{
EstateBan[] banlistcheck = Scene.RegionInfo.EstateSettings.EstateBans;
bool alreadyInList = false;
for (int i = 0; i < banlistcheck.Length; i++)
{
if (user == banlistcheck[i].BannedUserID)
{
alreadyInList = true;
break;
}
}
if (!alreadyInList)
{
if ((estateAccessType & 1) != 0) // All estates
{
List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner);
EstateSettings estateSettings;
foreach (int estateID in estateIDs)
{
if (estateID != Scene.RegionInfo.EstateSettings.EstateID)
{
EstateBan bitem = new EstateBan();
bitem.BannedUserID = user;
bitem.EstateID = (uint)estateID;
bitem.BannedHostAddress = "0.0.0.0";
bitem.BannedHostIPMask = "0.0.0.0";
estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID);
estateSettings.AddBan(bitem);
estateSettings.Save();
}
}
}
EstateBan item = new EstateBan();
item.BannedUserID = user;
item.EstateID = Scene.RegionInfo.EstateSettings.EstateID;
item.BannedHostAddress = "0.0.0.0";
item.BannedHostIPMask = "0.0.0.0";
Scene.RegionInfo.EstateSettings.AddBan(item);
Scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
ScenePresence s = Scene.GetScenePresence(user);
if (s != null)
{
if (!s.IsChildAgent)
{
if (!Scene.TeleportClientHome(user, s.ControllingClient))
{
s.ControllingClient.Kick("Your access to the region was revoked and TP home failed - you have been logged out.");
Scene.CloseAgent(s.UUID, false);
}
}
}
}
else
{
remote_client.SendAlertMessage("User is already on the region ban list");
}
//Scene.RegionInfo.regionBanlist.Add(Manager(user);
remote_client.SendBannedUserList(invoice, Scene.RegionInfo.EstateSettings.EstateBans, Scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & 128) != 0) // Ban remove
{
if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, false))
{
EstateBan[] banlistcheck = Scene.RegionInfo.EstateSettings.EstateBans;
bool alreadyInList = false;
EstateBan listitem = null;
for (int i = 0; i < banlistcheck.Length; i++)
{
if (user == banlistcheck[i].BannedUserID)
{
alreadyInList = true;
listitem = banlistcheck[i];
break;
}
}
if (alreadyInList && listitem != null)
{
if ((estateAccessType & 1) != 0) // All estates
{
List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner);
EstateSettings estateSettings;
foreach (int estateID in estateIDs)
{
if (estateID != Scene.RegionInfo.EstateSettings.EstateID)
{
estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID);
estateSettings.RemoveBan(user);
estateSettings.Save();
}
}
}
Scene.RegionInfo.EstateSettings.RemoveBan(listitem.BannedUserID);
Scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
}
else
{
remote_client.SendAlertMessage("User is not on the region ban list");
}
//Scene.RegionInfo.regionBanlist.Add(Manager(user);
remote_client.SendBannedUserList(invoice, Scene.RegionInfo.EstateSettings.EstateBans, Scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & 256) != 0) // Manager add
{
if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true))
{
if ((estateAccessType & 1) != 0) // All estates
{
List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner);
EstateSettings estateSettings;
foreach (int estateID in estateIDs)
{
if (estateID != Scene.RegionInfo.EstateSettings.EstateID)
{
estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID);
estateSettings.AddEstateManager(user);
estateSettings.Save();
}
}
}
Scene.RegionInfo.EstateSettings.AddEstateManager(user);
Scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, Scene.RegionInfo.EstateSettings.EstateManagers, Scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & 512) != 0) // Manager remove
{
if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true))
{
if ((estateAccessType & 1) != 0) // All estates
{
List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner);
EstateSettings estateSettings;
foreach (int estateID in estateIDs)
{
if (estateID != Scene.RegionInfo.EstateSettings.EstateID)
{
estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID);
estateSettings.RemoveEstateManager(user);
estateSettings.Save();
}
}
}
Scene.RegionInfo.EstateSettings.RemoveEstateManager(user);
Scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, Scene.RegionInfo.EstateSettings.EstateManagers, Scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
}
public void handleOnEstateManageTelehub(IClientAPI client, UUID invoice, UUID senderID, string cmd, uint param1)
{
SceneObjectPart part;
switch (cmd)
{
case "info ui":
break;
case "connect":
// Add the Telehub
part = Scene.GetSceneObjectPart((uint)param1);
if (part == null)
return;
SceneObjectGroup grp = part.ParentGroup;
m_Telehub.Connect(grp);
break;
case "delete":
// Disconnect Telehub
m_Telehub.Disconnect();
break;
case "spawnpoint add":
// Add SpawnPoint to the Telehub
part = Scene.GetSceneObjectPart((uint)param1);
if (part == null)
return;
m_Telehub.AddSpawnPoint(part.AbsolutePosition);
break;
case "spawnpoint remove":
// Remove SpawnPoint from Telehub
m_Telehub.RemoveSpawnPoint((int)param1);
break;
default:
break;
}
SendTelehubInfo(client);
}
private void SendSimulatorBlueBoxMessage(
IClientAPI remote_client, UUID invoice, UUID senderID, UUID sessionID, string senderName, string message)
{
IDialogModule dm = Scene.RequestModuleInterface<IDialogModule>();
if (dm != null)
dm.SendNotificationToUsersInRegion(senderID, senderName, message);
}
private void SendEstateBlueBoxMessage(
IClientAPI remote_client, UUID invoice, UUID senderID, UUID sessionID, string senderName, string message)
{
TriggerEstateMessage(senderID, senderName, message);
}
private void handleEstateDebugRegionRequest(
IClientAPI remote_client, UUID invoice, UUID senderID,
bool disableScripts, bool disableCollisions, bool disablePhysics)
{
Scene.RegionInfo.RegionSettings.DisablePhysics = disablePhysics;
Scene.RegionInfo.RegionSettings.DisableScripts = disableScripts;
Scene.RegionInfo.RegionSettings.DisableCollisions = disableCollisions;
Scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
ISceneCommandsModule scm = Scene.RequestModuleInterface<ISceneCommandsModule>();
if (scm != null)
{
scm.SetSceneDebugOptions(
new Dictionary<string, string>() {
{ "scripting", (!disableScripts).ToString() },
{ "collisions", (!disableCollisions).ToString() },
{ "physics", (!disablePhysics).ToString() }
}
);
}
}
private void handleEstateTeleportOneUserHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID, UUID prey)
{
if (!Scene.Permissions.CanIssueEstateCommand(remover_client.AgentId, false))
return;
if (prey != UUID.Zero)
{
ScenePresence s = Scene.GetScenePresence(prey);
if (s != null)
{
if (!Scene.TeleportClientHome(prey, s.ControllingClient))
{
s.ControllingClient.Kick("You were teleported home by the region owner, but the TP failed - you have been logged out.");
Scene.CloseAgent(s.UUID, false);
}
}
}
}
private void handleEstateTeleportAllUsersHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID)
{
if (!Scene.Permissions.CanIssueEstateCommand(remover_client.AgentId, false))
return;
Scene.ForEachRootClient(delegate(IClientAPI client)
{
if (client.AgentId != senderID)
{
// make sure they are still there, we could be working down a long list
// Also make sure they are actually in the region
ScenePresence p;
if(Scene.TryGetScenePresence(client.AgentId, out p))
{
if (!Scene.TeleportClientHome(p.UUID, p.ControllingClient))
{
p.ControllingClient.Kick("You were teleported home by the region owner, but the TP failed - you have been logged out.");
Scene.CloseAgent(p.UUID, false);
}
}
}
});
}
private void AbortTerrainXferHandler(IClientAPI remoteClient, ulong XferID)
{
lock (this)
{
if ((TerrainUploader != null) && (XferID == TerrainUploader.XferID))
{
remoteClient.OnXferReceive -= TerrainUploader.XferReceive;
remoteClient.OnAbortXfer -= AbortTerrainXferHandler;
TerrainUploader.TerrainUploadDone -= HandleTerrainApplication;
TerrainUploader = null;
remoteClient.SendAlertMessage("Terrain Upload aborted by the client");
}
}
}
private void HandleTerrainApplication(string filename, byte[] terrainData, IClientAPI remoteClient)
{
lock (this)
{
remoteClient.OnXferReceive -= TerrainUploader.XferReceive;
remoteClient.OnAbortXfer -= AbortTerrainXferHandler;
TerrainUploader.TerrainUploadDone -= HandleTerrainApplication;
TerrainUploader = null;
}
remoteClient.SendAlertMessage("Terrain Upload Complete. Loading....");
ITerrainModule terr = Scene.RequestModuleInterface<ITerrainModule>();
if (terr != null)
{
m_log.Warn("[CLIENT]: Got Request to Send Terrain in region " + Scene.RegionInfo.RegionName);
try
{
MemoryStream terrainStream = new MemoryStream(terrainData);
terr.LoadFromStream(filename, terrainStream);
terrainStream.Close();
FileInfo x = new FileInfo(filename);
remoteClient.SendAlertMessage("Your terrain was loaded as a " + x.Extension + " file. It may take a few moments to appear.");
}
catch (IOException e)
{
m_log.ErrorFormat("[TERRAIN]: Error Saving a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString());
remoteClient.SendAlertMessage("There was an IO Exception loading your terrain. Please check free space.");
return;
}
catch (SecurityException e)
{
m_log.ErrorFormat("[TERRAIN]: Error Saving a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString());
remoteClient.SendAlertMessage("There was a security Exception loading your terrain. Please check the security on the simulator drive");
return;
}
catch (UnauthorizedAccessException e)
{
m_log.ErrorFormat("[TERRAIN]: Error Saving a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString());
remoteClient.SendAlertMessage("There was a security Exception loading your terrain. Please check the security on the simulator drive");
return;
}
catch (Exception e)
{
m_log.ErrorFormat("[TERRAIN]: Error loading a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString());
remoteClient.SendAlertMessage("There was a general error loading your terrain. Please fix the terrain file and try again");
}
}
else
{
remoteClient.SendAlertMessage("Unable to apply terrain. Cannot get an instance of the terrain module");
}
}
private void handleUploadTerrain(IClientAPI remote_client, string clientFileName)
{
lock (this)
{
if (TerrainUploader == null)
{
m_log.DebugFormat("Starting to receive uploaded terrain");
TerrainUploader = new EstateTerrainXferHandler(remote_client, clientFileName);
remote_client.OnXferReceive += TerrainUploader.XferReceive;
remote_client.OnAbortXfer += AbortTerrainXferHandler;
TerrainUploader.TerrainUploadDone += HandleTerrainApplication;
TerrainUploader.RequestStartXfer(remote_client);
}
else
{
remote_client.SendAlertMessage("Another Terrain Upload is in progress. Please wait your turn!");
}
}
}
public bool IsTerrainXfer(ulong xferID)
{
lock (this)
{
if (TerrainUploader == null)
return false;
else
return TerrainUploader.XferID == xferID;
}
}
private void handleTerrainRequest(IClientAPI remote_client, string clientFileName)
{
// Save terrain here
ITerrainModule terr = Scene.RequestModuleInterface<ITerrainModule>();
if (terr != null)
{
m_log.Warn("[CLIENT]: Got Request to Send Terrain in region " + Scene.RegionInfo.RegionName);
if (File.Exists(Util.dataDir() + "/terrain.raw"))
{
File.Delete(Util.dataDir() + "/terrain.raw");
}
terr.SaveToFile(Util.dataDir() + "/terrain.raw");
FileStream input = new FileStream(Util.dataDir() + "/terrain.raw", FileMode.Open);
byte[] bdata = new byte[input.Length];
input.Read(bdata, 0, (int)input.Length);
remote_client.SendAlertMessage("Terrain file written, starting download...");
Scene.XferManager.AddNewFile("terrain.raw", bdata);
// Tell client about it
m_log.Warn("[CLIENT]: Sending Terrain to " + remote_client.Name);
remote_client.SendInitiateDownload("terrain.raw", clientFileName);
}
}
private void HandleRegionInfoRequest(IClientAPI remote_client)
{
RegionInfoForEstateMenuArgs args = new RegionInfoForEstateMenuArgs();
args.billableFactor = Scene.RegionInfo.EstateSettings.BillableFactor;
args.estateID = Scene.RegionInfo.EstateSettings.EstateID;
args.maxAgents = (byte)Scene.RegionInfo.RegionSettings.AgentLimit;
args.objectBonusFactor = (float)Scene.RegionInfo.RegionSettings.ObjectBonus;
args.parentEstateID = Scene.RegionInfo.EstateSettings.ParentEstateID;
args.pricePerMeter = Scene.RegionInfo.EstateSettings.PricePerMeter;
args.redirectGridX = Scene.RegionInfo.EstateSettings.RedirectGridX;
args.redirectGridY = Scene.RegionInfo.EstateSettings.RedirectGridY;
args.regionFlags = GetRegionFlags();
args.simAccess = Scene.RegionInfo.AccessLevel;
args.sunHour = (float)Scene.RegionInfo.RegionSettings.SunPosition;
args.terrainLowerLimit = (float)Scene.RegionInfo.RegionSettings.TerrainLowerLimit;
args.terrainRaiseLimit = (float)Scene.RegionInfo.RegionSettings.TerrainRaiseLimit;
args.useEstateSun = Scene.RegionInfo.RegionSettings.UseEstateSun;
args.waterHeight = (float)Scene.RegionInfo.RegionSettings.WaterHeight;
args.simName = Scene.RegionInfo.RegionName;
args.regionType = Scene.RegionInfo.RegionType;
remote_client.SendRegionInfoToEstateMenu(args);
}
private void HandleEstateCovenantRequest(IClientAPI remote_client)
{
remote_client.SendEstateCovenantInformation(Scene.RegionInfo.RegionSettings.Covenant);
}
private void HandleLandStatRequest(int parcelID, uint reportType, uint requestFlags, string filter, IClientAPI remoteClient)
{
if (!Scene.Permissions.CanIssueEstateCommand(remoteClient.AgentId, false))
return;
Dictionary<uint, float> sceneData = null;
if (reportType == 1)
{
sceneData = Scene.PhysicsScene.GetTopColliders();
}
else if (reportType == 0)
{
IScriptModule scriptModule = Scene.RequestModuleInterface<IScriptModule>();
if (scriptModule != null)
sceneData = scriptModule.GetObjectScriptsExecutionTimes();
}
List<LandStatReportItem> SceneReport = new List<LandStatReportItem>();
if (sceneData != null)
{
var sortedSceneData
= sceneData.Select(
item => new { Measurement = item.Value, Part = Scene.GetSceneObjectPart(item.Key) });
sortedSceneData.OrderBy(item => item.Measurement);
int items = 0;
foreach (var entry in sortedSceneData)
{
// The object may have been deleted since we received the data.
if (entry.Part == null)
continue;
// Don't show scripts that haven't executed or where execution time is below one microsecond in
// order to produce a more readable report.
if (entry.Measurement < 0.001)
continue;
items++;
SceneObjectGroup so = entry.Part.ParentGroup;
LandStatReportItem lsri = new LandStatReportItem();
lsri.LocationX = so.AbsolutePosition.X;
lsri.LocationY = so.AbsolutePosition.Y;
lsri.LocationZ = so.AbsolutePosition.Z;
lsri.Score = entry.Measurement;
lsri.TaskID = so.UUID;
lsri.TaskLocalID = so.LocalId;
lsri.TaskName = entry.Part.Name;
lsri.OwnerName = UserManager.GetUserName(so.OwnerID);
if (filter.Length != 0)
{
if ((lsri.OwnerName.Contains(filter) || lsri.TaskName.Contains(filter)))
{
}
else
{
continue;
}
}
SceneReport.Add(lsri);
if (items >= 100)
break;
}
}
remoteClient.SendLandStatReply(reportType, requestFlags, (uint)SceneReport.Count,SceneReport.ToArray());
}
#endregion
#region Outgoing Packets
public void sendRegionInfoPacketToAll()
{
Scene.ForEachRootClient(delegate(IClientAPI client)
{
HandleRegionInfoRequest(client);
});
}
public void sendRegionHandshake(IClientAPI remoteClient)
{
RegionHandshakeArgs args = new RegionHandshakeArgs();
args.isEstateManager = Scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(remoteClient.AgentId);
if (Scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero && Scene.RegionInfo.EstateSettings.EstateOwner == remoteClient.AgentId)
args.isEstateManager = true;
args.billableFactor = Scene.RegionInfo.EstateSettings.BillableFactor;
args.terrainStartHeight0 = (float)Scene.RegionInfo.RegionSettings.Elevation1SW;
args.terrainHeightRange0 = (float)Scene.RegionInfo.RegionSettings.Elevation2SW;
args.terrainStartHeight1 = (float)Scene.RegionInfo.RegionSettings.Elevation1NW;
args.terrainHeightRange1 = (float)Scene.RegionInfo.RegionSettings.Elevation2NW;
args.terrainStartHeight2 = (float)Scene.RegionInfo.RegionSettings.Elevation1SE;
args.terrainHeightRange2 = (float)Scene.RegionInfo.RegionSettings.Elevation2SE;
args.terrainStartHeight3 = (float)Scene.RegionInfo.RegionSettings.Elevation1NE;
args.terrainHeightRange3 = (float)Scene.RegionInfo.RegionSettings.Elevation2NE;
args.simAccess = Scene.RegionInfo.AccessLevel;
args.waterHeight = (float)Scene.RegionInfo.RegionSettings.WaterHeight;
args.regionFlags = GetRegionFlags();
args.regionName = Scene.RegionInfo.RegionName;
args.SimOwner = Scene.RegionInfo.EstateSettings.EstateOwner;
args.terrainBase0 = UUID.Zero;
args.terrainBase1 = UUID.Zero;
args.terrainBase2 = UUID.Zero;
args.terrainBase3 = UUID.Zero;
args.terrainDetail0 = Scene.RegionInfo.RegionSettings.TerrainTexture1;
args.terrainDetail1 = Scene.RegionInfo.RegionSettings.TerrainTexture2;
args.terrainDetail2 = Scene.RegionInfo.RegionSettings.TerrainTexture3;
args.terrainDetail3 = Scene.RegionInfo.RegionSettings.TerrainTexture4;
// m_log.DebugFormat("[ESTATE MANAGEMENT MODULE]: Sending terrain texture 1 {0} for region {1}", args.terrainDetail0, Scene.RegionInfo.RegionName);
// m_log.DebugFormat("[ESTATE MANAGEMENT MODULE]: Sending terrain texture 2 {0} for region {1}", args.terrainDetail1, Scene.RegionInfo.RegionName);
// m_log.DebugFormat("[ESTATE MANAGEMENT MODULE]: Sending terrain texture 3 {0} for region {1}", args.terrainDetail2, Scene.RegionInfo.RegionName);
// m_log.DebugFormat("[ESTATE MANAGEMENT MODULE]: Sending terrain texture 4 {0} for region {1}", args.terrainDetail3, Scene.RegionInfo.RegionName);
remoteClient.SendRegionHandshake(Scene.RegionInfo,args);
}
public void sendRegionHandshakeToAll()
{
Scene.ForEachClient(sendRegionHandshake);
}
public void handleEstateChangeInfo(IClientAPI remoteClient, UUID invoice, UUID senderID, UInt32 parms1, UInt32 parms2)
{
if (parms2 == 0)
{
Scene.RegionInfo.EstateSettings.UseGlobalTime = true;
Scene.RegionInfo.EstateSettings.SunPosition = 0.0;
}
else
{
Scene.RegionInfo.EstateSettings.UseGlobalTime = false;
Scene.RegionInfo.EstateSettings.SunPosition = (parms2 - 0x1800)/1024.0;
// Warning: FixedSun should be set to True, otherwise this sun position won't be used.
}
if ((parms1 & 0x00000010) != 0)
Scene.RegionInfo.EstateSettings.FixedSun = true;
else
Scene.RegionInfo.EstateSettings.FixedSun = false;
if ((parms1 & 0x00008000) != 0)
Scene.RegionInfo.EstateSettings.PublicAccess = true;
else
Scene.RegionInfo.EstateSettings.PublicAccess = false;
if ((parms1 & 0x10000000) != 0)
Scene.RegionInfo.EstateSettings.AllowVoice = true;
else
Scene.RegionInfo.EstateSettings.AllowVoice = false;
if ((parms1 & 0x00100000) != 0)
Scene.RegionInfo.EstateSettings.AllowDirectTeleport = true;
else
Scene.RegionInfo.EstateSettings.AllowDirectTeleport = false;
if ((parms1 & 0x00800000) != 0)
Scene.RegionInfo.EstateSettings.DenyAnonymous = true;
else
Scene.RegionInfo.EstateSettings.DenyAnonymous = false;
if ((parms1 & 0x01000000) != 0)
Scene.RegionInfo.EstateSettings.DenyIdentified = true;
else
Scene.RegionInfo.EstateSettings.DenyIdentified = false;
if ((parms1 & 0x02000000) != 0)
Scene.RegionInfo.EstateSettings.DenyTransacted = true;
else
Scene.RegionInfo.EstateSettings.DenyTransacted = false;
if ((parms1 & 0x40000000) != 0)
Scene.RegionInfo.EstateSettings.DenyMinors = true;
else
Scene.RegionInfo.EstateSettings.DenyMinors = false;
Scene.RegionInfo.EstateSettings.Save();
TriggerEstateInfoChange();
Scene.TriggerEstateSunUpdate();
sendDetailedEstateData(remoteClient, invoice);
}
#endregion
#region Other Functions
public void changeWaterHeight(float height)
{
setRegionTerrainSettings(height,
(float)Scene.RegionInfo.RegionSettings.TerrainRaiseLimit,
(float)Scene.RegionInfo.RegionSettings.TerrainLowerLimit,
Scene.RegionInfo.RegionSettings.UseEstateSun,
Scene.RegionInfo.RegionSettings.FixedSun,
(float)Scene.RegionInfo.RegionSettings.SunPosition,
Scene.RegionInfo.EstateSettings.UseGlobalTime,
Scene.RegionInfo.EstateSettings.FixedSun,
(float)Scene.RegionInfo.EstateSettings.SunPosition);
sendRegionInfoPacketToAll();
}
#endregion
private void EventManager_OnNewClient(IClientAPI client)
{
client.OnDetailedEstateDataRequest += clientSendDetailedEstateData;
client.OnSetEstateFlagsRequest += estateSetRegionInfoHandler;
// client.OnSetEstateTerrainBaseTexture += setEstateTerrainBaseTexture;
client.OnSetEstateTerrainDetailTexture += setEstateTerrainBaseTexture;
client.OnSetEstateTerrainTextureHeights += setEstateTerrainTextureHeights;
client.OnCommitEstateTerrainTextureRequest += handleCommitEstateTerrainTextureRequest;
client.OnSetRegionTerrainSettings += setRegionTerrainSettings;
client.OnEstateRestartSimRequest += handleEstateRestartSimRequest;
client.OnEstateChangeCovenantRequest += handleChangeEstateCovenantRequest;
client.OnEstateChangeInfo += handleEstateChangeInfo;
client.OnEstateManageTelehub += handleOnEstateManageTelehub;
client.OnUpdateEstateAccessDeltaRequest += handleEstateAccessDeltaRequest;
client.OnSimulatorBlueBoxMessageRequest += SendSimulatorBlueBoxMessage;
client.OnEstateBlueBoxMessageRequest += SendEstateBlueBoxMessage;
client.OnEstateDebugRegionRequest += handleEstateDebugRegionRequest;
client.OnEstateTeleportOneUserHomeRequest += handleEstateTeleportOneUserHomeRequest;
client.OnEstateTeleportAllUsersHomeRequest += handleEstateTeleportAllUsersHomeRequest;
client.OnRequestTerrain += handleTerrainRequest;
client.OnUploadTerrain += handleUploadTerrain;
client.OnRegionInfoRequest += HandleRegionInfoRequest;
client.OnEstateCovenantRequest += HandleEstateCovenantRequest;
client.OnLandStatRequest += HandleLandStatRequest;
sendRegionHandshake(client);
}
public uint GetRegionFlags()
{
RegionFlags flags = RegionFlags.None;
// Fully implemented
//
if (Scene.RegionInfo.RegionSettings.AllowDamage)
flags |= RegionFlags.AllowDamage;
if (Scene.RegionInfo.RegionSettings.BlockTerraform)
flags |= RegionFlags.BlockTerraform;
if (!Scene.RegionInfo.RegionSettings.AllowLandResell)
flags |= RegionFlags.BlockLandResell;
if (Scene.RegionInfo.RegionSettings.DisableCollisions)
flags |= RegionFlags.SkipCollisions;
if (Scene.RegionInfo.RegionSettings.DisableScripts)
flags |= RegionFlags.SkipScripts;
if (Scene.RegionInfo.RegionSettings.DisablePhysics)
flags |= RegionFlags.SkipPhysics;
if (Scene.RegionInfo.RegionSettings.BlockFly)
flags |= RegionFlags.NoFly;
if (Scene.RegionInfo.RegionSettings.RestrictPushing)
flags |= RegionFlags.RestrictPushObject;
if (Scene.RegionInfo.RegionSettings.AllowLandJoinDivide)
flags |= RegionFlags.AllowParcelChanges;
if (Scene.RegionInfo.RegionSettings.BlockShowInSearch)
flags |= RegionFlags.BlockParcelSearch;
if (Scene.RegionInfo.RegionSettings.FixedSun)
flags |= RegionFlags.SunFixed;
if (Scene.RegionInfo.RegionSettings.Sandbox)
flags |= RegionFlags.Sandbox;
if (Scene.RegionInfo.EstateSettings.AllowVoice)
flags |= RegionFlags.AllowVoice;
if (Scene.RegionInfo.EstateSettings.AllowLandmark)
flags |= RegionFlags.AllowLandmark;
if (Scene.RegionInfo.EstateSettings.AllowSetHome)
flags |= RegionFlags.AllowSetHome;
if (Scene.RegionInfo.EstateSettings.BlockDwell)
flags |= RegionFlags.BlockDwell;
if (Scene.RegionInfo.EstateSettings.ResetHomeOnTeleport)
flags |= RegionFlags.ResetHomeOnTeleport;
// TODO: SkipUpdateInterestList
// Omitted
//
// Omitted: NullLayer (what is that?)
// Omitted: SkipAgentAction (what does it do?)
return (uint)flags;
}
public uint GetEstateFlags()
{
RegionFlags flags = RegionFlags.None;
if (Scene.RegionInfo.EstateSettings.FixedSun)
flags |= RegionFlags.SunFixed;
if (Scene.RegionInfo.EstateSettings.PublicAccess)
flags |= (RegionFlags.PublicAllowed |
RegionFlags.ExternallyVisible);
if (Scene.RegionInfo.EstateSettings.AllowVoice)
flags |= RegionFlags.AllowVoice;
if (Scene.RegionInfo.EstateSettings.AllowDirectTeleport)
flags |= RegionFlags.AllowDirectTeleport;
if (Scene.RegionInfo.EstateSettings.DenyAnonymous)
flags |= RegionFlags.DenyAnonymous;
if (Scene.RegionInfo.EstateSettings.DenyIdentified)
flags |= RegionFlags.DenyIdentified;
if (Scene.RegionInfo.EstateSettings.DenyTransacted)
flags |= RegionFlags.DenyTransacted;
if (Scene.RegionInfo.EstateSettings.AbuseEmailToEstateOwner)
flags |= RegionFlags.AbuseEmailToEstateOwner;
if (Scene.RegionInfo.EstateSettings.BlockDwell)
flags |= RegionFlags.BlockDwell;
if (Scene.RegionInfo.EstateSettings.EstateSkipScripts)
flags |= RegionFlags.EstateSkipScripts;
if (Scene.RegionInfo.EstateSettings.ResetHomeOnTeleport)
flags |= RegionFlags.ResetHomeOnTeleport;
if (Scene.RegionInfo.EstateSettings.TaxFree)
flags |= RegionFlags.TaxFree;
if (Scene.RegionInfo.EstateSettings.AllowLandmark)
flags |= RegionFlags.AllowLandmark;
if (Scene.RegionInfo.EstateSettings.AllowParcelChanges)
flags |= RegionFlags.AllowParcelChanges;
if (Scene.RegionInfo.EstateSettings.AllowSetHome)
flags |= RegionFlags.AllowSetHome;
if (Scene.RegionInfo.EstateSettings.DenyMinors)
flags |= (RegionFlags)(1 << 30);
return (uint)flags;
}
public bool IsManager(UUID avatarID)
{
if (avatarID == Scene.RegionInfo.EstateSettings.EstateOwner)
return true;
List<UUID> ems = new List<UUID>(Scene.RegionInfo.EstateSettings.EstateManagers);
if (ems.Contains(avatarID))
return true;
return false;
}
public void TriggerRegionInfoChange()
{
m_regionChangeTimer.Stop();
m_regionChangeTimer.Start();
}
protected void RaiseRegionInfoChange(object sender, ElapsedEventArgs e)
{
ChangeDelegate change = OnRegionInfoChange;
if (change != null)
change(Scene.RegionInfo.RegionID);
}
public void TriggerEstateInfoChange()
{
ChangeDelegate change = OnEstateInfoChange;
if (change != null)
change(Scene.RegionInfo.RegionID);
}
public void TriggerEstateMessage(UUID fromID, string fromName, string message)
{
MessageDelegate onmessage = OnEstateMessage;
if (onmessage != null)
onmessage(Scene.RegionInfo.RegionID, fromID, fromName, message);
}
private void SendTelehubInfo(IClientAPI client)
{
RegionSettings settings =
this.Scene.RegionInfo.RegionSettings;
SceneObjectGroup telehub = null;
if (settings.TelehubObject != UUID.Zero &&
(telehub = Scene.GetSceneObjectGroup(settings.TelehubObject)) != null)
{
List<Vector3> spawnPoints = new List<Vector3>();
foreach (SpawnPoint sp in settings.SpawnPoints())
{
spawnPoints.Add(sp.GetLocation(Vector3.Zero, Quaternion.Identity));
}
client.SendTelehubInfo(settings.TelehubObject,
telehub.Name,
telehub.AbsolutePosition,
telehub.GroupRotation,
spawnPoints);
}
else
{
client.SendTelehubInfo(UUID.Zero,
String.Empty,
Vector3.Zero,
Quaternion.Identity,
new List<Vector3>());
}
}
}
}
| |
// 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;
namespace System.Xml
{
internal abstract class ArrayHelper<TArgument, TArray>
{
public TArray[] ReadArray(XmlDictionaryReader reader, TArgument localName, TArgument namespaceUri, int maxArrayLength)
{
TArray[][] arrays = null;
TArray[] array = null;
int arrayCount = 0;
int totalRead = 0;
int count;
if (reader.TryGetArrayLength(out count))
{
if (count > XmlDictionaryReader.MaxInitialArrayLength)
count = XmlDictionaryReader.MaxInitialArrayLength;
}
else
{
count = 32;
}
while (true)
{
array = new TArray[count];
int read = 0;
while (read < array.Length)
{
int actual = ReadArray(reader, localName, namespaceUri, array, read, array.Length - read);
if (actual == 0)
break;
read += actual;
}
totalRead += read;
if (read < array.Length || reader.NodeType == XmlNodeType.EndElement)
break;
if (arrays == null)
arrays = new TArray[32][];
arrays[arrayCount++] = array;
count = count * 2;
}
if (totalRead != array.Length || arrayCount > 0)
{
TArray[] newArray = new TArray[totalRead];
int offset = 0;
for (int i = 0; i < arrayCount; i++)
{
Array.Copy(arrays[i], 0, newArray, offset, arrays[i].Length);
offset += arrays[i].Length;
}
Array.Copy(array, 0, newArray, offset, totalRead - offset);
array = newArray;
}
return array;
}
public void WriteArray(XmlDictionaryWriter writer, string prefix, TArgument localName, TArgument namespaceUri, XmlDictionaryReader reader)
{
int count;
if (reader.TryGetArrayLength(out count))
count = Math.Min(count, 256);
else
count = 256;
TArray[] array = new TArray[count];
while (true)
{
int actual = ReadArray(reader, localName, namespaceUri, array, 0, array.Length);
if (actual == 0)
break;
WriteArray(writer, prefix, localName, namespaceUri, array, 0, actual);
}
}
protected abstract int ReadArray(XmlDictionaryReader reader, TArgument localName, TArgument namespaceUri, TArray[] array, int offset, int count);
protected abstract void WriteArray(XmlDictionaryWriter writer, string prefix, TArgument localName, TArgument namespaceUri, TArray[] array, int offset, int count);
}
// Supported array types
// bool
// Int16
// Int32
// Int64
// Float
// Double
// Decimal
// DateTime
// Guid
// TimeSpan
// Int8 is not supported since sbyte[] is non-CLS compliant, and uncommon
// UniqueId is not supported since elements may be variable size strings
internal class BooleanArrayHelperWithString : ArrayHelper<string, bool>
{
public static readonly BooleanArrayHelperWithString Instance = new BooleanArrayHelperWithString();
protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, bool[] array, int offset, int count)
{
return reader.ReadArray(localName, namespaceUri, array, offset, count);
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, bool[] array, int offset, int count)
{
writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
}
}
internal class BooleanArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, bool>
{
public static readonly BooleanArrayHelperWithDictionaryString Instance = new BooleanArrayHelperWithDictionaryString();
protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count)
{
return reader.ReadArray(localName, namespaceUri, array, offset, count);
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count)
{
writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
}
}
internal class Int16ArrayHelperWithString : ArrayHelper<string, short>
{
public static readonly Int16ArrayHelperWithString Instance = new Int16ArrayHelperWithString();
protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, short[] array, int offset, int count)
{
return reader.ReadArray(localName, namespaceUri, array, offset, count);
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, short[] array, int offset, int count)
{
writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
}
}
internal class Int16ArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, short>
{
public static readonly Int16ArrayHelperWithDictionaryString Instance = new Int16ArrayHelperWithDictionaryString();
protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count)
{
return reader.ReadArray(localName, namespaceUri, array, offset, count);
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count)
{
writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
}
}
internal class Int32ArrayHelperWithString : ArrayHelper<string, int>
{
public static readonly Int32ArrayHelperWithString Instance = new Int32ArrayHelperWithString();
protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, int[] array, int offset, int count)
{
return reader.ReadArray(localName, namespaceUri, array, offset, count);
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, int[] array, int offset, int count)
{
writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
}
}
internal class Int32ArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, int>
{
public static readonly Int32ArrayHelperWithDictionaryString Instance = new Int32ArrayHelperWithDictionaryString();
protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count)
{
return reader.ReadArray(localName, namespaceUri, array, offset, count);
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count)
{
writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
}
}
internal class Int64ArrayHelperWithString : ArrayHelper<string, long>
{
public static readonly Int64ArrayHelperWithString Instance = new Int64ArrayHelperWithString();
protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, long[] array, int offset, int count)
{
return reader.ReadArray(localName, namespaceUri, array, offset, count);
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, long[] array, int offset, int count)
{
writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
}
}
internal class Int64ArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, long>
{
public static readonly Int64ArrayHelperWithDictionaryString Instance = new Int64ArrayHelperWithDictionaryString();
protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count)
{
return reader.ReadArray(localName, namespaceUri, array, offset, count);
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count)
{
writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
}
}
internal class SingleArrayHelperWithString : ArrayHelper<string, float>
{
public static readonly SingleArrayHelperWithString Instance = new SingleArrayHelperWithString();
protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, float[] array, int offset, int count)
{
return reader.ReadArray(localName, namespaceUri, array, offset, count);
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, float[] array, int offset, int count)
{
writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
}
}
internal class SingleArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, float>
{
public static readonly SingleArrayHelperWithDictionaryString Instance = new SingleArrayHelperWithDictionaryString();
protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count)
{
return reader.ReadArray(localName, namespaceUri, array, offset, count);
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count)
{
writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
}
}
internal class DoubleArrayHelperWithString : ArrayHelper<string, double>
{
public static readonly DoubleArrayHelperWithString Instance = new DoubleArrayHelperWithString();
protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, double[] array, int offset, int count)
{
return reader.ReadArray(localName, namespaceUri, array, offset, count);
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, double[] array, int offset, int count)
{
writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
}
}
internal class DoubleArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, double>
{
public static readonly DoubleArrayHelperWithDictionaryString Instance = new DoubleArrayHelperWithDictionaryString();
protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count)
{
return reader.ReadArray(localName, namespaceUri, array, offset, count);
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count)
{
writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
}
}
internal class DecimalArrayHelperWithString : ArrayHelper<string, decimal>
{
public static readonly DecimalArrayHelperWithString Instance = new DecimalArrayHelperWithString();
protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, decimal[] array, int offset, int count)
{
return reader.ReadArray(localName, namespaceUri, array, offset, count);
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count)
{
writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
}
}
internal class DecimalArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, decimal>
{
public static readonly DecimalArrayHelperWithDictionaryString Instance = new DecimalArrayHelperWithDictionaryString();
protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count)
{
return reader.ReadArray(localName, namespaceUri, array, offset, count);
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count)
{
writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
}
}
internal class DateTimeArrayHelperWithString : ArrayHelper<string, DateTime>
{
public static readonly DateTimeArrayHelperWithString Instance = new DateTimeArrayHelperWithString();
protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, DateTime[] array, int offset, int count)
{
return reader.ReadArray(localName, namespaceUri, array, offset, count);
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count)
{
writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
}
}
internal class DateTimeArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, DateTime>
{
public static readonly DateTimeArrayHelperWithDictionaryString Instance = new DateTimeArrayHelperWithDictionaryString();
protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count)
{
return reader.ReadArray(localName, namespaceUri, array, offset, count);
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count)
{
writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
}
}
internal class GuidArrayHelperWithString : ArrayHelper<string, Guid>
{
public static readonly GuidArrayHelperWithString Instance = new GuidArrayHelperWithString();
protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, Guid[] array, int offset, int count)
{
return reader.ReadArray(localName, namespaceUri, array, offset, count);
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count)
{
writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
}
}
internal class GuidArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, Guid>
{
public static readonly GuidArrayHelperWithDictionaryString Instance = new GuidArrayHelperWithDictionaryString();
protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count)
{
return reader.ReadArray(localName, namespaceUri, array, offset, count);
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count)
{
writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
}
}
internal class TimeSpanArrayHelperWithString : ArrayHelper<string, TimeSpan>
{
public static readonly TimeSpanArrayHelperWithString Instance = new TimeSpanArrayHelperWithString();
protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, TimeSpan[] array, int offset, int count)
{
return reader.ReadArray(localName, namespaceUri, array, offset, count);
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count)
{
writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
}
}
internal class TimeSpanArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, TimeSpan>
{
public static readonly TimeSpanArrayHelperWithDictionaryString Instance = new TimeSpanArrayHelperWithDictionaryString();
protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count)
{
return reader.ReadArray(localName, namespaceUri, array, offset, count);
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count)
{
writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
#if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Utilities
{
internal static class StringUtils
{
public const string CarriageReturnLineFeed = "\r\n";
public const string Empty = "";
public const char CarriageReturn = '\r';
public const char LineFeed = '\n';
public const char Tab = '\t';
public static bool IsNullOrEmpty([NotNullWhen(false)] string? value)
{
return string.IsNullOrEmpty(value);
}
public static string FormatWith(this string format, IFormatProvider provider, object? arg0)
{
return format.FormatWith(provider, new object?[] { arg0 });
}
public static string FormatWith(this string format, IFormatProvider provider, object? arg0, object? arg1)
{
return format.FormatWith(provider, new object?[] { arg0, arg1 });
}
public static string FormatWith(this string format, IFormatProvider provider, object? arg0, object? arg1, object? arg2)
{
return format.FormatWith(provider, new object?[] { arg0, arg1, arg2 });
}
public static string FormatWith(this string format, IFormatProvider provider, object? arg0, object? arg1, object? arg2, object? arg3)
{
return format.FormatWith(provider, new object?[] { arg0, arg1, arg2, arg3 });
}
private static string FormatWith(this string format, IFormatProvider provider, params object?[] args)
{
// leave this a private to force code to use an explicit overload
// avoids stack memory being reserved for the object array
ValidationUtils.ArgumentNotNull(format, nameof(format));
return string.Format(provider, format, args);
}
/// <summary>
/// Determines whether the string is all white space. Empty string will return <c>false</c>.
/// </summary>
/// <param name="s">The string to test whether it is all white space.</param>
/// <returns>
/// <c>true</c> if the string is all white space; otherwise, <c>false</c>.
/// </returns>
public static bool IsWhiteSpace(string s)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
if (s.Length == 0)
{
return false;
}
for (int i = 0; i < s.Length; i++)
{
if (!char.IsWhiteSpace(s[i]))
{
return false;
}
}
return true;
}
public static StringWriter CreateStringWriter(int capacity)
{
StringBuilder sb = new StringBuilder(capacity);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
return sw;
}
public static void ToCharAsUnicode(char c, char[] buffer)
{
buffer[0] = '\\';
buffer[1] = 'u';
buffer[2] = MathUtils.IntToHex((c >> 12) & '\x000f');
buffer[3] = MathUtils.IntToHex((c >> 8) & '\x000f');
buffer[4] = MathUtils.IntToHex((c >> 4) & '\x000f');
buffer[5] = MathUtils.IntToHex(c & '\x000f');
}
public static TSource ForgivingCaseSensitiveFind<TSource>(this IEnumerable<TSource> source, Func<TSource, string> valueSelector, string testValue)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (valueSelector == null)
{
throw new ArgumentNullException(nameof(valueSelector));
}
IEnumerable<TSource> caseInsensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.OrdinalIgnoreCase));
if (caseInsensitiveResults.Count() <= 1)
{
return caseInsensitiveResults.SingleOrDefault();
}
else
{
// multiple results returned. now filter using case sensitivity
IEnumerable<TSource> caseSensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.Ordinal));
return caseSensitiveResults.SingleOrDefault();
}
}
public static string ToCamelCase(string s)
{
if (StringUtils.IsNullOrEmpty(s) || !char.IsUpper(s[0]))
{
return s;
}
char[] chars = s.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
if (i == 1 && !char.IsUpper(chars[i]))
{
break;
}
bool hasNext = (i + 1 < chars.Length);
if (i > 0 && hasNext && !char.IsUpper(chars[i + 1]))
{
// if the next character is a space, which is not considered uppercase
// (otherwise we wouldn't be here...)
// we want to ensure that the following:
// 'FOO bar' is rewritten as 'foo bar', and not as 'foO bar'
// The code was written in such a way that the first word in uppercase
// ends when if finds an uppercase letter followed by a lowercase letter.
// now a ' ' (space, (char)32) is considered not upper
// but in that case we still want our current character to become lowercase
if (char.IsSeparator(chars[i + 1]))
{
chars[i] = ToLower(chars[i]);
}
break;
}
chars[i] = ToLower(chars[i]);
}
return new string(chars);
}
private static char ToLower(char c)
{
#if HAVE_CHAR_TO_LOWER_WITH_CULTURE
c = char.ToLower(c, CultureInfo.InvariantCulture);
#else
c = char.ToLowerInvariant(c);
#endif
return c;
}
public static string ToSnakeCase(string s) => ToSeparatedCase(s, '_');
public static string ToKebabCase(string s) => ToSeparatedCase(s, '-');
private enum SeparatedCaseState
{
Start,
Lower,
Upper,
NewWord
}
private static string ToSeparatedCase(string s, char separator)
{
if (StringUtils.IsNullOrEmpty(s))
{
return s;
}
StringBuilder sb = new StringBuilder();
SeparatedCaseState state = SeparatedCaseState.Start;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == ' ')
{
if (state != SeparatedCaseState.Start)
{
state = SeparatedCaseState.NewWord;
}
}
else if (char.IsUpper(s[i]))
{
switch (state)
{
case SeparatedCaseState.Upper:
bool hasNext = (i + 1 < s.Length);
if (i > 0 && hasNext)
{
char nextChar = s[i + 1];
if (!char.IsUpper(nextChar) && nextChar != separator)
{
sb.Append(separator);
}
}
break;
case SeparatedCaseState.Lower:
case SeparatedCaseState.NewWord:
sb.Append(separator);
break;
}
char c;
#if HAVE_CHAR_TO_LOWER_WITH_CULTURE
c = char.ToLower(s[i], CultureInfo.InvariantCulture);
#else
c = char.ToLowerInvariant(s[i]);
#endif
sb.Append(c);
state = SeparatedCaseState.Upper;
}
else if (s[i] == separator)
{
sb.Append(separator);
state = SeparatedCaseState.Start;
}
else
{
if (state == SeparatedCaseState.NewWord)
{
sb.Append(separator);
}
sb.Append(s[i]);
state = SeparatedCaseState.Lower;
}
}
return sb.ToString();
}
public static bool IsHighSurrogate(char c)
{
#if HAVE_UNICODE_SURROGATE_DETECTION
return char.IsHighSurrogate(c);
#else
return (c >= 55296 && c <= 56319);
#endif
}
public static bool IsLowSurrogate(char c)
{
#if HAVE_UNICODE_SURROGATE_DETECTION
return char.IsLowSurrogate(c);
#else
return (c >= 56320 && c <= 57343);
#endif
}
public static bool StartsWith(this string source, char value)
{
return (source.Length > 0 && source[0] == value);
}
public static bool EndsWith(this string source, char value)
{
return (source.Length > 0 && source[source.Length - 1] == value);
}
public static string Trim(this string s, int start, int length)
{
// References: https://referencesource.microsoft.com/#mscorlib/system/string.cs,2691
// https://referencesource.microsoft.com/#mscorlib/system/string.cs,1226
if (s == null)
{
throw new ArgumentNullException();
}
if (start < 0)
{
throw new ArgumentOutOfRangeException(nameof(start));
}
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
int end = start + length - 1;
if (end >= s.Length)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
for (; start < end; start++)
{
if (!char.IsWhiteSpace(s[start]))
{
break;
}
}
for (; end >= start; end--)
{
if (!char.IsWhiteSpace(s[end]))
{
break;
}
}
return s.Substring(start, end - start + 1);
}
}
}
| |
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE
file for terms.
*/
// [AUTO_HEADER]
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Globalization;
using BaseIMEUI;
namespace TakaoPreference
{
/// <remarks>
/// The general settings.
/// </remarks>
partial class PanelGeneral : UserControl
{
#region Memebers
private Dictionary<string, string> m_generalDictionary;
private Dictionary<string, string> m_oneKeyDictionary;
private Dictionary<string, string> m_modulesDictionary;
private Button u_applyButton;
private bool m_init = false;
#endregion
public PanelGeneral(Dictionary<string, string> dictionary, Dictionary<string, string> oneKeyDictionary, Dictionary<string, string>generalInputmethods, Button button)
{
this.m_generalDictionary = dictionary;
this.m_oneKeyDictionary = oneKeyDictionary;
this.u_applyButton = button;
InitializeComponent();
this.m_modulesDictionary = new Dictionary<string,string>();
string currentLocale = CultureInfo.CurrentUICulture.Name;
if (currentLocale.Equals("zh-TW"))
{
this.m_modulesDictionary.Add("SmartMandarin", "\u597d\u6253\u6ce8\u97f3");
this.m_modulesDictionary.Add("TraditionalMandarins","\u50b3\u7d71\u6ce8\u97f3");
this.m_modulesDictionary.Add("Generic-cj-cin","\u5009\u9821");
this.m_modulesDictionary.Add("Generic-simplex-cin","\u7c21\u6613");
}
else if (currentLocale.Equals("zh-CN"))
{
this.m_modulesDictionary.Add("SmartMandarin", "\u597d\u6253\u6ce8\u97f3");
this.m_modulesDictionary.Add("TraditionalMandarins","\u4f20\u7edf\u6ce8\u97f3");
this.m_modulesDictionary.Add("Generic-cj-cin","\u4ed3\u9889");
this.m_modulesDictionary.Add("Generic-simplex-cin","\u7b80\u6613");
}
else
{
this.m_modulesDictionary.Add("SmartMandarin", "Smart Phontic");
this.m_modulesDictionary.Add("TraditionalMandarins","Traditional Phonetic");
this.m_modulesDictionary.Add("Generic-cj-cin","Cangjie");
this.m_modulesDictionary.Add("Generic-simplex-cin","Simplex");
}
foreach (KeyValuePair<string, string> kvp in generalInputmethods)
{
this.m_modulesDictionary.Add(kvp.Key, kvp.Value);
}
this.InitUI();
this.InitModules();
}
#region Init
private void InitUI()
{
this.m_init = true;
string buffer;
#region IgnoreShiftAsAlphanumericModeToggleKey
this.m_generalDictionary.TryGetValue("IgnoreShiftAsAlphanumericModeToggleKey", out buffer);
if (buffer == "true")
this.u_shiftKeyCheckBox.Checked = false;
else
this.u_shiftKeyCheckBox.Checked = true;
this.m_generalDictionary.TryGetValue("EnablesCapsLockAsAlphanumericModeToggle", out buffer);
if (buffer == "true")
this.u_capslockCheckBox.Checked = true;
else
this.u_capslockCheckBox.Checked = false;
this.m_generalDictionary.TryGetValue("ToggleInputMethodWithControlBackslash", out buffer);
if (buffer == "true")
this.u_ctrlBackslashCheckBox.Checked = true;
else
this.u_ctrlBackslashCheckBox.Checked = false;
this.m_generalDictionary.TryGetValue("ShouldUseNotifyWindow", out buffer);
if (buffer == "true")
this.u_notifyCheckBox.Checked = true;
else
this.u_notifyCheckBox.Checked = false;
this.m_oneKeyDictionary.TryGetValue("ShortcutKey", out buffer);
if (buffer == "~")
{
this.u_shortcutComboBox.SelectedIndex = 1;
this.u_shortcutComboBox.Text = "~";
}
else
{
this.u_shortcutComboBox.SelectedIndex = 0;
this.u_shortcutComboBox.Text = "`";
}
int i = 0;
//Chinese converter
this.m_generalDictionary.TryGetValue("ChineseConverterToggleKey", out buffer);
string chineseConverterToggleKey = "";
if (buffer != null && buffer.Length > 0)
{
if (buffer.Length > 1)
buffer = buffer.Remove(1);
chineseConverterToggleKey = buffer;
}
string noneString = "None";
string locale = CultureInfo.CurrentCulture.Name;
if (locale.Equals("zh-TW"))
locale = "\u7121";
else if (locale.Equals("zh-CN"))
locale = "\u65e0";
this.u_chineseConverterToggleComboBox.Items.Add(noneString);
for (i = 0; i < 26; i++)
{
char aChar = (char)('a' + i);
this.u_chineseConverterToggleComboBox.Items.Add(aChar);
}
if (chineseConverterToggleKey.Length > 0)
{
this.u_chineseConverterToggleComboBox.Text = chineseConverterToggleKey;
}
else
{
this.u_chineseConverterToggleComboBox.SelectedIndex = 0;
this.u_chineseConverterToggleComboBox.Text = noneString;
}
// Repeat last
this.m_generalDictionary.TryGetValue("RepeatLastCommitTextKey", out buffer);
string repeatKey = "";
if (buffer != null && buffer.Length > 0)
{
if (buffer.Length > 1)
buffer = buffer.Remove(1);
repeatKey = buffer;
}
this.u_repeatComboBox.Items.Add(noneString);
for (i = 0; i < 26; i++)
{
char aChar = (char)('a' + i);
this.u_repeatComboBox.Items.Add(aChar);
}
if (repeatKey.Length > 0)
{
this.u_repeatComboBox.Text = repeatKey;
}
else
{
this.u_repeatComboBox.SelectedIndex = 0;
this.u_repeatComboBox.Text = noneString;
}
BIServerConnector callback = BIServerConnector.SharedInstance;
if (callback != null)
{
if (callback.moduleWithWildcardNameExists("ReverseLookup-*") == false)
{
this.u_reverseLookupComboBox.Enabled = false;
this.u_lookupLabel.Enabled = false;
this.ReverseLookupMethod = "";
}
else
{
this.u_reverseLookupComboBox.Enabled = true;
this.u_lookupLabel.Enabled = true;
this.u_reverseLookupComboBox.SelectedIndex = 0;
this.ReverseLookupMethod = "";
this.m_generalDictionary.TryGetValue("ActivatedAroundFilters", out buffer);
if (buffer != null && buffer.Length > 0 && buffer.StartsWith("ARRAY:"))
{
string stringToExplode = buffer.Remove(0, 6);
string[] aroundFilters = stringToExplode.Split(", ".ToCharArray());
foreach (string aroundFilter in aroundFilters)
{
if (aroundFilter == "ReverseLookup-Generic-cj-cin")
{
this.u_reverseLookupComboBox.SelectedIndex = 1;
this.ReverseLookupMethod = aroundFilter;
break;
}
else if (aroundFilter == "ReverseLookup-Mandarin-bpmf-cin")
{
this.u_reverseLookupComboBox.SelectedIndex = 2;
this.ReverseLookupMethod = aroundFilter;
break;
}
else if (aroundFilter == "ReverseLookup-Mandarin-bpmf-cin-HanyuPinyin")
{
this.u_reverseLookupComboBox.SelectedIndex = 3;
this.ReverseLookupMethod = aroundFilter;
break;
}
}
}
}
}
this.m_init = false;
#endregion
}
private void InitModules()
{
string modulesSuppressedFromUI;
this.m_generalDictionary.TryGetValue("ModulesSuppressedFromUI", out modulesSuppressedFromUI);
List<string> modulesSuppressed = new List<string>();
if (modulesSuppressedFromUI != null && modulesSuppressedFromUI.Length > 0 && modulesSuppressedFromUI.StartsWith("ARRAY:"))
{
string stringToExplode = modulesSuppressedFromUI.Remove(0, 6);
string[] explodedStrings = stringToExplode.Split(", ".ToCharArray());
foreach (string item in explodedStrings)
{
modulesSuppressed.Add(item);
}
}
foreach (KeyValuePair<string, string> kvp in m_modulesDictionary)
{
bool shouldShow = true;
string moduleName = kvp.Key;
if (modulesSuppressed.Contains(moduleName))
shouldShow = false;
this.u_moduleCheckListBox.Items.Add(kvp.Value, shouldShow);
}
}
#endregion
#region Event Handlers
/// <summary>
/// Handle enabling or disabling associted-phrases.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void u_chkAssociatedPhrases_CheckedChanged(object sender, EventArgs e)
{
if (this.m_init)
return;
try
{
this.m_generalDictionary.Remove("IgnoreShiftAsAlphanumericModeToggleKey");
}
catch { }
if (u_shiftKeyCheckBox.Checked == true)
{
this.m_generalDictionary.Add("IgnoreShiftAsAlphanumericModeToggleKey", "false");
this.u_capslockCheckBox.Checked = false;
}
else
{
this.m_generalDictionary.Add("IgnoreShiftAsAlphanumericModeToggleKey", "true");
}
this.u_applyButton.Enabled = true;
}
private void u_capslockCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (this.m_init)
return;
try
{
this.m_generalDictionary.Remove("EnablesCapsLockAsAlphanumericModeToggle");
}
catch { }
if (this.u_capslockCheckBox.Checked == true)
{
this.m_generalDictionary.Add("EnablesCapsLockAsAlphanumericModeToggle", "true");
this.u_shiftKeyCheckBox.Checked = false;
}
else
{
this.m_generalDictionary.Add("EnablesCapsLockAsAlphanumericModeToggle", "false");
}
this.u_applyButton.Enabled = true;
}
private void u_chkCtrlBackslash_CheckedChanged(object sender, EventArgs e)
{
if (this.m_init)
return;
try
{
this.m_generalDictionary.Remove("ToggleInputMethodWithControlBackslash");
}
catch { }
if (this.u_ctrlBackslashCheckBox.Checked == true)
this.m_generalDictionary.Add("ToggleInputMethodWithControlBackslash", "true");
else
this.m_generalDictionary.Add("ToggleInputMethodWithControlBackslash", "false");
this.u_applyButton.Enabled = true;
}
private void u_chkNotify_CheckedChanged(object sender, EventArgs e)
{
if (this.m_init)
return;
try
{
this.m_generalDictionary.Remove("ShouldUseNotifyWindow");
}
catch { }
if (this.u_notifyCheckBox.Checked == true)
this.m_generalDictionary.Add("ShouldUseNotifyWindow", "true");
else
this.m_generalDictionary.Add("ShouldUseNotifyWindow", "false");
this.u_applyButton.Enabled = true;
}
private void u_shortcut_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.m_init)
return;
try
{
this.m_oneKeyDictionary.Remove("ShortcutKey");
}
catch { }
if (this.u_shortcutComboBox.SelectedIndex == 1)
this.m_oneKeyDictionary.Add("ShortcutKey", "~");
else
this.m_oneKeyDictionary.Add("ShortcutKey", "`");
this.u_applyButton.Enabled = true;
}
private void u_moduleCheckListBox_SelectedValueChanged(object sender, EventArgs e)
{
if (this.m_init)
return;
if (this.u_moduleCheckListBox.CheckedItems.Count == 0)
this.u_moduleCheckListBox.SetItemChecked(this.u_moduleCheckListBox.SelectedIndex, true);
try
{
this.m_generalDictionary.Remove("ModulesSuppressedFromUI");
}
catch { }
int i = 0;
List<string> modules = new List<string>();
foreach (KeyValuePair<string, string> kvp in m_modulesDictionary)
{
bool itemChecked = u_moduleCheckListBox.GetItemChecked(i);
if (itemChecked == false)
{
string moduleName = kvp.Key;
modules.Add(moduleName);
}
i++;
}
string serializedString = TakaoHelper.SerializeListToString(modules);
this.m_generalDictionary.Add("ModulesSuppressedFromUI", serializedString);
this.u_applyButton.Enabled = true;
}
private void u_comboChineseConverterToggle_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.m_init)
return;
if (this.u_chineseConverterToggleComboBox.SelectedIndex != 0 &&
this.u_chineseConverterToggleComboBox.Text == u_repeatComboBox.Text)
{
string buffer;
this.m_oneKeyDictionary.TryGetValue("ChineseConverterToggleKey", out buffer);
string chineseConverterToggleKey = "s";
if (this.u_repeatComboBox.Text == "s")
chineseConverterToggleKey = "g";
else if (buffer != null && buffer.Length > 0)
chineseConverterToggleKey = buffer.Remove(1);
this.u_chineseConverterToggleComboBox.Text = chineseConverterToggleKey;
return;
}
try
{
this.m_generalDictionary.Remove("ChineseConverterToggleKey");
}
catch { }
if (this.u_chineseConverterToggleComboBox.SelectedIndex == 0)
this.m_generalDictionary.Add("ChineseConverterToggleKey", "");
else
this.m_generalDictionary.Add("ChineseConverterToggleKey",
this.u_chineseConverterToggleComboBox.Text);
this.u_applyButton.Enabled = true;
}
private void u_comboRepeat_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.m_init)
return;
if (this.u_repeatComboBox.SelectedIndex != 0 &&
this.u_repeatComboBox.Text == this.u_chineseConverterToggleComboBox.Text)
{
string buffer;
this.m_oneKeyDictionary.TryGetValue("RepeatLastCommitTextKey", out buffer);
string repeatKey = "g";
if (this.u_chineseConverterToggleComboBox.Text == "g")
repeatKey = "s";
else if (buffer != null && buffer.Length > 0)
repeatKey = buffer.Remove(1);
this.u_repeatComboBox.Text = repeatKey;
return;
}
try
{
this.m_generalDictionary.Remove("RepeatLastCommitTextKey");
}
catch { }
if (this.u_repeatComboBox.SelectedIndex == 0)
this.m_generalDictionary.Add("RepeatLastCommitTextKey", "");
else
this.m_generalDictionary.Add("RepeatLastCommitTextKey", this.u_repeatComboBox.Text);
this.u_applyButton.Enabled = true;
}
public string ReverseLookupMethod = "";
private void u_reverseLookupComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
switch (this.u_reverseLookupComboBox.SelectedIndex)
{
case 0:
this.ReverseLookupMethod = "";
break;
case 1:
this.ReverseLookupMethod = "ReverseLookup-Generic-cj-cin";
break;
case 2:
this.ReverseLookupMethod = "ReverseLookup-Mandarin-bpmf-cin";
break;
case 3:
this.ReverseLookupMethod = "ReverseLookup-Mandarin-bpmf-cin-HanyuPinyin";
break;
default:
this.ReverseLookupMethod = "";
break;
}
this.u_applyButton.Enabled = true;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Microsoft.Build.BuildEngine.Shared;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// This class is responsible for determining on which node and when a task should be executed. It
/// receives work requests from the Target class and communicates to the appropriate node.
/// </summary>
internal class Scheduler
{
#region Constructors
/// <summary>
/// Create the scheduler.
/// </summary>
/// <param name="nodeId">the id of the node where the scheduler was instantiated on</param>
/// <param name="parentEngine">a reference to the engine who instantiated the scheduler</param>
internal Scheduler(int nodeId, Engine parentEngine)
{
this.localNodeId = nodeId;
this.childMode = true;
this.parentEngine = parentEngine;
}
#endregion
#region Properties
#endregion
#region Methods
/// <summary>
/// Provide the scheduler with the information about the available nodes. This function has to be
/// called after the NodeManager has initialzed all the node providers
/// </summary>
internal void Initialize(INodeDescription[] nodeDescriptions)
{
this.nodes = nodeDescriptions;
this.childMode = false;
this.handleIdToScheduleRecord = new Dictionary<ScheduleRecordKey, ScheduleRecord>();
this.scheduleTableLock = new object();
this.totalRequestsPerNode = new int[nodes.Length];
this.blockedRequestsPerNode = new int[nodes.Length];
this.postBlockCount = new int[nodes.Length];
for (int i = 0; i < totalRequestsPerNode.Length; i++)
{
totalRequestsPerNode[i] = 0;
blockedRequestsPerNode[i] = 0;
postBlockCount[i] = 0;
}
this.useLoadBalancing = (Environment.GetEnvironmentVariable("MSBUILDLOADBALANCE") != "0");
this.lastUsedNode = 0;
}
/// <summary>
/// This method specifies which node a particular build request has to be evaluated on.
/// </summary>>
/// <returns>Id of the node on which the build request should be performed</returns>
internal int CalculateNodeForBuildRequest(BuildRequest currentRequest, int nodeIndexCurrent)
{
int nodeUsed = EngineCallback.inProcNode;
if (childMode)
{
// If the project is already loaded on the current node or if the request
// was sent from the parent - evaluate the request locally. In all other
// cases send the request over to the parent
if (nodeIndexCurrent != localNodeId && !currentRequest.IsExternalRequest)
{
// This is the same as using EngineCallback.parentNode
nodeUsed = -1;
}
}
else
{
// In single proc case return the current node
if (nodes.Length == 1)
{
return nodeUsed;
}
// If the project is not loaded either locally or on a remote node - calculate the best node to use
// If there are nodes with less than "nodeWorkLoadProjectCount" projects in progress, choose the node
// with the lowest in progress projects. Otherwise choose a node which has the least
// number of projects loaded. Resolve a tie in number of projects loaded by looking at the number
// of inprogress projects
nodeUsed = nodeIndexCurrent;
// If we have not chosen an node yet, this can happen if the node was loaded previously on a child node
if (nodeUsed == EngineCallback.invalidNode)
{
if (useLoadBalancing)
{
#region UseLoadBalancing
int blockedNode = EngineCallback.invalidNode;
int blockedNodeRemainingProjectCount = nodeWorkLoadProjectCount;
int leastBusyNode = EngineCallback.invalidNode;
int leastBusyInProgressCount = -1;
int leastLoadedNode = EngineCallback.inProcNode;
int leastLoadedLoadCount = totalRequestsPerNode[EngineCallback.inProcNode];
int leastLoadedBlockedCount = blockedRequestsPerNode[EngineCallback.inProcNode];
for (int i = 0; i < nodes.Length; i++)
{
//postBlockCount indicates the number of projects which should be sent to a node to unblock it due to the
//node running out of work.
if (postBlockCount[i] != 0 && postBlockCount[i] < blockedNodeRemainingProjectCount)
{
blockedNode = i;
blockedNodeRemainingProjectCount = postBlockCount[i];
}
else
{
// Figure out which node has the least ammount of in progress work
int perNodeInProgress = totalRequestsPerNode[i] - blockedRequestsPerNode[i];
if ((perNodeInProgress < nodeWorkLoadProjectCount) &&
(perNodeInProgress < leastBusyInProgressCount || leastBusyInProgressCount == -1))
{
leastBusyNode = i;
leastBusyInProgressCount = perNodeInProgress;
}
// Find the node with the least ammount of requests in total
// or if the number of requests are the same find the node with the
// node with the least number of blocked requests
if ((totalRequestsPerNode[i] < leastLoadedLoadCount) ||
(totalRequestsPerNode[i] == leastLoadedLoadCount && blockedRequestsPerNode[i] < leastLoadedBlockedCount))
{
leastLoadedNode = i;
leastLoadedLoadCount = totalRequestsPerNode[i];
leastLoadedBlockedCount = perNodeInProgress;
}
}
}
// Give the work to a node blocked due to having no work . If there are no nodes without work
// give the work to the least loaded node
if (blockedNode != EngineCallback.invalidNode)
{
nodeUsed = blockedNode;
postBlockCount[blockedNode]--;
}
else
{
nodeUsed = (leastBusyNode != EngineCallback.invalidNode) ? leastBusyNode : leastLoadedNode;
}
#endregion
}
else
{
// round robin schedule the build request
nodeUsed = (lastUsedNode % nodes.Length);
// Running total of the number of times this round robin scheduler has been called
lastUsedNode++;
if (postBlockCount[nodeUsed] != 0)
{
postBlockCount[nodeUsed]--;
}
}
}
// Update the internal data structure to reflect the scheduling decision
NotifyOfSchedulingDecision(currentRequest, nodeUsed);
}
return nodeUsed;
}
/// <summary>
/// This method is called to update the datastructures to reflect that given request will
/// be built on a given node.
/// </summary>
/// <param name="currentRequest"></param>
/// <param name="nodeUsed"></param>
internal void NotifyOfSchedulingDecision(BuildRequest currentRequest, int nodeUsed)
{
// Don't update structures on the child node or in single proc mode
if (childMode || nodes.Length == 1)
{
return;
}
// Update the count of requests being build on the node
totalRequestsPerNode[nodeUsed]++;
// Ignore host requests
if (currentRequest.HandleId == EngineCallback.invalidEngineHandle)
{
return;
}
if (Engine.debugMode)
{
string targetnames = currentRequest.TargetNames != null ? String.Join(";", currentRequest.TargetNames) : "null";
Console.WriteLine("Sending project " + currentRequest.ProjectFileName + " Target " + targetnames + " to " + nodeUsed);
}
// Update the records
ScheduleRecordKey recordKey = new ScheduleRecordKey(currentRequest.HandleId, currentRequest.RequestId);
ScheduleRecordKey parentKey = new ScheduleRecordKey(currentRequest.ParentHandleId, currentRequest.ParentRequestId);
ScheduleRecord record = new ScheduleRecord(recordKey, parentKey, nodeUsed, currentRequest.ProjectFileName,
currentRequest.ToolsetVersion, currentRequest.TargetNames);
lock (scheduleTableLock)
{
ErrorUtilities.VerifyThrow(!handleIdToScheduleRecord.ContainsKey(recordKey),
"Schedule record should not be in the table");
handleIdToScheduleRecord.Add(recordKey, record);
// The ParentHandleId is an invalidEngineHandle when the host is the one who created
// the current request
if (currentRequest.ParentHandleId != EngineCallback.invalidEngineHandle)
{
ErrorUtilities.VerifyThrow(handleIdToScheduleRecord.ContainsKey(parentKey),
"Parent schedule record should be in the table");
ScheduleRecord parentRecord = handleIdToScheduleRecord[parentKey];
if (!parentRecord.Blocked)
{
blockedRequestsPerNode[parentRecord.EvaluationNode]++;
}
parentRecord.AddChildRecord(record);
}
}
}
/// <summary>
/// This method is called when a build request is completed on a particular node. NodeId is never used instead we look up the node from the build request
/// and the schedule record table
/// </summary>
internal void NotifyOfBuildResult(int nodeId, BuildResult buildResult)
{
if (!childMode && nodes.Length > 1)
{
// Ignore host requests
if (buildResult.HandleId == EngineCallback.invalidEngineHandle)
{
return;
}
ScheduleRecordKey recordKey = new ScheduleRecordKey(buildResult.HandleId, buildResult.RequestId);
ScheduleRecord scheduleRecord = null;
lock (scheduleTableLock)
{
ErrorUtilities.VerifyThrow(handleIdToScheduleRecord.ContainsKey(recordKey),
"Schedule record should be in the table");
scheduleRecord = handleIdToScheduleRecord[recordKey];
totalRequestsPerNode[scheduleRecord.EvaluationNode]--;
handleIdToScheduleRecord.Remove(recordKey);
if (scheduleRecord.ParentKey.HandleId != EngineCallback.invalidEngineHandle)
{
ErrorUtilities.VerifyThrow(handleIdToScheduleRecord.ContainsKey(scheduleRecord.ParentKey),
"Parent schedule record should be in the table");
ScheduleRecord parentRecord = handleIdToScheduleRecord[scheduleRecord.ParentKey];
// As long as there are child requests under the parent request the parent request is considered blocked
// Remove this build request from the list of requests the parent request is waiting on. This may unblock the parent request
parentRecord.ReportChildCompleted(recordKey);
// If completing the child request has unblocked the parent request due to all of the the Child requests being completed
// decrement the number of blocked requests.
if (!parentRecord.Blocked)
{
blockedRequestsPerNode[parentRecord.EvaluationNode]--;
}
}
}
// Dump some interesting information to the console if profile build is turned on by an environment variable
if (parentEngine.ProfileBuild && scheduleRecord != null && buildResult.TaskTime != 0 )
{
Console.WriteLine("N " + scheduleRecord.EvaluationNode + " Name " + scheduleRecord.ProjectName + ":" +
scheduleRecord.ParentKey.HandleId + ":" + scheduleRecord.ParentKey.RequestId +
" Total " + buildResult.TotalTime + " Engine " + buildResult.EngineTime + " Task " + buildResult.TaskTime);
}
}
}
/// <summary>
/// Called when the engine is in the process of sending a buildRequest to a child node. The entire purpose of this method
/// is to switch the traversal strategy of the systems if there are nodes which do not have enough work availiable to them.
/// </summary>
internal void NotifyOfBuildRequest(int nodeIndex, BuildRequest currentRequest, int parentHandleId)
{
// This will only be null when the scheduler is instantiated on a child process in which case the initialize method
// of the scheduler will not be called and therefore not initialize totalRequestsPerNode.
if (totalRequestsPerNode != null)
{
// Check if it makes sense to switch from one traversal strategy to the other
if (parentEngine.NodeManager.TaskExecutionModule.UseBreadthFirstTraversal)
{
// Check if a switch to depth first traversal is in order
bool useBreadthFirstTraversal = false;
for (int i = 0; i < totalRequestsPerNode.Length; i++)
{
// Continue using breadth-first traversal as long as the non-blocked work load for this node is below
// the nodeWorkloadProjectCount or its postBlockCount is non-zero
if ((totalRequestsPerNode[i] - blockedRequestsPerNode[i]) < nodeWorkLoadProjectCount || postBlockCount[i] != 0 )
{
useBreadthFirstTraversal = true;
break;
}
}
if (!useBreadthFirstTraversal)
{
if (Engine.debugMode)
{
Console.WriteLine("Switching to depth first traversal because all node have workitems");
}
parentEngine.NodeManager.TaskExecutionModule.UseBreadthFirstTraversal = false;
// Switch to depth first and change the traversal strategy of the entire system by notifying all child nodes of the change
parentEngine.PostEngineCommand(new ChangeTraversalTypeCommand(false, false));
}
}
}
}
/// <summary>
/// Called by the engine to indicate that a particular request is blocked waiting for another
/// request to finish building a target.
/// </summary>
internal void NotifyOfBlockedRequest(BuildRequest currentRequest)
{
if (!childMode && nodes.Length > 1)
{
ScheduleRecordKey recordKey = new ScheduleRecordKey(currentRequest.HandleId, currentRequest.RequestId);
// Ignore host requests
if (currentRequest.HandleId == EngineCallback.invalidEngineHandle)
{
return;
}
lock (scheduleTableLock)
{
ErrorUtilities.VerifyThrow(handleIdToScheduleRecord.ContainsKey(recordKey),
"Schedule record should be in the table");
handleIdToScheduleRecord[recordKey].Blocked = true;
blockedRequestsPerNode[handleIdToScheduleRecord[recordKey].EvaluationNode]++;
}
}
}
/// <summary>
/// Called by the engine to indicate that a particular request is no longer blocked waiting for another
/// request to finish building a target
/// </summary>
internal void NotifyOfUnblockedRequest(BuildRequest currentRequest)
{
if (!childMode && nodes.Length > 1)
{
ScheduleRecordKey recordKey = new ScheduleRecordKey(currentRequest.HandleId, currentRequest.RequestId);
lock (scheduleTableLock)
{
ErrorUtilities.VerifyThrow(handleIdToScheduleRecord.ContainsKey(recordKey),
"Schedule record should be in the table");
handleIdToScheduleRecord[recordKey].Blocked = false;
blockedRequestsPerNode[handleIdToScheduleRecord[recordKey].EvaluationNode]--;
}
}
}
/// <summary>
/// Called by the engine to indicate that a node has run out of work
/// </summary>
/// <param name="nodeIndex"></param>
internal void NotifyOfBlockedNode(int nodeId)
{
if (Engine.debugMode)
{
Console.WriteLine("Switch to breadth first traversal is requested by " + nodeId);
}
postBlockCount[nodeId] = nodeWorkLoadProjectCount/2;
}
/// <summary>
/// Used by the introspector to dump the state when the nodes are being shutdown due to an error.
/// </summary>
internal void DumpState()
{
for (int i = 0; i < totalRequestsPerNode.Length; i++)
{
Console.WriteLine("Node " + i + " Outstanding " + totalRequestsPerNode[i] + " Blocked " + blockedRequestsPerNode[i]);
}
foreach (ScheduleRecordKey key in handleIdToScheduleRecord.Keys)
{
ScheduleRecord record = handleIdToScheduleRecord[key];
Console.WriteLine(key.HandleId + ":" + key.RequestId + " " + record.ProjectName + " on node " + record.EvaluationNode);
}
}
#endregion
#region Data
/// <summary>
/// NodeId of the engine who instantiated the scheduler. This is used to determine if a
/// BuildRequest should be build locally as the project has already been loaded on this node.
/// </summary>
private int localNodeId;
/// <summary>
/// An array of nodes to which the scheduler can schedule work.
/// </summary>
private INodeDescription[] nodes;
/// <summary>
/// Counts the total number of outstanding requests (no result has been seen for the request) for a node.
/// This is incremented in NotifyOfSchedulingDecision when a request it given to a node
/// and decremented in NotifyOfBuildResult when results are returned (posted) from a node.
/// </summary>
private int[] totalRequestsPerNode;
/// <summary>
/// The number of BuildRequests blocked waiting for results for each node.
/// This will be incremented once when a build request is scheduled which was generated as part of a msbuild callback
/// and once for each call to NotifyOfBlockedRequest.
///
/// It is decremented for each call to NotifyOfUnblockedRequest and once all of the child requests have been fullfilled.
/// </summary>
private int[] blockedRequestsPerNode;
/// <summary>
/// Keeps track of how many projects need to be sent to a node after the node has told the scheduler it has run out of work.
/// </summary>
private int[] postBlockCount;
/// <summary>
/// Indicates the scheduler should balance work accross nodes.
/// This is only true when the environment variable MSBUILDLOADBALANCE is not 0
/// </summary>
private bool useLoadBalancing;
/// <summary>
/// Lock object for the handleIdToScheduleRecord dictionary
/// </summary>
private object scheduleTableLock;
/// <summary>
/// Keep track of build requsts to determine how many requests are blocked waiting on other build requests to complete.
/// </summary>
private Dictionary<ScheduleRecordKey, ScheduleRecord> handleIdToScheduleRecord;
/// <summary>
/// Indicates the scheduler is instantiated on a child node. This is being determined by
/// initializaing the variable to true in the constructor and then setting it to false in the
/// initialize method (the initialize method will only be called on the parent engine)
/// </summary>
private bool childMode;
/// <summary>
/// Reference to the engine who instantiated the scheduler
/// </summary>
private Engine parentEngine;
/// <summary>
/// Number of requests a node should have in an unblocked state before the system switches to a depth first traversal strategy.
/// </summary>
private const int nodeWorkLoadProjectCount = 4;
/// <summary>
/// Used to calculate which node a build request should be sent to if the scheduler is operating in a round robin fashion.
/// Each time a build request is scheduled to a node in CalculateNodeForBuildRequest the lastUsedNode is incremented.
/// This value is then mod'd (%) with the number of nodes to alternate which node the next build request goes to.
/// </summary>
private int lastUsedNode;
#endregion
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Targets.Wrappers
{
using System;
using System.Collections.Generic;
using System.Threading;
using NLog.Common;
using NLog.Targets;
using NLog.Targets.Wrappers;
using Xunit;
public class SplitGroupTargetTests : NLogTestBase
{
[Fact]
public void SplitGroupSyncTest1()
{
var myTarget1 = new MyTarget();
var myTarget2 = new MyTarget();
var myTarget3 = new MyTarget();
var wrapper = new SplitGroupTarget()
{
Targets = { myTarget1, myTarget2, myTarget3 },
};
myTarget1.Initialize(null);
myTarget2.Initialize(null);
myTarget3.Initialize(null);
wrapper.Initialize(null);
List<Exception> exceptions = new List<Exception>();
var inputEvents = new List<LogEventInfo>();
for (int i = 0; i < 10; ++i)
{
inputEvents.Add(LogEventInfo.CreateNullEvent());
}
int remaining = inputEvents.Count;
var allDone = new ManualResetEvent(false);
// no exceptions
for (int i = 0; i < inputEvents.Count; ++i)
{
wrapper.WriteAsyncLogEvent(inputEvents[i].WithContinuation(ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
if (Interlocked.Decrement(ref remaining) == 0)
{
allDone.Set();
}
};
}));
}
allDone.WaitOne();
Assert.Equal(inputEvents.Count, exceptions.Count);
foreach (var e in exceptions)
{
Assert.Null(e);
}
Assert.Equal(inputEvents.Count, myTarget1.WriteCount);
Assert.Equal(inputEvents.Count, myTarget2.WriteCount);
Assert.Equal(inputEvents.Count, myTarget3.WriteCount);
for (int i = 0; i < inputEvents.Count; ++i)
{
Assert.Same(inputEvents[i], myTarget1.WrittenEvents[i]);
Assert.Same(inputEvents[i], myTarget2.WrittenEvents[i]);
Assert.Same(inputEvents[i], myTarget3.WrittenEvents[i]);
}
Exception flushException = null;
var flushHit = new ManualResetEvent(false);
wrapper.Flush(ex => { flushException = ex; flushHit.Set(); });
flushHit.WaitOne();
if (flushException != null)
{
Assert.True(false, flushException.ToString());
}
Assert.Equal(1, myTarget1.FlushCount);
Assert.Equal(1, myTarget2.FlushCount);
Assert.Equal(1, myTarget3.FlushCount);
}
[Fact]
public void SplitGroupSyncTest2()
{
var wrapper = new SplitGroupTarget()
{
// no targets
};
wrapper.Initialize(null);
List<Exception> exceptions = new List<Exception>();
// no exceptions
for (int i = 0; i < 10; ++i)
{
wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
}
Assert.Equal(10, exceptions.Count);
foreach (var e in exceptions)
{
Assert.Null(e);
}
Exception flushException = new Exception("Flush not hit synchronously.");
wrapper.Flush(ex => flushException = ex);
if (flushException != null)
{
Assert.True(false, flushException.ToString());
}
}
public class MyAsyncTarget : Target
{
public int FlushCount { get; private set; }
public int WriteCount { get; private set; }
protected override void Write(LogEventInfo logEvent)
{
throw new NotSupportedException();
}
protected override void Write(AsyncLogEventInfo logEvent)
{
Assert.True(this.FlushCount <= this.WriteCount);
this.WriteCount++;
ThreadPool.QueueUserWorkItem(
s =>
{
if (this.ThrowExceptions)
{
logEvent.Continuation(new InvalidOperationException("Some problem!"));
logEvent.Continuation(new InvalidOperationException("Some problem!"));
}
else
{
logEvent.Continuation(null);
logEvent.Continuation(null);
}
});
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
this.FlushCount++;
ThreadPool.QueueUserWorkItem(
s => asyncContinuation(null));
}
public bool ThrowExceptions { get; set; }
}
public class MyTarget : Target
{
public MyTarget()
{
this.WrittenEvents = new List<LogEventInfo>();
}
public int FlushCount { get; set; }
public int WriteCount { get; set; }
public int FailCounter { get; set; }
public List<LogEventInfo> WrittenEvents { get; private set; }
protected override void Write(LogEventInfo logEvent)
{
Assert.True(this.FlushCount <= this.WriteCount);
lock (this)
{
this.WriteCount++;
this.WrittenEvents.Add(logEvent);
}
if (this.FailCounter > 0)
{
this.FailCounter--;
throw new InvalidOperationException("Some failure.");
}
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
this.FlushCount++;
asyncContinuation(null);
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="FilteredBindingList.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>Provides a filtered view into an existing IList(Of T).</summary>
//-----------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections;
using Csla.Properties;
namespace Csla
{
/// <summary>
/// Provides a filtered view into an existing IList(Of T).
/// </summary>
/// <typeparam name="T">The type of the objects contained
/// in the original list.</typeparam>
public class FilteredBindingList<T> :
IList<T>, IBindingList, IEnumerable<T>,
ICancelAddNew
{
#region ListItem class
private class ListItem
{
private object _key;
private int _baseIndex;
public object Key
{
get { return _key; }
}
public int BaseIndex
{
get { return _baseIndex; }
set { _baseIndex = value; }
}
public ListItem(object key, int baseIndex)
{
_key = key;
_baseIndex = baseIndex;
}
public override string ToString()
{
return Key.ToString();
}
}
#endregion
#region Filtered enumerator
private class FilteredEnumerator : IEnumerator<T>
{
private IList<T> _list;
private List<ListItem> _filterIndex;
private int _index;
public FilteredEnumerator(
IList<T> list,
List<ListItem> filterIndex)
{
_list = list;
_filterIndex = filterIndex;
Reset();
}
public T Current
{
get { return _list[_filterIndex[_index].BaseIndex]; }
}
Object System.Collections.IEnumerator.Current
{
get { return _list[_filterIndex[_index].BaseIndex]; }
}
public bool MoveNext()
{
if (_index < _filterIndex.Count - 1)
{
_index++;
return true;
}
else
return false;
}
public void Reset()
{
_index = -1;
}
#region IDisposable Support
private bool _disposedValue = false; // To detect redundant calls.
// IDisposable
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
// free unmanaged resources when explicitly called
}
// free shared unmanaged resources
}
_disposedValue = true;
}
// this code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
GC.SuppressFinalize(this);
}
~FilteredEnumerator()
{
Dispose(false);
}
#endregion
}
#endregion
#region Filter/Unfilter
private void DoFilter()
{
int index = 0;
_filterIndex.Clear();
if (_provider == null)
_provider = DefaultFilter.Filter;
if (_filterBy == null)
{
foreach (T obj in _list)
{
if (_provider.Invoke(obj, _filter))
_filterIndex.Add(new ListItem(obj, index));
index++;
}
}
else
{
foreach (T obj in _list)
{
object tmp = _filterBy.GetValue(obj);
if (_provider.Invoke(tmp, _filter))
_filterIndex.Add(new ListItem(tmp, index));
index++;
}
}
_filtered = true;
OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, 0));
}
private void UnDoFilter()
{
_filterIndex.Clear();
_filterBy = null;
_filter = null;
_filtered = false;
OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, 0));
}
#endregion
#region IEnumerable<T>
/// <summary>
/// Gets an enumerator object.
/// </summary>
/// <returns></returns>
public IEnumerator<T> GetEnumerator()
{
if (_filtered)
return new FilteredEnumerator(_list, _filterIndex);
else
return _list.GetEnumerator();
}
#endregion
#region IBindingList, IList<T>
/// <summary>
/// Implemented by IList source object.
/// </summary>
/// <param name="property">Property on which
/// to build the index.</param>
public void AddIndex(PropertyDescriptor property)
{
if (_supportsBinding)
_bindingList.AddIndex(property);
}
/// <summary>
/// Implemented by IList source object.
/// </summary>
public object AddNew()
{
T result;
if (_supportsBinding)
result = (T)_bindingList.AddNew();
else
result = default(T);
//_newItem = (T)result;
return result;
}
/// <summary>
/// Implemented by IList source object.
/// </summary>
public bool AllowEdit
{
get
{
if (_supportsBinding)
return _bindingList.AllowEdit;
else
return false;
}
}
/// <summary>
/// Implemented by IList source object.
/// </summary>
public bool AllowNew
{
get
{
if (_supportsBinding)
return _bindingList.AllowNew;
else
return false;
}
}
/// <summary>
/// Implemented by IList source object.
/// </summary>
public bool AllowRemove
{
get
{
if (_supportsBinding)
return _bindingList.AllowRemove;
else
return false;
}
}
/// <summary>
/// Sorts the list if the original list
/// supports sorting.
/// </summary>
/// <param name="property">Property on which to sort.</param>
/// <param name="direction">Direction of the sort.</param>
public void ApplySort(
PropertyDescriptor property, ListSortDirection direction)
{
if (SupportsSorting)
_bindingList.ApplySort(property, direction);
else
throw new NotSupportedException(Resources.SortingNotSupported);
}
/// <summary>
/// Sorts the list if the original list
/// supports sorting.
/// </summary>
/// <param name="propertyName">PropertyName on which to sort.</param>
/// <param name="direction">Direction of the sort.</param>
public void ApplySort(
string propertyName, ListSortDirection direction)
{
if (SupportsSorting)
{
var property = GetPropertyDescriptor(propertyName);
_bindingList.ApplySort(property, direction);
}
else
throw new NotSupportedException(Resources.SortingNotSupported);
}
/// <summary>
/// Gets the property descriptor.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <returns>PropertyDescriptor</returns>
private static PropertyDescriptor GetPropertyDescriptor(string propertyName)
{
PropertyDescriptor property = null;
if (!String.IsNullOrEmpty(propertyName))
{
Type itemType = typeof(T);
foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(itemType))
{
if (prop.Name == propertyName)
{
property = prop;
break;
}
}
// throw exception if propertyDescriptor could not be found
if (property == null)
throw new ArgumentException(string.Format(Resources.SortedBindingListPropertyNameNotFound, propertyName), propertyName);
}
return property;
}
/// <summary>
/// Finds an item in the view
/// </summary>
/// <param name="propertyName">Name of the property to search</param>
/// <param name="key">Value to find</param>
public int Find(string propertyName, object key)
{
PropertyDescriptor findProperty = null;
if (!String.IsNullOrEmpty(propertyName))
{
Type itemType = typeof(T);
foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(itemType))
{
if (prop.Name == propertyName)
{
findProperty = prop;
break;
}
}
}
return Find(findProperty, key);
}
/// <summary>
/// Implemented by IList source object.
/// </summary>
/// <param name="key">Key value for which to search.</param>
/// <param name="property">Property to search for the key
/// value.</param>
public int Find(PropertyDescriptor property, object key)
{
if (_supportsBinding)
return FilteredIndex(_bindingList.Find(property, key));
else
return -1;
}
/// <summary>
/// Returns True if the view is currently sorted.
/// </summary>
public bool IsSorted
{
get
{
if (SupportsSorting)
return _bindingList.IsSorted;
else
return false;
}
}
/// <summary>
/// Raised to indicate that the list's data has changed.
/// </summary>
/// <remarks>
/// This event is raised if the underling IList object's data changes
/// (assuming the underling IList also implements the IBindingList
/// interface). It is also raised if the filter
/// is changed to indicate that the view's data has changed.
/// </remarks>
public event ListChangedEventHandler ListChanged;
/// <summary>
/// Raises the ListChanged event.
/// </summary>
/// <param name="e">Parameter for the event.</param>
protected void OnListChanged(ListChangedEventArgs e)
{
if (ListChanged != null)
ListChanged(this, e);
}
/// <summary>
/// Implemented by IList source object.
/// </summary>
/// <param name="property">Property for which the
/// index should be removed.</param>
public void RemoveIndex(PropertyDescriptor property)
{
if (_supportsBinding)
_bindingList.RemoveIndex(property);
}
/// <summary>
/// Removes any sort currently applied to the view.
/// </summary>
public void RemoveSort()
{
if (SupportsSorting)
_bindingList.RemoveSort();
else
throw new NotSupportedException(Resources.SortingNotSupported);
}
/// <summary>
/// Returns the direction of the current sort.
/// </summary>
public ListSortDirection SortDirection
{
get
{
if (SupportsSorting)
return _bindingList.SortDirection;
else
return ListSortDirection.Ascending;
}
}
/// <summary>
/// Returns the PropertyDescriptor of the current sort.
/// </summary>
public PropertyDescriptor SortProperty
{
get
{
if (SupportsSorting)
return _bindingList.SortProperty;
else
return null;
}
}
/// <summary>
/// Returns True since this object does raise the
/// ListChanged event.
/// </summary>
public bool SupportsChangeNotification
{
get { return true; }
}
/// <summary>
/// Implemented by IList source object.
/// </summary>
public bool SupportsSearching
{
get
{
if (_supportsBinding)
return _bindingList.SupportsSearching;
else
return false;
}
}
/// <summary>
/// Returns True. Sorting is supported.
/// </summary>
public bool SupportsSorting
{
get
{
if (_supportsBinding)
return _bindingList.SupportsSorting;
else
return false;
}
}
/// <summary>
/// Copies the contents of the list to
/// an array.
/// </summary>
/// <param name="array">Array to receive the data.</param>
/// <param name="arrayIndex">Starting array index.</param>
public void CopyTo(T[] array, int arrayIndex)
{
int pos = arrayIndex;
foreach (T child in this)
{
array[pos] = child;
pos++;
}
}
void System.Collections.ICollection.CopyTo(System.Array array, int index)
{
T[] tmp = new T[array.Length];
CopyTo(tmp, index);
Array.Copy(tmp, 0, array, index, array.Length);
}
/// <summary>
/// Gets the number of items in the list.
/// </summary>
public int Count
{
get
{
if (_filtered)
return _filterIndex.Count;
else
return _list.Count;
}
}
bool System.Collections.ICollection.IsSynchronized
{
get { return false; }
}
object System.Collections.ICollection.SyncRoot
{
get { return _list; }
}
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Adds an item to the list.
/// </summary>
/// <param name="item">Item to be added.</param>
public void Add(T item)
{
_list.Add(item);
}
int System.Collections.IList.Add(object value)
{
Add((T)value);
int index = FilteredIndex(_list.Count - 1);
if (index > -1)
return index;
else
return 0;
}
/// <summary>
/// Clears the list.
/// </summary>
public void Clear()
{
if (_filtered)
for (int index = Count - 1; index >= 0; index--)
RemoveAt(index);
else
_list.Clear();
}
/// <summary>
/// Determines whether the specified
/// item is contained in the list.
/// </summary>
/// <param name="item">Item to find.</param>
/// <returns>true if the item is
/// contained in the list.</returns>
public bool Contains(T item)
{
return _list.Contains(item);
}
bool System.Collections.IList.Contains(object value)
{
return Contains((T)value);
}
/// <summary>
/// Gets the 0-based index of an
/// item in the list.
/// </summary>
/// <param name="item">The item to find.</param>
/// <returns>0-based index of the item
/// in the list.</returns>
public int IndexOf(T item)
{
return FilteredIndex(_list.IndexOf(item));
}
int System.Collections.IList.IndexOf(object value)
{
return IndexOf((T)value);
}
/// <summary>
/// Inserts an item into the list.
/// </summary>
/// <param name="index">Index at
/// which to insert the item.</param>
/// <param name="item">Item to insert.</param>
public void Insert(int index, T item)
{
_list.Insert(index, item);
}
void System.Collections.IList.Insert(int index, object value)
{
Insert(index, (T)value);
}
bool System.Collections.IList.IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the list
/// is read-only.
/// </summary>
public bool IsReadOnly
{
get { return _list.IsReadOnly; }
}
object System.Collections.IList.this[int index]
{
get
{
return this[index];
}
set
{
this[index] = (T)value;
}
}
/// <summary>
/// Removes an item from the list.
/// </summary>
/// <param name="item">Item to remove.</param>
/// <returns>true if the
/// remove succeeds.</returns>
public bool Remove(T item)
{
return _list.Remove(item);
}
void System.Collections.IList.Remove(object value)
{
Remove((T)value);
}
/// <summary>
/// Removes an item from the list.
/// </summary>
/// <param name="index">Index of item
/// to be removed.</param>
public void RemoveAt(int index)
{
if (_filtered)
{
_list.RemoveAt(OriginalIndex(index));
}
else
_list.RemoveAt(index);
}
/// <summary>
/// Gets or sets the item at
/// the specified index.
/// </summary>
/// <param name="index">Index of the item.</param>
/// <returns>Item at the specified index.</returns>
public T this[int index]
{
get
{
if (_filtered)
{
int src = OriginalIndex(index);
return _list[src];
}
else
return _list[index];
}
set
{
if (_filtered)
_list[OriginalIndex(index)] = value;
else
_list[index] = value;
}
}
#endregion
#region SourceList
/// <summary>
/// Gets the source list over which this
/// SortedBindingList is a view.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public IList<T> SourceList
{
get
{
return _list;
}
}
#endregion
private IList<T> _list;
private bool _supportsBinding;
private IBindingList _bindingList;
private bool _filtered;
private PropertyDescriptor _filterBy;
private object _filter;
FilterProvider _provider = null;
private List<ListItem> _filterIndex =
new List<ListItem>();
/// <summary>
/// Creates a new view based on the provided IList object.
/// </summary>
/// <param name="list">The IList (collection) containing the data.</param>
public FilteredBindingList(IList<T> list)
{
_list = list;
if (_list is IBindingList)
{
_supportsBinding = true;
_bindingList = (IBindingList)_list;
_bindingList.ListChanged +=
new ListChangedEventHandler(SourceChanged);
}
}
/// <summary>
/// Creates a new view based on the provided IList object.
/// </summary>
/// <param name="list">The IList (collection) containing the data.</param>
/// <param name="filterProvider">
/// Delegate pointer to a method that implements the filter behavior.
/// </param>
public FilteredBindingList(IList<T> list, FilterProvider filterProvider) : this(list)
{
_provider = filterProvider;
}
/// <summary>
/// Gets or sets the filter provider method.
/// </summary>
/// <value>
/// Delegate pointer to a method that implements the filter behavior.
/// </value>
/// <returns>
/// Delegate pointer to a method that implements the filter behavior.
/// </returns>
/// <remarks>
/// If this value is set to Nothing (null in C#) then the default
/// filter provider, <see cref="DefaultFilter" /> will be used.
/// </remarks>
public FilterProvider FilterProvider
{
get
{
return _provider;
}
set
{
_provider = value;
}
}
/// <summary>
/// The property on which the items will be filtered.
/// </summary>
/// <value>A descriptor for the property on which
/// the items in the collection will be filtered.</value>
/// <returns></returns>
/// <remarks></remarks>
public PropertyDescriptor FilterProperty
{
get { return _filterBy; }
}
/// <summary>
/// Returns True if the view is currently filtered.
/// </summary>
public bool IsFiltered
{
get { return _filtered; }
}
/// <summary>
/// Applies a filter to the view using the
/// most recently used property name and
/// filter provider.
/// </summary>
public void ApplyFilter()
{
if (_filterBy == null || _filter == null)
throw new ArgumentNullException(Resources.FilterRequiredException);
DoFilter();
}
/// <summary>
/// Applies a filter to the view.
/// </summary>
/// <param name="propertyName">The text name of the property on which to filter.</param>
/// <param name="filter">The filter criteria.</param>
public void ApplyFilter(string propertyName, object filter)
{
_filterBy = null;
_filter = filter;
if (!String.IsNullOrEmpty(propertyName))
{
Type itemType = typeof(T);
foreach (PropertyDescriptor prop in
TypeDescriptor.GetProperties(itemType))
{
if (prop.Name == propertyName)
{
_filterBy = prop;
break;
}
}
}
ApplyFilter(_filterBy, filter);
}
/// <summary>
/// Applies a filter to the view.
/// </summary>
/// <param name="property">A PropertyDescriptor for the property on which to filter.</param>
/// <param name="filter">The filter criteria.</param>
public void ApplyFilter(
PropertyDescriptor property, object filter)
{
_filterBy = property;
_filter = filter;
DoFilter();
}
/// <summary>
/// Removes the filter from the list,
/// so the view reflects the state of
/// the original list.
/// </summary>
public void RemoveFilter()
{
UnDoFilter();
}
private void SourceChanged(
object sender, ListChangedEventArgs e)
{
if (_filtered)
{
int listIndex;
int filteredIndex = -1;
T newItem;
object newKey;
switch (e.ListChangedType)
{
case ListChangedType.ItemAdded:
listIndex = e.NewIndex;
// add new value to index
newItem = _list[listIndex];
if (_filterBy != null)
newKey = _filterBy.GetValue(newItem);
else
newKey = newItem;
_filterIndex.Add(
new ListItem(newKey, listIndex));
filteredIndex = _filterIndex.Count - 1;
// raise event
OnListChanged(
new ListChangedEventArgs(
e.ListChangedType, filteredIndex));
break;
case ListChangedType.ItemChanged:
listIndex = e.NewIndex;
// update index value
filteredIndex = FilteredIndex(listIndex);
if (filteredIndex != -1)
{
newItem = _list[listIndex];
if (_filterBy != null)
newKey = _filterBy.GetValue(newItem);
else
newKey = newItem;
_filterIndex[filteredIndex] =
new ListItem(newKey, listIndex);
}
// raise event if appropriate
if (filteredIndex > -1)
OnListChanged(
new ListChangedEventArgs(
e.ListChangedType, filteredIndex, e.PropertyDescriptor));
break;
case ListChangedType.ItemDeleted:
listIndex = e.NewIndex;
// delete corresponding item from index
// (if any)
filteredIndex = FilteredIndex(listIndex);
if (filteredIndex != -1)
_filterIndex.RemoveAt(filteredIndex);
// adjust index xref values
foreach (ListItem item in _filterIndex)
if (item.BaseIndex > e.NewIndex)
item.BaseIndex--;
// raise event if appropriate
if (filteredIndex > -1)
OnListChanged(
new ListChangedEventArgs(
e.ListChangedType, filteredIndex));
break;
case ListChangedType.PropertyDescriptorAdded:
case ListChangedType.PropertyDescriptorChanged:
case ListChangedType.PropertyDescriptorDeleted:
OnListChanged(e);
break;
default:
DoFilter();
OnListChanged(
new ListChangedEventArgs(
ListChangedType.Reset, 0));
break;
}
}
else
OnListChanged(e);
}
private int OriginalIndex(int filteredIndex)
{
if (_filtered)
return _filterIndex[filteredIndex].BaseIndex;
else
return filteredIndex;
}
private int FilteredIndex(int originalIndex)
{
int result = -1;
if (_filtered)
{
for (int index = 0; index < _filterIndex.Count; index++)
{
if (_filterIndex[index].BaseIndex == originalIndex)
{
result = index;
break;
}
}
}
else
result = originalIndex;
return result;
}
#region ICancelAddNew Members
//private T _newItem;
//void ICancelAddNew.CancelNew(int itemIndex)
//{
// if (_newItem != null)
// Remove(_newItem);
//}
//void ICancelAddNew.EndNew(int itemIndex)
//{
// // do nothing
//}
void ICancelAddNew.CancelNew(int itemIndex)
{
if (itemIndex <= -1) return;
ICancelAddNew can = _list as ICancelAddNew;
if (can != null)
can.CancelNew(OriginalIndex(itemIndex));
else
_list.RemoveAt(OriginalIndex(itemIndex));
}
void ICancelAddNew.EndNew(int itemIndex)
{
ICancelAddNew can = _list as ICancelAddNew;
if (can != null)
can.EndNew(OriginalIndex(itemIndex));
}
#endregion
#region ToArray
/// <summary>
/// Get an array containing all items in the list.
/// </summary>
public T[] ToArray()
{
List<T> result = new List<T>();
foreach (T item in this)
result.Add(item);
return result.ToArray();
}
#endregion
}
}
| |
// ***********************************************************************
// <copyright file="ProcessUtils.cs" company="ServiceStack, Inc.">
// Copyright (c) ServiceStack, Inc. All Rights Reserved.
// </copyright>
// <summary>Fork for YetAnotherForum.NET, Licensed under the Apache License, Version 2.0</summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using ServiceStack.Text;
namespace ServiceStack
{
/// <summary>
/// Async Process Helper
/// - https://gist.github.com/Indigo744/b5f3bd50df4b179651c876416bf70d0a
/// </summary>
public static class ProcessUtils
{
/// <summary>
/// .NET Core / Win throws Win32Exception (193): The specified executable is not a valid application for this OS platform.
/// This method converts it to a cmd.exe /c execute to workaround this
/// </summary>
/// <param name="startInfo">The start information.</param>
/// <returns>ProcessStartInfo.</returns>
public static ProcessStartInfo ConvertToCmdExec(this ProcessStartInfo startInfo)
{
var to = new ProcessStartInfo
{
FileName = Env.IsWindows
? "cmd.exe"
: "/bin/bash",
WorkingDirectory = startInfo.WorkingDirectory,
Arguments = Env.IsWindows
? $"/c \"\"{startInfo.FileName}\" {startInfo.Arguments}\""
: $"-c \"{startInfo.FileName} {startInfo.Arguments}\"",
};
return to;
}
/// <summary>
/// Returns path of executable if exists within PATH
/// </summary>
/// <param name="exeName">Name of the executable.</param>
/// <returns>System.String.</returns>
public static string FindExePath(string exeName)
{
try
{
var p = new Process
{
StartInfo =
{
UseShellExecute = false,
FileName = Env.IsWindows
? "where" //Win 7/Server 2003+
: "which", //macOS / Linux
Arguments = exeName,
RedirectStandardOutput = true
}
};
p.Start();
var output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
if (p.ExitCode == 0)
{
// just return first match
var fullPath = output.Substring(0, output.IndexOf(Environment.NewLine, StringComparison.Ordinal));
if (!string.IsNullOrEmpty(fullPath))
{
return fullPath;
}
}
}
catch
{
// ignored
}
return null;
}
/// <summary>
/// Run the command with the OS's command runner
/// </summary>
/// <param name="arguments">The arguments.</param>
/// <param name="workingDir">The working dir.</param>
/// <returns>System.String.</returns>
/// <exception cref="System.ArgumentNullException">arguments</exception>
public static string RunShell(string arguments, string workingDir = null)
{
if (string.IsNullOrEmpty(arguments))
throw new ArgumentNullException(nameof(arguments));
if (Env.IsWindows)
{
var cmdArgs = "/C " + arguments;
return Run("cmd.exe", cmdArgs, workingDir);
}
else
{
var escapedArgs = arguments.Replace("\"", "\\\"");
var cmdArgs = $"-c \"{escapedArgs}\"";
return Run("/bin/bash", cmdArgs, workingDir);
}
}
/// <summary>
/// Run the process and return the Standard Output, any Standard Error output will throw an Exception
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="arguments">The arguments.</param>
/// <param name="workingDir">The working dir.</param>
/// <returns>System.String.</returns>
/// <exception cref="System.Exception">`{fileName} {process.StartInfo.Arguments}` command failed, stderr: " + error + ", stdout:" + output</exception>
public static string Run(string fileName, string arguments = null, string workingDir = null)
{
var process = CreateProcess(fileName, arguments, workingDir);
using (process)
{
process.StartInfo.RedirectStandardError = true;
process.Start();
var output = process.StandardOutput.ReadToEnd();
var error = process.StandardError.ReadToEnd();
process.WaitForExit();
process.Close();
if (!string.IsNullOrEmpty(error))
throw new Exception($"`{fileName} {process.StartInfo.Arguments}` command failed, stderr: " + error + ", stdout:" + output);
return output;
}
}
public static Process CreateProcess(string fileName, string arguments, string workingDir)
{
var process = new Process
{
StartInfo =
{
FileName = fileName,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
}
};
if (arguments != null)
process.StartInfo.Arguments = arguments;
if (workingDir != null)
process.StartInfo.WorkingDirectory = workingDir;
return process;
}
/// <summary>
/// Run the command with the OS's command runner
/// </summary>
public static async Task RunShellAsync(string arguments, string workingDir = null, int? timeoutMs = null,
Action<string> onOut = null, Action<string> onError = null)
{
if (string.IsNullOrEmpty(arguments))
throw new ArgumentNullException(nameof(arguments));
if (Env.IsWindows)
{
var cmdArgs = "/C " + arguments;
await RunAsync(CreateProcess("cmd.exe", cmdArgs, workingDir).StartInfo, timeoutMs, onOut, onError);
}
else
{
var escapedArgs = arguments.Replace("\"", "\\\"");
var cmdArgs = $"-c \"{escapedArgs}\"";
await RunAsync(CreateProcess("/bin/bash", cmdArgs, workingDir).StartInfo, timeoutMs, onOut, onError);
}
}
/// <summary>
/// Run a Process asynchronously, returning entire captured process output, whilst streaming stdOut, stdErr callbacks
/// </summary>
/// <param name="startInfo">The start information.</param>
/// <param name="timeoutMs">The timeout ms.</param>
/// <param name="onOut">The on out.</param>
/// <param name="onError">The on error.</param>
/// <returns>A Task<ProcessResult> representing the asynchronous operation.</returns>
public static async Task<ProcessResult> RunAsync(ProcessStartInfo startInfo, int? timeoutMs = null,
Action<string> onOut = null, Action<string> onError = null)
{
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
using var process = new Process
{
StartInfo = startInfo,
EnableRaisingEvents = true,
};
// List of tasks to wait for a whole process exit
var processTasks = new List<Task>();
// === EXITED Event handling ===
var processExitEvent = new TaskCompletionSource<object>();
process.Exited += (sender, args) =>
{
processExitEvent.TrySetResult(true);
};
processTasks.Add(processExitEvent.Task);
long callbackTicks = 0;
// === STDOUT handling ===
var stdOutBuilder = StringBuilderCache.Allocate();
var stdOutCloseEvent = new TaskCompletionSource<bool>();
process.OutputDataReceived += (s, e) =>
{
if (e.Data == null)
{
stdOutCloseEvent.TrySetResult(true);
}
else
{
stdOutBuilder.AppendLine(e.Data);
if (onOut != null)
{
var swCallback = Stopwatch.StartNew();
onOut(e.Data);
callbackTicks += swCallback.ElapsedTicks;
}
}
};
processTasks.Add(stdOutCloseEvent.Task);
// === STDERR handling ===
var stdErrBuilder = StringBuilderCacheAlt.Allocate();
var stdErrCloseEvent = new TaskCompletionSource<bool>();
process.ErrorDataReceived += (s, e) =>
{
if (e.Data == null)
{
stdErrCloseEvent.TrySetResult(true);
}
else
{
stdErrBuilder.AppendLine(e.Data);
if (onError != null)
{
var swCallback = Stopwatch.StartNew();
onError(e.Data);
callbackTicks += swCallback.ElapsedTicks;
}
}
};
processTasks.Add(stdErrCloseEvent.Task);
// === START OF PROCESS ===
var sw = Stopwatch.StartNew();
var result = new ProcessResult
{
StartAt = DateTime.UtcNow,
};
if (!process.Start())
{
result.ExitCode = process.ExitCode;
return result;
}
// Reads the output stream first as needed and then waits because deadlocks are possible
process.BeginOutputReadLine();
process.BeginErrorReadLine();
// === ASYNC WAIT OF PROCESS ===
// Process completion = exit AND stdout (if defined) AND stderr (if defined)
var processCompletionTask = Task.WhenAll(processTasks);
// Task to wait for exit OR timeout (if defined)
var awaitingTask = timeoutMs.HasValue
? Task.WhenAny(Task.Delay(timeoutMs.Value), processCompletionTask)
: Task.WhenAny(processCompletionTask);
// Let's now wait for something to end...
if (await awaitingTask.ConfigureAwait(false) == processCompletionTask)
{
// -> Process exited cleanly
result.ExitCode = process.ExitCode;
}
else
{
// -> Timeout, let's kill the process
try
{
process.Kill();
}
catch
{
// ignored
}
}
// Read stdout/stderr
result.EndAt = DateTime.UtcNow;
if (callbackTicks > 0)
{
var callbackMs = callbackTicks / Stopwatch.Frequency * 1000;
result.CallbackDurationMs = callbackMs;
result.DurationMs = sw.ElapsedMilliseconds - callbackMs;
}
else
{
result.DurationMs = sw.ElapsedMilliseconds;
}
result.StdOut = StringBuilderCache.ReturnAndFree(stdOutBuilder);
result.StdErr = StringBuilderCacheAlt.ReturnAndFree(stdErrBuilder);
return result;
}
/// <summary>
/// Creates the error result.
/// </summary>
/// <param name="e">The e.</param>
/// <returns>ProcessResult.</returns>
public static ProcessResult CreateErrorResult(Exception e)
{
return new ProcessResult
{
StartAt = DateTime.UtcNow,
EndAt = DateTime.UtcNow,
DurationMs = 0,
CallbackDurationMs = 0,
StdErr = e.ToString(),
ExitCode = -1,
};
}
}
/// <summary>
/// Run process result
/// </summary>
public class ProcessResult
{
/// <summary>
/// Exit code
/// <para>If NULL, process exited due to timeout</para>
/// </summary>
/// <value>The exit code.</value>
public int? ExitCode { get; set; } = null;
/// <summary>
/// Standard error stream
/// </summary>
/// <value>The standard error.</value>
public string StdErr { get; set; }
/// <summary>
/// Standard output stream
/// </summary>
/// <value>The standard out.</value>
public string StdOut { get; set; }
/// <summary>
/// UTC Start
/// </summary>
/// <value>The start at.</value>
public DateTime StartAt { get; set; }
/// <summary>
/// UTC End
/// </summary>
/// <value>The end at.</value>
public DateTime EndAt { get; set; }
/// <summary>
/// Duration (ms)
/// </summary>
/// <value>The duration ms.</value>
public long DurationMs { get; set; }
/// <summary>
/// Duration (ms)
/// </summary>
/// <value>The callback duration ms.</value>
public long? CallbackDurationMs { 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.
//
//
using System;
using System.Globalization;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
using System.Threading;
namespace System.Globalization
{
// This calendar recognizes two era values:
// 0 CurrentEra (AD)
// 1 BeforeCurrentEra (BC)
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class GregorianCalendar : Calendar
{
/*
A.D. = anno Domini
*/
public const int ADEra = 1;
internal const int DatePartYear = 0;
internal const int DatePartDayOfYear = 1;
internal const int DatePartMonth = 2;
internal const int DatePartDay = 3;
//
// This is the max Gregorian year can be represented by DateTime class. The limitation
// is derived from DateTime class.
//
internal const int MaxYear = 9999;
internal GregorianCalendarTypes m_type;
internal static readonly int[] DaysToMonth365 =
{
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
};
internal static readonly int[] DaysToMonth366 =
{
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366
};
private static volatile Calendar s_defaultInstance;
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
if (m_type < GregorianCalendarTypes.Localized ||
m_type > GregorianCalendarTypes.TransliteratedFrench)
{
throw new SerializationException(
String.Format(CultureInfo.CurrentCulture, SR.Serialization_MemberOutOfRange, "type", "GregorianCalendar"));
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public override CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.SolarCalendar;
}
}
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of GregorianCalendar. Used by NLS+ implementation
** and other calendars.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
internal static Calendar GetDefaultInstance()
{
if (s_defaultInstance == null)
{
s_defaultInstance = new GregorianCalendar();
}
return (s_defaultInstance);
}
// Construct an instance of gregorian calendar.
public GregorianCalendar() :
this(GregorianCalendarTypes.Localized)
{
}
public GregorianCalendar(GregorianCalendarTypes type)
{
if ((int)type < (int)GregorianCalendarTypes.Localized || (int)type > (int)GregorianCalendarTypes.TransliteratedFrench)
{
throw new ArgumentOutOfRangeException(
nameof(type),
SR.Format(SR.ArgumentOutOfRange_Range,
GregorianCalendarTypes.Localized, GregorianCalendarTypes.TransliteratedFrench));
}
Contract.EndContractBlock();
this.m_type = type;
}
public virtual GregorianCalendarTypes CalendarType
{
get
{
return (m_type);
}
set
{
VerifyWritable();
switch (value)
{
case GregorianCalendarTypes.Localized:
case GregorianCalendarTypes.USEnglish:
case GregorianCalendarTypes.MiddleEastFrench:
case GregorianCalendarTypes.Arabic:
case GregorianCalendarTypes.TransliteratedEnglish:
case GregorianCalendarTypes.TransliteratedFrench:
m_type = value;
break;
default:
throw new ArgumentOutOfRangeException("m_type", SR.ArgumentOutOfRange_Enum);
}
}
}
internal override CalendarId ID
{
get
{
// By returning different ID for different variations of GregorianCalendar,
// we can support the Transliterated Gregorian calendar.
// DateTimeFormatInfo will use this ID to get formatting information about
// the calendar.
return ((CalendarId)m_type);
}
}
// Returns a given date part of this DateTime. This method is used
// to compute the year, day-of-year, month, or day part.
internal virtual int GetDatePart(long ticks, int part)
{
// n = number of days since 1/1/0001
int n = (int)(ticks / TicksPerDay);
// y400 = number of whole 400-year periods since 1/1/0001
int y400 = n / DaysPer400Years;
// n = day number within 400-year period
n -= y400 * DaysPer400Years;
// y100 = number of whole 100-year periods within 400-year period
int y100 = n / DaysPer100Years;
// Last 100-year period has an extra day, so decrement result if 4
if (y100 == 4) y100 = 3;
// n = day number within 100-year period
n -= y100 * DaysPer100Years;
// y4 = number of whole 4-year periods within 100-year period
int y4 = n / DaysPer4Years;
// n = day number within 4-year period
n -= y4 * DaysPer4Years;
// y1 = number of whole years within 4-year period
int y1 = n / DaysPerYear;
// Last year has an extra day, so decrement result if 4
if (y1 == 4) y1 = 3;
// If year was requested, compute and return it
if (part == DatePartYear)
{
return (y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1);
}
// n = day number within year
n -= y1 * DaysPerYear;
// If day-of-year was requested, return it
if (part == DatePartDayOfYear)
{
return (n + 1);
}
// Leap year calculation looks different from IsLeapYear since y1, y4,
// and y100 are relative to year 1, not year 0
bool leapYear = (y1 == 3 && (y4 != 24 || y100 == 3));
int[] days = leapYear ? DaysToMonth366 : DaysToMonth365;
// All months have less than 32 days, so n >> 5 is a good conservative
// estimate for the month
int m = (n >> 5) + 1;
// m = 1-based month number
while (n >= days[m]) m++;
// If month was requested, return it
if (part == DatePartMonth) return (m);
// Return 1-based day-of-month
return (n - days[m - 1] + 1);
}
/*=================================GetAbsoluteDate==========================
**Action: Gets the absolute date for the given Gregorian date. The absolute date means
** the number of days from January 1st, 1 A.D.
**Returns: the absolute date
**Arguments:
** year the Gregorian year
** month the Gregorian month
** day the day
**Exceptions:
** ArgumentOutOfRangException if year, month, day value is valid.
**Note:
** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars.
** Number of Days in Prior Years (both common and leap years) +
** Number of Days in Prior Months of Current Year +
** Number of Days in Current Month
**
============================================================================*/
internal static long GetAbsoluteDate(int year, int month, int day)
{
if (year >= 1 && year <= MaxYear && month >= 1 && month <= 12)
{
int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366 : DaysToMonth365;
if (day >= 1 && (day <= days[month] - days[month - 1]))
{
int y = year - 1;
int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1;
return (absoluteDate);
}
}
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}
// Returns the tick count corresponding to the given year, month, and day.
// Will check the if the parameters are valid.
internal virtual long DateToTicks(int year, int month, int day)
{
return (GetAbsoluteDate(year, month, day) * TicksPerDay);
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
nameof(months),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
-120000,
120000));
}
Contract.EndContractBlock();
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366 : DaysToMonth365;
int days = (daysArray[m] - daysArray[m - 1]);
if (d > days)
{
d = days;
}
long ticks = DateToTicks(y, m, d) + time.Ticks % TicksPerDay;
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public override DateTime AddYears(DateTime time, int years)
{
return (AddMonths(time, years * 12));
}
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public override int GetDayOfMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDay));
}
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public override int GetDayOfYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
// Returns the number of days in the month given by the year and
// month arguments.
//
public override int GetDaysInMonth(int year, int month, int era)
{
if (era == CurrentEra || era == ADEra)
{
if (year < 1 || year > MaxYear)
{
throw new ArgumentOutOfRangeException(nameof(year), SR.Format(SR.ArgumentOutOfRange_Range,
1, MaxYear));
}
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month);
}
int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365);
return (days[month] - days[month - 1]);
}
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
// Returns the number of days in the year given by the year argument for the current era.
//
public override int GetDaysInYear(int year, int era)
{
if (era == CurrentEra || era == ADEra)
{
if (year >= 1 && year <= MaxYear)
{
return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366 : 365);
}
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxYear));
}
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
// Returns the era for the specified DateTime value.
public override int GetEra(DateTime time)
{
return (ADEra);
}
public override int[] Eras
{
get
{
return (new int[] { ADEra });
}
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public override int GetMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartMonth));
}
// Returns the number of months in the specified year and era.
public override int GetMonthsInYear(int year, int era)
{
if (era == CurrentEra || era == ADEra)
{
if (year >= 1 && year <= MaxYear)
{
return (12);
}
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxYear));
}
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and 9999.
//
public override int GetYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartYear));
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public override bool IsLeapDay(int year, int month, int day, int era)
{
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(nameof(month), SR.Format(SR.ArgumentOutOfRange_Range,
1, 12));
}
Contract.EndContractBlock();
if (era != CurrentEra && era != ADEra)
{
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
if (year < 1 || year > MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
SR.Format(SR.ArgumentOutOfRange_Range, 1, MaxYear));
}
if (day < 1 || day > GetDaysInMonth(year, month))
{
throw new ArgumentOutOfRangeException(nameof(day), SR.Format(SR.ArgumentOutOfRange_Range,
1, GetDaysInMonth(year, month)));
}
if (!IsLeapYear(year))
{
return (false);
}
if (month == 2 && day == 29)
{
return (true);
}
return (false);
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetLeapMonth(int year, int era)
{
if (era != CurrentEra && era != ADEra)
{
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
if (year < 1 || year > MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range, 1, MaxYear));
}
Contract.EndContractBlock();
return (0);
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public override bool IsLeapMonth(int year, int month, int era)
{
if (era != CurrentEra && era != ADEra)
{
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
if (year < 1 || year > MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range, 1, MaxYear));
}
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(nameof(month), SR.Format(SR.ArgumentOutOfRange_Range,
1, 12));
}
Contract.EndContractBlock();
return (false);
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public override bool IsLeapYear(int year, int era)
{
if (era == CurrentEra || era == ADEra)
{
if (year >= 1 && year <= MaxYear)
{
return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
}
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range, 1, MaxYear));
}
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
if (era == CurrentEra || era == ADEra)
{
return new DateTime(year, month, day, hour, minute, second, millisecond);
}
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
internal override Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result)
{
if (era == CurrentEra || era == ADEra)
{
try
{
result = new DateTime(year, month, day, hour, minute, second, millisecond);
return true;
}
catch (ArgumentOutOfRangeException)
{
result = DateTime.Now;
return false;
}
catch (ArgumentException)
{
result = DateTime.Now;
return false;
}
}
result = DateTime.MinValue;
return false;
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 2029;
public override int TwoDigitYearMax
{
get
{
if (twoDigitYearMax == -1)
{
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
99,
MaxYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
if (year > MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range, 1, MaxYear));
}
return (base.ToFourDigitYear(year));
}
}
}
| |
// 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Collections.Immutable
{
/// <content>
/// Contains the inner <see cref="ImmutableSortedSet{T}.Builder"/> class.
/// </content>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
public sealed partial class ImmutableSortedSet<T>
{
/// <summary>
/// A sorted set that mutates with little or no memory allocations,
/// can produce and/or build on immutable sorted set instances very efficiently.
/// </summary>
/// <remarks>
/// <para>
/// While <see cref="ImmutableSortedSet{T}.Union"/> and other bulk change methods
/// already provide fast bulk change operations on the collection, this class allows
/// multiple combinations of changes to be made to a set with equal efficiency.
/// </para>
/// <para>
/// Instance members of this class are <em>not</em> thread-safe.
/// </para>
/// </remarks>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")]
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableSortedSetBuilderDebuggerProxy<>))]
public sealed class Builder : ISortKeyCollection<T>, IReadOnlyCollection<T>, ISet<T>, ICollection
{
/// <summary>
/// The root of the binary tree that stores the collection. Contents are typically not entirely frozen.
/// </summary>
private ImmutableSortedSet<T>.Node _root = ImmutableSortedSet<T>.Node.EmptyNode;
/// <summary>
/// The comparer to use for sorting the set.
/// </summary>
private IComparer<T> _comparer = Comparer<T>.Default;
/// <summary>
/// Caches an immutable instance that represents the current state of the collection.
/// </summary>
/// <value>Null if no immutable view has been created for the current version.</value>
private ImmutableSortedSet<T> _immutable;
/// <summary>
/// A number that increments every time the builder changes its contents.
/// </summary>
private int _version;
/// <summary>
/// The object callers may use to synchronize access to this collection.
/// </summary>
private object _syncRoot;
/// <summary>
/// Initializes a new instance of the <see cref="Builder"/> class.
/// </summary>
/// <param name="set">A set to act as the basis for a new set.</param>
internal Builder(ImmutableSortedSet<T> set)
{
Requires.NotNull(set, nameof(set));
_root = set._root;
_comparer = set.KeyComparer;
_immutable = set;
}
#region ISet<T> Properties
/// <summary>
/// Gets the number of elements in this set.
/// </summary>
public int Count
{
get { return this.Root.Count; }
}
/// <summary>
/// Gets a value indicating whether this instance is read-only.
/// </summary>
/// <value>Always <c>false</c>.</value>
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
#endregion
/// <summary>
/// Gets the element of the set at the given index.
/// </summary>
/// <param name="index">The 0-based index of the element in the set to return.</param>
/// <returns>The element at the given position.</returns>
/// <remarks>
/// No index setter is offered because the element being replaced may not sort
/// to the same position in the sorted collection as the replacing element.
/// </remarks>
public T this[int index]
{
#if FEATURE_ITEMREFAPI
get { return _root.ItemRef(index); }
#else
get { return _root[index]; }
#endif
}
#if FEATURE_ITEMREFAPI
/// <summary>
/// Gets a read-only reference to the element of the set at the given index.
/// </summary>
/// <param name="index">The 0-based index of the element in the set to return.</param>
/// <returns>A read-only reference to the element at the given position.</returns>
public ref readonly T ItemRef(int index)
{
return ref _root.ItemRef(index);
}
#endif
/// <summary>
/// Gets the maximum value in the collection, as defined by the comparer.
/// </summary>
/// <value>The maximum value in the set.</value>
public T Max
{
get { return _root.Max; }
}
/// <summary>
/// Gets the minimum value in the collection, as defined by the comparer.
/// </summary>
/// <value>The minimum value in the set.</value>
public T Min
{
get { return _root.Min; }
}
/// <summary>
/// Gets or sets the <see cref="IComparer{T}"/> object that is used to determine equality for the values in the <see cref="ImmutableSortedSet{T}"/>.
/// </summary>
/// <value>The comparer that is used to determine equality for the values in the set.</value>
/// <remarks>
/// When changing the comparer in such a way as would introduce collisions, the conflicting elements are dropped,
/// leaving only one of each matching pair in the collection.
/// </remarks>
public IComparer<T> KeyComparer
{
get
{
return _comparer;
}
set
{
Requires.NotNull(value, nameof(value));
if (value != _comparer)
{
var newRoot = Node.EmptyNode;
foreach (T item in this)
{
bool mutated;
newRoot = newRoot.Add(item, value, out mutated);
}
_immutable = null;
_comparer = value;
this.Root = newRoot;
}
}
}
/// <summary>
/// Gets the current version of the contents of this builder.
/// </summary>
internal int Version
{
get { return _version; }
}
/// <summary>
/// Gets or sets the root node that represents the data in this collection.
/// </summary>
private Node Root
{
get
{
return _root;
}
set
{
// We *always* increment the version number because some mutations
// may not create a new value of root, although the existing root
// instance may have mutated.
_version++;
if (_root != value)
{
_root = value;
// Clear any cached value for the immutable view since it is now invalidated.
_immutable = null;
}
}
}
#region ISet<T> Methods
/// <summary>
/// Adds an element to the current set and returns a value to indicate if the
/// element was successfully added.
/// </summary>
/// <param name="item">The element to add to the set.</param>
/// <returns>true if the element is added to the set; false if the element is already in the set.</returns>
public bool Add(T item)
{
bool mutated;
this.Root = this.Root.Add(item, _comparer, out mutated);
return mutated;
}
/// <summary>
/// Removes all elements in the specified collection from the current set.
/// </summary>
/// <param name="other">The collection of items to remove from the set.</param>
public void ExceptWith(IEnumerable<T> other)
{
Requires.NotNull(other, nameof(other));
foreach (T item in other)
{
bool mutated;
this.Root = this.Root.Remove(item, _comparer, out mutated);
}
}
/// <summary>
/// Modifies the current set so that it contains only elements that are also in a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
public void IntersectWith(IEnumerable<T> other)
{
Requires.NotNull(other, nameof(other));
var result = ImmutableSortedSet<T>.Node.EmptyNode;
foreach (T item in other)
{
if (this.Contains(item))
{
bool mutated;
result = result.Add(item, _comparer, out mutated);
}
}
this.Root = result;
}
/// <summary>
/// Determines whether the current set is a proper (strict) subset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a correct subset of other; otherwise, false.</returns>
public bool IsProperSubsetOf(IEnumerable<T> other)
{
return this.ToImmutable().IsProperSubsetOf(other);
}
/// <summary>
/// Determines whether the current set is a proper (strict) superset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a superset of other; otherwise, false.</returns>
public bool IsProperSupersetOf(IEnumerable<T> other)
{
return this.ToImmutable().IsProperSupersetOf(other);
}
/// <summary>
/// Determines whether the current set is a subset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a subset of other; otherwise, false.</returns>
public bool IsSubsetOf(IEnumerable<T> other)
{
return this.ToImmutable().IsSubsetOf(other);
}
/// <summary>
/// Determines whether the current set is a superset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a superset of other; otherwise, false.</returns>
public bool IsSupersetOf(IEnumerable<T> other)
{
return this.ToImmutable().IsSupersetOf(other);
}
/// <summary>
/// Determines whether the current set overlaps with the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set and other share at least one common element; otherwise, false.</returns>
public bool Overlaps(IEnumerable<T> other)
{
return this.ToImmutable().Overlaps(other);
}
/// <summary>
/// Determines whether the current set and the specified collection contain the same elements.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is equal to other; otherwise, false.</returns>
public bool SetEquals(IEnumerable<T> other)
{
return this.ToImmutable().SetEquals(other);
}
/// <summary>
/// Modifies the current set so that it contains only elements that are present either in the current set or in the specified collection, but not both.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
public void SymmetricExceptWith(IEnumerable<T> other)
{
this.Root = this.ToImmutable().SymmetricExcept(other)._root;
}
/// <summary>
/// Modifies the current set so that it contains all elements that are present in both the current set and in the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
public void UnionWith(IEnumerable<T> other)
{
Requires.NotNull(other, nameof(other));
foreach (T item in other)
{
bool mutated;
this.Root = this.Root.Add(item, _comparer, out mutated);
}
}
/// <summary>
/// Adds an element to the current set and returns a value to indicate if the
/// element was successfully added.
/// </summary>
/// <param name="item">The element to add to the set.</param>
void ICollection<T>.Add(T item)
{
this.Add(item);
}
/// <summary>
/// Removes all elements from this set.
/// </summary>
public void Clear()
{
this.Root = ImmutableSortedSet<T>.Node.EmptyNode;
}
/// <summary>
/// Determines whether the set contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the set.</param>
/// <returns>true if item is found in the set; false otherwise.</returns>
public bool Contains(T item)
{
return this.Root.Contains(item, _comparer);
}
/// <summary>
/// See <see cref="ICollection{T}"/>
/// </summary>
void ICollection<T>.CopyTo(T[] array, int arrayIndex)
{
_root.CopyTo(array, arrayIndex);
}
/// <summary>
/// Removes the first occurrence of a specific object from the set.
/// </summary>
/// <param name="item">The object to remove from the set.</param>
/// <returns><c>true</c> if the item was removed from the set; <c>false</c> if the item was not found in the set.</returns>
public bool Remove(T item)
{
bool mutated;
this.Root = this.Root.Remove(item, _comparer, out mutated);
return mutated;
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A enumerator that can be used to iterate through the collection.</returns>
public ImmutableSortedSet<T>.Enumerator GetEnumerator()
{
return this.Root.GetEnumerator(this);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A enumerator that can be used to iterate through the collection.</returns>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.Root.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A enumerator that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
/// <summary>
/// Returns an <see cref="IEnumerable{T}"/> that iterates over this
/// collection in reverse order.
/// </summary>
/// <returns>
/// An enumerator that iterates over the <see cref="ImmutableSortedSet{T}.Builder"/>
/// in reverse order.
/// </returns>
[Pure]
public IEnumerable<T> Reverse()
{
return new ReverseEnumerable(_root);
}
/// <summary>
/// Creates an immutable sorted set based on the contents of this instance.
/// </summary>
/// <returns>An immutable set.</returns>
/// <remarks>
/// This method is an O(n) operation, and approaches O(1) time as the number of
/// actual mutations to the set since the last call to this method approaches 0.
/// </remarks>
public ImmutableSortedSet<T> ToImmutable()
{
// Creating an instance of ImmutableSortedSet<T> with our root node automatically freezes our tree,
// ensuring that the returned instance is immutable. Any further mutations made to this builder
// will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked.
if (_immutable == null)
{
_immutable = ImmutableSortedSet<T>.Wrap(this.Root, _comparer);
}
return _immutable;
}
#region ICollection members
/// <summary>
/// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
void ICollection.CopyTo(Array array, int arrayIndex)
{
this.Root.CopyTo(array, arrayIndex);
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe).
/// </summary>
/// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool ICollection.IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>.
/// </summary>
/// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
#endregion
}
}
}
| |
using System;
using System.Linq;
using GraphQL.Types;
namespace GraphQL.Introspection
{
public class __Type : ObjectGraphType
{
public __Type()
{
Name = "__Type";
Field<NonNullGraphType<__TypeKind>>("kind", null, null, context =>
{
if (context.Source is GraphType)
{
return KindForInstance((GraphType)context.Source);
}
else if (context.Source is Type)
{
return KindForType((Type)context.Source);
}
throw new ExecutionError("Unkown kind of type: {0}".ToFormat(context.Source));
});
Field<StringGraphType>("name", resolve: context =>
{
if (context.Source is Type)
{
var type = (Type) context.Source;
if (typeof (NonNullGraphType).IsAssignableFrom(type)
|| typeof (ListGraphType).IsAssignableFrom(type))
{
return null;
}
var resolved = context.Schema.FindType(type);
return resolved.Name;
}
return ((GraphType) context.Source).Name;
});
Field<StringGraphType>("description");
Field<ListGraphType<NonNullGraphType<__Field>>>("fields", null,
new QueryArguments(new[]
{
new QueryArgument<BooleanGraphType>
{
Name = "includeDeprecated",
DefaultValue = false
}
}),
context =>
{
if (context.Source is ObjectGraphType || context.Source is InterfaceGraphType)
{
var includeDeprecated = (bool)context.Arguments["includeDeprecated"];
var type = context.Source as GraphType;
return !includeDeprecated
? type.Fields.Where(f => string.IsNullOrWhiteSpace(f.DeprecationReason))
: type.Fields;
}
return Enumerable.Empty<FieldType>();
});
Field<ListGraphType<NonNullGraphType<__Type>>>("interfaces", resolve: context =>
{
var type = context.Source as IImplementInterfaces;
return type != null ? type.Interfaces : Enumerable.Empty<Type>();
});
Field<ListGraphType<NonNullGraphType<__Type>>>("possibleTypes", resolve: context =>
{
if (context.Source is InterfaceGraphType || context.Source is UnionGraphType)
{
var type = (GraphType)context.Source;
return context.Schema.FindImplemenationsOf(type.GetType());
}
return Enumerable.Empty<GraphType>();
});
Field<ListGraphType<NonNullGraphType<__EnumValue>>>("enumValues", null,
new QueryArguments(new[]
{
new QueryArgument<BooleanGraphType>
{
Name = "includeDeprecated",
DefaultValue = false
}
}),
context =>
{
var type = context.Source as EnumerationGraphType;
if (type != null)
{
var includeDeprecated = (bool)context.Arguments["includeDeprecated"];
var values = !includeDeprecated
? type.Values.Where(e => string.IsNullOrWhiteSpace(e.DeprecationReason)).ToList()
: type.Values.ToList();
return values;
}
return Enumerable.Empty<EnumValue>();
});
Field<ListGraphType<NonNullGraphType<__InputValue>>>("inputFields", resolve: context =>
{
var type = context.Source as InputObjectGraphType;
return type != null ? type.Fields : Enumerable.Empty<FieldType>();
});
Field<__Type>("ofType", resolve: context =>
{
if (context.Source is Type)
{
var type = (Type) context.Source;
var genericType = type.IsConstructedGenericType ? type.GetGenericArguments()[0] : null;
return genericType;
}
if (context.Source is NonNullGraphType)
{
return ((NonNullGraphType) context.Source).Type;
}
if (context.Source is ListGraphType)
{
return ((ListGraphType) context.Source).Type;
}
return null;
});
}
public TypeKind KindForInstance(GraphType type)
{
if (type is EnumerationGraphType)
{
return TypeKind.ENUM;
}
if (type is ScalarGraphType)
{
return TypeKind.SCALAR;
}
if (type is ObjectGraphType)
{
return TypeKind.OBJECT;
}
if (type is InterfaceGraphType)
{
return TypeKind.INTERFACE;
}
if (type is UnionGraphType)
{
return TypeKind.UNION;
}
if (type is InputObjectGraphType)
{
return TypeKind.INPUT_OBJECT;
}
if (type is ListGraphType)
{
return TypeKind.LIST;
}
if (type is NonNullGraphType)
{
return TypeKind.NON_NULL;
}
throw new ExecutionError("Unkown kind of type: {0}".ToFormat(type));
}
public TypeKind KindForType(Type type)
{
if (typeof(EnumerationGraphType).IsAssignableFrom(type))
{
return TypeKind.ENUM;
}
if (typeof(ScalarGraphType).IsAssignableFrom(type))
{
return TypeKind.SCALAR;
}
if (typeof(ObjectGraphType).IsAssignableFrom(type))
{
return TypeKind.OBJECT;
}
if (typeof(InterfaceGraphType).IsAssignableFrom(type))
{
return TypeKind.INTERFACE;
}
if (typeof(UnionGraphType).IsAssignableFrom(type))
{
return TypeKind.UNION;
}
if (typeof (InputObjectGraphType).IsAssignableFrom(type))
{
return TypeKind.INPUT_OBJECT;
}
if (typeof (ListGraphType).IsAssignableFrom(type))
{
return TypeKind.LIST;
}
if (typeof(NonNullGraphType).IsAssignableFrom(type))
{
return TypeKind.NON_NULL;
}
throw new ExecutionError("Unkown kind of type: {0}".ToFormat(type));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using Xunit;
namespace System.IO.MemoryMappedFiles.Tests
{
/// <summary>
/// Tests for MemoryMappedViewAccessor.
/// </summary>
public class MemoryMappedViewAccessorTests : MemoryMappedFilesTestBase
{
/// <summary>
/// Test to validate the offset, size, and access parameters to MemoryMappedFile.CreateViewAccessor.
/// </summary>
[Fact]
public void InvalidArguments()
{
int mapLength = s_pageSize.Value;
foreach (MemoryMappedFile mmf in CreateSampleMaps(mapLength))
{
using (mmf)
{
// Offset
Assert.Throws<ArgumentOutOfRangeException>("offset", () => mmf.CreateViewAccessor(-1, mapLength));
Assert.Throws<ArgumentOutOfRangeException>("offset", () => mmf.CreateViewAccessor(-1, mapLength, MemoryMappedFileAccess.ReadWrite));
// Size
Assert.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewAccessor(0, -1));
Assert.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewAccessor(0, -1, MemoryMappedFileAccess.ReadWrite));
if (IntPtr.Size == 4)
{
Assert.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewAccessor(0, 1 + (long)uint.MaxValue));
Assert.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewAccessor(0, 1 + (long)uint.MaxValue, MemoryMappedFileAccess.ReadWrite));
}
else
{
Assert.Throws<IOException>(() => mmf.CreateViewAccessor(0, long.MaxValue));
Assert.Throws<IOException>(() => mmf.CreateViewAccessor(0, long.MaxValue, MemoryMappedFileAccess.ReadWrite));
}
// Offset + Size
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, mapLength + 1));
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, mapLength + 1, MemoryMappedFileAccess.ReadWrite));
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(mapLength, 1));
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(mapLength, 1, MemoryMappedFileAccess.ReadWrite));
// Access
Assert.Throws<ArgumentOutOfRangeException>("access", () => mmf.CreateViewAccessor(0, mapLength, (MemoryMappedFileAccess)(-1)));
Assert.Throws<ArgumentOutOfRangeException>("access", () => mmf.CreateViewAccessor(0, mapLength, (MemoryMappedFileAccess)(42)));
}
}
}
[Theory]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.CopyOnWrite)]
public void ValidAccessLevelCombinations(MemoryMappedFileAccess mapAccess, MemoryMappedFileAccess viewAccess)
{
const int Capacity = 4096;
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, Capacity, mapAccess))
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, Capacity, viewAccess))
{
ValidateMemoryMappedViewAccessor(acc, Capacity, viewAccess);
}
}
[Theory]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)]
public void InvalidAccessLevelsCombinations(MemoryMappedFileAccess mapAccess, MemoryMappedFileAccess viewAccess)
{
const int Capacity = 4096;
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, Capacity, mapAccess))
{
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, Capacity, viewAccess));
}
}
/// <summary>
/// Test to verify the accessor's PointerOffset.
/// </summary>
[Fact]
public void PointerOffsetMatchesViewStart()
{
const int MapLength = 4096;
foreach (MemoryMappedFile mmf in CreateSampleMaps(MapLength))
{
using (mmf)
{
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor())
{
Assert.Equal(0, acc.PointerOffset);
}
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, MapLength))
{
Assert.Equal(0, acc.PointerOffset);
}
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(1, MapLength - 1))
{
Assert.Equal(1, acc.PointerOffset);
}
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(MapLength - 1, 1))
{
Assert.Equal(MapLength - 1, acc.PointerOffset);
}
// On Unix creating a view of size zero will result in an offset and capacity
// of 0 due to mmap behavior, whereas on Windows it's possible to create a
// zero-size view anywhere in the created file mapping.
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(MapLength, 0))
{
Assert.Equal(
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? MapLength : 0,
acc.PointerOffset);
}
}
}
}
/// <summary>
/// Test all of the Read/Write accessor methods against a variety of maps and accessors.
/// </summary>
[Theory]
[InlineData(0, 8192)]
[InlineData(8100, 92)]
[InlineData(0, 20)]
[InlineData(1, 8191)]
[InlineData(17, 8175)]
[InlineData(17, 20)]
public void AllReadWriteMethods(long offset, long size)
{
foreach (MemoryMappedFile mmf in CreateSampleMaps(8192))
{
using (mmf)
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(offset, size))
{
AssertWritesReads(acc);
}
}
}
/// <summary>Performs many reads and writes of various data types against the accessor.</summary>
private static unsafe void AssertWritesReads(MemoryMappedViewAccessor acc) // TODO: unsafe can be removed once using C# 6 compiler
{
// Successful reads and writes at the beginning for each data type
AssertWriteRead<bool>(false, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos));
AssertWriteRead<bool>(true, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos));
AssertWriteRead<byte>(42, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadByte(pos));
AssertWriteRead<char>('c', 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadChar(pos));
AssertWriteRead<decimal>(9, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadDecimal(pos));
AssertWriteRead<double>(10, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadDouble(pos));
AssertWriteRead<short>(11, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadInt16(pos));
AssertWriteRead<int>(12, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadInt32(pos));
AssertWriteRead<long>(13, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadInt64(pos));
AssertWriteRead<sbyte>(14, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadSByte(pos));
AssertWriteRead<float>(15, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadSingle(pos));
AssertWriteRead<ushort>(16, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt16(pos));
AssertWriteRead<uint>(17, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt32(pos));
AssertWriteRead<ulong>(17, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt64(pos));
// Successful reads and writes at the end for each data type
long end = acc.Capacity;
AssertWriteRead<bool>(false, end - sizeof(bool), (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos));
AssertWriteRead<bool>(true, end - sizeof(bool), (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos));
AssertWriteRead<byte>(42, end - sizeof(byte), (pos, value) => acc.Write(pos, value), pos => acc.ReadByte(pos));
AssertWriteRead<char>('c', end - sizeof(char), (pos, value) => acc.Write(pos, value), pos => acc.ReadChar(pos));
AssertWriteRead<decimal>(9, end - sizeof(decimal), (pos, value) => acc.Write(pos, value), pos => acc.ReadDecimal(pos));
AssertWriteRead<double>(10, end - sizeof(double), (pos, value) => acc.Write(pos, value), pos => acc.ReadDouble(pos));
AssertWriteRead<short>(11, end - sizeof(short), (pos, value) => acc.Write(pos, value), pos => acc.ReadInt16(pos));
AssertWriteRead<int>(12, end - sizeof(int), (pos, value) => acc.Write(pos, value), pos => acc.ReadInt32(pos));
AssertWriteRead<long>(13, end - sizeof(long), (pos, value) => acc.Write(pos, value), pos => acc.ReadInt64(pos));
AssertWriteRead<sbyte>(14, end - sizeof(sbyte), (pos, value) => acc.Write(pos, value), pos => acc.ReadSByte(pos));
AssertWriteRead<float>(15, end - sizeof(float), (pos, value) => acc.Write(pos, value), pos => acc.ReadSingle(pos));
AssertWriteRead<ushort>(16, end - sizeof(ushort), (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt16(pos));
AssertWriteRead<uint>(17, end - sizeof(uint), (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt32(pos));
AssertWriteRead<ulong>(17, end - sizeof(ulong), (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt64(pos));
// Failed reads and writes just at the border of the end. This triggers different exception types
// for some types than when we're completely beyond the end.
long beyondEnd = acc.Capacity + 1;
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadBoolean(beyondEnd - sizeof(bool)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadByte(beyondEnd - sizeof(byte)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadSByte(beyondEnd - sizeof(sbyte)));
Assert.Throws<ArgumentException>("position", () => acc.ReadChar(beyondEnd - sizeof(char)));
Assert.Throws<ArgumentException>("position", () => acc.ReadDecimal(beyondEnd - sizeof(decimal)));
Assert.Throws<ArgumentException>("position", () => acc.ReadDouble(beyondEnd - sizeof(double)));
Assert.Throws<ArgumentException>("position", () => acc.ReadInt16(beyondEnd - sizeof(short)));
Assert.Throws<ArgumentException>("position", () => acc.ReadInt32(beyondEnd - sizeof(int)));
Assert.Throws<ArgumentException>("position", () => acc.ReadInt64(beyondEnd - sizeof(long)));
Assert.Throws<ArgumentException>("position", () => acc.ReadSingle(beyondEnd - sizeof(float)));
Assert.Throws<ArgumentException>("position", () => acc.ReadUInt16(beyondEnd - sizeof(ushort)));
Assert.Throws<ArgumentException>("position", () => acc.ReadUInt32(beyondEnd - sizeof(uint)));
Assert.Throws<ArgumentException>("position", () => acc.ReadUInt64(beyondEnd - sizeof(ulong)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(bool), false));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(byte), (byte)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(sbyte), (sbyte)0));
Assert.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(char), 'c'));
Assert.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(decimal), (decimal)0));
Assert.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(double), (double)0));
Assert.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(short), (short)0));
Assert.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(int), (int)0));
Assert.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(long), (long)0));
Assert.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(float), (float)0));
Assert.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(ushort), (ushort)0));
Assert.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(uint), (uint)0));
Assert.Throws<ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(ulong), (ulong)0));
// Failed reads and writes well past the end
beyondEnd = acc.Capacity + 20;
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadBoolean(beyondEnd - sizeof(bool)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadByte(beyondEnd - sizeof(byte)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadSByte(beyondEnd - sizeof(sbyte)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadChar(beyondEnd - sizeof(char)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadDecimal(beyondEnd - sizeof(decimal)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadDouble(beyondEnd - sizeof(double)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadInt16(beyondEnd - sizeof(short)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadInt32(beyondEnd - sizeof(int)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadInt64(beyondEnd - sizeof(long)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadSingle(beyondEnd - sizeof(float)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadUInt16(beyondEnd - sizeof(ushort)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadUInt32(beyondEnd - sizeof(uint)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.ReadUInt64(beyondEnd - sizeof(ulong)));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(bool), false));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(byte), (byte)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(sbyte), (sbyte)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(char), 'c'));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(decimal), (decimal)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(double), (double)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(short), (short)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(int), (int)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(long), (long)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(float), (float)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(ushort), (ushort)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(uint), (uint)0));
Assert.Throws<ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(ulong), (ulong)0));
}
/// <summary>Performs and verifies a read and write against an accessor.</summary>
/// <typeparam name="T">The type of data being read and written.</typeparam>
/// <param name="expected">The data expected to be read.</param>
/// <param name="position">The position of the read and write.</param>
/// <param name="write">The function to perform the write, handed the position at which to write and the value to write.</param>
/// <param name="read">The function to perform the read, handed the position from which to read and returning the read value.</param>
private static void AssertWriteRead<T>(T expected, long position, Action<long, T> write, Func<long, T> read)
{
write(position, expected);
Assert.Equal(expected, read(position));
}
/// <summary>
/// Test to verify that Flush is supported regardless of the accessor's access level
/// </summary>
[Theory]
[InlineData(MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.Write)]
[InlineData(MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite)]
public void FlushSupportedOnBothReadAndWriteAccessors(MemoryMappedFileAccess access)
{
const int Capacity = 256;
foreach (MemoryMappedFile mmf in CreateSampleMaps(Capacity))
{
using (mmf)
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, Capacity, access))
{
acc.Flush();
}
}
}
/// <summary>
/// Test to validate that multiple accessors over the same map share data appropriately.
/// </summary>
[Fact]
public void ViewsShareData()
{
const int MapLength = 256;
foreach (MemoryMappedFile mmf in CreateSampleMaps(MapLength))
{
using (mmf)
{
// Create two views over the same map, and verify that data
// written to one is readable by the other.
using (MemoryMappedViewAccessor acc1 = mmf.CreateViewAccessor())
using (MemoryMappedViewAccessor acc2 = mmf.CreateViewAccessor())
{
for (int i = 0; i < MapLength; i++)
{
acc1.Write(i, (byte)i);
}
acc1.Flush();
for (int i = 0; i < MapLength; i++)
{
Assert.Equal(i, acc2.ReadByte(i));
}
}
// Then verify that after those views have been disposed of,
// we can create another view and still read the same data.
using (MemoryMappedViewAccessor acc3 = mmf.CreateViewAccessor())
{
for (int i = 0; i < MapLength; i++)
{
Assert.Equal(i, acc3.ReadByte(i));
}
}
// Finally, make sure such data is also visible to a stream view
// created subsequently from the same map.
using (MemoryMappedViewStream stream4 = mmf.CreateViewStream())
{
for (int i = 0; i < MapLength; i++)
{
Assert.Equal(i, stream4.ReadByte());
}
}
}
}
}
/// <summary>
/// Test to verify copy-on-write behavior of accessors.
/// </summary>
[Fact]
public void CopyOnWrite()
{
const int MapLength = 256;
foreach (MemoryMappedFile mmf in CreateSampleMaps(MapLength))
{
using (mmf)
{
// Create a normal view, make sure the original data is there, then write some new data.
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, MapLength, MemoryMappedFileAccess.ReadWrite))
{
Assert.Equal(0, acc.ReadInt32(0));
acc.Write(0, 42);
}
// In a CopyOnWrite view, verify the previously written data is there, then write some new data
// and verify it's visible through this view.
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, MapLength, MemoryMappedFileAccess.CopyOnWrite))
{
Assert.Equal(42, acc.ReadInt32(0));
acc.Write(0, 84);
Assert.Equal(84, acc.ReadInt32(0));
}
// Finally, verify that the CopyOnWrite data is not visible to others using the map.
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, MapLength, MemoryMappedFileAccess.Read))
{
Assert.Equal(42, acc.ReadInt32(0));
}
}
}
}
/// <summary>
/// Test to verify that we can dispose of an accessor multiple times.
/// </summary>
[Fact]
public void DisposeMultipleTimes()
{
foreach (MemoryMappedFile mmf in CreateSampleMaps())
{
using (mmf)
{
MemoryMappedViewAccessor acc = mmf.CreateViewAccessor();
acc.Dispose();
acc.Dispose();
}
}
}
/// <summary>
/// Test to verify that a view becomes unusable after it's been disposed.
/// </summary>
[Fact]
public void InvalidAfterDisposal()
{
foreach (MemoryMappedFile mmf in CreateSampleMaps())
{
using (mmf)
{
MemoryMappedViewAccessor acc = mmf.CreateViewAccessor();
SafeMemoryMappedViewHandle handle = acc.SafeMemoryMappedViewHandle;
Assert.False(handle.IsClosed);
acc.Dispose();
Assert.True(handle.IsClosed);
Assert.Throws<ObjectDisposedException>(() => acc.ReadByte(0));
Assert.Throws<ObjectDisposedException>(() => acc.Write(0, (byte)0));
Assert.Throws<ObjectDisposedException>(() => acc.Flush());
}
}
}
/// <summary>
/// Test to verify that we can still use a view after the associated map has been disposed.
/// </summary>
[Fact]
public void UseAfterMMFDisposal()
{
foreach (MemoryMappedFile mmf in CreateSampleMaps(8192))
{
// Create the view, then dispose of the map
MemoryMappedViewAccessor acc;
using (mmf) acc = mmf.CreateViewAccessor();
// Validate we can still use the view
ValidateMemoryMappedViewAccessor(acc, 8192, MemoryMappedFileAccess.ReadWrite);
acc.Dispose();
}
}
/// <summary>
/// Test to allow a map and view to be finalized, just to ensure we don't crash.
/// </summary>
[Fact]
public void AllowFinalization()
{
// Explicitly do not dispose, to allow finalization to happen, just to try to verify
// that nothing fails when it does.
MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, 4096);
MemoryMappedViewAccessor acc = mmf.CreateViewAccessor();
var mmfWeak = new WeakReference<MemoryMappedFile>(mmf);
var accWeak = new WeakReference<MemoryMappedViewAccessor>(acc);
mmf = null;
acc = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Assert.False(mmfWeak.TryGetTarget(out mmf));
Assert.False(accWeak.TryGetTarget(out acc));
}
}
}
| |
using System;
using System.Text;
using System.Net;
using System.IO;
using System.Threading.Tasks;
using System.Collections.Generic;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Widget;
using Android.Provider;
using Android.Net;
using Android.Graphics;
using Android.Telephony;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using PrimusFlex.Mobile.Common;
using Primusflex.Mobile.Common;
using Newtonsoft.Json;
using Primusflex.Mobile.Models;
using Android.Views;
using System.Collections;
namespace Primusflex.Mobile
{
[Activity(Label = "Welcome", Theme = "@style/CustomActionBarTheme")]
public class HomeActivity : Activity
{
// Access Token
string accessToken;
// Kitchen Plot Details
string userName;
string siteName;
string plotNumber;
string picName;
string kitchenModelName;
// Table
TableLayout table;
// Cloud Storage
static CloudStorageAccount storageAccount;
static CloudBlobClient blobClient;
static CloudBlobContainer container;
string sas;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// disable default ActionBar view and set custom view
ActionBar.SetCustomView(Resource.Layout.action_bar);
ActionBar.SetDisplayShowCustomEnabled(true);
LinearLayout history = (LinearLayout)FindViewById(Resource.Id.historyMenu);
history.Click += LoadHistory;
SetContentView(Resource.Layout.Home);
// get access token
accessToken = Intent.GetStringExtra("access_token");
userName = Intent.GetStringExtra("user_name");
//Parse the connection string and return a reference to the storage account.
storageAccount = StorageHelpers.StorageAccount(accessToken);
//Create the blob client object.
blobClient = storageAccount.CreateCloudBlobClient();
//Get a reference to a container to use for the sample code, and create it if it does not exist.
container = blobClient.GetContainerReference(Constant.IMAGE_STORAGE_CONTAINER_NAME);
// Use the shared access signature (SAS) to perform container operations
sas = StorageHelpers.GetContainerSasUri(container);
var updateMenu = FindViewById<LinearLayout>(Resource.Id.updateMenu);
updateMenu.Selected = true;
CheckBox checkBox = FindViewById<CheckBox>(Resource.Id.checkBox1);
checkBox.CheckedChange += CheckBox_CheckedChange;
CameraHelpers.CreateDirectoryForPictures();
Button btnOpenCamera = FindViewById<Button>(Resource.Id.btnOpenCamera);
btnOpenCamera.Click += TakeAPicture;
Button btnRefresh = (Button)FindViewById(Resource.Id.btnRefresh);
btnRefresh.Click += UpdateLastKitchenInfo;
Button btnHistory = FindViewById<Button>(Resource.Id.btnHistory);
btnHistory.Click += LoadHistory;
EditText siteName = FindViewById<EditText>(Resource.Id.site);
siteName.TextChanged += (sender, e) => TryToEnableCameraButton(sender, e);
EditText plotNumber = FindViewById<EditText>(Resource.Id.plot);
plotNumber.TextChanged += (sender, e) => TryToEnableCameraButton(sender, e);
// Set spinners for Sites
IList sitesList = GetSiteList();
Spinner siteSpinner = FindViewById<Spinner>(Resource.Id.siteSpinner);
ArrayAdapter siteAdapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, sitesList);
siteAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
siteSpinner.Adapter = siteAdapter;
siteSpinner.Tag = "siteSpinner";
siteSpinner.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs>(SpinnerItemSelected);
// Set spinner for kitchen models
Spinner kitchenSpinner = FindViewById<Spinner>(Resource.Id.kitchenSpinner);
ArrayAdapter adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, Constant.KITCHEN_MODELS);
adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
kitchenSpinner.Adapter = adapter;
kitchenSpinner.Tag = "kitchenSpinner";
kitchenModelName = Constant.KITCHEN_MODELS[0];
kitchenSpinner.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs>(SpinnerItemSelected);
// Table
table = this.FindViewById<TableLayout>(Resource.Id.tableLayout1);
// TODO: Add last day uploads review
AddLastKitchenInformation(userName);
}
private IList GetSiteList()
{
string uri = Constant.STORAGE_URL + "/GetSiteList";
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
request.Headers.Add("Authorization", "Bearer " + accessToken);
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
var stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
var responseFromServer = reader.ReadToEnd();
return JsonConvert.DeserializeObject<List<string>>(responseFromServer);
}
}
private void CheckBox_CheckedChange(object sender, EventArgs e)
{
Spinner siteSpinner = FindViewById<Spinner>(Resource.Id.siteSpinner);
EditText siteEditText = FindViewById<EditText>(Resource.Id.site);
TextView checkBoxLabel = FindViewById<TextView>(Resource.Id.checkBoxLabel);
var checkBox = sender as CheckBox;
if (checkBox.Checked)
{
//Toast.MakeText(this, "checked", ToastLength.Short).Show();
siteSpinner.Visibility = ViewStates.Gone;
siteEditText.Visibility = ViewStates.Visible;
checkBoxLabel.Text = "Unchecked box to select site name from list.";
}
else
{
//Toast.MakeText(this, "UNchecked", ToastLength.Short).Show();
siteEditText.Visibility = ViewStates.Gone;
siteSpinner.Visibility = ViewStates.Visible;
checkBoxLabel.Text = "Site is not i the list.";
}
}
private void LoadHistory(object sender, EventArgs e)
{
Intent history = new Intent(this, typeof(HistoryActivity));
history.PutExtra("access_token", accessToken);
history.PutExtra("user_name", userName);
StartActivity(history);
}
private void UpdateLastKitchenInfo(Object sender, EventArgs args)
{
table.RemoveAllViews();
AddLastKitchenInformation(userName);
}
private void AddLastKitchenInformation(string userName)
{
var lastKitchenInfo = GetLastDayKitchenInfo(userName);
if (lastKitchenInfo != null)
{
TableLayout.LayoutParams layoutParameters = new TableLayout.LayoutParams(
TableLayout.LayoutParams.MatchParent, TableLayout.LayoutParams.WrapContent);
layoutParameters.SetMargins(5, 5, 5, 5);
layoutParameters.Weight = 1;
SetTableHeader(layoutParameters);
foreach (var lki in lastKitchenInfo)
{
TableRow tr = new TableRow(this);
tr.LayoutParameters = layoutParameters;
TextView site = new TextView(this);
site.Text = lki.SiteName;
tr.AddView(site);
TextView space1 = new TextView(this);
space1.Text = " ";
tr.AddView(space1);
TextView plotNo = new TextView(this);
plotNo.Text = lki.PlotNumber;
tr.AddView(plotNo);
TextView space2 = new TextView(this);
space2.Text = " ";
tr.AddView(space2);
TextView kitchenModel = new TextView(this);
kitchenModel.Text = lki.KitchenModel.ToString();
tr.AddView(kitchenModel);
TextView space3 = new TextView(this);
space3.Text = " ";
tr.AddView(space3);
TextView imgNo = new TextView(this);
imgNo.Text = lki.ImageNumber.ToString() + (lki.ImageNumber == 1 ? "pic" : "pics");
tr.AddView(imgNo);
table.AddView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.MatchParent,
TableLayout.LayoutParams.WrapContent));
}
// getting last kitchen images
HttpWebRequest request = WebRequest.Create(Constant.STORAGE_URL + "/lastKitchenImages") as HttpWebRequest;
request.Headers.Add("Authorization", "Bearer " + accessToken);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
var responseFromServer = reader.ReadToEnd();
List<ImageViewModel> images = JsonConvert.DeserializeObject<List<ImageViewModel>>(responseFromServer);
CloudStorageAccount account = StorageHelpers.StorageAccount(accessToken);
CloudBlobClient blobClient = account.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(Constant.IMAGE_STORAGE_CONTAINER_NAME);
Bitmap[] bitmaps = new Bitmap[images.Count];
int position = 0;
foreach (var image in images)
{
using (MemoryStream ms = new MemoryStream())
{
CloudBlockBlob blockBlob = container.GetBlockBlobReference(image.Name);
blockBlob.DownloadToStream(ms);
byte[] data = ms.ToArray();
bitmaps[position] = BitmapHelpers.DecodeSampledBitmapFromByteArray(data, 100, 100);
}
position++;
}
var gridView = FindViewById<GridView>(Resource.Id.gridView1);
gridView.Adapter = new ImageAdapter(this, bitmaps);
}
}
}
private void SetTableHeader(TableLayout.LayoutParams layoutParameters)
{
TableRow tr = new TableRow(this);
tr.LayoutParameters = layoutParameters;
TextView site = new TextView(this);
site.SetTypeface(null, TypefaceStyle.Bold);
site.Text = "Site";
tr.AddView(site);
TextView space1 = new TextView(this);
space1.Text = " ";
tr.AddView(space1);
TextView plotNo = new TextView(this);
plotNo.SetTypeface(null, TypefaceStyle.Bold);
plotNo.Text = "Plot";
tr.AddView(plotNo);
TextView space2 = new TextView(this);
space2.Text = " ";
tr.AddView(space2);
TextView kitchenModel = new TextView(this);
kitchenModel.SetTypeface(null, TypefaceStyle.Bold);
kitchenModel.Text = "Kitchen";
tr.AddView(kitchenModel);
TextView space3 = new TextView(this);
space3.Text = " ";
tr.AddView(space3);
TextView imgNo = new TextView(this);
imgNo.SetTypeface(null, TypefaceStyle.Bold);
imgNo.Text = "Pics";
tr.AddView(imgNo);
table.AddView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.MatchParent,
TableLayout.LayoutParams.WrapContent));
}
private List<KitchenInfoModel> GetLastDayKitchenInfo(string username)
{
string uri = Constant.STORAGE_URL + "/lastkitcheninfo?username=" + username;
WebRequest request = WebRequest.Create(uri);
request.Headers.Add("Authorization", "Bearer " + accessToken);
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if(response.StatusCode == HttpStatusCode.OK)
{
var responseFromServer = new StreamReader(response.GetResponseStream()).ReadToEnd();
var resultAsObject = JsonConvert.DeserializeObject<List<KitchenInfoModel>>(responseFromServer);
return resultAsObject;
}
}
return null;
}
private void SpinnerItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
{
Spinner spinner = (Spinner) sender;
switch ((string)spinner.Tag)
{
case "siteSpinner":
Toast.MakeText(this, "site", ToastLength.Short).Show();
break;
case "kitchenSpinner":
kitchenModelName = spinner.GetItemAtPosition(e.Position).ToString();
Toast.MakeText(this, "kitchen", ToastLength.Short).Show();
break;
default:
break;
}
}
public override void OnBackPressed()
{
// Do nothing
}
private void TryToEnableCameraButton(object sender, EventArgs e)
{
bool enableCameraButton = true;
Button cameraButton = FindViewById<Button>(Resource.Id.btnOpenCamera);
LinearLayout layoutPictureInfo = FindViewById<LinearLayout>(Resource.Id.layoutPictureInfo);
for (int i = 0; i < layoutPictureInfo.ChildCount; i++)
{
var childView = layoutPictureInfo.GetChildAt(i);
if (childView is EditText)
{
EditText childViewAsEditText = (EditText)childView;
if (string.IsNullOrEmpty(childViewAsEditText.Text) ||
string.IsNullOrWhiteSpace(childViewAsEditText.Text))
{
enableCameraButton = false;
break;
}
}
}
FindViewById<Button>(Resource.Id.btnOpenCamera).Enabled = enableCameraButton;
cameraButton.Alpha = enableCameraButton ? 1 : Constant.BUTTON_ALPHA;
}
private void TakeAPicture(object sender, EventArgs e)
{
// Collect plot details
siteName = FindViewById<EditText>(Resource.Id.site).Text;
plotNumber = FindViewById<EditText>(Resource.Id.plot).Text;
picName = String.Format("img_{0}.jpg", DateTime.Now.ToString("yyyyMMddHHmmss"));
Intent intent = new Intent(MediaStore.ActionImageCapture);
App.File = new Java.IO.File(App.Dir,picName);
intent.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(App.File));
StartActivityForResult(intent, 0);
}
protected override async void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (resultCode == Result.Ok)
{
// Detect if there is network connection
ConnectivityManager connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);
NetworkInfo activeConnection = connectivityManager.ActiveNetworkInfo;
bool isOnline = (activeConnection != null) && activeConnection.IsConnected;
if (isOnline)
{
// save imige information in azure sql database
SaveImage(Intent.GetStringExtra("user_name") , siteName, plotNumber, picName, kitchenModelName);
// upload image from camera to azure blob storage
App.Bitmap = App.File.Path.LoadBitmap();
await UploadPhoto(sas);
// delete picture from gallery
// TODO: delete does not work correctly!
if (App.File.Exists())
{
App.File.Delete();
}
}
else
{
// Make it available in the gallery
Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
Android.Net.Uri contentUri = Android.Net.Uri.FromFile(App.File);
mediaScanIntent.SetData(contentUri);
SendBroadcast(mediaScanIntent);
}
}
}
private void SaveImage(string userName, string siteName, string plotNumber, string picName, string kitchenModelName)
{
System.Uri uri = new System.Uri(Constant.STORAGE_URL + "/saveimage");
string postData = string.Format("UserName={0}&SiteName={1}&PlotNumber={2}&ImageName={3}&KitchenModel={4}", userName, siteName, plotNumber, picName, kitchenModelName);
try
{
using (WebClient wc = new WebClient())
{
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.Headers.Add("Authorization", "Bearer " + accessToken);
wc.UploadString(uri, "POST", postData);
}
}
catch(WebException e)
{
var errorMessage = (new StreamReader(e.Response.GetResponseStream())).ReadToEnd();
}
}
private async Task UploadPhoto(string sas)
{
try
{
//Write operation: write a new blob to the container.
CloudBlockBlob blob = container.GetBlockBlobReference(App.File.Name);
//await blob.UploadFromFileAsync(App.File.Path);
using (var stream = new MemoryStream())
{
App.Bitmap.Compress(Bitmap.CompressFormat.Jpeg, Constant.IMAGE_QUALITY, stream);
var bitmapBytes = stream.ToArray();
await blob.UploadFromByteArrayAsync(bitmapBytes, 0, bitmapBytes.Length);
}
}
catch (Exception e)
{
// TODO:
}
}
}
}
| |
// 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.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.WebSockets.Client.Tests
{
/// <summary>
/// ClientWebSocket unit tests that do not require a remote server.
/// </summary>
public class ClientWebSocketUnitTest
{
private readonly ITestOutputHelper _output;
public ClientWebSocketUnitTest(ITestOutputHelper output)
{
_output = output;
}
private static bool WebSocketsSupported { get { return WebSocketHelper.WebSocketsSupported; } }
[ConditionalFact(nameof(WebSocketsSupported))]
public void Ctor_Success()
{
var cws = new ClientWebSocket();
cws.Dispose();
}
[ConditionalFact(nameof(WebSocketsSupported))]
public void Abort_CreateAndAbort_StateIsClosed()
{
using (var cws = new ClientWebSocket())
{
cws.Abort();
Assert.Equal(WebSocketState.Closed, cws.State);
}
}
[ConditionalFact(nameof(WebSocketsSupported))]
public void CloseAsync_CreateAndClose_ThrowsInvalidOperationException()
{
using (var cws = new ClientWebSocket())
{
Assert.Throws<InvalidOperationException>(() =>
{ Task t = cws.CloseAsync(WebSocketCloseStatus.Empty, "", new CancellationToken()); });
Assert.Equal(WebSocketState.None, cws.State);
}
}
[ConditionalFact(nameof(WebSocketsSupported))]
public void CloseAsync_CreateAndCloseOutput_ThrowsInvalidOperationExceptionWithMessage()
{
using (var cws = new ClientWebSocket())
{
AssertExtensions.Throws<InvalidOperationException>(
() =>
cws.CloseOutputAsync(WebSocketCloseStatus.Empty, "", new CancellationToken()).GetAwaiter().GetResult(),
ResourceHelper.GetExceptionMessage("net_WebSockets_NotConnected"));
Assert.Equal(WebSocketState.None, cws.State);
}
}
[ConditionalFact(nameof(WebSocketsSupported))]
public void CloseAsync_CreateAndReceive_ThrowsInvalidOperationException()
{
using (var cws = new ClientWebSocket())
{
var buffer = new byte[100];
var segment = new ArraySegment<byte>(buffer);
var ct = new CancellationToken();
Assert.Throws<InvalidOperationException>(() =>
{ Task t = cws.ReceiveAsync(segment, ct); });
Assert.Equal(WebSocketState.None, cws.State);
}
}
[ConditionalFact(nameof(WebSocketsSupported))]
public void CloseAsync_CreateAndReceive_ThrowsInvalidOperationExceptionWithMessage()
{
using (var cws = new ClientWebSocket())
{
var buffer = new byte[100];
var segment = new ArraySegment<byte>(buffer);
var ct = new CancellationToken();
AssertExtensions.Throws<InvalidOperationException>(
() => cws.ReceiveAsync(segment, ct).GetAwaiter().GetResult(),
ResourceHelper.GetExceptionMessage("net_WebSockets_NotConnected"));
Assert.Equal(WebSocketState.None, cws.State);
}
}
[ConditionalFact(nameof(WebSocketsSupported))]
public void CloseAsync_CreateAndSend_ThrowsInvalidOperationException()
{
using (var cws = new ClientWebSocket())
{
var buffer = new byte[100];
var segment = new ArraySegment<byte>(buffer);
var ct = new CancellationToken();
Assert.Throws<InvalidOperationException>(() =>
{ Task t = cws.SendAsync(segment, WebSocketMessageType.Text, false, ct); });
Assert.Equal(WebSocketState.None, cws.State);
}
}
[ConditionalFact(nameof(WebSocketsSupported))]
public void CloseAsync_CreateAndSend_ThrowsInvalidOperationExceptionWithMessage()
{
using (var cws = new ClientWebSocket())
{
var buffer = new byte[100];
var segment = new ArraySegment<byte>(buffer);
var ct = new CancellationToken();
AssertExtensions.Throws<InvalidOperationException>(
() => cws.SendAsync(segment, WebSocketMessageType.Text, false, ct).GetAwaiter().GetResult(),
ResourceHelper.GetExceptionMessage("net_WebSockets_NotConnected"));
Assert.Equal(WebSocketState.None, cws.State);
}
}
[ConditionalFact(nameof(WebSocketsSupported))]
public void Ctor_ExpectedPropertyValues()
{
using (var cws = new ClientWebSocket())
{
Assert.Equal(null, cws.CloseStatus);
Assert.Equal(null, cws.CloseStatusDescription);
Assert.NotEqual(null, cws.Options);
Assert.Equal(WebSocketState.None, cws.State);
Assert.Equal(null, cws.SubProtocol);
Assert.Equal("System.Net.WebSockets.ClientWebSocket", cws.ToString());
}
}
[ConditionalFact(nameof(WebSocketsSupported))]
public void Abort_CreateAndDisposeAndAbort_StateIsClosedSuccess()
{
var cws = new ClientWebSocket();
cws.Dispose();
cws.Abort();
Assert.Equal(WebSocketState.Closed, cws.State);
}
[ConditionalFact(nameof(WebSocketsSupported))]
public void CloseAsync_DisposeAndClose_ThrowsObjectDisposedException()
{
var cws = new ClientWebSocket();
cws.Dispose();
Assert.Throws<ObjectDisposedException>(() =>
{ Task t = cws.CloseAsync(WebSocketCloseStatus.Empty, "", new CancellationToken()); });
Assert.Equal(WebSocketState.Closed, cws.State);
}
[ConditionalFact(nameof(WebSocketsSupported))]
public void CloseAsync_DisposeAndCloseOutput_ThrowsObjectDisposedExceptionWithMessage()
{
var cws = new ClientWebSocket();
cws.Dispose();
var expectedException = new ObjectDisposedException(cws.GetType().FullName);
AssertExtensions.Throws<ObjectDisposedException>(
() =>
cws.CloseOutputAsync(WebSocketCloseStatus.Empty, "", new CancellationToken()).GetAwaiter().GetResult(),
expectedException.Message);
Assert.Equal(WebSocketState.Closed, cws.State);
}
[ConditionalFact(nameof(WebSocketsSupported))]
public void ReceiveAsync_CreateAndDisposeAndReceive_ThrowsObjectDisposedExceptionWithMessage()
{
var cws = new ClientWebSocket();
cws.Dispose();
var buffer = new byte[100];
var segment = new ArraySegment<byte>(buffer);
var ct = new CancellationToken();
var expectedException = new ObjectDisposedException(cws.GetType().FullName);
AssertExtensions.Throws<ObjectDisposedException>(
() => cws.ReceiveAsync(segment, ct).GetAwaiter().GetResult(),
expectedException.Message);
Assert.Equal(WebSocketState.Closed, cws.State);
}
[ConditionalFact(nameof(WebSocketsSupported))]
public void SendAsync_CreateAndDisposeAndSend_ThrowsObjectDisposedExceptionWithMessage()
{
var cws = new ClientWebSocket();
cws.Dispose();
var buffer = new byte[100];
var segment = new ArraySegment<byte>(buffer);
var ct = new CancellationToken();
var expectedException = new ObjectDisposedException(cws.GetType().FullName);
AssertExtensions.Throws<ObjectDisposedException>(
() => cws.SendAsync(segment, WebSocketMessageType.Text, false, ct).GetAwaiter().GetResult(),
expectedException.Message);
Assert.Equal(WebSocketState.Closed, cws.State);
}
[ConditionalFact(nameof(WebSocketsSupported))]
public void Dispose_CreateAndDispose_ExpectedPropertyValues()
{
var cws = new ClientWebSocket();
cws.Dispose();
Assert.Equal(null, cws.CloseStatus);
Assert.Equal(null, cws.CloseStatusDescription);
Assert.NotEqual(null, cws.Options);
Assert.Equal(WebSocketState.Closed, cws.State);
Assert.Equal(null, cws.SubProtocol);
Assert.Equal("System.Net.WebSockets.ClientWebSocket", cws.ToString());
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Encog.ML.EA.Exceptions;
using Encog.ML.EA.Genome;
using Encog.ML.EA.Population;
using Encog.ML.EA.Species;
using Encog.ML.Prg.ExpValue;
using Encog.ML.Prg.Ext;
using Encog.ML.Prg.Train;
using Encog.MathUtil.Randomize;
using Encog.MathUtil.Randomize.Factory;
using Encog.Neural.Networks.Training;
using Encog.Util.Concurrency;
namespace Encog.ML.Prg.Generator
{
/// <summary>
/// The abstract base for Full and Grow program generation.
/// </summary>
public abstract class AbstractPrgGenerator : IPrgGenerator, IMultiThreadable
{
/// <summary>
/// The contents of this population, stored in rendered form. This prevents
/// duplicates.
/// </summary>
private readonly HashSet<String> _contents = new HashSet<String>();
/// <summary>
/// The program context to use.
/// </summary>
private readonly EncogProgramContext _context;
/// <summary>
/// True, if the program has enums.
/// </summary>
private readonly bool _hasEnum;
/// <summary>
/// The maximum depth to generate to.
/// </summary>
private readonly int _maxDepth;
/// <summary>
/// Construct the generator.
/// </summary>
/// <param name="theContext">The context that is to be used for generation.</param>
/// <param name="theMaxDepth">The maximum depth to generate to.</param>
protected AbstractPrgGenerator(EncogProgramContext theContext,
int theMaxDepth)
{
if (theContext.Functions.Count == 0)
{
throw new EncogError("There are no opcodes defined");
}
_context = theContext;
_maxDepth = theMaxDepth;
_hasEnum = _context.HasEnum;
Score = new ZeroEvalScoreFunction();
MinConst = -10;
MaxConst = 10;
RandomFactory = EncogFramework.Instance.RandomFactory.FactorFactory();
MaxGenerationErrors = 500;
}
/// <summary>
/// An optional scoring function.
/// </summary>
public ICalculateScore Score { get; set; }
/// <summary>
/// The minimum const to generate.
/// </summary>
public double MinConst { get; set; }
/// <summary>
/// The maximum const to generate.
/// </summary>
public double MaxConst { get; set; }
/// <summary>
/// A random number generator factory.
/// </summary>
public IRandomFactory RandomFactory { get; set; }
/// <summary>
/// The context.
/// </summary>
public EncogProgramContext Context
{
get { return _context; }
}
/// <summary>
/// The max depth.
/// </summary>
public int MaxDepth
{
get { return _maxDepth; }
}
/// <summary>
/// Do we have enums?
/// </summary>
public bool HasEnum
{
get { return _hasEnum; }
}
/// <summary>
/// The number of threads to use.
/// </summary>
public int ThreadCount { get; set; }
/// <summary>
/// The maximum number of allowed generation errors.
/// </summary>
public int MaxGenerationErrors { get; set; }
/// <inheritdoc />
public IGenome Generate(EncogRandom rnd)
{
var program = new EncogProgram(_context);
IList<EPLValueType> types = new List<EPLValueType>();
types.Add(_context.Result.VariableType);
program.RootNode = CreateNode(rnd, program, DetermineMaxDepth(rnd),
types);
return program;
}
/// <inheritdoc />
public void Generate(EncogRandom rnd, IPopulation pop)
{
// prepare population
_contents.Clear();
pop.Species.Clear();
ISpecies defaultSpecies = pop.CreateSpecies();
if (Score.RequireSingleThreaded || ThreadCount == 1)
{
for (int i = 0; i < pop.PopulationSize; i++)
{
EncogProgram prg = AttemptCreateGenome(rnd, pop);
AddPopulationMember(pop, prg);
}
}
else
{
Parallel.For(0, pop.PopulationSize, i =>
{
EncogProgram prg = AttemptCreateGenome(rnd, pop);
AddPopulationMember(pop, prg);
});
}
// just pick a leader, for the default species.
defaultSpecies.Leader = defaultSpecies.Members[0];
}
/// <inheritdoc />
public abstract ProgramNode CreateNode(EncogRandom rnd, EncogProgram program, int depthRemaining,
IList<EPLValueType> types);
/// <summary>
/// Add a population member from one of the threads.
/// </summary>
/// <param name="population">The population to add to.</param>
/// <param name="prg">The program to add.</param>
public void AddPopulationMember(IPopulation population,
EncogProgram prg)
{
lock (this)
{
ISpecies defaultSpecies = population.Species[0];
prg.Species = defaultSpecies;
defaultSpecies.Add(prg);
_contents.Add(prg.DumpAsCommonExpression());
}
}
/// <summary>
/// Attempt to create a genome. Cycle the specified number of times if an
/// error occurs.
/// </summary>
/// <param name="rnd">The random number generator.</param>
/// <param name="pop">The population.</param>
/// <returns>The generated genome.</returns>
public EncogProgram AttemptCreateGenome(EncogRandom rnd,
IPopulation pop)
{
bool done = false;
EncogProgram result = null;
int tries = MaxGenerationErrors;
while (!done)
{
result = (EncogProgram) Generate(rnd);
result.Population = pop;
double s;
try
{
tries--;
s = Score.CalculateScore(result);
}
catch (EARuntimeError)
{
s = double.NaN;
}
if (tries < 0)
{
throw new EncogError("Could not generate a valid genome after "
+ MaxGenerationErrors + " tries.");
}
if (!Double.IsNaN(s) && !Double.IsInfinity(s)
&& !_contents.Contains(result.DumpAsCommonExpression()))
{
done = true;
}
}
return result;
}
/// <summary>
/// Create a random note according to the specified paramaters.
/// </summary>
/// <param name="rnd">A random number generator.</param>
/// <param name="program">The program to generate for.</param>
/// <param name="depthRemaining">The depth remaining to generate.</param>
/// <param name="types">The types to generate.</param>
/// <param name="includeTerminal">Should we include terminal nodes.</param>
/// <param name="includeFunction">Should we include function nodes.</param>
/// <returns>The generated program node.</returns>
public ProgramNode CreateRandomNode(EncogRandom rnd,
EncogProgram program, int depthRemaining,
IList<EPLValueType> types, bool includeTerminal,
bool includeFunction)
{
// if we've hit the max depth, then create a terminal nodes, so it stops
// here
if (depthRemaining == 0)
{
return CreateTerminalNode(rnd, program, types);
}
// choose which opcode set we might create the node from
IList<IProgramExtensionTemplate> opcodeSet = Context.Functions.FindOpcodes(types, Context,
includeTerminal, includeFunction);
// choose a random opcode
IProgramExtensionTemplate temp = GenerateRandomOpcode(rnd,
opcodeSet);
if (temp == null)
{
throw new EACompileError(
"Trying to generate a random opcode when no opcodes exist.");
}
// create the child nodes
int childNodeCount = temp.ChildNodeCount;
var children = new ProgramNode[childNodeCount];
if (EncogOpcodeRegistry.IsOperator(temp.NodeType) && children.Length >= 2)
{
// for an operator of size 2 or greater make sure all children are
// the same time
IList<EPLValueType> childTypes = temp.Params[0]
.DetermineArgumentTypes(types);
EPLValueType selectedType = childTypes[rnd
.Next(childTypes.Count)];
childTypes.Clear();
childTypes.Add(selectedType);
// now create the children of a common type
for (int i = 0; i < children.Length; i++)
{
children[i] = CreateNode(rnd, program, depthRemaining - 1,
childTypes);
}
}
else
{
// otherwise, let the children have their own types
for (int i = 0; i < children.Length; i++)
{
IList<EPLValueType> childTypes = temp.Params[i]
.DetermineArgumentTypes(types);
children[i] = CreateNode(rnd, program, depthRemaining - 1,
childTypes);
}
}
// now actually create the node
var result = new ProgramNode(program, temp, children);
temp.Randomize(rnd, types, result, MinConst, MaxConst);
return result;
}
/// <summary>
/// Create a terminal node.
/// </summary>
/// <param name="rnd">A random number generator.</param>
/// <param name="program">The program to generate for.</param>
/// <param name="types">The types that we might generate.</param>
/// <returns>The terminal program node.</returns>
public ProgramNode CreateTerminalNode(EncogRandom rnd,
EncogProgram program, IList<EPLValueType> types)
{
IProgramExtensionTemplate temp = GenerateRandomOpcode(
rnd,
Context.Functions.FindOpcodes(types, _context,
true, false));
if (temp == null)
{
throw new EACompileError("No opcodes exist for the type: "
+ types);
}
var result = new ProgramNode(program, temp,
new ProgramNode[] {});
temp.Randomize(rnd, types, result, MinConst, MaxConst);
return result;
}
/// <summary>
/// Determine the max depth.
/// </summary>
/// <param name="rnd">Random number generator.</param>
/// <returns>The max depth.</returns>
public virtual int DetermineMaxDepth(EncogRandom rnd)
{
return _maxDepth;
}
/// <summary>
/// Generate a random opcode.
/// </summary>
/// <param name="rnd">Random number generator.</param>
/// <param name="opcodes">The opcodes to choose from.</param>
/// <returns>The selected opcode.</returns>
public IProgramExtensionTemplate GenerateRandomOpcode(EncogRandom rnd,
IList<IProgramExtensionTemplate> opcodes)
{
int maxOpCode = opcodes.Count;
if (maxOpCode == 0)
{
return null;
}
int tries = 10000;
IProgramExtensionTemplate result = null;
while (result == null)
{
int opcode = rnd.Next(maxOpCode);
result = opcodes[opcode];
tries--;
if (tries < 0)
{
throw new EACompileError(
"Could not generate an opcode. Make sure you have valid opcodes defined.");
}
}
return result;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Utils.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.DataMovement
{
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.File;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
/// <summary>
/// Class for various utils.
/// </summary>
internal static class Utils
{
private const int RequireBufferMaxRetryCount = 10;
/// <summary>
/// Define the various possible size postfixes.
/// </summary>
private static readonly string[] SizeFormats =
{
Resources.ReadableSizeFormatBytes,
Resources.ReadableSizeFormatKiloBytes,
Resources.ReadableSizeFormatMegaBytes,
Resources.ReadableSizeFormatGigaBytes,
Resources.ReadableSizeFormatTeraBytes,
Resources.ReadableSizeFormatPetaBytes,
Resources.ReadableSizeFormatExaBytes
};
/// <summary>
/// Translate a size in bytes to human readable form.
/// </summary>
/// <param name="size">Size in bytes.</param>
/// <returns>Human readable form string.</returns>
public static string BytesToHumanReadableSize(double size)
{
int order = 0;
while (size >= 1024 && order + 1 < SizeFormats.Length)
{
++order;
size /= 1024;
}
return string.Format(CultureInfo.CurrentCulture, SizeFormats[order], size);
}
public static void CheckCancellation(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
throw new OperationCanceledException(Resources.TransferCancelledException);
}
}
/// <summary>
/// Generate an AccessCondition instance of IfMatchETag with customer condition.
/// For download/copy, if it succeeded at the first operation to fetching attribute with customer condition,
/// it means that the blob totally meet the condition.
/// Here, only need to keep LeaseId in the customer condition for the following operations.
/// </summary>
/// <param name="etag">ETag string.</param>
/// <param name="customCondition">Condition customer input in TransferLocation.</param>
/// <param name="checkedCustomAC">To specify whether have already verified the custom access condition against the blob.</param>
/// <returns>AccessCondition instance of IfMatchETag with customer condition's LeaseId.</returns>
public static AccessCondition GenerateIfMatchConditionWithCustomerCondition(
string etag,
AccessCondition customCondition,
bool checkedCustomAC = true)
{
if (!checkedCustomAC)
{
return customCondition;
}
AccessCondition accessCondition = AccessCondition.GenerateIfMatchCondition(etag);
if (null != customCondition)
{
accessCondition.LeaseId = customCondition.LeaseId;
}
return accessCondition;
}
public static bool DictionaryEquals(
this IDictionary<string, string> firstDic, IDictionary<string, string> secondDic)
{
if (firstDic == secondDic)
{
return true;
}
if (firstDic == null || secondDic == null)
{
return false;
}
if (firstDic.Count != secondDic.Count)
{
return false;
}
foreach (var pair in firstDic)
{
string secondValue;
if (!secondDic.TryGetValue(pair.Key, out secondValue))
{
return false;
}
if (!string.Equals(pair.Value, secondValue, StringComparison.Ordinal))
{
return false;
}
}
return true;
}
public static Attributes GenerateAttributes(CloudBlob blob)
{
return new Attributes()
{
CacheControl = blob.Properties.CacheControl,
ContentDisposition = blob.Properties.ContentDisposition,
ContentEncoding = blob.Properties.ContentEncoding,
ContentLanguage = blob.Properties.ContentLanguage,
ContentMD5 = blob.Properties.ContentMD5,
ContentType = blob.Properties.ContentType,
Metadata = blob.Metadata,
OverWriteAll = true
};
}
public static Attributes GenerateAttributes(CloudFile file)
{
return new Attributes()
{
CacheControl = file.Properties.CacheControl,
ContentDisposition = file.Properties.ContentDisposition,
ContentEncoding = file.Properties.ContentEncoding,
ContentLanguage = file.Properties.ContentLanguage,
ContentMD5 = file.Properties.ContentMD5,
ContentType = file.Properties.ContentType,
Metadata = file.Metadata,
OverWriteAll = true
};
}
public static void SetAttributes(CloudBlob blob, Attributes attributes)
{
if (attributes.OverWriteAll)
{
blob.Properties.CacheControl = attributes.CacheControl;
blob.Properties.ContentDisposition = attributes.ContentDisposition;
blob.Properties.ContentEncoding = attributes.ContentEncoding;
blob.Properties.ContentLanguage = attributes.ContentLanguage;
blob.Properties.ContentMD5 = attributes.ContentMD5;
blob.Properties.ContentType = attributes.ContentType;
blob.Metadata.Clear();
foreach (var metadataPair in attributes.Metadata)
{
blob.Metadata.Add(metadataPair);
}
}
else
{
blob.Properties.ContentMD5 = attributes.ContentMD5;
if (null != attributes.ContentType)
{
blob.Properties.ContentType = attributes.ContentType;
}
}
}
public static void SetAttributes(CloudFile file, Attributes attributes)
{
if (attributes.OverWriteAll)
{
file.Properties.CacheControl = attributes.CacheControl;
file.Properties.ContentDisposition = attributes.ContentDisposition;
file.Properties.ContentEncoding = attributes.ContentEncoding;
file.Properties.ContentLanguage = attributes.ContentLanguage;
file.Properties.ContentMD5 = attributes.ContentMD5;
file.Properties.ContentType = attributes.ContentType;
file.Metadata.Clear();
foreach (var metadataPair in attributes.Metadata)
{
file.Metadata.Add(metadataPair);
}
}
else
{
file.Properties.ContentMD5 = attributes.ContentMD5;
if (null != attributes.ContentType)
{
file.Properties.ContentType = attributes.ContentType;
}
}
}
public static bool CompareProperties(Attributes first, Attributes second)
{
return string.Equals(first.CacheControl, second.CacheControl)
&& string.Equals(first.ContentDisposition, second.ContentDisposition)
&& string.Equals(first.ContentEncoding, second.ContentEncoding)
&& string.Equals(first.ContentLanguage, second.ContentLanguage)
&& string.Equals(first.ContentMD5, second.ContentMD5)
&& string.Equals(first.ContentType, second.ContentType);
}
/// <summary>
/// Generate an AccessCondition instance with lease id customer condition.
/// For upload/copy, if it succeeded at the first operation to fetching destination attribute with customer condition,
/// it means that the blob totally meet the condition.
/// Here, only need to keep LeaseId in the customer condition for the following operations.
/// </summary>
/// <param name="customCondition">Condition customer input in TransferLocation.</param>
/// <param name="checkedCustomAC">To specify whether have already verified the custom access condition against the blob.</param>
/// <returns>AccessCondition instance with customer condition's LeaseId.</returns>
public static AccessCondition GenerateConditionWithCustomerCondition(
AccessCondition customCondition,
bool checkedCustomAC = true)
{
if (!checkedCustomAC)
{
return customCondition;
}
if ((null != customCondition)
&& !string.IsNullOrEmpty(customCondition.LeaseId))
{
return AccessCondition.GenerateLeaseCondition(customCondition.LeaseId);
}
return null;
}
/// <summary>
/// Generate a BlobRequestOptions with custom BlobRequestOptions.
/// We have default MaximumExecutionTime, ServerTimeout and RetryPolicy.
/// If user doesn't set these properties, we should use the default ones.
/// Others, we should the custom ones.
/// </summary>
/// <param name="customRequestOptions">BlobRequestOptions customer input in TransferLocation.</param>
/// <param name="isCreationRequest">Indicate whether to generate request options for a CREATE requestion which requires shorter server timeout. </param>
/// <returns>BlobRequestOptions instance with custom BlobRequestOptions properties.</returns>
public static BlobRequestOptions GenerateBlobRequestOptions(
BlobRequestOptions customRequestOptions, bool isCreationRequest = false)
{
var requestOptions = Transfer_RequestOptions.DefaultBlobRequestOptions;
if (isCreationRequest)
{
requestOptions.ServerTimeout = Transfer_RequestOptions.DefaultCreationServerTimeout;
}
if (null != customRequestOptions)
{
AssignToRequestOptions(requestOptions, customRequestOptions);
if (null != customRequestOptions.UseTransactionalMD5)
{
requestOptions.UseTransactionalMD5 = customRequestOptions.UseTransactionalMD5;
}
requestOptions.DisableContentMD5Validation = customRequestOptions.DisableContentMD5Validation;
}
return requestOptions;
}
/// <summary>
/// Generate a FileRequestOptions with custom FileRequestOptions.
/// We have default MaximumExecutionTime, ServerTimeout and RetryPolicy.
/// If user doesn't set these properties, we should use the default ones.
/// Others, we should the custom ones.
/// </summary>
/// <param name="customRequestOptions">FileRequestOptions customer input in TransferLocation.</param>
/// <param name="isCreationRequest">Indicate whether to generate request options for a CREATE requestion which requires shorter server timeout. </param>
/// <returns>FileRequestOptions instance with custom FileRequestOptions properties.</returns>
public static FileRequestOptions GenerateFileRequestOptions(
FileRequestOptions customRequestOptions, bool isCreationRequest = false)
{
var requestOptions = Transfer_RequestOptions.DefaultFileRequestOptions;
if (isCreationRequest)
{
requestOptions.ServerTimeout = Transfer_RequestOptions.DefaultCreationServerTimeout;
}
if (null != customRequestOptions)
{
AssignToRequestOptions(requestOptions, customRequestOptions);
if (null != customRequestOptions.UseTransactionalMD5)
{
requestOptions.UseTransactionalMD5 = customRequestOptions.UseTransactionalMD5;
}
requestOptions.DisableContentMD5Validation = customRequestOptions.DisableContentMD5Validation;
}
return requestOptions;
}
/// <summary>
/// Generate an OperationContext from the the specified TransferContext.
/// </summary>
/// <param name="transferContext">Transfer context</param>
/// <returns>An <see cref="OperationContext"/> object.</returns>
public static OperationContext GenerateOperationContext(
TransferContext transferContext)
{
if (transferContext == null)
{
return null;
}
OperationContext operationContext = new OperationContext()
{
LogLevel = transferContext.LogLevel
};
if (transferContext.ClientRequestId != null)
{
operationContext.ClientRequestID = transferContext.ClientRequestId;
}
return operationContext;
}
public static CloudBlob GetBlobReference(Uri blobUri, StorageCredentials credentials, BlobType blobType)
{
switch (blobType)
{
case BlobType.BlockBlob:
return new CloudBlockBlob(blobUri, credentials);
case BlobType.PageBlob:
return new CloudPageBlob(blobUri, credentials);
case BlobType.AppendBlob:
return new CloudAppendBlob(blobUri, credentials);
default:
throw new InvalidOperationException(
string.Format(
CultureInfo.CurrentCulture,
Resources.NotSupportedBlobType,
blobType));
}
}
public static string GetExceptionMessage(this Exception ex)
{
if (ex == null)
{
throw new ArgumentNullException("ex");
}
string exceptionMessage;
#if DEBUG
exceptionMessage = ex.ToString();
#else
var storageEx = ex as StorageException;
if (storageEx != null)
{
exceptionMessage = storageEx.ToErrorDetail();
}
else
{
exceptionMessage = ex.Message;
}
#endif
return exceptionMessage;
}
/// <summary>
/// Returns a string that represents error details of the corresponding <see cref="StorageException"/>.
/// </summary>
/// <param name="ex">The given exception.</param>
/// <returns>A string that represents error details of the corresponding <see cref="StorageException"/>.</returns>
public static string ToErrorDetail(this StorageException ex)
{
if (ex == null)
{
throw new ArgumentNullException("ex");
}
var messageBuilder = new StringBuilder();
messageBuilder.Append(ex.Message);
if (ex.RequestInformation != null)
{
string errorDetails = ex.RequestInformation.HttpStatusMessage;
if (ex.RequestInformation.ExtendedErrorInformation != null)
{
// Overrides the error details with error message inside
// extended error information if avaliable.
errorDetails = ex.RequestInformation.ExtendedErrorInformation.ErrorMessage;
}
else
{
// If available, try to fetch the TimeoutException from the inner exception
// to provide more detail.
if (ex.InnerException != null)
{
var timeoutException = ex.InnerException as TimeoutException;
if (timeoutException != null)
{
errorDetails = timeoutException.Message;
}
}
}
messageBuilder.AppendLine();
messageBuilder.Append(errorDetails);
}
return messageBuilder.ToString();
}
public static byte[] RequireBuffer(MemoryManager memoryManager, Action checkCancellation)
{
byte[] buffer;
buffer = memoryManager.RequireBuffer();
if (null == buffer)
{
int retryCount = 0;
int retryInterval = 100;
while ((retryCount < RequireBufferMaxRetryCount)
&& (null == buffer))
{
checkCancellation();
retryInterval <<= 1;
Thread.Sleep(retryInterval);
buffer = memoryManager.RequireBuffer();
++retryCount;
}
}
if (null == buffer)
{
throw new TransferException(
TransferErrorCode.FailToAllocateMemory,
Resources.FailedToAllocateMemoryException);
}
return buffer;
}
public static bool IsExpectedHttpStatusCodes(StorageException e, params HttpStatusCode[] expectedStatusCodes)
{
if (e == null || e.RequestInformation == null)
{
return false;
}
int statusCode = e.RequestInformation.HttpStatusCode;
foreach(HttpStatusCode expectedStatusCode in expectedStatusCodes)
{
if (statusCode == (int)expectedStatusCode)
{
return true;
}
}
return false;
}
#if DEBUG
/// <summary>
/// Append snapshot time to a file name.
/// </summary>
/// <param name="fileName">Original file name.</param>
/// <param name="snapshotTime">Snapshot time to append.</param>
/// <returns>A file name with appended snapshot time.</returns>
public static string AppendSnapShotTimeToFileName(string fileName, DateTimeOffset? snapshotTime)
{
string resultName = fileName;
if (snapshotTime.HasValue)
{
string pathAndFileNameNoExt = Path.ChangeExtension(fileName, null);
string extension = Path.GetExtension(fileName);
string timeStamp = string.Format(
CultureInfo.InvariantCulture,
"{0:yyyy-MM-dd HHmmss fff}",
snapshotTime.Value);
resultName = string.Format(
CultureInfo.InvariantCulture,
"{0} ({1}){2}",
pathAndFileNameNoExt,
timeStamp,
extension);
}
return resultName;
}
#endif
private static void AssignToRequestOptions(IRequestOptions targetRequestOptions, IRequestOptions customRequestOptions)
{
if (null != customRequestOptions.MaximumExecutionTime)
{
targetRequestOptions.MaximumExecutionTime = customRequestOptions.MaximumExecutionTime;
}
if (null != customRequestOptions.RetryPolicy)
{
targetRequestOptions.RetryPolicy = customRequestOptions.RetryPolicy;
}
if (null != customRequestOptions.ServerTimeout)
{
targetRequestOptions.ServerTimeout = customRequestOptions.ServerTimeout;
}
targetRequestOptions.LocationMode = customRequestOptions.LocationMode;
}
}
}
| |
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Data;
using InstallerLib;
using System.ComponentModel.Design;
using System.IO;
using SourceLibrary.Windows.Forms;
using Microsoft.Win32;
namespace InstallerEditor
{
/// <summary>
/// Summary description for MainForm.
/// </summary>
public class MainForm : System.Windows.Forms.Form, IMRUClient
{
private System.Windows.Forms.MainMenu mainMenu;
private MenuItem mnFile;
private MenuItem mnNew;
private MenuItem mnClose;
private MenuItem mnSave;
private MenuItem mnExit;
private MenuItem mnOpen;
private MenuItem menuItem1;
private MenuItem menuItem2;
private MenuItem mnCreateExe;
private MenuItem menuItem4;
private System.Windows.Forms.TreeView configurationTree;
private System.Windows.Forms.PropertyGrid propertyGrid;
private System.Windows.Forms.ImageList imageList;
private System.Windows.Forms.ContextMenu contextMenuTreeView;
private System.Windows.Forms.Splitter splitter1;
private MenuItem mnAdd;
private MenuItem mnAddSetupConfiguration;
private MenuItem mnAddWebConfiguration;
private MenuItem menuSep2;
private MenuItem mnDelete;
private MenuItem mnAddDownloadFile;
private MenuItem mnView;
private MenuItem mnRefresh;
private MenuItem mnAddMsiComponent;
private MenuItem mnAddMspComponent;
private MenuItem mnAddCommandComponent;
private MenuItem mnAddInstalledCheckRegistry;
private MenuItem mnAddInstalledCheckFile;
private MenuItem mnAddDownloadDialog;
private MenuItem mnSaveAs;
private MenuItem mnEditWithNotepad;
private MenuItem mnTools;
private MenuItem mnTemplates;
private MenuItem mnHelp;
private MenuItem mnHomePage;
private MenuItem mnAddOpenFileComponent;
private MenuItem mnHelpAbout;
private MenuItem mnCustomizeTemplates;
private MenuItem mnAddComponentWizard2;
private MenuItem mnAddInstalledCheckProduct;
private MenuItem mnAddEmbedFile;
private MenuItem mnAddInstalledCheckOperator;
private SplitContainer mainSplitContainer;
private TextBox txtComment;
private MenuItem mnMove;
private MenuItem mnMoveUp;
private MenuItem mnMoveDown;
private MenuItem menuSep1;
private MenuItem mnExpandAll;
private MenuItem mnCollapseAll;
private StatusStrip statusStrip;
private ToolStripStatusLabel statusLabel;
private MenuItem mnUsersGuide;
private MenuItem menuItem10;
private MenuItem mnAddEmbedFolder;
private MenuItem mnAddMsuComponent;
private MenuItem mnAddInstalledCheckDirectory;
private MenuItem menuConfigurations;
private MenuItem menuComponents;
private MenuItem menuSep3;
private MenuItem menuChecks;
private MenuItem menuDownload;
private MenuItem menuEmbed;
private MenuItem mnAddLabelControl;
private MenuItem mnAddCheckboxControl;
private MenuItem menuControls;
private MenuItem mnAddEditControl;
private MenuItem mnAddBrowseControl;
private MenuItem menuSep4;
private MenuItem mnAddLicenseAgreement;
private MenuItem mnAddHyperlinkControl;
private MenuItem mnEdit;
private MenuItem mnAddExeComponent;
private System.ComponentModel.IContainer components;
private MenuItem mnOpenRecent;
private MenuItem menuItem3;
public const string registryPath = @"Software\dotNetInstaller\InstallerEditor";
private MRUManager m_recentFiles = new MRUManager();
private MRUManager m_templateFiles = new MRUManager();
private RegistryKey m_makeExeRegistry;
private MenuItem mnAddImageControl;
private RegistryKey m_settingsRegistry;
private FileSystemWatcher m_configFileWatcher;
public MainForm()
{
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.mainMenu = new System.Windows.Forms.MainMenu(this.components);
this.mnFile = new System.Windows.Forms.MenuItem();
this.mnNew = new System.Windows.Forms.MenuItem();
this.mnOpen = new System.Windows.Forms.MenuItem();
this.mnClose = new System.Windows.Forms.MenuItem();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.mnSave = new System.Windows.Forms.MenuItem();
this.mnSaveAs = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.mnEditWithNotepad = new System.Windows.Forms.MenuItem();
this.mnCreateExe = new System.Windows.Forms.MenuItem();
this.menuItem4 = new System.Windows.Forms.MenuItem();
this.mnOpenRecent = new System.Windows.Forms.MenuItem();
this.menuItem3 = new System.Windows.Forms.MenuItem();
this.mnExit = new System.Windows.Forms.MenuItem();
this.mnEdit = new System.Windows.Forms.MenuItem();
this.mnAdd = new System.Windows.Forms.MenuItem();
this.menuConfigurations = new System.Windows.Forms.MenuItem();
this.mnAddSetupConfiguration = new System.Windows.Forms.MenuItem();
this.mnAddWebConfiguration = new System.Windows.Forms.MenuItem();
this.menuComponents = new System.Windows.Forms.MenuItem();
this.mnAddComponentWizard2 = new System.Windows.Forms.MenuItem();
this.menuSep3 = new System.Windows.Forms.MenuItem();
this.mnAddMsiComponent = new System.Windows.Forms.MenuItem();
this.mnAddMsuComponent = new System.Windows.Forms.MenuItem();
this.mnAddMspComponent = new System.Windows.Forms.MenuItem();
this.mnAddExeComponent = new System.Windows.Forms.MenuItem();
this.mnAddCommandComponent = new System.Windows.Forms.MenuItem();
this.mnAddOpenFileComponent = new System.Windows.Forms.MenuItem();
this.menuChecks = new System.Windows.Forms.MenuItem();
this.mnAddInstalledCheckRegistry = new System.Windows.Forms.MenuItem();
this.mnAddInstalledCheckFile = new System.Windows.Forms.MenuItem();
this.mnAddInstalledCheckDirectory = new System.Windows.Forms.MenuItem();
this.mnAddInstalledCheckOperator = new System.Windows.Forms.MenuItem();
this.mnAddInstalledCheckProduct = new System.Windows.Forms.MenuItem();
this.menuDownload = new System.Windows.Forms.MenuItem();
this.mnAddDownloadDialog = new System.Windows.Forms.MenuItem();
this.mnAddDownloadFile = new System.Windows.Forms.MenuItem();
this.menuEmbed = new System.Windows.Forms.MenuItem();
this.mnAddEmbedFile = new System.Windows.Forms.MenuItem();
this.mnAddEmbedFolder = new System.Windows.Forms.MenuItem();
this.menuControls = new System.Windows.Forms.MenuItem();
this.mnAddLabelControl = new System.Windows.Forms.MenuItem();
this.mnAddEditControl = new System.Windows.Forms.MenuItem();
this.mnAddCheckboxControl = new System.Windows.Forms.MenuItem();
this.mnAddBrowseControl = new System.Windows.Forms.MenuItem();
this.mnAddHyperlinkControl = new System.Windows.Forms.MenuItem();
this.menuSep4 = new System.Windows.Forms.MenuItem();
this.mnAddLicenseAgreement = new System.Windows.Forms.MenuItem();
this.mnMove = new System.Windows.Forms.MenuItem();
this.mnMoveUp = new System.Windows.Forms.MenuItem();
this.mnMoveDown = new System.Windows.Forms.MenuItem();
this.menuSep1 = new System.Windows.Forms.MenuItem();
this.mnExpandAll = new System.Windows.Forms.MenuItem();
this.mnCollapseAll = new System.Windows.Forms.MenuItem();
this.menuSep2 = new System.Windows.Forms.MenuItem();
this.mnDelete = new System.Windows.Forms.MenuItem();
this.mnView = new System.Windows.Forms.MenuItem();
this.mnRefresh = new System.Windows.Forms.MenuItem();
this.mnTools = new System.Windows.Forms.MenuItem();
this.mnTemplates = new System.Windows.Forms.MenuItem();
this.mnCustomizeTemplates = new System.Windows.Forms.MenuItem();
this.mnHelp = new System.Windows.Forms.MenuItem();
this.mnUsersGuide = new System.Windows.Forms.MenuItem();
this.menuItem10 = new System.Windows.Forms.MenuItem();
this.mnHomePage = new System.Windows.Forms.MenuItem();
this.mnHelpAbout = new System.Windows.Forms.MenuItem();
this.contextMenuTreeView = new System.Windows.Forms.ContextMenu();
this.imageList = new System.Windows.Forms.ImageList(this.components);
this.mainSplitContainer = new System.Windows.Forms.SplitContainer();
this.splitter1 = new System.Windows.Forms.Splitter();
this.propertyGrid = new System.Windows.Forms.PropertyGrid();
this.configurationTree = new System.Windows.Forms.TreeView();
this.statusStrip = new System.Windows.Forms.StatusStrip();
this.statusLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.txtComment = new System.Windows.Forms.TextBox();
this.mnAddImageControl = new System.Windows.Forms.MenuItem();
this.mainSplitContainer.Panel1.SuspendLayout();
this.mainSplitContainer.Panel2.SuspendLayout();
this.mainSplitContainer.SuspendLayout();
this.statusStrip.SuspendLayout();
this.SuspendLayout();
//
// mainMenu
//
this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnFile,
this.mnEdit,
this.mnView,
this.mnTools,
this.mnHelp});
//
// mnFile
//
this.mnFile.Index = 0;
this.mnFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnNew,
this.mnOpen,
this.mnClose,
this.menuItem1,
this.mnSave,
this.mnSaveAs,
this.menuItem2,
this.mnEditWithNotepad,
this.mnCreateExe,
this.menuItem4,
this.mnOpenRecent,
this.menuItem3,
this.mnExit});
this.mnFile.Text = "&File";
this.mnFile.Click += new System.EventHandler(this.mnFile_Click);
//
// mnNew
//
this.mnNew.Index = 0;
this.mnNew.Shortcut = System.Windows.Forms.Shortcut.CtrlN;
this.mnNew.Text = "&New";
this.mnNew.Click += new System.EventHandler(this.mnNew_Click);
//
// mnOpen
//
this.mnOpen.Index = 1;
this.mnOpen.Shortcut = System.Windows.Forms.Shortcut.CtrlO;
this.mnOpen.Text = "&Open...";
this.mnOpen.Click += new System.EventHandler(this.mnOpen_Click);
//
// mnClose
//
this.mnClose.Enabled = false;
this.mnClose.Index = 2;
this.mnClose.Text = "&Close";
this.mnClose.Click += new System.EventHandler(this.mnClose_Click);
//
// menuItem1
//
this.menuItem1.Index = 3;
this.menuItem1.Text = "-";
//
// mnSave
//
this.mnSave.Enabled = false;
this.mnSave.Index = 4;
this.mnSave.Shortcut = System.Windows.Forms.Shortcut.CtrlS;
this.mnSave.Text = "&Save";
this.mnSave.Click += new System.EventHandler(this.mnSave_Click);
//
// mnSaveAs
//
this.mnSaveAs.Enabled = false;
this.mnSaveAs.Index = 5;
this.mnSaveAs.Text = "Save As...";
this.mnSaveAs.Click += new System.EventHandler(this.mnSaveAs_Click);
//
// menuItem2
//
this.menuItem2.Index = 6;
this.menuItem2.Text = "-";
//
// mnEditWithNotepad
//
this.mnEditWithNotepad.Enabled = false;
this.mnEditWithNotepad.Index = 7;
this.mnEditWithNotepad.Text = "Edit With Notepad";
this.mnEditWithNotepad.Click += new System.EventHandler(this.mnEditWithNotepad_Click);
//
// mnCreateExe
//
this.mnCreateExe.Enabled = false;
this.mnCreateExe.Index = 8;
this.mnCreateExe.Shortcut = System.Windows.Forms.Shortcut.F10;
this.mnCreateExe.Text = "Create Exe...";
this.mnCreateExe.Click += new System.EventHandler(this.mnCreateExe_Click);
//
// menuItem4
//
this.menuItem4.Index = 9;
this.menuItem4.Text = "-";
//
// mnOpenRecent
//
this.mnOpenRecent.Index = 10;
this.mnOpenRecent.Text = "&Recent Files";
//
// menuItem3
//
this.menuItem3.Index = 11;
this.menuItem3.Text = "-";
//
// mnExit
//
this.mnExit.Index = 12;
this.mnExit.Shortcut = System.Windows.Forms.Shortcut.AltF4;
this.mnExit.Text = "E&xit";
this.mnExit.Click += new System.EventHandler(this.mnExit_Click);
//
// mnEdit
//
this.mnEdit.Index = 1;
this.mnEdit.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnAdd,
this.mnMove,
this.menuSep1,
this.mnExpandAll,
this.mnCollapseAll,
this.menuSep2,
this.mnDelete});
this.mnEdit.Text = "&Edit";
this.mnEdit.Popup += new System.EventHandler(this.mnEdit_Popup);
//
// mnAdd
//
this.mnAdd.Index = 0;
this.mnAdd.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuConfigurations,
this.menuComponents,
this.menuChecks,
this.menuDownload,
this.menuEmbed,
this.menuControls});
this.mnAdd.Text = "&Add";
//
// menuConfigurations
//
this.menuConfigurations.Index = 0;
this.menuConfigurations.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnAddSetupConfiguration,
this.mnAddWebConfiguration});
this.menuConfigurations.Text = "&Configurations";
//
// mnAddSetupConfiguration
//
this.mnAddSetupConfiguration.Index = 0;
this.mnAddSetupConfiguration.Text = "Setup Configuration";
this.mnAddSetupConfiguration.Click += new System.EventHandler(this.mnAddSetupConfiguration_Click);
//
// mnAddWebConfiguration
//
this.mnAddWebConfiguration.Index = 1;
this.mnAddWebConfiguration.Text = "Web Configuration";
this.mnAddWebConfiguration.Click += new System.EventHandler(this.mnAddWebConfiguration_Click);
//
// menuComponents
//
this.menuComponents.Index = 1;
this.menuComponents.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnAddComponentWizard2,
this.menuSep3,
this.mnAddMsiComponent,
this.mnAddMsuComponent,
this.mnAddMspComponent,
this.mnAddExeComponent,
this.mnAddCommandComponent,
this.mnAddOpenFileComponent});
this.menuComponents.Text = "Co&mponents";
//
// mnAddComponentWizard2
//
this.mnAddComponentWizard2.Index = 0;
this.mnAddComponentWizard2.Text = "Component Wizard ...";
this.mnAddComponentWizard2.Click += new System.EventHandler(this.mnAddComponentWizard2_Click);
//
// menuSep3
//
this.menuSep3.Index = 1;
this.menuSep3.Text = "-";
//
// mnAddMsiComponent
//
this.mnAddMsiComponent.Index = 2;
this.mnAddMsiComponent.Text = "Msi Component";
this.mnAddMsiComponent.Click += new System.EventHandler(this.mnAddMsiComponent_Click);
//
// mnAddMsuComponent
//
this.mnAddMsuComponent.Index = 3;
this.mnAddMsuComponent.Text = "Msu Component";
this.mnAddMsuComponent.Click += new System.EventHandler(this.mnAddMsuComponent_Click);
//
// mnAddMspComponent
//
this.mnAddMspComponent.Index = 4;
this.mnAddMspComponent.Text = "Msp Component";
this.mnAddMspComponent.Click += new System.EventHandler(this.mnAddMspComponent_Click);
//
// mnAddExeComponent
//
this.mnAddExeComponent.Index = 5;
this.mnAddExeComponent.Text = "Exe Component";
this.mnAddExeComponent.Click += new System.EventHandler(this.mnAddExeComponent_Click);
//
// mnAddCommandComponent
//
this.mnAddCommandComponent.Index = 6;
this.mnAddCommandComponent.Text = "Command Component";
this.mnAddCommandComponent.Click += new System.EventHandler(this.mnAddCommandComponent_Click);
//
// mnAddOpenFileComponent
//
this.mnAddOpenFileComponent.Index = 7;
this.mnAddOpenFileComponent.Text = "OpenFile Component";
this.mnAddOpenFileComponent.Click += new System.EventHandler(this.mnAddOpenFileComponent_Click);
//
// menuChecks
//
this.menuChecks.Index = 2;
this.menuChecks.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnAddInstalledCheckRegistry,
this.mnAddInstalledCheckFile,
this.mnAddInstalledCheckDirectory,
this.mnAddInstalledCheckOperator,
this.mnAddInstalledCheckProduct});
this.menuChecks.Text = "Chec&ks";
//
// mnAddInstalledCheckRegistry
//
this.mnAddInstalledCheckRegistry.Index = 0;
this.mnAddInstalledCheckRegistry.Text = "Installed Check Registry";
this.mnAddInstalledCheckRegistry.Click += new System.EventHandler(this.mnAddInstalledCheckRegistry_Click);
//
// mnAddInstalledCheckFile
//
this.mnAddInstalledCheckFile.Index = 1;
this.mnAddInstalledCheckFile.Text = "Installed Check File";
this.mnAddInstalledCheckFile.Click += new System.EventHandler(this.mnInstalledCheckFile_Click);
//
// mnAddInstalledCheckDirectory
//
this.mnAddInstalledCheckDirectory.Index = 2;
this.mnAddInstalledCheckDirectory.Text = "Installed Check Directory";
this.mnAddInstalledCheckDirectory.Click += new System.EventHandler(this.mnAddInstalledCheckDirectory_Click);
//
// mnAddInstalledCheckOperator
//
this.mnAddInstalledCheckOperator.Index = 3;
this.mnAddInstalledCheckOperator.Text = "Installed Check Operator";
this.mnAddInstalledCheckOperator.Click += new System.EventHandler(this.mnAddInstalledCheckOperator_Click);
//
// mnAddInstalledCheckProduct
//
this.mnAddInstalledCheckProduct.Index = 4;
this.mnAddInstalledCheckProduct.Text = "Installed Check ProductCode";
this.mnAddInstalledCheckProduct.Click += new System.EventHandler(this.mnAddInstalledCheckProduct_Click);
//
// menuDownload
//
this.menuDownload.Index = 3;
this.menuDownload.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnAddDownloadDialog,
this.mnAddDownloadFile});
this.menuDownload.Text = "&Download";
//
// mnAddDownloadDialog
//
this.mnAddDownloadDialog.Index = 0;
this.mnAddDownloadDialog.Text = "Download Dialog";
this.mnAddDownloadDialog.Click += new System.EventHandler(this.mnAddDownloadDialog_Click);
//
// mnAddDownloadFile
//
this.mnAddDownloadFile.Index = 1;
this.mnAddDownloadFile.Text = "Download File";
this.mnAddDownloadFile.Click += new System.EventHandler(this.mnAddDownloadFile_Click);
//
// menuEmbed
//
this.menuEmbed.Index = 4;
this.menuEmbed.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnAddEmbedFile,
this.mnAddEmbedFolder});
this.menuEmbed.Text = "&Embed";
//
// mnAddEmbedFile
//
this.mnAddEmbedFile.Index = 0;
this.mnAddEmbedFile.Text = "&Embed File";
this.mnAddEmbedFile.Click += new System.EventHandler(this.mnAddEmbedFile_Click);
//
// mnAddEmbedFolder
//
this.mnAddEmbedFolder.Index = 1;
this.mnAddEmbedFolder.Text = "Embed Folder";
this.mnAddEmbedFolder.Click += new System.EventHandler(this.mnAddEmbedFolder_Click);
//
// menuControls
//
this.menuControls.Index = 5;
this.menuControls.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnAddLabelControl,
this.mnAddEditControl,
this.mnAddCheckboxControl,
this.mnAddBrowseControl,
this.mnAddHyperlinkControl,
this.mnAddImageControl,
this.menuSep4,
this.mnAddLicenseAgreement});
this.menuControls.Text = "Contro&ls";
//
// mnAddLabelControl
//
this.mnAddLabelControl.Index = 0;
this.mnAddLabelControl.Text = "&Label";
this.mnAddLabelControl.Click += new System.EventHandler(this.mnAddLabelControl_Click);
//
// mnAddEditControl
//
this.mnAddEditControl.Index = 1;
this.mnAddEditControl.Text = "&Edit";
this.mnAddEditControl.Click += new System.EventHandler(this.mnAddEditControl_Click);
//
// mnAddCheckboxControl
//
this.mnAddCheckboxControl.Index = 2;
this.mnAddCheckboxControl.Text = "&Checkbox";
this.mnAddCheckboxControl.Click += new System.EventHandler(this.mnAddCheckboxControl_Click);
//
// mnAddBrowseControl
//
this.mnAddBrowseControl.Index = 3;
this.mnAddBrowseControl.Text = "&Browse";
this.mnAddBrowseControl.Click += new System.EventHandler(this.mnAddBrowseControl_Click);
//
// mnAddHyperlinkControl
//
this.mnAddHyperlinkControl.Index = 4;
this.mnAddHyperlinkControl.Text = "&Hyperlink";
this.mnAddHyperlinkControl.Click += new System.EventHandler(this.mnAddHyperlinkControl_Click);
//
// menuSep4
//
this.menuSep4.Index = 6;
this.menuSep4.Text = "-";
//
// mnAddLicenseAgreement
//
this.mnAddLicenseAgreement.Index = 7;
this.mnAddLicenseAgreement.Text = "License &Agreement";
this.mnAddLicenseAgreement.Click += new System.EventHandler(this.mnAddLicenseAgreement_Click);
//
// mnMove
//
this.mnMove.Index = 1;
this.mnMove.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnMoveUp,
this.mnMoveDown});
this.mnMove.Text = "&Move";
//
// mnMoveUp
//
this.mnMoveUp.Index = 0;
this.mnMoveUp.Text = "&Up";
this.mnMoveUp.Click += new System.EventHandler(this.mnMoveUp_Click);
//
// mnMoveDown
//
this.mnMoveDown.Index = 1;
this.mnMoveDown.Text = "&Down";
this.mnMoveDown.Click += new System.EventHandler(this.mnMoveDown_Click);
//
// menuSep1
//
this.menuSep1.Index = 2;
this.menuSep1.Text = "-";
//
// mnExpandAll
//
this.mnExpandAll.Index = 3;
this.mnExpandAll.Text = "&Expand All";
this.mnExpandAll.Click += new System.EventHandler(this.mnExpandAll_Click);
//
// mnCollapseAll
//
this.mnCollapseAll.Index = 4;
this.mnCollapseAll.Text = "&Collapse All";
this.mnCollapseAll.Click += new System.EventHandler(this.mnCollapseAll_Click);
//
// menuSep2
//
this.menuSep2.Index = 5;
this.menuSep2.Text = "-";
//
// mnDelete
//
this.mnDelete.Index = 6;
this.mnDelete.Text = "&Delete";
this.mnDelete.Click += new System.EventHandler(this.mnDelete_Click);
//
// mnView
//
this.mnView.Index = 2;
this.mnView.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnRefresh});
this.mnView.Text = "&View";
//
// mnRefresh
//
this.mnRefresh.Index = 0;
this.mnRefresh.Shortcut = System.Windows.Forms.Shortcut.F5;
this.mnRefresh.Text = "&Refresh";
this.mnRefresh.Click += new System.EventHandler(this.mnRefresh_Click);
//
// mnTools
//
this.mnTools.Index = 3;
this.mnTools.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnTemplates,
this.mnCustomizeTemplates});
this.mnTools.Text = "&Tools";
//
// mnTemplates
//
this.mnTemplates.Index = 0;
this.mnTemplates.Text = "Template For New &Item";
//
// mnCustomizeTemplates
//
this.mnCustomizeTemplates.Index = 1;
this.mnCustomizeTemplates.Text = "&Customize Templates";
this.mnCustomizeTemplates.Click += new System.EventHandler(this.mnCustomizeTemplates_Click);
//
// mnHelp
//
this.mnHelp.Index = 4;
this.mnHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnUsersGuide,
this.menuItem10,
this.mnHomePage,
this.mnHelpAbout});
this.mnHelp.Text = "Help";
//
// mnUsersGuide
//
this.mnUsersGuide.Index = 0;
this.mnUsersGuide.Text = "&Users Guide";
this.mnUsersGuide.Click += new System.EventHandler(this.mnUsersGuide_Click);
//
// menuItem10
//
this.menuItem10.Index = 1;
this.menuItem10.Text = "-";
//
// mnHomePage
//
this.mnHomePage.Index = 2;
this.mnHomePage.Text = "&Home Page";
this.mnHomePage.Click += new System.EventHandler(this.mnHomePage_Click);
//
// mnHelpAbout
//
this.mnHelpAbout.Index = 3;
this.mnHelpAbout.Text = "&About";
this.mnHelpAbout.Click += new System.EventHandler(this.mnHelpAbout_Click);
//
// contextMenuTreeView
//
this.contextMenuTreeView.Popup += new System.EventHandler(this.contextMenuTreeView_Popup);
//
// imageList
//
this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream")));
this.imageList.TransparentColor = System.Drawing.Color.Transparent;
this.imageList.Images.SetKeyName(0, "");
this.imageList.Images.SetKeyName(1, "");
this.imageList.Images.SetKeyName(2, "");
this.imageList.Images.SetKeyName(3, "");
this.imageList.Images.SetKeyName(4, "");
this.imageList.Images.SetKeyName(5, "");
this.imageList.Images.SetKeyName(6, "");
this.imageList.Images.SetKeyName(7, "");
this.imageList.Images.SetKeyName(8, "");
this.imageList.Images.SetKeyName(9, "");
this.imageList.Images.SetKeyName(10, "");
this.imageList.Images.SetKeyName(11, "");
this.imageList.Images.SetKeyName(12, "");
this.imageList.Images.SetKeyName(13, "");
this.imageList.Images.SetKeyName(14, "");
this.imageList.Images.SetKeyName(15, "");
this.imageList.Images.SetKeyName(16, "");
this.imageList.Images.SetKeyName(17, "");
this.imageList.Images.SetKeyName(18, "");
this.imageList.Images.SetKeyName(19, "");
this.imageList.Images.SetKeyName(20, "");
this.imageList.Images.SetKeyName(21, "");
this.imageList.Images.SetKeyName(22, "");
this.imageList.Images.SetKeyName(23, "");
this.imageList.Images.SetKeyName(24, "");
this.imageList.Images.SetKeyName(25, "");
this.imageList.Images.SetKeyName(26, "");
//
// mainSplitContainer
//
this.mainSplitContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.mainSplitContainer.Location = new System.Drawing.Point(0, 0);
this.mainSplitContainer.Name = "mainSplitContainer";
this.mainSplitContainer.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// mainSplitContainer.Panel1
//
this.mainSplitContainer.Panel1.Controls.Add(this.splitter1);
this.mainSplitContainer.Panel1.Controls.Add(this.propertyGrid);
this.mainSplitContainer.Panel1.Controls.Add(this.configurationTree);
//
// mainSplitContainer.Panel2
//
this.mainSplitContainer.Panel2.Controls.Add(this.statusStrip);
this.mainSplitContainer.Panel2.Controls.Add(this.txtComment);
this.mainSplitContainer.Size = new System.Drawing.Size(620, 346);
this.mainSplitContainer.SplitterDistance = 278;
this.mainSplitContainer.TabIndex = 4;
//
// splitter1
//
this.splitter1.Location = new System.Drawing.Point(176, 0);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(3, 278);
this.splitter1.TabIndex = 4;
this.splitter1.TabStop = false;
//
// propertyGrid
//
this.propertyGrid.AccessibleName = "propertyGrid";
this.propertyGrid.Dock = System.Windows.Forms.DockStyle.Fill;
this.propertyGrid.LineColor = System.Drawing.SystemColors.ScrollBar;
this.propertyGrid.Location = new System.Drawing.Point(176, 0);
this.propertyGrid.Name = "propertyGrid";
this.propertyGrid.Size = new System.Drawing.Size(444, 278);
this.propertyGrid.TabIndex = 3;
this.propertyGrid.PropertyValueChanged += new System.Windows.Forms.PropertyValueChangedEventHandler(this.propertyGrid_PropertyValueChanged);
//
// configurationTree
//
this.configurationTree.AccessibleName = "configurationTree";
this.configurationTree.AllowDrop = true;
this.configurationTree.ContextMenu = this.contextMenuTreeView;
this.configurationTree.Dock = System.Windows.Forms.DockStyle.Left;
this.configurationTree.HideSelection = false;
this.configurationTree.ImageIndex = 0;
this.configurationTree.ImageList = this.imageList;
this.configurationTree.Location = new System.Drawing.Point(0, 0);
this.configurationTree.Name = "configurationTree";
this.configurationTree.SelectedImageIndex = 0;
this.configurationTree.Size = new System.Drawing.Size(176, 278);
this.configurationTree.TabIndex = 1;
this.configurationTree.DragDrop += new System.Windows.Forms.DragEventHandler(this.treeView_DragDrop);
this.configurationTree.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView_AfterSelect);
this.configurationTree.MouseDown += new System.Windows.Forms.MouseEventHandler(this.treeView_MouseDown);
this.configurationTree.DragEnter += new System.Windows.Forms.DragEventHandler(this.treeView_DragEnter);
this.configurationTree.KeyUp += new System.Windows.Forms.KeyEventHandler(this.treeView_KeyUp);
this.configurationTree.BeforeSelect += new System.Windows.Forms.TreeViewCancelEventHandler(this.treeView_BeforeSelect);
this.configurationTree.KeyDown += new System.Windows.Forms.KeyEventHandler(this.treeView_KeyDown);
this.configurationTree.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.treeView_ItemDrag);
this.configurationTree.DragOver += new System.Windows.Forms.DragEventHandler(this.treeView_DragOver);
//
// statusStrip
//
this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.statusLabel});
this.statusStrip.Location = new System.Drawing.Point(0, 42);
this.statusStrip.Name = "statusStrip";
this.statusStrip.Size = new System.Drawing.Size(620, 22);
this.statusStrip.TabIndex = 1;
this.statusStrip.Text = "statusStrip";
//
// statusLabel
//
this.statusLabel.Name = "statusLabel";
this.statusLabel.Size = new System.Drawing.Size(39, 17);
this.statusLabel.Text = "Ready";
//
// txtComment
//
this.txtComment.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
this.txtComment.Dock = System.Windows.Forms.DockStyle.Fill;
this.txtComment.Location = new System.Drawing.Point(0, 0);
this.txtComment.Multiline = true;
this.txtComment.Name = "txtComment";
this.txtComment.Size = new System.Drawing.Size(620, 64);
this.txtComment.TabIndex = 0;
this.txtComment.Visible = false;
//
// mnAddImageControl
//
this.mnAddImageControl.Index = 5;
this.mnAddImageControl.Text = "&Image";
this.mnAddImageControl.Click += new System.EventHandler(this.mnAddImageControl_Click);
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(620, 346);
this.Controls.Add(this.mainSplitContainer);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Menu = this.mainMenu;
this.Name = "MainForm";
this.Text = "Installer Editor";
this.Load += new System.EventHandler(this.MainForm_Load);
this.Closing += new System.ComponentModel.CancelEventHandler(this.MainForm_Closing);
this.mainSplitContainer.Panel1.ResumeLayout(false);
this.mainSplitContainer.Panel2.ResumeLayout(false);
this.mainSplitContainer.Panel2.PerformLayout();
this.mainSplitContainer.ResumeLayout(false);
this.statusStrip.ResumeLayout(false);
this.statusStrip.PerformLayout();
this.ResumeLayout(false);
}
void treeView_KeyUp(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
// delete
case Keys.Delete:
if (mnDelete.Enabled) mnDelete_Click(sender, e);
break;
// insert
case Keys.Insert:
contextMenuTreeView.Show(configurationTree, configurationTree.SelectedNode != null
? new Point(configurationTree.SelectedNode.Bounds.Location.X + 5, configurationTree.SelectedNode.Bounds.Location.Y + 5)
: new Point(0, 0));
break;
}
}
#endregion
private void mnExit_Click(object sender, System.EventArgs e)
{
try
{
Close();
}
catch (Exception err)
{
AppUtility.ShowError(this, err);
}
}
private TreeNodeConfigFile m_TreeNodeConfigFile = null;
private bool NewConfiguration()
{
try
{
CloseConfiguration();
m_TreeNodeConfigFile = new TreeNodeConfigFile(new ConfigFile());
m_TreeNodeConfigFile.IsDirty = true;
m_TreeNodeConfigFile.CreateChildNodes();
RefreshMenu();
LoadTreeView(m_TreeNodeConfigFile);
statusLabel.Text = "Ready";
return true;
}
catch (Exception err)
{
AppUtility.ShowError(this, err);
return false;
}
}
private bool OpenConfiguration()
{
OpenFileDialog l_dg = new OpenFileDialog();
l_dg.Filter = "Xml Files(*.xml)|*.xml|All Files(*.*)|*.*";
l_dg.DefaultExt = "xml";
if (l_dg.ShowDialog(this) == DialogResult.OK)
{
return OpenConfiguration(l_dg.FileName);
}
return false;
}
private bool OpenConfiguration(string filename)
{
if (! CloseConfiguration())
return false;
try
{
ConfigFile l_File = new ConfigFile();
l_File.Load(filename);
if (!l_File.editor.IsCurrent())
{
DialogResult convertResult = MessageBox.Show(this, string.Format("Do you want to convert configuration file version {0} to {1}?",
l_File.editor.loaded_version, l_File.editor.current_version), "Convert config file?",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (convertResult == DialogResult.No)
{
return false;
}
}
MonitorChanges(filename);
m_TreeNodeConfigFile = new TreeNodeConfigFile(l_File);
m_TreeNodeConfigFile.IsDirty = !l_File.editor.IsCurrent();
m_TreeNodeConfigFile.CreateChildNodes();
RefreshMenu();
LoadTreeView(m_TreeNodeConfigFile);
statusLabel.Text = string.Format("Loaded {0}", m_TreeNodeConfigFile.Instance.filename);
m_recentFiles.Add(Path.GetFullPath(m_TreeNodeConfigFile.Instance.filename));
}
catch
{
m_recentFiles.Remove(filename);
throw;
}
return true;
}
private bool CloseConfiguration()
{
MonitorChanges(null);
if (m_TreeNodeConfigFile != null)
{
if (m_TreeNodeConfigFile.IsDirty)
{
DialogResult l_ret = MessageBox.Show(this, "Do you want to save your changes?", "Setup Installer", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (l_ret == DialogResult.Yes)
{
if (SaveConfiguration() == false)
return false;
}
else if (l_ret == DialogResult.Cancel)
{
return false;
}
}
}
m_TreeNodeConfigFile = null;
CloseTreeView();
propertyGrid.SelectedObject = null;
RefreshMenu();
statusLabel.Text = "Ready";
return true;
}
private void MonitorChanges(string filename)
{
if (m_configFileWatcher != null)
{
m_configFileWatcher.EnableRaisingEvents = false;
m_configFileWatcher = null;
}
if (!string.IsNullOrEmpty(filename))
{
m_configFileWatcher = new FileSystemWatcher();
m_configFileWatcher.Path = Path.GetDirectoryName(filename);
m_configFileWatcher.Changed += new FileSystemEventHandler(MonitorChanges_Changed);
m_configFileWatcher.EnableRaisingEvents = true;
}
}
private void ReopenConfiguration(string configFile)
{
if (!String.IsNullOrEmpty(configFile))
{
CloseConfiguration();
OpenConfiguration(configFile);
}
}
private delegate void DelegateReopenConfiguration(string configFile);
private void MonitorChanges_Changed(object sender, FileSystemEventArgs e)
{
if (e.FullPath == m_TreeNodeConfigFile.Instance.filename)
{
switch (e.ChangeType)
{
case WatcherChangeTypes.Changed:
m_configFileWatcher.EnableRaisingEvents = false;
if (MessageBox.Show("File '" + e.FullPath + "' has changed. Reload?", "File Changed",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
configurationTree.Invoke(new DelegateReopenConfiguration(ReopenConfiguration),
new object[] { e.FullPath });
}
else
{
m_configFileWatcher.EnableRaisingEvents = true;
}
break;
}
}
}
private bool SaveConfiguration()
{
if (m_TreeNodeConfigFile != null)
{
if (m_TreeNodeConfigFile.Instance.filename == null)
{
SaveFileDialog l_dg = new SaveFileDialog();
l_dg.Filter = "Xml Files(*.xml)|*.xml|All Files(*.*)|*.*";
l_dg.DefaultExt = "xml";
if (l_dg.ShowDialog(this) == DialogResult.OK)
{
m_TreeNodeConfigFile.Instance.SaveAs(l_dg.FileName);
MonitorChanges(l_dg.FileName);
}
else
{
return false;
}
}
else
{
MonitorChanges(null);
m_TreeNodeConfigFile.Instance.Save();
MonitorChanges(m_TreeNodeConfigFile.Instance.filename);
}
}
m_TreeNodeConfigFile.IsDirty = false;
statusLabel.Text = string.Format("Written {0}", m_TreeNodeConfigFile.Instance.filename);
m_recentFiles.Add(m_TreeNodeConfigFile.Instance.filename);
RefreshMenu();
return true;
}
private void RefreshMenu()
{
mnClose.Enabled = (m_TreeNodeConfigFile != null);
mnSaveAs.Enabled = (m_TreeNodeConfigFile != null);
if (m_TreeNodeConfigFile != null &&
m_TreeNodeConfigFile.Instance != null &&
m_TreeNodeConfigFile.Instance.filename != null)
{
Text = "Installer Editor - " + m_TreeNodeConfigFile.Instance.filename;
mnEditWithNotepad.Enabled = true;
mnSave.Enabled = true;
mnCreateExe.Enabled = true;
}
else
{
Text = "Installer Editor";
mnEditWithNotepad.Enabled = false;
mnSave.Enabled = false;
mnCreateExe.Enabled = false;
}
RefreshCommentPanel();
}
private void RefreshCommentPanel()
{
if (configurationTree.SelectedNode != null && configurationTree.SelectedNode.Tag is XmlClass)
{
txtComment.Visible = true;
txtComment.Text = ((XmlClass)configurationTree.SelectedNode.Tag).Comment;
}
else
{
txtComment.Visible = false;
txtComment.Text = string.Empty;
}
}
private void mnSave_Click(object sender, System.EventArgs e)
{
try
{
configurationTree.Select();
SaveConfiguration();
}
catch (Exception err)
{
AppUtility.ShowError(this, err);
}
}
private void mnClose_Click(object sender, System.EventArgs e)
{
try
{
CloseConfiguration();
}
catch (Exception err)
{
AppUtility.ShowError(this, err);
}
}
public ConfigFile ConfigFile
{
get { return m_TreeNodeConfigFile.Instance; }
set { m_TreeNodeConfigFile.Instance = value; }
}
private void CloseTreeView()
{
configurationTree.Nodes.Clear();
}
private void LoadTreeView(TreeNodeConfigFile p_Configuration)
{
CloseTreeView();
configurationTree.Nodes.Add(p_Configuration);
configurationTree.ExpandAll();
configurationTree.SelectedNode = p_Configuration;
}
private void mnNew_Click(object sender, System.EventArgs e)
{
try
{
NewConfiguration();
}
catch (Exception err)
{
AppUtility.ShowError(this, err);
}
}
private void mnOpen_Click(object sender, System.EventArgs e)
{
try
{
OpenConfiguration();
}
catch (Exception err)
{
AppUtility.ShowError(this, err);
}
}
private void treeView_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
try
{
propertyGrid.SelectedObject = e.Node.Tag;
RefreshNodeContextMenu();
RefreshCommentPanel();
statusLabel.Text = m_TreeNodeConfigFile != null
? m_TreeNodeConfigFile.Instance.filename
: string.Empty;
}
catch (Exception err)
{
AppUtility.ShowError(this, err);
}
}
private void RefreshNodeContextMenu()
{
if (configurationTree.SelectedNode != null && configurationTree.SelectedNode.Tag is XmlClass)
{
XmlClass item = (XmlClass)configurationTree.SelectedNode.Tag;
mnDelete.Enabled = true;
mnAddSetupConfiguration.Enabled = (item.Children.CanAdd(typeof(SetupConfiguration)));
mnAddWebConfiguration.Enabled = (item.Children.CanAdd(typeof(WebConfiguration)));
mnAddCommandComponent.Enabled = (item.Children.CanAdd(typeof(ComponentCmd)));
mnAddExeComponent.Enabled = (item.Children.CanAdd(typeof(ComponentExe)));
mnAddMsiComponent.Enabled = (item.Children.CanAdd(typeof(ComponentMsi)));
mnAddMsuComponent.Enabled = (item.Children.CanAdd(typeof(ComponentMsu)));
mnAddMspComponent.Enabled = (item.Children.CanAdd(typeof(ComponentMsp)));
mnAddOpenFileComponent.Enabled = (item.Children.CanAdd(typeof(ComponentOpenFile)));
mnAddEmbedFile.Enabled = (item.Children.CanAdd(typeof(EmbedFile)));
mnAddEmbedFolder.Enabled = (item.Children.CanAdd(typeof(EmbedFolder)));
mnAddDownloadDialog.Enabled = (item.Children.CanAdd(typeof(DownloadDialog)));
mnAddDownloadFile.Enabled = (item.Children.CanAdd(typeof(Download)));
mnAddInstalledCheckFile.Enabled = (item.Children.CanAdd(typeof(InstalledCheckFile)));
mnAddInstalledCheckDirectory.Enabled = (item.Children.CanAdd(typeof(InstalledCheckDirectory)));
mnAddInstalledCheckRegistry.Enabled = (item.Children.CanAdd(typeof(InstalledCheckRegistry)));
mnAddInstalledCheckProduct.Enabled = (item.Children.CanAdd(typeof(InstalledCheckProduct)));
mnAddInstalledCheckOperator.Enabled = (item.Children.CanAdd(typeof(InstalledCheckOperator)));
mnAddComponentWizard2.Enabled = (item is SetupConfiguration);
mnMoveUp.Enabled = (configurationTree.SelectedNode.PrevNode != null);
mnMoveDown.Enabled = (configurationTree.SelectedNode.NextNode != null);
mnMove.Enabled = mnMoveUp.Enabled || mnMoveDown.Enabled;
mnAddLabelControl.Enabled = (item.Children.CanAdd(typeof(ControlLabel)));
mnAddCheckboxControl.Enabled = (item.Children.CanAdd(typeof(ControlCheckBox)));
mnAddEditControl.Enabled = (item.Children.CanAdd(typeof(ControlEdit)));
mnAddBrowseControl.Enabled = (item.Children.CanAdd(typeof(ControlBrowse)));
mnAddLicenseAgreement.Enabled = (item.Children.CanAdd(typeof(ControlLicense)));
mnAddHyperlinkControl.Enabled = (item.Children.CanAdd(typeof(ControlHyperlink)));
mnAddImageControl.Enabled = (item.Children.CanAdd(typeof(ControlImage)));
}
else
{
mnDelete.Enabled = false;
mnAddSetupConfiguration.Enabled = false;
mnAddWebConfiguration.Enabled = false;
mnAddCommandComponent.Enabled = false;
mnAddExeComponent.Enabled = false;
mnAddMsiComponent.Enabled = false;
mnAddMsuComponent.Enabled = false;
mnAddOpenFileComponent.Enabled = false;
mnAddEmbedFile.Enabled = false;
mnAddEmbedFolder.Enabled = false;
mnAddDownloadDialog.Enabled = false;
mnAddInstalledCheckFile.Enabled = false;
mnAddInstalledCheckDirectory.Enabled = false;
mnAddInstalledCheckRegistry.Enabled = false;
mnAddInstalledCheckProduct.Enabled = false;
mnAddInstalledCheckOperator.Enabled = false;
mnAddComponentWizard2.Enabled = false;
mnMove.Enabled = false;
mnMoveUp.Enabled = false;
mnMoveDown.Enabled = false;
mnAddLabelControl.Enabled = false;
mnAddCheckboxControl.Enabled = false;
mnAddEditControl.Enabled = false;
mnAddBrowseControl.Enabled = false;
mnAddLicenseAgreement.Enabled = false;
mnAddHyperlinkControl.Enabled = false;
mnAddImageControl.Enabled = false;
}
}
#region Nodes
private T Add<T>(XmlClass parent)
where T : XmlClass, new()
{
T component = new T();
parent.Children.Add(component);
return component;
}
private void AddTreeNode(TreeNode node, XmlTreeNodeImpl treeNode)
{
node.Nodes.Add(treeNode);
m_TreeNodeConfigFile.IsDirty = true;
node.Expand();
configurationTree.SelectedNode = treeNode;
treeNode.ExpandAll();
}
private void AddTreeNode<T>()
where T : XmlClass, new()
{
T xmlitem = new T();
((XmlClass)configurationTree.SelectedNode.Tag).Children.Add(xmlitem);
XmlTreeNodeImpl xmlitemnode = XmlTreeNodeImpl.CreateNode(xmlitem);
AddTreeNode(configurationTree.SelectedNode, xmlitemnode);
}
private void AddTreeNode_Click<T>()
where T : XmlClass, new()
{
try
{
AddTreeNode<T>();
}
catch (Exception err)
{
AppUtility.ShowError(this, err);
}
}
private void mnAddEmbedFolder_Click(object sender, EventArgs e)
{
AddTreeNode_Click<EmbedFolder>();
}
private void mnAddInstalledCheckProduct_Click(object sender, EventArgs e)
{
AddTreeNode_Click<InstalledCheckProduct>();
}
private void mnAddMsuComponent_Click(object sender, EventArgs e)
{
AddTreeNode_Click<ComponentMsu>();
}
private void mnAddInstalledCheckDirectory_Click(object sender, EventArgs e)
{
AddTreeNode_Click<InstalledCheckDirectory>();
}
private void mnAddLabelControl_Click(object sender, EventArgs e)
{
AddTreeNode_Click<ControlLabel>();
}
private void mnAddCheckboxControl_Click(object sender, EventArgs e)
{
AddTreeNode_Click<ControlCheckBox>();
}
private void mnAddEditControl_Click(object sender, EventArgs e)
{
AddTreeNode_Click<ControlEdit>();
}
private void mnAddBrowseControl_Click(object sender, EventArgs e)
{
AddTreeNode_Click<ControlBrowse>();
}
private void mnAddOpenFileComponent_Click(object sender, System.EventArgs e)
{
AddTreeNode_Click<ComponentOpenFile>();
}
private void mnAddLicenseAgreement_Click(object sender, EventArgs e)
{
AddTreeNode_Click<ControlLicense>();
}
private void mnAddSetupConfiguration_Click(object sender, System.EventArgs e)
{
configurationTree.SelectedNode = m_TreeNodeConfigFile;
AddTreeNode_Click<SetupConfiguration>();
}
private void mnAddWebConfiguration_Click(object sender, System.EventArgs e)
{
configurationTree.SelectedNode = m_TreeNodeConfigFile;
AddTreeNode_Click<WebConfiguration>();
}
private void mnAddDownloadFile_Click(object sender, System.EventArgs e)
{
AddTreeNode_Click<Download>();
}
private void mnAddMsiComponent_Click(object sender, System.EventArgs e)
{
AddTreeNode_Click<ComponentMsi>();
}
private void mnAddMspComponent_Click(object sender, System.EventArgs e)
{
AddTreeNode_Click<ComponentMsp>();
}
private void mnAddCommandComponent_Click(object sender, System.EventArgs e)
{
AddTreeNode_Click<ComponentCmd>();
}
private void mnAddInstalledCheckRegistry_Click(object sender, System.EventArgs e)
{
AddTreeNode_Click<InstalledCheckRegistry>();
}
private void mnInstalledCheckFile_Click(object sender, System.EventArgs e)
{
AddTreeNode_Click<InstalledCheckFile>();
}
private void mnAddDownloadDialog_Click(object sender, System.EventArgs e)
{
AddTreeNode_Click<DownloadDialog>();
}
private void mnAddEmbedFile_Click(object sender, EventArgs e)
{
AddTreeNode_Click<EmbedFile>();
}
private void mnAddInstalledCheckOperator_Click(object sender, EventArgs e)
{
AddTreeNode_Click<InstalledCheckOperator>();
}
private void mnAddHyperlinkControl_Click(object sender, EventArgs e)
{
AddTreeNode_Click<ControlHyperlink>();
}
private void mnAddImageControl_Click(object sender, EventArgs e)
{
AddTreeNode_Click<ControlImage>();
}
#endregion
private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (CloseConfiguration() == false)
{
e.Cancel = true;
return;
}
if (WindowState != FormWindowState.Minimized)
{
m_settingsRegistry.SetValue("WindowState", WindowState.ToString());
m_settingsRegistry.SetValue("Bounds", XmlRectangle.ToString(Bounds));
}
m_settingsRegistry.SetValue("ConfigurationTreeWidth", configurationTree.Width);
m_settingsRegistry.SetValue("CommentsDistance", mainSplitContainer.SplitterDistance);
}
private void mnDelete_Click(object sender, System.EventArgs e)
{
try
{
if (configurationTree.SelectedNode != null && configurationTree.SelectedNode.Parent != null)
{
if (configurationTree.SelectedNode.Tag is XmlClass && configurationTree.SelectedNode.Parent.Tag is XmlClass)
{
XmlClass item = (XmlClass)configurationTree.SelectedNode.Tag;
XmlClass parent = (XmlClass)configurationTree.SelectedNode.Parent.Tag;
parent.Children.Remove(item);
configurationTree.SelectedNode.Remove();
m_TreeNodeConfigFile.IsDirty = true;
}
}
}
catch (Exception err)
{
AppUtility.ShowError(this, err);
}
}
private void mnRefresh_Click(object sender, System.EventArgs e)
{
try
{
if (m_TreeNodeConfigFile != null && m_TreeNodeConfigFile.Instance != null)
{
m_TreeNodeConfigFile = new TreeNodeConfigFile(m_TreeNodeConfigFile.Instance);
m_TreeNodeConfigFile.CreateChildNodes();
LoadTreeView(m_TreeNodeConfigFile);
}
statusLabel.Text = "Ready";
}
catch (Exception err)
{
AppUtility.ShowError(this, err);
}
}
private void treeView_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
try
{
TreeNode l_Node = configurationTree.GetNodeAt(e.X, e.Y);
if (l_Node != null)
{
configurationTree.SelectedNode = l_Node;
}
}
catch (Exception err)
{
AppUtility.ShowError(this, err);
}
}
private void mnSaveAs_Click(object sender, System.EventArgs e)
{
try
{
if (m_TreeNodeConfigFile != null && m_TreeNodeConfigFile.Instance != null)
{
m_TreeNodeConfigFile.Instance.filename = null;
SaveConfiguration();
}
}
catch (Exception err)
{
AppUtility.ShowError(this, err);
}
}
private void mnEditWithNotepad_Click(object sender, System.EventArgs e)
{
try
{
if (m_TreeNodeConfigFile.Instance.filename != null)
{
System.Diagnostics.ProcessStartInfo p = new System.Diagnostics.ProcessStartInfo("NOTEPAD.EXE", "\"" + m_TreeNodeConfigFile.Instance.filename + "\"");
p.UseShellExecute = false;
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo = p;
process.Start();
}
}
catch (Exception err)
{
AppUtility.ShowError(this, err);
}
}
private void mnHomePage_Click(object sender, System.EventArgs e)
{
try
{
SourceLibrary.Utility.Shell.ExecCommand("http://www.codeplex.com/dotnetinstaller/");
}
catch (Exception err)
{
AppUtility.ShowError(this, err);
}
}
private void LoadSettings()
{
try
{
bool migrateSettings = (Registry.CurrentUser.OpenSubKey(registryPath) == null);
m_settingsRegistry = Registry.CurrentUser.CreateSubKey(registryPath);
m_recentFiles.Initialize(this, mnOpenRecent, registryPath + @"\RecentFiles");
m_templateFiles.Initialize(this, null, registryPath + @"\TemplateFiles");
m_templateFiles.MaxMRULength = 48;
m_makeExeRegistry = Registry.CurrentUser.CreateSubKey(registryPath + @"\MakeExe");
if (migrateSettings)
{
MigrateLegacySettings();
}
RefreshTemplateFilesMenu();
// window state, don't start minimized
FormWindowState windowState = (FormWindowState)Enum.Parse(typeof(FormWindowState), (string)m_settingsRegistry.GetValue("WindowState", WindowState.ToString()));
if (windowState != FormWindowState.Minimized)
{
WindowState = windowState;
// bounds are invalid for a minimized window
Rectangle bounds = XmlRectangle.FromString((string)m_settingsRegistry.GetValue("Bounds", XmlRectangle.ToString(Bounds)));
if (!bounds.IsEmpty) Bounds = bounds;
}
// configuration tree width
int configurationTreeWidth = (int)m_settingsRegistry.GetValue("ConfigurationTreeWidth", configurationTree.Width);
if (configurationTreeWidth >= 0) configurationTree.Width = configurationTreeWidth;
// comments splitter distance
int commentsDistance = (int)m_settingsRegistry.GetValue("CommentsDistance", mainSplitContainer.SplitterDistance);
if (commentsDistance >= 0) mainSplitContainer.SplitterDistance = commentsDistance;
}
catch (Exception err)
{
ErrorDialog.Show(this, err, "Error loading settings");
}
}
private void MainForm_Load(object sender, System.EventArgs e)
{
LoadSettings();
try
{
if (!string.IsNullOrEmpty(InstallerEditor.CmdArgs.configfile))
{
OpenConfiguration(InstallerEditor.CmdArgs.configfile);
}
}
catch (FileNotFoundException err)
{
Environment.ExitCode = -2;
ErrorDialog.Show(this, err, "Error");
Close();
}
catch (Exception err)
{
Environment.ExitCode = -3;
ErrorDialog.Show(this, err, "Error");
Close();
}
}
private void MigrateLegacySettings()
{
AppSetting legacyAppSetting = new AppSetting();
legacyAppSetting.Load();
if (legacyAppSetting.BannerBitmapFile != null)
m_makeExeRegistry.SetValue("BannerBitmap", legacyAppSetting.BannerBitmapFile);
if (legacyAppSetting.IconFile != null)
m_makeExeRegistry.SetValue("IconFile", legacyAppSetting.IconFile);
if (legacyAppSetting.OutputMakeFile != null)
m_makeExeRegistry.SetValue("OutputFile", legacyAppSetting.OutputMakeFile);
if (legacyAppSetting.TemplateConfigFile != null)
m_makeExeRegistry.SetValue("TemplateFile", legacyAppSetting.TemplateConfigFile);
if (legacyAppSetting.TemplateConfigFile != null)
m_settingsRegistry.SetValue("TemplateConfigFile", legacyAppSetting.TemplateConfigFile);
foreach (string template in legacyAppSetting.AvailableTemplates)
{
m_templateFiles.Add(template);
}
legacyAppSetting.Reset();
}
/// <summary>
/// Select a template from previously saved settings.
/// </summary>
private void SelectTemplate()
{
foreach (MenuItemTemplate menuItem in mnTemplates.MenuItems)
{
if (menuItem.AreEqual((string) m_settingsRegistry.GetValue("TemplateConfigFile", "English")))
{
menuItem.PerformClick();
return;
}
}
mnTemplates.MenuItems[0].PerformClick();
}
private void mnCreateExe_Click(object sender, System.EventArgs e)
{
try
{
if (m_TreeNodeConfigFile == null || m_TreeNodeConfigFile.Instance == null)
{
throw new ApplicationException("Missing configuration");
}
MakeExe l_frmMakeExe = new MakeExe();
l_frmMakeExe.TemplateFile = (string) m_makeExeRegistry.GetValue("TemplateFile", string.Empty);
l_frmMakeExe.BannerBitmapFile = (string) m_makeExeRegistry.GetValue("BannerBitmapFile", string.Empty);
l_frmMakeExe.IconFile = (string) m_makeExeRegistry.GetValue("IconFile", string.Empty);
l_frmMakeExe.OutputFileName = (string) m_makeExeRegistry.GetValue("OutputFileName", string.Empty);
l_frmMakeExe.SplashBitmapFile = (string)m_makeExeRegistry.GetValue("SplashBitmapFile", string.Empty);
l_frmMakeExe.ManifestFile = (string)m_makeExeRegistry.GetValue("ManifestFile", string.Empty);
l_frmMakeExe.Embed = ((int) m_makeExeRegistry.GetValue("Embed", 1) != 0);
l_frmMakeExe.ConfigFile = Path.GetTempFileName();
try
{
m_TreeNodeConfigFile.Instance.WriteTo(l_frmMakeExe.ConfigFile);
l_frmMakeExe.ShowDialog(this);
}
finally
{
File.Delete(l_frmMakeExe.ConfigFile);
}
m_makeExeRegistry.SetValue("TemplateFile", l_frmMakeExe.TemplateFile);
m_makeExeRegistry.SetValue("BannerBitmapFile", l_frmMakeExe.BannerBitmapFile);
m_makeExeRegistry.SetValue("IconFile", l_frmMakeExe.IconFile);
m_makeExeRegistry.SetValue("OutputFileName", l_frmMakeExe.OutputFileName);
m_makeExeRegistry.SetValue("SplashBitmapFile", l_frmMakeExe.SplashBitmapFile);
m_makeExeRegistry.SetValue("ManifestFile", l_frmMakeExe.ManifestFile);
m_makeExeRegistry.SetValue("Embed", l_frmMakeExe.Embed ? 1 : 0);
}
catch (Exception err)
{
AppUtility.ShowError(this, err);
}
}
private void mnHelpAbout_Click(object sender, System.EventArgs e)
{
About a = new About();
a.ShowDialog(this);
}
private void mnCustomizeTemplates_Click(object sender, System.EventArgs e)
{
TemplatesEditor editors = new TemplatesEditor();
editors.AvailableTemplateFiles = new List<String>(m_templateFiles);
if (editors.ShowDialog(this) == DialogResult.OK)
{
m_templateFiles.Clear();
m_templateFiles.AddRange(editors.AvailableTemplateFiles);
RefreshTemplateFilesMenu();
}
}
private void RefreshTemplateFilesMenu()
{
mnTemplates.MenuItems.Clear();
foreach (Template template in Template.EmbeddedTemplates)
{
MenuItemTemplateInstance templateMenuItem = new MenuItemTemplateInstance(template);
templateMenuItem.Click += new EventHandler(
delegate(object sender, EventArgs e)
{
m_settingsRegistry.SetValue("TemplateConfigFile", templateMenuItem.Text);
}
);
mnTemplates.MenuItems.Add(templateMenuItem);
}
foreach (string file in m_templateFiles)
{
try
{
MenuItemTemplateFile templateFileMenuItem = new MenuItemTemplateFile(file);
templateFileMenuItem.Click += new EventHandler(
delegate(object sender, EventArgs e)
{
m_settingsRegistry.SetValue("TemplateConfigFile", file);
}
);
mnTemplates.MenuItems.Add(templateFileMenuItem);
}
catch (Exception err)
{
ErrorDialog.Show(this, err, "Error");
}
}
SelectTemplate();
}
private void mnAddComponentWizard2_Click(object sender, System.EventArgs e)
{
try
{
if (configurationTree.SelectedNode != null && configurationTree.SelectedNode.Tag is SetupConfiguration)
{
SetupConfiguration l_Setup = (SetupConfiguration)configurationTree.SelectedNode.Tag;
ComponentWizard2 l_frmWizard = new ComponentWizard2();
if (l_frmWizard.ShowDialog(this) == DialogResult.OK)
{
foreach (Component c in l_frmWizard.SelectedComponents)
{
l_Setup.Children.Add(c);
TreeNodeComponent<Component> componentNode = new TreeNodeComponent<Component>(c);
componentNode.CreateChildNodes();
AddTreeNode(configurationTree.SelectedNode, componentNode);
}
}
}
}
catch (Exception err)
{
AppUtility.ShowError(this, err);
}
}
private void treeView_BeforeSelect(object sender, TreeViewCancelEventArgs e)
{
if (configurationTree.SelectedNode != null && configurationTree.SelectedNode.Tag is XmlClass)
{
((XmlClass)configurationTree.SelectedNode.Tag).Comment = txtComment.Text;
}
}
private void mnMoveUp_Click(object sender, EventArgs e)
{
configurationTree.BeginUpdate();
try
{
if (configurationTree.SelectedNode == null)
throw new ApplicationException("Missing node");
if (configurationTree.SelectedNode.PrevNode == null)
throw new ApplicationException("Missing previous node");
if (configurationTree.Parent == null)
throw new ApplicationException("Missing parent node");
XmlTreeNodeImpl nodeMoved = (XmlTreeNodeImpl)configurationTree.SelectedNode;
nodeMoved.MoveTo(nodeMoved.Index - 1);
m_TreeNodeConfigFile.IsDirty = true;
}
catch (Exception err)
{
AppUtility.ShowError(this, err);
}
finally
{
configurationTree.EndUpdate();
}
}
private void mnMoveDown_Click(object sender, EventArgs e)
{
configurationTree.BeginUpdate();
try
{
if (configurationTree.SelectedNode == null)
throw new ApplicationException("Missing node");
if (configurationTree.SelectedNode.NextNode == null)
throw new ApplicationException("Missing next node");
if (configurationTree.Parent == null)
throw new ApplicationException("Missing parent node");
XmlTreeNodeImpl nodeMoved = (XmlTreeNodeImpl)configurationTree.SelectedNode;
nodeMoved.MoveTo(nodeMoved.Index + 1);
m_TreeNodeConfigFile.IsDirty = true;
}
catch (Exception err)
{
AppUtility.ShowError(this, err);
}
finally
{
configurationTree.EndUpdate();
}
}
private void treeView_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control)
{
switch (e.KeyCode)
{
case Keys.Up:
// up
if (mnMoveUp.Enabled) mnMoveUp_Click(sender, e);
break;
case Keys.Down:
//down
if (mnMoveDown.Enabled) mnMoveDown_Click(sender, e);
break;
}
}
}
#region Drag and Drop
/// <summary>
/// A node container for drag-and-drop
/// </summary>
private class TreeNodeImplContainer
{
private XmlTreeNodeImpl m_data = null;
public XmlTreeNodeImpl NodeData
{
get
{
return m_data;
}
}
public TreeNodeImplContainer(XmlTreeNodeImpl value)
{
m_data = value;
}
}
private void treeView_ItemDrag(object sender, ItemDragEventArgs e)
{
TreeNodeImplContainer container = new TreeNodeImplContainer((XmlTreeNodeImpl)e.Item);
DoDragDrop(container, DragDropEffects.Move);
}
private void treeView_DragDrop(object sender, DragEventArgs e)
{
configurationTree.BeginUpdate();
try
{
if (!e.Data.GetDataPresent(typeof(TreeNodeImplContainer)))
return;
// target node
Point pos = configurationTree.PointToClient(new Point(e.X, e.Y));
XmlTreeNodeImpl targetNode = (XmlTreeNodeImpl)configurationTree.GetNodeAt(pos);
// node being dragged
XmlTreeNodeImpl dropNode = ((TreeNodeImplContainer)e.Data.GetData(typeof(TreeNodeImplContainer))).NodeData;
// check that this node data type can be dropped here at all
XmlClass dropItem = (XmlClass)dropNode.Tag;
dropNode.MoveTo(targetNode);
m_TreeNodeConfigFile.IsDirty = true;
}
finally
{
configurationTree.EndUpdate();
}
}
private void treeView_DragEnter(object sender, DragEventArgs e)
{
e.Effect = (e.Data.GetDataPresent(typeof(TreeNodeImplContainer)))
? DragDropEffects.Move
: DragDropEffects.None;
}
private void treeView_DragOver(object sender, DragEventArgs e)
{
if (!e.Data.GetDataPresent(typeof(TreeNodeImplContainer)))
{
e.Effect = DragDropEffects.None;
return;
}
// target node
Point pos = configurationTree.PointToClient(new Point(e.X, e.Y));
TreeNode targetNode = configurationTree.GetNodeAt(pos);
if (targetNode == null)
{
e.Effect = DragDropEffects.None;
return;
}
// if the target node is selected, don't validate again
if (configurationTree.SelectedNode == targetNode)
return;
configurationTree.SelectedNode = targetNode;
// node being dragged
XmlTreeNodeImpl dropNode = ((TreeNodeImplContainer)e.Data.GetData(typeof(TreeNodeImplContainer))).NodeData;
if (dropNode.Parent == targetNode)
{
e.Effect = DragDropEffects.None;
return;
}
// check that this node data type can be dropped here at all
XmlClass dropItem = (XmlClass)dropNode.Tag;
XmlClass targetItem = (XmlClass)targetNode.Tag;
if (!targetItem.Children.CanAdd(dropItem))
{
e.Effect = DragDropEffects.None;
return;
}
// check that the selected node is not the dropNode and also that it is not a child of the dropNode
while (targetNode != null)
{
if (targetNode == dropNode)
{
e.Effect = DragDropEffects.None;
return;
}
targetNode = targetNode.Parent;
}
e.Effect = DragDropEffects.Move;
}
#endregion
private void mnExpandAll_Click(object sender, EventArgs e)
{
try
{
configurationTree.SelectedNode.ExpandAll();
}
catch (Exception err)
{
AppUtility.ShowError(this, err);
}
}
private void mnCollapseAll_Click(object sender, EventArgs e)
{
try
{
configurationTree.SelectedNode.Collapse(false);
}
catch (Exception err)
{
AppUtility.ShowError(this, err);
}
}
private void mnUsersGuide_Click(object sender, EventArgs e)
{
try
{
string chm = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), @"..\doc\dotNetInstaller.chm");
System.Diagnostics.ProcessStartInfo p = new System.Diagnostics.ProcessStartInfo(chm);
p.UseShellExecute = true;
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo = p;
process.Start();
}
catch (Exception err)
{
AppUtility.ShowError(this, err);
}
}
private void propertyGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
{
if (m_TreeNodeConfigFile != null)
{
m_TreeNodeConfigFile.IsDirty = true;
}
}
private void mnEdit_Popup(object sender, EventArgs e)
{
mnAdd.Enabled = (m_TreeNodeConfigFile != null);
mnDelete.Enabled = (configurationTree.SelectedNode != null);
mnExpandAll.Enabled = (configurationTree.SelectedNode != null && configurationTree.SelectedNode.Nodes.Count > 0);
mnCollapseAll.Enabled = (configurationTree.SelectedNode != null && configurationTree.SelectedNode.IsExpanded);
mnMove.Enabled = (m_TreeNodeConfigFile != null);
}
private void contextMenuTreeView_Popup(object sender, EventArgs e)
{
mnEdit_Popup(sender, e);
contextMenuTreeView.MenuItems.Clear();
contextMenuTreeView.MergeMenu(mnEdit);
}
private void mnAddExeComponent_Click(object sender, System.EventArgs e)
{
AddTreeNode_Click<ComponentExe>();
}
private void mnFile_Click(object sender, EventArgs e)
{
if (mnOpenRecent.MenuItems.Count == 0)
{
mnOpenRecent.Enabled = false;
}
}
#region IMRUClient Members
public void OpenMRUFile(string fileName)
{
OpenConfiguration(fileName);
}
#endregion
}
}
| |
//
// SimProcess.cs
//
// Author(s):
// Alessio Parma <alessio.parma@gmail.com>
//
// Copyright (c) 2012-2016 Alessio Parma <alessio.parma@gmail.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.
namespace DIBRIS.Dessert
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using Core;
using Events;
using Finsa.CodeServices.Common.Collections;
/// <summary>
///
/// </summary>
/// <remarks>
/// This class could not be named "Process" in order to make its usage easier.
/// In fact, commonly used "System" namespace already contains a "Process" class.
///
/// This class implements the <see cref="ILinkedList{T}"/> interface to perform an effective
/// optimization when one event is yielded by a process only, which is a common situation.
/// </remarks>
public sealed class SimProcess : SimEvent<SimProcess, object>, ILinkedList<SimProcess>
{
/// <summary>
///
/// </summary>
IInternalCall _currentCall;
uint _interruptCount;
object _interruptValue;
/// <summary>
/// Stores a reference to the <see cref="IEnumerator{T}"/> returned by the generator method.
/// It is used to activate and stop generator execution flow.
/// </summary>
IEnumerator<SimEvent> _steps;
/// <summary>
///
/// </summary>
object _value;
/// <summary>
///
/// </summary>
/// <param name="env"></param>
/// <param name="steps"></param>
internal SimProcess(SimEnvironment env, IEnumerator<SimEvent> steps) : base(env)
{
_steps = steps;
}
/// <summary>
/// Called when this event is the first in the agenda.
/// </summary>
internal override void Step()
{
// Target has to be cleaned before process is started up again.
Target = null;
// In SimPy 3, interrupts are sent to processes as exceptions.
// However, this cannot be done in .NET; therefore, we dediced to throw
// an exception if a process was interrupted, but it did not check for that.
// To achieve this, we need to record the number of interrupts
// this process has and we will see if it has properly decreased.
var oldInterruptCount = _interruptCount;
// We start the process again and see if it produces more events.
if (_steps.MoveNext() && !ReferenceEquals(Target = _steps.Current, Env.EndEvent)) {
// User has yielded an event. Since users may yield null events,
// we need to check for them, as they are not allowed.
if (Target == null) {
throw new ArgumentNullException(ErrorMessages.NullEvent);
}
// If the interrupt count was zero, then we have nothing more to check.
// Otherwise, we will need to check that it was decreased at least by one.
if (oldInterruptCount != 0 && _interruptCount == oldInterruptCount) {
throw new InterruptUncaughtException();
}
Target.Subscribe(this);
return;
}
// Body of generator has finished, therefore process or call has finished.
// If the interrupt count was zero, then we have nothing more to check.
// Otherwise, we will need to check that it was decreased at least by one.
if (oldInterruptCount != 0 && _interruptCount == oldInterruptCount) {
throw new InterruptUncaughtException();
}
// If target event is the end event, then the process should exit,
// no matter how many interrupts have been received.
if (_currentCall != null) {
_steps = _currentCall.Steps;
_currentCall = _currentCall.PreviousCall;
} else {
// We have to remove current process from the agenda.
Env.UnscheduleActiveProcess();
// Marks this event as succeeded, as processes cannot fail.
End();
}
}
internal void SetExitValue(object value)
{
if (_currentCall != null) {
_currentCall.SetValue(value);
} else {
_value = value;
}
}
/// <summary>
/// Updates current steps, so that <see cref="IInternalCall.Steps"/> are used instead.
/// Moreover, it adjusts the stack of calls, since that is necessary to maintain integrity.
/// </summary>
/// <param name="call">The call from which new steps are taken.</param>
internal void PushCall(IInternalCall call)
{
var tmp = call.Steps;
call.Steps = _steps;
_steps = tmp;
call.PreviousCall = _currentCall;
_currentCall = call;
}
internal void ReceiveInterrupt(object value)
{
Debug.Assert(Target != null);
Target.RemoveSubscriber(this);
Env.ScheduleProcess(this);
_interruptValue = value;
}
#region Public Members
/// <summary>
/// Returns whether the process has been processed or not.
/// </summary>
[System.Diagnostics.Contracts.Pure]
public bool IsAlive
{
get { return !Succeeded; }
}
/// <summary>
/// The event that the process is currently waiting for.
/// May be a null event if the process was just started
/// or interrupted and it did not yet yield a new event.
/// </summary>
[Pure]
public SimEvent Target { get; private set; }
/// <summary>
///
/// </summary>
/// <exception cref="InvalidOperationException">
/// Process it not alive or a process is trying to interrupt itself.
/// </exception>
public void Interrupt()
{
Contract.Requires<InvalidOperationException>(IsAlive, ErrorMessages.EndedProcess);
Contract.Requires<InvalidOperationException>(!ReferenceEquals(this, Env.ActiveProcess), ErrorMessages.InterruptSameProcess);
// Code below is the same in other Interrupt overloads, remember to update them.
var interrupt = new Interrupt(Env, this, Default.Value);
Env.ScheduleInterrupt(interrupt);
_interruptCount++;
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <exception cref="InvalidOperationException">
/// Process it not alive or a process is trying to interrupt itself.
/// </exception>
public void Interrupt(object value)
{
Contract.Requires<InvalidOperationException>(IsAlive, ErrorMessages.EndedProcess);
Contract.Requires<InvalidOperationException>(!ReferenceEquals(this, Env.ActiveProcess), ErrorMessages.InterruptSameProcess);
// Code below is the same in other Interrupt overloads, remember to update them.
var interrupt = new Interrupt(Env, this, value);
Env.ScheduleInterrupt(interrupt);
_interruptCount++;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="InvalidOperationException">
/// Process it not alive or a process is trying to query another process for interrupts.
/// </exception>
public bool Interrupted()
{
Contract.Requires<InvalidOperationException>(IsAlive, ErrorMessages.EndedProcess);
Contract.Requires<InvalidOperationException>(ReferenceEquals(this, Env.ActiveProcess), ErrorMessages.InterruptedDifferentProcess);
// Code below is the same in other Interrupted overloads, remember to update them.
if (_interruptCount > 0) {
_interruptCount--;
return true;
}
return false;
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException">
/// Process it not alive or a process is trying to query another process for interrupts.
/// </exception>
public bool Interrupted(out object value)
{
Contract.Requires<InvalidOperationException>(IsAlive, ErrorMessages.EndedProcess);
Contract.Requires<InvalidOperationException>(ReferenceEquals(this, Env.ActiveProcess), ErrorMessages.InterruptedDifferentProcess);
// Code below is the same in other Interrupted overloads, remember to update them.
if (_interruptCount > 0) {
_interruptCount--;
value = _interruptValue;
return true;
}
value = null;
return false;
}
public bool Preempted()
{
object obj;
if (Interrupted(out obj)) {
if (obj is PreemptionInfo) {
return true;
}
_interruptCount++;
return false;
}
return false;
}
public bool Preempted(out PreemptionInfo info)
{
object obj;
if (Interrupted(out obj)) {
info = obj as PreemptionInfo;
if (info != null) {
return true;
}
_interruptCount++;
return false;
}
info = null;
return false;
}
#endregion
#region SimEvent Members
public override object Value
{
get { return _value; }
}
#endregion
#region ILinkedList Members
int ICollection<SimProcess>.Count
{
get { return 1; }
}
SimProcess IThinLinkedList<SimProcess>.First
{
get { return this; }
}
bool ICollection<SimProcess>.Contains(SimProcess item)
{
return Equals(item);
}
IEnumerator<SimProcess> IEnumerable<SimProcess>.GetEnumerator()
{
yield return this;
}
IEqualityComparer<SimProcess> IThinLinkedList<SimProcess>.EqualityComparer
{
get { throw new DessertException(ErrorMessages.InvalidMethod); }
}
bool ICollection<SimProcess>.IsReadOnly
{
get { throw new DessertException(ErrorMessages.InvalidMethod); }
}
SimProcess ILinkedList<SimProcess>.Last
{
get { throw new DessertException(ErrorMessages.InvalidMethod); }
}
void ICollection<SimProcess>.Add(SimProcess item)
{
throw new DessertException(ErrorMessages.InvalidMethod);
}
void IThinLinkedList<SimProcess>.AddFirst(SimProcess item)
{
throw new DessertException(ErrorMessages.InvalidMethod);
}
void ILinkedList<SimProcess>.AddLast(SimProcess item)
{
throw new DessertException(ErrorMessages.InvalidMethod);
}
void ILinkedList<SimProcess>.Append(ILinkedList<SimProcess> list)
{
throw new DessertException(ErrorMessages.InvalidMethod);
}
void ICollection<SimProcess>.Clear()
{
throw new DessertException(ErrorMessages.InvalidMethod);
}
void ICollection<SimProcess>.CopyTo(SimProcess[] array, int arrayIndex)
{
throw new DessertException(ErrorMessages.InvalidMethod);
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new DessertException(ErrorMessages.InvalidMethod);
}
bool ICollection<SimProcess>.Remove(SimProcess item)
{
throw new DessertException(ErrorMessages.InvalidMethod);
}
SimProcess IThinLinkedList<SimProcess>.RemoveFirst()
{
throw new DessertException(ErrorMessages.InvalidMethod);
}
#endregion
}
public sealed class PreemptionInfo
{
readonly SimProcess _by;
readonly Double _usageSince;
internal PreemptionInfo(SimProcess by, Double usageSince)
{
_by = by;
_usageSince = usageSince;
}
/// <summary>
///
/// </summary>
[Pure]
public SimProcess By
{
get { return _by; }
}
/// <summary>
///
/// </summary>
[System.Diagnostics.Contracts.Pure]
public double UsageSince
{
get { return _usageSince; }
}
}
}
| |
using UnityEngine;
using System.Collections;
namespace UnityStandardAssets.Characters.ThirdPerson
{
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]
[RequireComponent(typeof(Animator))]
public class ThirdPersonCharacter : MonoBehaviour
{
[SerializeField] float m_MovingTurnSpeed = 360;
[SerializeField] float m_StationaryTurnSpeed = 180;
[SerializeField] float m_JumpPower;
private const float JumpPower_FOR_FOOT = 6f;
private const float JumpPower_FOR_EXOSKELETON = 6f;
private float lastJumpPressedAt;
private const float EXOSKELETON_DOUBLE_JUMP_PRESS_TIME = 0.5f;
private float jumpLandingTime;
private float lastJumpedTime;
private const float JUMP_ALLOWED_FREQUENCY = 0.3f;
// if the player has landed few moments ago, his jumping speed should be increased
// this variable determines the timeframe for that
private const float EXOSKELETON_DOUBLE_JUMP_TIME = 0.5f;
private bool justLandedFromJump = false;
[Range(1f, 4f)][SerializeField] float m_GravityMultiplier = 2f;
[SerializeField] float m_RunCycleLegOffset = 0.2f; //specific to the character in sample assets, will need to be modified to work with others
[SerializeField] float m_MoveSpeedMultiplier = 1f;
private const float MoveSpeedMultiplier_FOR_FOOT = 1f;
private const float MoveSpeedMultiplier_FOR_EXOSKELETON = 1.5f;
[SerializeField] float m_AnimSpeedMultiplier = 1f;
[SerializeField] float m_GroundCheckDistance = 0.1f;
private const float GroundCheckDistance_FOR_FOOT = 0.3f;
private const float GroundCheckDistance_FOR_EXOSKELETON = 0.9f;
private const float COLLIDER_CENTER_FOR_FOOT = 1.08f;
private const float COLLIDER_HEIGHT_FOR_FOOT = 2.16f;
private const float COLLIDER_CENTER_FOR_EXOSKELETON = 0.87f;
private const float COLLIDER_HEIGHT_FOR_EXOSKELETON = 2.4f;
[SerializeField] bool m_HasExoskeleton = false;
[SerializeField] GameObject m_ExoskeletonLeft;
[SerializeField] GameObject m_ExoskeletonRight;
[SerializeField] PhysicMaterial m_PhysicsMaterialForFoot;
[SerializeField] PhysicMaterial m_PhysicsMaterialForExoskeleton;
private bool hasJumped = false;
[SerializeField] bool m_HasJetPack = false;
[SerializeField] float m_JetPackForce = 15f;
[SerializeField] AudioSource m_JetPackAudioSource;
[SerializeField] ParticleSystem[] m_JetPackParticles;
[SerializeField] GameObject m_JetPack;
private const int JETPACK_LAYER_INDEX = 1;
private const float JETPACK_TOP_REACH = 40;
private const float JETPACK_MIN_VOLUME = 0.5f;
private const float JETPACK_MIN_DOWNWARD_VELOCITY = -5f;
Rigidbody m_Rigidbody;
Animator m_Animator;
AudioSource m_AudioSource;
bool m_IsGrounded;
float m_OrigGroundCheckDistance;
const float k_Half = 0.5f;
float m_TurnAmount;
float m_ForwardAmount;
Vector3 m_GroundNormal;
float m_CapsuleHeight;
Vector3 m_CapsuleCenter;
CapsuleCollider m_Capsule;
bool m_Crouching;
[SerializeField] Transform m_CharacterRoot;
private float lastRunClipPlayedAt;
public AudioClip runClip;
public AudioClip jumpClip;
public AudioClip landClip;
public AudioClip runClipExosKeleton;
public AudioClip jumpClipExosKeleton;
public AudioClip landClipExosKeleton;
public static ThirdPersonCharacter Instance;
void Start()
{
Instance = this;
m_Animator = GetComponent<Animator>();
m_AudioSource = GetComponent<AudioSource>();
m_Rigidbody = GetComponent<Rigidbody>();
m_Capsule = GetComponent<CapsuleCollider>();
m_CapsuleHeight = m_Capsule.height;
m_CapsuleCenter = m_Capsule.center;
m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ;
m_OrigGroundCheckDistance = m_GroundCheckDistance;
setJetPack(m_HasJetPack, true);
m_JetPackAudioSource.volume = JETPACK_MIN_VOLUME;
setExoskeleton(m_HasExoskeleton, true);
}
public bool hasExoskeleton()
{
return m_HasExoskeleton;
}
public void setExoskeleton(bool val, bool force = false)
{
if(m_IsGrounded == false)
{
if(!force)
{
Debug.LogError("Player needs to be grounded before toggling Exoskeleton");
return;
}
}
if(val)
{
m_HasExoskeleton = true;
m_Capsule.height = COLLIDER_HEIGHT_FOR_EXOSKELETON;
m_Capsule.center = new Vector3(m_Capsule.center.x, COLLIDER_CENTER_FOR_EXOSKELETON, m_Capsule.center.z);
m_GroundCheckDistance = GroundCheckDistance_FOR_EXOSKELETON;
m_JumpPower = JumpPower_FOR_EXOSKELETON;
m_MoveSpeedMultiplier = MoveSpeedMultiplier_FOR_EXOSKELETON;
m_Capsule.material = m_PhysicsMaterialForExoskeleton;
setJetPack(false, true);
}
else
{
m_HasExoskeleton = false;
m_Capsule.height = COLLIDER_HEIGHT_FOR_FOOT;
m_Capsule.center = new Vector3(m_Capsule.center.x, COLLIDER_CENTER_FOR_FOOT, m_Capsule.center.z);
m_GroundCheckDistance = GroundCheckDistance_FOR_FOOT;
m_JumpPower = JumpPower_FOR_FOOT;
m_MoveSpeedMultiplier = MoveSpeedMultiplier_FOR_FOOT;
m_Capsule.material = m_PhysicsMaterialForFoot;
}
m_ExoskeletonLeft.SetActive(val);
m_ExoskeletonRight.SetActive(val);
m_CapsuleHeight = m_Capsule.height;
m_CapsuleCenter = m_Capsule.center;
m_OrigGroundCheckDistance = m_GroundCheckDistance;
}
public bool hasJetPack()
{
return m_HasJetPack;
}
public void setJetPack(bool val, bool force = false)
{
if(m_IsGrounded == false)
{
if(!force)
{
Debug.LogError("Player needs to be grounded before toggling JetPack");
return;
}
}
if(val)
{
m_HasJetPack = true;
m_Animator.SetLayerWeight(JETPACK_LAYER_INDEX, 1);
setExoskeleton(false, true);
}
else
{
m_HasJetPack = false;
m_Animator.SetLayerWeight(JETPACK_LAYER_INDEX, 0);
}
m_JetPack.SetActive(val);
}
public void addJetPackForce()
{
if(m_HasJetPack && transform.position.y < JETPACK_TOP_REACH)
{
hasJumped = true;
// remove all his previous force
m_Rigidbody.velocity = Vector3.zero;
m_Rigidbody.AddForce(Vector3.up * m_JetPackForce, ForceMode.Impulse);
m_JetPackAudioSource.Play();
if(m_JetPackAudioSource.volume == JETPACK_MIN_VOLUME)
{
m_JetPackAudioSource.volume = 1;
StartCoroutine("reduceJetSound");
}
else
{
m_JetPackAudioSource.volume = 1;
}
foreach(ParticleSystem ps in m_JetPackParticles)
{
ps.Play();
ps.startSpeed = 10f;
}
if(IsInvoking("reduceJetBurne"))
{
CancelInvoke("reduceJetBurne");
}
Invoke("reduceJetBurne", 0.5f);
}
}
void reduceJetBurne()
{
foreach(ParticleSystem ps in m_JetPackParticles)
{
ps.startSpeed = 3f;
}
}
IEnumerator reduceJetSound()
{
while(m_JetPackAudioSource.volume > JETPACK_MIN_VOLUME)
{
m_JetPackAudioSource.volume = Mathf.Lerp(m_JetPackAudioSource.volume, JETPACK_MIN_VOLUME, Time.deltaTime * 3f);
yield return null;
}
m_JetPackAudioSource.volume = JETPACK_MIN_VOLUME;
}
public void Move(Vector3 move, bool crouch, bool jump)
{
if(Input.GetKeyDown(KeyCode.LeftCommand))
{
m_MoveSpeedMultiplier = 3;
}
else if(Input.GetKeyUp(KeyCode.LeftCommand))
{
m_MoveSpeedMultiplier = 1;
}
// convert the world relative moveInput vector into a local-relative
// turn amount and forward amount required to head in the desired
// direction.
if (move.magnitude > 1f) move.Normalize();
move = transform.InverseTransformDirection(move);
CheckGroundStatus();
move = Vector3.ProjectOnPlane(move, m_GroundNormal);
//Debug.Log(move);
m_TurnAmount = Mathf.Atan2(move.x, move.z);
//Debug.Log(m_TurnAmount);
m_ForwardAmount = move.z;
ApplyExtraTurnRotation();
if(jump)
{
lastJumpPressedAt = Time.time;
}
if(justLandedFromJump && m_IsGrounded && hasExoskeleton() && lastJumpPressedAt > Time.time - EXOSKELETON_DOUBLE_JUMP_PRESS_TIME)
{
// if the player has pressed jump button few moments ago when in air. allow it to work now that he is on ground
jump = true;
//Debug.Log("Delayed Jump");
}
justLandedFromJump = false;
// control and velocity handling is different when grounded and airborne:
if(jump && m_HasJetPack)
{
addJetPackForce();
hasJumped = true;
}
else if (m_IsGrounded && !hasJumped)
{
HandleGroundedMovement(crouch, jump, move);
}
else
{
HandleAirborneMovement();
}
ScaleCapsuleForCrouching(crouch);
PreventStandingInLowHeadroom();
// send input and other state parameters to the animator
UpdateAnimator(move);
if(m_HasJetPack)
{
if(hasJumped)
{
// player has a jetpack and he has jumped already
transform.Translate(Vector3.forward * m_ForwardAmount * m_JetPackForce * 2f * Time.deltaTime);
m_Animator.SetLayerWeight(2, 1);
//Debug.Log(m_Rigidbody.velocity);
// rotate the player forward a bit when he is using the jet and moving forward
Vector3 rotation = new Vector3(move.z == 0 ? 0 : Mathf.Clamp(15f / move.z, -15, 15) , 0, 0);
//Debug.Log("Move: " + move);
//Debug.Log(rotation);
m_CharacterRoot.localRotation = Quaternion.Lerp(m_CharacterRoot.localRotation, Quaternion.Euler(rotation), Time.deltaTime * 10) ;
}
else
{
m_Animator.SetLayerWeight(2, 0);
m_CharacterRoot.localRotation = Quaternion.Euler(Vector3.zero);
}
}
}
void ScaleCapsuleForCrouching(bool crouch)
{
if (m_IsGrounded && crouch)
{
if (m_Crouching) return;
m_Capsule.height = m_Capsule.height / 2f;
m_Capsule.center = m_Capsule.center / 2f;
m_Crouching = true;
}
else
{
Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half;
if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, ~0, QueryTriggerInteraction.Ignore))
{
m_Crouching = true;
return;
}
m_Capsule.height = m_CapsuleHeight;
m_Capsule.center = m_CapsuleCenter;
m_Crouching = false;
}
}
void PreventStandingInLowHeadroom()
{
// prevent standing up in crouch-only zones
if (!m_Crouching)
{
Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half;
if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, ~0, QueryTriggerInteraction.Ignore))
{
m_Crouching = true;
}
}
}
void UpdateAnimator(Vector3 move)
{
// update the animator parameters
m_Animator.SetFloat("Forward", m_ForwardAmount, 0.1f, Time.deltaTime);
m_Animator.SetFloat("Turn", m_TurnAmount, 0.1f, Time.deltaTime);
m_Animator.SetBool("Crouch", m_Crouching);
m_Animator.SetBool("OnGround", m_IsGrounded);
if(hasExoskeleton())
{
// when player is in idle mode players leg should not move while using Exoskeleton
if(m_IsGrounded && m_ForwardAmount == 0 && m_TurnAmount == 0)
{
m_Animator.SetLayerWeight(3, 1);
}
else
{
m_Animator.SetLayerWeight(3, 0);
}
}
if (!m_IsGrounded && !m_HasJetPack)
{
m_Animator.SetFloat("Jump", m_Rigidbody.velocity.y);
}
// calculate which leg is behind, so as to leave that leg trailing in the jump animation
// (This code is reliant on the specific run cycle offset in our animations,
// and assumes one leg passes the other at the normalized clip times of 0.0 and 0.5)
float runCycle =
Mathf.Repeat(
m_Animator.GetCurrentAnimatorStateInfo(0).normalizedTime + m_RunCycleLegOffset, 1);
float jumpLeg = (runCycle < k_Half ? 1 : -1) * m_ForwardAmount;
if (m_IsGrounded)
{
m_Animator.SetFloat("JumpLeg", jumpLeg);
}
// the anim speed multiplier allows the overall speed of walking/running to be tweaked in the inspector,
// which affects the movement speed because of the root motion.
if (m_IsGrounded && move.magnitude > 0)
{
m_Animator.speed = m_AnimSpeedMultiplier;
}
else
{
// don't use that while airborne
m_Animator.speed = 1;
}
}
void HandleAirborneMovement()
{
// apply extra gravity from multiplier:
Vector3 extraGravityForce = (Physics.gravity * m_GravityMultiplier) - Physics.gravity;
m_Rigidbody.AddForce(extraGravityForce);
m_GroundCheckDistance = m_Rigidbody.velocity.y < 0 ? m_OrigGroundCheckDistance : 0.01f;
if(m_HasJetPack && hasJumped)
{
// if player has jetpack, he should not have too much downward velocity
if(m_Rigidbody.velocity.y < JETPACK_MIN_DOWNWARD_VELOCITY) m_Rigidbody.velocity = new Vector3(m_Rigidbody.velocity.x, JETPACK_MIN_DOWNWARD_VELOCITY, m_Rigidbody.velocity.z);
}
}
void HandleGroundedMovement(bool crouch, bool jump, Vector3 moveDirection)
{
// check whether conditions are right to allow a jump:
if (jump && !crouch
&& lastJumpedTime < Time.time - JUMP_ALLOWED_FREQUENCY
&& (m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Grounded")
|| (hasExoskeleton() && lastJumpPressedAt > Time.time - EXOSKELETON_DOUBLE_JUMP_PRESS_TIME )
)
)
{
// jump!
//m_Rigidbody.velocity = new Vector3(m_Rigidbody.velocity.x, hasExoskeleton() && jumpLandingTime > Time.time - EXOSKELETON_DOUBLE_JUMP_TIME ? m_JumpPower * 1.25f : m_JumpPower, m_Rigidbody.velocity.z);
moveDirection = transform.TransformDirection(moveDirection);
//Debug.Log("Direction: " + moveDirection);
//Debug.Log("Jumped");
lastJumpPressedAt = 0;
lastJumpedTime = Time.time;
float maxHorizontalVelocity = 6.67f * m_MoveSpeedMultiplier;
Vector3 velocity = new Vector3( maxHorizontalVelocity * moveDirection.x,
hasExoskeleton() && jumpLandingTime > Time.time - EXOSKELETON_DOUBLE_JUMP_TIME ? m_JumpPower * 1.25f : m_JumpPower,
maxHorizontalVelocity * moveDirection.z
);
m_Rigidbody.velocity = velocity;
//Debug.Log("Velocity: " + m_Rigidbody.velocity);
/*
m_Rigidbody.AddForce(new Vector3(moveDirection.x,
(hasExoskeleton() && jumpLandingTime > Time.time - EXOSKELETON_DOUBLE_JUMP_TIME ? 2f : 1.5f),
moveDirection.z)
* m_JumpPower, ForceMode.VelocityChange);
*/
m_IsGrounded = false;
m_Animator.applyRootMotion = false;
m_GroundCheckDistance = 0.1f;
m_AudioSource.PlayOneShot(hasExoskeleton() ? jumpClipExosKeleton : jumpClip);
hasJumped = true;
}
}
void ApplyExtraTurnRotation()
{
// help the character turn faster (this is in addition to root rotation in the animation)
float turnSpeed = Mathf.Lerp(m_StationaryTurnSpeed, m_MovingTurnSpeed, m_ForwardAmount);
transform.Rotate(0, m_TurnAmount * turnSpeed * Time.deltaTime, 0);
}
public void footPlaced()
{
if(Time.time - lastRunClipPlayedAt > 0.1f)
{
lastRunClipPlayedAt = Time.time;
m_AudioSource.PlayOneShot(hasExoskeleton() ? runClipExosKeleton : runClip, m_ForwardAmount / 3f);
}
}
public void OnAnimatorMove()
{
// we implement this function to override the default root motion.
// this allows us to modify the positional speed before it's applied.
if (m_IsGrounded && hasJumped == false && Time.deltaTime > 0)
{
Vector3 v = (m_Animator.deltaPosition * m_MoveSpeedMultiplier) / Time.deltaTime;
// we preserve the existing y part of the current velocity.
v.y = m_Rigidbody.velocity.y;
m_Rigidbody.velocity = v;
}
}
void CheckGroundStatus()
{
RaycastHit hitInfo;
#if UNITY_EDITOR
// helper to visualise the ground check ray in the scene view
Debug.DrawLine(transform.position + (Vector3.up * 0.1f), transform.position + (Vector3.up * 0.1f) + (Vector3.down * m_GroundCheckDistance));
#endif
// 0.1f is a small offset to start the ray from inside the character
// it is also good to note that the transform position in the sample assets is at the base of the character
if (Physics.Raycast(transform.position + (Vector3.up * 0.1f), Vector3.down, out hitInfo, m_GroundCheckDistance))
{
if(m_IsGrounded == false)
{
// player has just landed
//Debug.Log("Hit Ground");
//Debug.Log("Volume: " + Mathf.Clamp01( Mathf.Abs(m_Rigidbody.velocity.y) / 7f));
m_AudioSource.PlayOneShot(hasExoskeleton() ? landClipExosKeleton : landClip, Mathf.Clamp01( Mathf.Abs(m_Rigidbody.velocity.y) / 7f) );
jumpLandingTime = Time.time;
hasJumped = false;
m_JetPackAudioSource.Stop();
foreach(ParticleSystem ps in m_JetPackParticles)
{
ps.Stop();
}
justLandedFromJump = true;
}
m_GroundNormal = hitInfo.normal;
m_IsGrounded = true;
m_Animator.applyRootMotion = true;
}
else
{
m_IsGrounded = false;
m_GroundNormal = Vector3.up;
m_Animator.applyRootMotion = false;
}
}
}
}
| |
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// 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 Castle.DynamicProxy.Internal
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using Castle.DynamicProxy.Generators;
public static class AttributeUtil
{
private static readonly IDictionary<Type, IAttributeDisassembler> disassemblers =
new Dictionary<Type, IAttributeDisassembler>();
private static IAttributeDisassembler fallbackDisassembler = new AttributeDisassembler();
public static IAttributeDisassembler FallbackDisassembler
{
get { return fallbackDisassembler; }
set { fallbackDisassembler = value; }
}
/// <summary>
/// Registers custom disassembler to handle disassembly of specified type of attributes.
/// </summary>
/// <typeparam name = "TAttribute">Type of attributes to handle</typeparam>
/// <param name = "disassembler">Disassembler converting existing instances of Attributes to CustomAttributeBuilders</param>
/// <remarks>
/// When disassembling an attribute Dynamic Proxy will first check if an custom disassembler has been registered to handle attributes of that type,
/// and if none is found, it'll use the <see cref = "FallbackDisassembler" />.
/// </remarks>
public static void AddDisassembler<TAttribute>(IAttributeDisassembler disassembler) where TAttribute : Attribute
{
if (disassembler == null)
{
throw new ArgumentNullException("disassembler");
}
disassemblers[typeof(TAttribute)] = disassembler;
}
#if !SILVERLIGHT
public static CustomAttributeBuilder CreateBuilder(CustomAttributeData attribute)
{
Debug.Assert(attribute != null, "attribute != null");
PropertyInfo[] properties;
object[] propertyValues;
FieldInfo[] fields;
object[] fieldValues;
GetSettersAndFields(attribute.NamedArguments, out properties, out propertyValues, out fields, out fieldValues);
var constructorArgs = GetArguments(attribute.ConstructorArguments);
return new CustomAttributeBuilder(attribute.Constructor,
constructorArgs,
properties,
propertyValues,
fields,
fieldValues);
}
private static object[] GetArguments(IList<CustomAttributeTypedArgument> constructorArguments)
{
var arguments = new object[constructorArguments.Count];
for (var i = 0; i < constructorArguments.Count; i++)
{
arguments[i] = ReadAttributeValue(constructorArguments[i]);
}
return arguments;
}
private static object ReadAttributeValue(CustomAttributeTypedArgument argument)
{
var value = argument.Value;
if (argument.ArgumentType.GetTypeInfo().IsArray == false)
{
return value;
}
//special case for handling arrays in attributes
var arguments = GetArguments((IList<CustomAttributeTypedArgument>)value);
var array = Array.CreateInstance(argument.ArgumentType.GetElementType() ?? typeof(object), arguments.Length);
arguments.CopyTo(array, 0);
return array;
}
private static void GetSettersAndFields(IEnumerable<CustomAttributeNamedArgument> namedArguments,
out PropertyInfo[] properties, out object[] propertyValues,
out FieldInfo[] fields, out object[] fieldValues)
{
var propertyList = new List<PropertyInfo>();
var propertyValuesList = new List<object>();
var fieldList = new List<FieldInfo>();
var fieldValuesList = new List<object>();
foreach (var argument in namedArguments)
{
switch (argument.MemberInfo.MemberType)
{
case MemberTypes.Property:
propertyList.Add(argument.MemberInfo as PropertyInfo);
propertyValuesList.Add(ReadAttributeValue(argument.TypedValue));
break;
case MemberTypes.Field:
fieldList.Add(argument.MemberInfo as FieldInfo);
fieldValuesList.Add(ReadAttributeValue(argument.TypedValue));
break;
default:
// NOTE: can this ever happen?
throw new ArgumentException(string.Format("Unexpected member type {0} in custom attribute.",
argument.MemberInfo.MemberType));
}
}
properties = propertyList.ToArray();
propertyValues = propertyValuesList.ToArray();
fields = fieldList.ToArray();
fieldValues = fieldValuesList.ToArray();
}
#else
// CustomAttributeData is internal in Silverlight
#endif
public static IEnumerable<CustomAttributeBuilder> GetNonInheritableAttributes(this MemberInfo member)
{
Debug.Assert(member != null, "member != null");
var attributes =
#if SILVERLIGHT
member.GetCustomAttributes(false);
#else
CustomAttributeData.GetCustomAttributes(member);
#endif
foreach (var attribute in attributes)
{
var attributeType =
#if SILVERLIGHT
attribute.GetType();
#else
attribute.Constructor.DeclaringType;
#endif
if (ShouldSkipAttributeReplication(attributeType))
{
continue;
}
CustomAttributeBuilder builder;
try
{
builder = CreateBuilder(attribute
#if SILVERLIGHT
as Attribute
#endif
);
}
catch (ArgumentException e)
{
var message =
string.Format(
"Due to limitations in CLR, DynamicProxy was unable to successfully replicate non-inheritable attribute {0} on {1}{2}. To avoid this error you can chose not to replicate this attribute type by calling '{3}.Add(typeof({0}))'.",
attributeType.FullName, (member.ReflectedType == null) ? "" : member.ReflectedType.FullName,
(member is Type) ? "" : ("." + member.Name), typeof(AttributesToAvoidReplicating).FullName);
throw new ProxyGenerationException(message, e);
}
if (builder != null)
{
yield return builder;
}
}
}
public static IEnumerable<CustomAttributeBuilder> GetNonInheritableAttributes(this ParameterInfo parameter)
{
Debug.Assert(parameter != null, "parameter != null");
var attributes =
#if SILVERLIGHT
parameter.GetCustomAttributes(false);
#else
CustomAttributeData.GetCustomAttributes(parameter);
#endif
foreach (var attribute in attributes)
{
var attributeType =
#if SILVERLIGHT
attribute.GetType();
#else
attribute.Constructor.DeclaringType;
#endif
if (ShouldSkipAttributeReplication(attributeType))
{
continue;
}
var builder = CreateBuilder(attribute
#if SILVERLIGHT
as Attribute
#endif
);
if (builder != null)
{
yield return builder;
}
}
}
/// <summary>
/// Attributes should be replicated if they are non-inheritable,
/// but there are some special cases where the attributes means
/// something to the CLR, where they should be skipped.
/// </summary>
private static bool ShouldSkipAttributeReplication(Type attribute)
{
if (attribute.GetTypeInfo().IsPublic == false)
{
return true;
}
if (SpecialCaseAttributThatShouldNotBeReplicated(attribute))
{
return true;
}
var attrs = attribute.GetCustomAttributes(typeof(AttributeUsageAttribute), true);
if (attrs.Length != 0)
{
var usage = (AttributeUsageAttribute)attrs[0];
return usage.Inherited;
}
return true;
}
private static bool SpecialCaseAttributThatShouldNotBeReplicated(Type attribute)
{
return AttributesToAvoidReplicating.Contains(attribute);
}
public static CustomAttributeBuilder CreateBuilder<TAttribute>() where TAttribute : Attribute, new()
{
var constructor = typeof(TAttribute).GetConstructor(Type.EmptyTypes);
Debug.Assert(constructor != null, "constructor != null");
return new CustomAttributeBuilder(constructor, new object[0]);
}
public static CustomAttributeBuilder CreateBuilder(Type attribute, object[] constructorArguments)
{
Debug.Assert(attribute != null, "attribute != null");
Debug.Assert(typeof(Attribute).IsAssignableFrom(attribute), "typeof(Attribute).IsAssignableFrom(attribute)");
Debug.Assert(constructorArguments != null, "constructorArguments != null");
var constructor = attribute.GetConstructor(GetTypes(constructorArguments));
Debug.Assert(constructor != null, "constructor != null");
return new CustomAttributeBuilder(constructor, constructorArguments);
}
// NOTE: Use other overloads if possible. This method is here to support Silverlight and legacy scenarios.
internal static CustomAttributeBuilder CreateBuilder(Attribute attribute)
{
var type = attribute.GetType();
IAttributeDisassembler disassembler;
if (disassemblers.TryGetValue(type, out disassembler))
{
return disassembler.Disassemble(attribute);
}
return FallbackDisassembler.Disassemble(attribute);
}
private static Type[] GetTypes(object[] objects)
{
var types = new Type[objects.Length];
for (var i = 0; i < types.Length; i++)
{
types[i] = objects[i].GetType();
}
return types;
}
}
}
| |
// 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!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>CustomerManagerLink</c> resource.</summary>
public sealed partial class CustomerManagerLinkName : gax::IResourceName, sys::IEquatable<CustomerManagerLinkName>
{
/// <summary>The possible contents of <see cref="CustomerManagerLinkName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}</c>.
/// </summary>
CustomerManagerCustomerManagerLink = 1,
}
private static gax::PathTemplate s_customerManagerCustomerManagerLink = new gax::PathTemplate("customers/{customer_id}/customerManagerLinks/{manager_customer_id_manager_link_id}");
/// <summary>Creates a <see cref="CustomerManagerLinkName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="CustomerManagerLinkName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static CustomerManagerLinkName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CustomerManagerLinkName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CustomerManagerLinkName"/> with the pattern
/// <c>customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="managerCustomerId">The <c>ManagerCustomer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="managerLinkId">The <c>ManagerLink</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="CustomerManagerLinkName"/> constructed from the provided ids.
/// </returns>
public static CustomerManagerLinkName FromCustomerManagerCustomerManagerLink(string customerId, string managerCustomerId, string managerLinkId) =>
new CustomerManagerLinkName(ResourceNameType.CustomerManagerCustomerManagerLink, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), managerCustomerId: gax::GaxPreconditions.CheckNotNullOrEmpty(managerCustomerId, nameof(managerCustomerId)), managerLinkId: gax::GaxPreconditions.CheckNotNullOrEmpty(managerLinkId, nameof(managerLinkId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomerManagerLinkName"/> with pattern
/// <c>customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="managerCustomerId">The <c>ManagerCustomer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="managerLinkId">The <c>ManagerLink</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CustomerManagerLinkName"/> with pattern
/// <c>customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}</c>.
/// </returns>
public static string Format(string customerId, string managerCustomerId, string managerLinkId) =>
FormatCustomerManagerCustomerManagerLink(customerId, managerCustomerId, managerLinkId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomerManagerLinkName"/> with pattern
/// <c>customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="managerCustomerId">The <c>ManagerCustomer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="managerLinkId">The <c>ManagerLink</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CustomerManagerLinkName"/> with pattern
/// <c>customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}</c>.
/// </returns>
public static string FormatCustomerManagerCustomerManagerLink(string customerId, string managerCustomerId, string managerLinkId) =>
s_customerManagerCustomerManagerLink.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(managerCustomerId, nameof(managerCustomerId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(managerLinkId, nameof(managerLinkId)))}");
/// <summary>
/// Parses the given resource name string into a new <see cref="CustomerManagerLinkName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="customerManagerLinkName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CustomerManagerLinkName"/> if successful.</returns>
public static CustomerManagerLinkName Parse(string customerManagerLinkName) => Parse(customerManagerLinkName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CustomerManagerLinkName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customerManagerLinkName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="CustomerManagerLinkName"/> if successful.</returns>
public static CustomerManagerLinkName Parse(string customerManagerLinkName, bool allowUnparsed) =>
TryParse(customerManagerLinkName, allowUnparsed, out CustomerManagerLinkName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CustomerManagerLinkName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="customerManagerLinkName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CustomerManagerLinkName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string customerManagerLinkName, out CustomerManagerLinkName result) =>
TryParse(customerManagerLinkName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CustomerManagerLinkName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customerManagerLinkName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CustomerManagerLinkName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string customerManagerLinkName, bool allowUnparsed, out CustomerManagerLinkName result)
{
gax::GaxPreconditions.CheckNotNull(customerManagerLinkName, nameof(customerManagerLinkName));
gax::TemplatedResourceName resourceName;
if (s_customerManagerCustomerManagerLink.TryParseName(customerManagerLinkName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerManagerCustomerManagerLink(resourceName[0], split1[0], split1[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(customerManagerLinkName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private CustomerManagerLinkName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string managerCustomerId = null, string managerLinkId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
ManagerCustomerId = managerCustomerId;
ManagerLinkId = managerLinkId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CustomerManagerLinkName"/> class from the component parts of
/// pattern <c>customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="managerCustomerId">The <c>ManagerCustomer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="managerLinkId">The <c>ManagerLink</c> ID. Must not be <c>null</c> or empty.</param>
public CustomerManagerLinkName(string customerId, string managerCustomerId, string managerLinkId) : this(ResourceNameType.CustomerManagerCustomerManagerLink, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), managerCustomerId: gax::GaxPreconditions.CheckNotNullOrEmpty(managerCustomerId, nameof(managerCustomerId)), managerLinkId: gax::GaxPreconditions.CheckNotNullOrEmpty(managerLinkId, nameof(managerLinkId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>ManagerCustomer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string ManagerCustomerId { get; }
/// <summary>
/// The <c>ManagerLink</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ManagerLinkId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerManagerCustomerManagerLink: return s_customerManagerCustomerManagerLink.Expand(CustomerId, $"{ManagerCustomerId}~{ManagerLinkId}");
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as CustomerManagerLinkName);
/// <inheritdoc/>
public bool Equals(CustomerManagerLinkName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CustomerManagerLinkName a, CustomerManagerLinkName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CustomerManagerLinkName a, CustomerManagerLinkName b) => !(a == b);
}
public partial class CustomerManagerLink
{
/// <summary>
/// <see cref="CustomerManagerLinkName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal CustomerManagerLinkName ResourceNameAsCustomerManagerLinkName
{
get => string.IsNullOrEmpty(ResourceName) ? null : CustomerManagerLinkName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CustomerName"/>-typed view over the <see cref="ManagerCustomer"/> resource name property.
/// </summary>
internal CustomerName ManagerCustomerAsCustomerName
{
get => string.IsNullOrEmpty(ManagerCustomer) ? null : CustomerName.Parse(ManagerCustomer, allowUnparsed: true);
set => ManagerCustomer = value?.ToString() ?? "";
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using Roslyn.Utilities;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.CodeAnalysis.CompilerServer;
namespace Microsoft.CodeAnalysis.BuildTasks
{
/// <summary>
/// This class defines all of the common stuff that is shared between the Vbc and Csc tasks.
/// This class is not instantiatable as a Task just by itself.
/// </summary>
public abstract class ManagedCompiler : ToolTask
{
private CancellationTokenSource _sharedCompileCts;
internal readonly PropertyDictionary _store = new PropertyDictionary();
public ManagedCompiler()
{
this.TaskResources = ErrorString.ResourceManager;
}
#region Properties
// Please keep these alphabetized.
public string[] AdditionalLibPaths
{
set { _store[nameof(AdditionalLibPaths)] = value; }
get { return (string[])_store[nameof(AdditionalLibPaths)]; }
}
public string[] AddModules
{
set { _store[nameof(AddModules)] = value; }
get { return (string[])_store[nameof(AddModules)]; }
}
public ITaskItem[] AdditionalFiles
{
set { _store[nameof(AdditionalFiles)] = value; }
get { return (ITaskItem[])_store[nameof(AdditionalFiles)]; }
}
public ITaskItem[] Analyzers
{
set { _store[nameof(Analyzers)] = value; }
get { return (ITaskItem[])_store[nameof(Analyzers)]; }
}
// We do not support BugReport because it always requires user interaction,
// which will cause a hang.
public string CodeAnalysisRuleSet
{
set { _store[nameof(CodeAnalysisRuleSet)] = value; }
get { return (string)_store[nameof(CodeAnalysisRuleSet)]; }
}
public int CodePage
{
set { _store[nameof(CodePage)] = value; }
get { return _store.GetOrDefault(nameof(CodePage), 0); }
}
[Output]
public ITaskItem[] CommandLineArgs
{
set { _store[nameof(CommandLineArgs)] = value; }
get { return (ITaskItem[])_store[nameof(CommandLineArgs)]; }
}
public string DebugType
{
set { _store[nameof(DebugType)] = value; }
get { return (string)_store[nameof(DebugType)]; }
}
public string DefineConstants
{
set { _store[nameof(DefineConstants)] = value; }
get { return (string)_store[nameof(DefineConstants)]; }
}
public bool DelaySign
{
set { _store[nameof(DelaySign)] = value; }
get { return _store.GetOrDefault(nameof(DelaySign), false); }
}
public bool EmitDebugInformation
{
set { _store[nameof(EmitDebugInformation)] = value; }
get { return _store.GetOrDefault(nameof(EmitDebugInformation), false); }
}
public string ErrorLog
{
set { _store[nameof(ErrorLog)] = value; }
get { return (string)_store[nameof(ErrorLog)]; }
}
public string Features
{
set { _store[nameof(Features)] = value; }
get { return (string)_store[nameof(Features)]; }
}
public int FileAlignment
{
set { _store[nameof(FileAlignment)] = value; }
get { return _store.GetOrDefault(nameof(FileAlignment), 0); }
}
public bool HighEntropyVA
{
set { _store[nameof(HighEntropyVA)] = value; }
get { return _store.GetOrDefault(nameof(HighEntropyVA), false); }
}
public string KeyContainer
{
set { _store[nameof(KeyContainer)] = value; }
get { return (string)_store[nameof(KeyContainer)]; }
}
public string KeyFile
{
set { _store[nameof(KeyFile)] = value; }
get { return (string)_store[nameof(KeyFile)]; }
}
public ITaskItem[] LinkResources
{
set { _store[nameof(LinkResources)] = value; }
get { return (ITaskItem[])_store[nameof(LinkResources)]; }
}
public string MainEntryPoint
{
set { _store[nameof(MainEntryPoint)] = value; }
get { return (string)_store[nameof(MainEntryPoint)]; }
}
public bool NoConfig
{
set { _store[nameof(NoConfig)] = value; }
get { return _store.GetOrDefault(nameof(NoConfig), false); }
}
public bool NoLogo
{
set { _store[nameof(NoLogo)] = value; }
get { return _store.GetOrDefault(nameof(NoLogo), false); }
}
public bool NoWin32Manifest
{
set { _store[nameof(NoWin32Manifest)] = value; }
get { return _store.GetOrDefault(nameof(NoWin32Manifest), false); }
}
public bool Optimize
{
set { _store[nameof(Optimize)] = value; }
get { return _store.GetOrDefault(nameof(Optimize), false); }
}
[Output]
public ITaskItem OutputAssembly
{
set { _store[nameof(OutputAssembly)] = value; }
get { return (ITaskItem)_store[nameof(OutputAssembly)]; }
}
public string Platform
{
set { _store[nameof(Platform)] = value; }
get { return (string)_store[nameof(Platform)]; }
}
public bool Prefer32Bit
{
set { _store[nameof(Prefer32Bit)] = value; }
get { return _store.GetOrDefault(nameof(Prefer32Bit), false); }
}
public bool ProvideCommandLineArgs
{
set { _store[nameof(ProvideCommandLineArgs)] = value; }
get { return _store.GetOrDefault(nameof(ProvideCommandLineArgs), false); }
}
public ITaskItem[] References
{
set { _store[nameof(References)] = value; }
get { return (ITaskItem[])_store[nameof(References)]; }
}
public bool ReportAnalyzer
{
set { _store[nameof(ReportAnalyzer)] = value; }
get { return _store.GetOrDefault(nameof(ReportAnalyzer), false); }
}
public ITaskItem[] Resources
{
set { _store[nameof(Resources)] = value; }
get { return (ITaskItem[])_store[nameof(Resources)]; }
}
public ITaskItem[] ResponseFiles
{
set { _store[nameof(ResponseFiles)] = value; }
get { return (ITaskItem[])_store[nameof(ResponseFiles)]; }
}
public bool SkipCompilerExecution
{
set { _store[nameof(SkipCompilerExecution)] = value; }
get { return _store.GetOrDefault(nameof(SkipCompilerExecution), false); }
}
public ITaskItem[] Sources
{
set
{
if (UsedCommandLineTool)
{
NormalizePaths(value);
}
_store[nameof(Sources)] = value;
}
get { return (ITaskItem[])_store[nameof(Sources)]; }
}
public string SubsystemVersion
{
set { _store[nameof(SubsystemVersion)] = value; }
get { return (string)_store[nameof(SubsystemVersion)]; }
}
public string TargetType
{
set { _store[nameof(TargetType)] = value.ToLower(CultureInfo.InvariantCulture); }
get { return (string)_store[nameof(TargetType)]; }
}
public bool TreatWarningsAsErrors
{
set { _store[nameof(TreatWarningsAsErrors)] = value; }
get { return _store.GetOrDefault(nameof(TreatWarningsAsErrors), false); }
}
public bool Utf8Output
{
set { _store[nameof(Utf8Output)] = value; }
get { return _store.GetOrDefault(nameof(Utf8Output), false); }
}
public string Win32Icon
{
set { _store[nameof(Win32Icon)] = value; }
get { return (string)_store[nameof(Win32Icon)]; }
}
public string Win32Manifest
{
set { _store[nameof(Win32Manifest)] = value; }
get { return (string)_store[nameof(Win32Manifest)]; }
}
public string Win32Resource
{
set { _store[nameof(Win32Resource)] = value; }
get { return (string)_store[nameof(Win32Resource)]; }
}
/// <summary>
/// If this property is true then the task will take every C# or VB
/// compilation which is queued by MSBuild and send it to the
/// VBCSCompiler server instance, starting a new instance if necessary.
/// If false, we will use the values from ToolPath/Exe.
/// </summary>
public bool UseSharedCompilation
{
set { _store[nameof(UseSharedCompilation)] = value; }
get { return _store.GetOrDefault(nameof(UseSharedCompilation), false); }
}
// Map explicit platform of "AnyCPU" or the default platform (null or ""), since it is commonly understood in the
// managed build process to be equivalent to "AnyCPU", to platform "AnyCPU32BitPreferred" if the Prefer32Bit
// property is set.
internal string PlatformWith32BitPreference
{
get
{
string platform = this.Platform;
if ((String.IsNullOrEmpty(platform) || platform.Equals("anycpu", StringComparison.OrdinalIgnoreCase)) && this.Prefer32Bit)
{
platform = "anycpu32bitpreferred";
}
return platform;
}
}
/// <summary>
/// Overridable property specifying the encoding of the captured task standard output stream
/// </summary>
protected override Encoding StandardOutputEncoding
{
get
{
return (Utf8Output) ? Encoding.UTF8 : base.StandardOutputEncoding;
}
}
#endregion
internal abstract BuildProtocolConstants.RequestLanguage Language { get; }
protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands)
{
if (ProvideCommandLineArgs)
{
CommandLineArgs = GetArguments(commandLineCommands, responseFileCommands)
.Select(arg => new TaskItem(arg)).ToArray();
}
if (SkipCompilerExecution)
{
return 0;
}
if (!UseSharedCompilation || !String.IsNullOrEmpty(this.ToolPath))
{
return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
}
using (_sharedCompileCts = new CancellationTokenSource())
{
try
{
CompilerServerLogger.Log($"CommandLine = '{commandLineCommands}'");
CompilerServerLogger.Log($"BuildResponseFile = '{responseFileCommands}'");
var responseTask = BuildClient.TryRunServerCompilation(
Language,
TryGetClientDir() ?? Path.GetDirectoryName(pathToTool),
CurrentDirectoryToUse(),
GetArguments(commandLineCommands, responseFileCommands),
_sharedCompileCts.Token,
libEnvVariable: LibDirectoryToUse());
responseTask.Wait(_sharedCompileCts.Token);
var response = responseTask.Result;
if (response != null)
{
ExitCode = HandleResponse(response, pathToTool, responseFileCommands, commandLineCommands);
}
else
{
ExitCode = base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
}
}
catch (OperationCanceledException)
{
ExitCode = 0;
}
catch (Exception e)
{
Log.LogErrorWithCodeFromResources("Compiler_UnexpectedException");
LogErrorOutput(e.ToString());
ExitCode = -1;
}
}
return ExitCode;
}
/// <summary>
/// Try to get the directory this assembly is in. Returns null if assembly
/// was in the GAC.
/// </summary>
private static string TryGetClientDir()
{
var assembly = typeof(ManagedCompiler).Assembly;
if (assembly.GlobalAssemblyCache)
return null;
var uri = new Uri(assembly.CodeBase);
string assemblyPath = uri.IsFile
? uri.LocalPath
: Assembly.GetCallingAssembly().Location;
return Path.GetDirectoryName(assemblyPath);
}
/// <summary>
/// Cancel the in-process build task.
/// </summary>
public override void Cancel()
{
base.Cancel();
_sharedCompileCts?.Cancel();
}
/// <summary>
/// Get the current directory that the compiler should run in.
/// </summary>
private string CurrentDirectoryToUse()
{
// ToolTask has a method for this. But it may return null. Use the process directory
// if ToolTask didn't override. MSBuild uses the process directory.
string workingDirectory = GetWorkingDirectory();
if (string.IsNullOrEmpty(workingDirectory))
workingDirectory = Directory.GetCurrentDirectory();
return workingDirectory;
}
/// <summary>
/// Get the "LIB" environment variable, or NULL if none.
/// </summary>
private string LibDirectoryToUse()
{
// First check the real environment.
string libDirectory = Environment.GetEnvironmentVariable("LIB");
// Now go through additional environment variables.
string[] additionalVariables = this.EnvironmentVariables;
if (additionalVariables != null)
{
foreach (string var in this.EnvironmentVariables)
{
if (var.StartsWith("LIB=", StringComparison.OrdinalIgnoreCase))
{
libDirectory = var.Substring(4);
}
}
}
return libDirectory;
}
/// <summary>
/// The return code of the compilation. Strangely, this isn't overridable from ToolTask, so we need
/// to create our own.
/// </summary>
[Output]
public new int ExitCode { get; private set; }
/// <summary>
/// Handle a response from the server, reporting messages and returning
/// the appropriate exit code.
/// </summary>
private int HandleResponse(BuildResponse response, string pathToTool, string responseFileCommands, string commandLineCommands)
{
switch (response.Type)
{
case BuildResponse.ResponseType.MismatchedVersion:
LogErrorOutput(CommandLineParser.MismatchedVersionErrorText);
return -1;
case BuildResponse.ResponseType.Completed:
var completedResponse = (CompletedBuildResponse)response;
LogMessages(completedResponse.Output, this.StandardOutputImportanceToUse);
if (LogStandardErrorAsError)
{
LogErrorOutput(completedResponse.ErrorOutput);
}
else
{
LogMessages(completedResponse.ErrorOutput, this.StandardErrorImportanceToUse);
}
return completedResponse.ReturnCode;
case BuildResponse.ResponseType.AnalyzerInconsistency:
return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
default:
throw new InvalidOperationException("Encountered unknown response type");
}
}
private void LogErrorOutput(string output)
{
string[] lines = output.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
string trimmedMessage = line.Trim();
if (trimmedMessage != "")
{
Log.LogError(trimmedMessage);
}
}
}
/// <summary>
/// Log each of the messages in the given output with the given importance.
/// We assume each line is a message to log.
/// </summary>
/// <remarks>
/// Should be "private protected" visibility once it is introduced into C#.
/// </remarks>
internal abstract void LogMessages(string output, MessageImportance messageImportance);
public string GenerateResponseFileContents()
{
return GenerateResponseFileCommands();
}
/// <summary>
/// Get the command line arguments to pass to the compiler.
/// </summary>
private string[] GetArguments(string commandLineCommands, string responseFileCommands)
{
var commandLineArguments =
CommandLineParser.SplitCommandLineIntoArguments(commandLineCommands, removeHashComments: true);
var responseFileArguments =
CommandLineParser.SplitCommandLineIntoArguments(responseFileCommands, removeHashComments: true);
return commandLineArguments.Concat(responseFileArguments).ToArray();
}
/// <summary>
/// Returns the command line switch used by the tool executable to specify the response file
/// Will only be called if the task returned a non empty string from GetResponseFileCommands
/// Called after ValidateParameters, SkipTaskExecution and GetResponseFileCommands
/// </summary>
protected override string GenerateResponseFileCommands()
{
CommandLineBuilderExtension commandLineBuilder = new CommandLineBuilderExtension();
AddResponseFileCommands(commandLineBuilder);
return commandLineBuilder.ToString();
}
protected override string GenerateCommandLineCommands()
{
CommandLineBuilderExtension commandLineBuilder = new CommandLineBuilderExtension();
AddCommandLineCommands(commandLineBuilder);
return commandLineBuilder.ToString();
}
/// <summary>
/// Fills the provided CommandLineBuilderExtension with those switches and other information that can't go into a response file and
/// must go directly onto the command line.
/// </summary>
protected internal virtual void AddCommandLineCommands(CommandLineBuilderExtension commandLine)
{
commandLine.AppendWhenTrue("/noconfig", this._store, "NoConfig");
}
/// <summary>
/// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file.
/// </summary>
protected internal virtual void AddResponseFileCommands(CommandLineBuilderExtension commandLine)
{
// If outputAssembly is not specified, then an "/out: <name>" option won't be added to
// overwrite the one resulting from the OutputAssembly member of the CompilerParameters class.
// In that case, we should set the outputAssembly member based on the first source file.
if (
(OutputAssembly == null) &&
(Sources != null) &&
(Sources.Length > 0) &&
(this.ResponseFiles == null) // The response file may already have a /out: switch in it, so don't try to be smart here.
)
{
try
{
OutputAssembly = new TaskItem(Path.GetFileNameWithoutExtension(Sources[0].ItemSpec));
}
catch (ArgumentException e)
{
throw new ArgumentException(e.Message, "Sources");
}
if (String.Compare(TargetType, "library", StringComparison.OrdinalIgnoreCase) == 0)
{
OutputAssembly.ItemSpec += ".dll";
}
else if (String.Compare(TargetType, "module", StringComparison.OrdinalIgnoreCase) == 0)
{
OutputAssembly.ItemSpec += ".netmodule";
}
else
{
OutputAssembly.ItemSpec += ".exe";
}
}
commandLine.AppendSwitchIfNotNull("/addmodule:", this.AddModules, ",");
commandLine.AppendSwitchWithInteger("/codepage:", this._store, "CodePage");
ConfigureDebugProperties();
// The "DebugType" parameter should be processed after the "EmitDebugInformation" parameter
// because it's more specific. Order matters on the command-line, and the last one wins.
// /debug+ is just a shorthand for /debug:full. And /debug- is just a shorthand for /debug:none.
commandLine.AppendPlusOrMinusSwitch("/debug", this._store, "EmitDebugInformation");
commandLine.AppendSwitchIfNotNull("/debug:", this.DebugType);
commandLine.AppendPlusOrMinusSwitch("/delaysign", this._store, "DelaySign");
commandLine.AppendSwitchWithInteger("/filealign:", this._store, "FileAlignment");
commandLine.AppendSwitchIfNotNull("/keycontainer:", this.KeyContainer);
commandLine.AppendSwitchIfNotNull("/keyfile:", this.KeyFile);
// If the strings "LogicalName" or "Access" ever change, make sure to search/replace everywhere in vsproject.
commandLine.AppendSwitchIfNotNull("/linkresource:", this.LinkResources, new string[] { "LogicalName", "Access" });
commandLine.AppendWhenTrue("/nologo", this._store, "NoLogo");
commandLine.AppendWhenTrue("/nowin32manifest", this._store, "NoWin32Manifest");
commandLine.AppendPlusOrMinusSwitch("/optimize", this._store, "Optimize");
commandLine.AppendSwitchIfNotNull("/out:", this.OutputAssembly);
commandLine.AppendSwitchIfNotNull("/ruleset:", this.CodeAnalysisRuleSet);
commandLine.AppendSwitchIfNotNull("/errorlog:", this.ErrorLog);
commandLine.AppendSwitchIfNotNull("/subsystemversion:", this.SubsystemVersion);
commandLine.AppendWhenTrue("/reportanalyzer", this._store, "ReportAnalyzer");
// If the strings "LogicalName" or "Access" ever change, make sure to search/replace everywhere in vsproject.
commandLine.AppendSwitchIfNotNull("/resource:", this.Resources, new string[] { "LogicalName", "Access" });
commandLine.AppendSwitchIfNotNull("/target:", this.TargetType);
commandLine.AppendPlusOrMinusSwitch("/warnaserror", this._store, "TreatWarningsAsErrors");
commandLine.AppendWhenTrue("/utf8output", this._store, "Utf8Output");
commandLine.AppendSwitchIfNotNull("/win32icon:", this.Win32Icon);
commandLine.AppendSwitchIfNotNull("/win32manifest:", this.Win32Manifest);
this.AddFeatures(commandLine);
this.AddAnalyzersToCommandLine(commandLine);
this.AddAdditionalFilesToCommandLine(commandLine);
// Append the sources.
commandLine.AppendFileNamesIfNotNull(Sources, " ");
}
/// <summary>
/// Adds a "/features:" switch to the command line for each provided feature.
/// </summary>
/// <param name="commandLine"></param>
private void AddFeatures(CommandLineBuilderExtension commandLine)
{
var features = Features;
if (string.IsNullOrEmpty(features))
{
return;
}
foreach (var feature in CompilerOptionParseUtilities.ParseFeatureFromMSBuild(features))
{
commandLine.AppendSwitchIfNotNull("/features:", feature.Trim());
}
}
/// <summary>
/// Adds a "/analyzer:" switch to the command line for each provided analyzer.
/// </summary>
private void AddAnalyzersToCommandLine(CommandLineBuilderExtension commandLine)
{
// If there were no analyzers passed in, don't add any /analyzer: switches
// on the command-line.
if ((this.Analyzers == null) || (this.Analyzers.Length == 0))
{
return;
}
foreach (ITaskItem analyzer in this.Analyzers)
{
commandLine.AppendSwitchIfNotNull("/analyzer:", analyzer.ItemSpec);
}
}
/// <summary>
/// Adds a "/additionalfile:" switch to the command line for each additional file.
/// </summary>
private void AddAdditionalFilesToCommandLine(CommandLineBuilderExtension commandLine)
{
// If there were no additional files passed in, don't add any /additionalfile: switches
// on the command-line.
if ((this.AdditionalFiles == null) || (this.AdditionalFiles.Length == 0))
{
return;
}
foreach (ITaskItem additionalFile in this.AdditionalFiles)
{
commandLine.AppendSwitchIfNotNull("/additionalfile:", additionalFile.ItemSpec);
}
}
/// <summary>
/// Configure the debug switches which will be placed on the compiler command-line.
/// The matrix of debug type and symbol inputs and the desired results is as follows:
///
/// Debug Symbols DebugType Desired Results
/// True Full /debug+ /debug:full
/// True PdbOnly /debug+ /debug:PdbOnly
/// True None /debug-
/// True Blank /debug+
/// False Full /debug- /debug:full
/// False PdbOnly /debug- /debug:PdbOnly
/// False None /debug-
/// False Blank /debug-
/// Blank Full /debug:full
/// Blank PdbOnly /debug:PdbOnly
/// Blank None /debug-
/// Debug: Blank Blank /debug+ //Microsoft.common.targets will set this
/// Release: Blank Blank "Nothing for either switch"
///
/// The logic is as follows:
/// If debugtype is none set debugtype to empty and debugSymbols to false
/// If debugType is blank use the debugsymbols "as is"
/// If debug type is set, use its value and the debugsymbols value "as is"
/// </summary>
private void ConfigureDebugProperties()
{
// If debug type is set we need to take some action depending on the value. If debugtype is not set
// We don't need to modify the EmitDebugInformation switch as its value will be used as is.
if (_store["DebugType"] != null)
{
// If debugtype is none then only show debug- else use the debug type and the debugsymbols as is.
if (string.Compare((string)_store["DebugType"], "none", StringComparison.OrdinalIgnoreCase) == 0)
{
_store["DebugType"] = null;
_store["EmitDebugInformation"] = false;
}
}
}
/// <summary>
/// Validate parameters, log errors and warnings and return true if
/// Execute should proceed.
/// </summary>
protected override bool ValidateParameters()
{
return ListHasNoDuplicateItems(this.Resources, "Resources", "LogicalName") && ListHasNoDuplicateItems(this.Sources, "Sources");
}
/// <summary>
/// Returns true if the provided item list contains duplicate items, false otherwise.
/// </summary>
protected bool ListHasNoDuplicateItems(ITaskItem[] itemList, string parameterName)
{
return ListHasNoDuplicateItems(itemList, parameterName, null);
}
/// <summary>
/// Returns true if the provided item list contains duplicate items, false otherwise.
/// </summary>
/// <param name="itemList"></param>
/// <param name="disambiguatingMetadataName">Optional name of metadata that may legitimately disambiguate items. May be null.</param>
/// <param name="parameterName"></param>
private bool ListHasNoDuplicateItems(ITaskItem[] itemList, string parameterName, string disambiguatingMetadataName)
{
if (itemList == null || itemList.Length == 0)
{
return true;
}
Hashtable alreadySeen = new Hashtable(StringComparer.OrdinalIgnoreCase);
foreach (ITaskItem item in itemList)
{
string key;
string disambiguatingMetadataValue = null;
if (disambiguatingMetadataName != null)
{
disambiguatingMetadataValue = item.GetMetadata(disambiguatingMetadataName);
}
if (disambiguatingMetadataName == null || String.IsNullOrEmpty(disambiguatingMetadataValue))
{
key = item.ItemSpec;
}
else
{
key = item.ItemSpec + ":" + disambiguatingMetadataValue;
}
if (alreadySeen.ContainsKey(key))
{
if (disambiguatingMetadataName == null || String.IsNullOrEmpty(disambiguatingMetadataValue))
{
Log.LogErrorWithCodeFromResources("General_DuplicateItemsNotSupported", item.ItemSpec, parameterName);
}
else
{
Log.LogErrorWithCodeFromResources("General_DuplicateItemsNotSupportedWithMetadata", item.ItemSpec, parameterName, disambiguatingMetadataValue, disambiguatingMetadataName);
}
return false;
}
else
{
alreadySeen[key] = String.Empty;
}
}
return true;
}
/// <summary>
/// Allows tool to handle the return code.
/// This method will only be called with non-zero exitCode.
/// </summary>
protected override bool HandleTaskExecutionErrors()
{
// For managed compilers, the compiler should emit the appropriate
// error messages before returning a non-zero exit code, so we don't
// normally need to emit any additional messages now.
//
// If somehow the compiler DID return a non-zero exit code and didn't log an error, we'd like to log that exit code.
// We can only do this for the command line compiler: if the inproc compiler was used,
// we can't tell what if anything it logged as it logs directly to Visual Studio's output window.
//
if (!Log.HasLoggedErrors && UsedCommandLineTool)
{
// This will log a message "MSB3093: The command exited with code {0}."
base.HandleTaskExecutionErrors();
}
return false;
}
/// <summary>
/// Takes a list of files and returns the normalized locations of these files
/// </summary>
private void NormalizePaths(ITaskItem[] taskItems)
{
foreach (var item in taskItems)
{
item.ItemSpec = Utilities.GetFullPathNoThrow(item.ItemSpec);
}
}
/// <summary>
/// Whether the command line compiler was invoked, instead
/// of the host object compiler.
/// </summary>
protected bool UsedCommandLineTool
{
get;
set;
}
private bool _hostCompilerSupportsAllParameters;
protected bool HostCompilerSupportsAllParameters
{
get { return _hostCompilerSupportsAllParameters; }
set { _hostCompilerSupportsAllParameters = value; }
}
/// <summary>
/// Checks the bool result from calling one of the methods on the host compiler object to
/// set one of the parameters. If it returned false, that means the host object doesn't
/// support a particular parameter or variation on a parameter. So we log a comment,
/// and set our state so we know not to call the host object to do the actual compilation.
/// </summary>
/// <owner>RGoel</owner>
protected void CheckHostObjectSupport
(
string parameterName,
bool resultFromHostObjectSetOperation
)
{
if (!resultFromHostObjectSetOperation)
{
Log.LogMessageFromResources(MessageImportance.Normal, "General_ParameterUnsupportedOnHostCompiler", parameterName);
_hostCompilerSupportsAllParameters = false;
}
}
/// <summary>
/// Checks to see whether all of the passed-in references exist on disk before we launch the compiler.
/// </summary>
/// <owner>RGoel</owner>
protected bool CheckAllReferencesExistOnDisk()
{
if (null == this.References)
{
// No references
return true;
}
bool success = true;
foreach (ITaskItem reference in this.References)
{
if (!File.Exists(reference.ItemSpec))
{
success = false;
Log.LogErrorWithCodeFromResources("General_ReferenceDoesNotExist", reference.ItemSpec);
}
}
return success;
}
/// <summary>
/// The IDE and command line compilers unfortunately differ in how win32
/// manifests are specified. In particular, the command line compiler offers a
/// "/nowin32manifest" switch, while the IDE compiler does not offer analogous
/// functionality. If this switch is omitted from the command line and no win32
/// manifest is specified, the compiler will include a default win32 manifest
/// named "default.win32manifest" found in the same directory as the compiler
/// executable. Again, the IDE compiler does not offer analogous support.
///
/// We'd like to imitate the command line compiler's behavior in the IDE, but
/// it isn't aware of the default file, so we must compute the path to it if
/// noDefaultWin32Manifest is false and no win32Manifest was provided by the
/// project.
///
/// This method will only be called during the initialization of the host object,
/// which is only used during IDE builds.
/// </summary>
/// <returns>the path to the win32 manifest to provide to the host object</returns>
internal string GetWin32ManifestSwitch
(
bool noDefaultWin32Manifest,
string win32Manifest
)
{
if (!noDefaultWin32Manifest)
{
if (String.IsNullOrEmpty(win32Manifest) && String.IsNullOrEmpty(this.Win32Resource))
{
// We only want to consider the default.win32manifest if this is an executable
if (!String.Equals(TargetType, "library", StringComparison.OrdinalIgnoreCase)
&& !String.Equals(TargetType, "module", StringComparison.OrdinalIgnoreCase))
{
// We need to compute the path to the default win32 manifest
string pathToDefaultManifest = ToolLocationHelper.GetPathToDotNetFrameworkFile
(
"default.win32manifest",
TargetDotNetFrameworkVersion.VersionLatest
);
if (null == pathToDefaultManifest)
{
// This is rather unlikely, and the inproc compiler seems to log an error anyway.
// So just a message is fine.
Log.LogMessageFromResources
(
"General_ExpectedFileMissing",
"default.win32manifest"
);
}
return pathToDefaultManifest;
}
}
}
return win32Manifest;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Cryptography;
using System.Text;
namespace DbMigrations.Client.Infrastructure
{
public static class StringExtensions
{
// ReSharper disable once InconsistentNaming
private static readonly MD5 MD5 = MD5.Create();
public static string Checksum(this string input)
{
var bytes = Encoding.UTF8.GetBytes(input);
var hash = MD5.ComputeHash(bytes);
var checksum = BitConverter.ToString(hash).Replace("-", "");
return checksum;
}
public static IEnumerable<string> Lines(this string text)
{
var lineStart = 0;
var lineEnd = -1;
while (lineEnd < text.Length - 1)
{
lineEnd = text.IndexOf('\n', lineStart);
if (lineEnd == -1)
{
lineEnd = text.Length - 1;
}
var line = text.Substring(lineStart, lineEnd + 1 - lineStart);
yield return line;
lineStart = lineEnd + 1;
}
}
public static IEnumerable<string> Parameters(this string s, string escapeChar)
{
if (string.IsNullOrEmpty(s)) throw new ArgumentNullException(nameof(s));
return IterateParameters(s, escapeChar);
}
private static IEnumerable<string> IterateParameters(string s, string escapeChar)
{
bool isParameter = false;
var sb = new StringBuilder();
foreach (var c in s)
{
if (sb.ToString().EndsWith(escapeChar))
{
if (isParameter)
throw new InvalidOperationException("Invalid query");
isParameter = true;
sb.Clear();
}
if (isParameter && sb.Length == 0 && char.IsLetter(c))
sb.Append(c);
else if (isParameter && sb.Length > 0 && char.IsLetterOrDigit(c))
sb.Append(c);
else if (isParameter)
{
yield return sb.ToString();
isParameter = false;
sb.Clear();
}
else
{
sb.Append(c);
}
}
if (sb.Length > 0 && isParameter)
yield return sb.ToString();
}
public static IEnumerable<string> Words(this string s)
{
if (string.IsNullOrEmpty(s)) throw new ArgumentNullException(nameof(s));
return IterateWords(s);
}
private static IEnumerable<string> IterateWords(string s)
{
var sb = new StringBuilder();
foreach (var c in s)
{
if (char.IsUpper(c) && sb.Length > 0 && !char.IsUpper(sb[sb.Length - 1]))
{
yield return sb.ToString();
sb.Clear();
sb.Append(c);
}
else
{
sb.Append(c);
}
}
if (sb.Length > 0)
yield return sb.ToString();
}
public static string ToUpperCaseWithUnderscores(this string text)
{
return string.Join("_",
text.Words().Select(s => s.ToUpperInvariant())
);
}
public static string FormatWith(this string format, object parameters)
{
if (format == null)
{
throw new ArgumentNullException(nameof(format));
}
var sb = new StringBuilder(format.Length*2);
foreach (var fragment in format.Fragments())
{
sb.Append(fragment.ToString(parameters));
}
return sb.ToString();
}
class Fragment
{
public static Fragment Literal()
{
return new Fragment((content, ignored) => content);
}
public static Fragment Expression()
{
return new Fragment((expression, source) => expression.Eval(source));
}
private Fragment(Func<string, object, string> toString)
{
_toString = toString;
}
private readonly StringBuilder _s = new StringBuilder();
private readonly Func<string, object, string> _toString;
public void Append(char c)
{
_s.Append(c);
}
public string ToString(object source)
{
return _toString(_s.ToString(), source);
}
public override string ToString()
{
return _s.ToString();
}
}
static IEnumerable<Fragment> Fragments(this string s)
{
return new FragmentIterator().GetFragments(s);
}
class FragmentIterator
{
private readonly Queue<Fragment> _fragments = new Queue<Fragment>();
private Fragment _currentFragment;
enum Location
{
OutsideExpression,
InsideExpression,
OnCloseBracket,
OnOpenBracket
}
public IEnumerable<Fragment> GetFragments(string format)
{
NextFragment(Fragment.Literal());
var l = Location.OutsideExpression;
foreach (var c in format)
{
switch (l)
{
case Location.OutsideExpression:
l = OnOutsideExpression(l, c);
break;
case Location.InsideExpression:
l = OnInsideExpression(l, c);
break;
case Location.OnCloseBracket:
l = OnCloseBracket(l, c);
break;
case Location.OnOpenBracket:
l = OnOpenBracket(l, c);
break;
default:
throw new ArgumentOutOfRangeException();
}
while (_fragments.Any())
{
yield return _fragments.Dequeue();
}
}
if (l != Location.OutsideExpression)
throw new FormatException();
if (_currentFragment != null)
yield return _currentFragment;
}
private Location OnOpenBracket(Location l, char c)
{
if (l != Location.OnOpenBracket)
throw new ArgumentException("l");
if (c == '{')
{
_currentFragment.Append('{');
return Location.OutsideExpression;
}
NextFragment(Fragment.Expression());
_currentFragment.Append(c);
return Location.InsideExpression;
}
private Location OnCloseBracket(Location l, char c)
{
if (l != Location.OnCloseBracket)
throw new ArgumentException("l");
if (c == '}')
{
_currentFragment.Append('}');
return Location.OutsideExpression;
}
throw new FormatException();
}
private Location OnInsideExpression(Location l, char c)
{
if (l != Location.InsideExpression)
throw new ArgumentException("l");
if (c == '}')
{
NextFragment(Fragment.Literal());
return Location.OutsideExpression;
}
_currentFragment.Append(c);
return l;
}
private Location OnOutsideExpression(Location l, char c)
{
if (l != Location.OutsideExpression)
throw new ArgumentException("l");
if (c == '{')
{
return Location.OnOpenBracket;
}
if (c == '}')
{
return Location.OnCloseBracket;
}
_currentFragment.Append(c);
return l;
}
private void NextFragment(Fragment fragment)
{
if (_currentFragment != null)
_fragments.Enqueue(_currentFragment);
_currentFragment = fragment;
}
}
public static string Eval(this string expression, object obj)
{
var colonIndex = expression.IndexOf(':');
if (colonIndex > 0)
{
var format = "{0:" + expression.Substring(colonIndex + 1) + "}";
expression = expression.Substring(0, colonIndex);
var value = Evaluate(expression, obj);
return string.Format(format, value);
}
else
{
var value = Evaluate(expression, obj);
if (value == null) return string.Empty;
return value.ToString();
}
}
private static object Evaluate(string expression, object target)
{
var targetType = target.GetType();
Delegate d;
var key = new {targetType, expression};
if (!Delegates.TryGetValue(key, out d))
{
ParameterExpression[] parameters = { Expression.Parameter(targetType, "") };
var parser = new ExpressionParser(parameters, expression, null);
var body = parser.Parse(typeof (object));
var lambda = Expression.Lambda(body, parameters);
d = lambda.Compile();
Delegates[key] = d;
}
var value = d.DynamicInvoke(target);
return value;
}
static readonly IDictionary<object, Delegate> Delegates = new Dictionary<object, Delegate>();
}
}
| |
// 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.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Text;
namespace System.Reflection.Internal
{
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
internal unsafe struct MemoryBlock
{
internal readonly byte* Pointer;
internal readonly int Length;
internal MemoryBlock(byte* buffer, int length)
{
Debug.Assert(length >= 0 && (buffer != null || length == 0));
this.Pointer = buffer;
this.Length = length;
}
internal static MemoryBlock CreateChecked(byte* buffer, int length)
{
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
if (buffer == null && length != 0)
{
throw new ArgumentNullException(nameof(buffer));
}
return new MemoryBlock(buffer, length);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckBounds(int offset, int byteCount)
{
if (unchecked((ulong)(uint)offset + (uint)byteCount) > (ulong)Length)
{
Throw.OutOfBounds();
}
}
internal byte[] ToArray()
{
return Pointer == null ? null : PeekBytes(0, Length);
}
private string GetDebuggerDisplay()
{
if (Pointer == null)
{
return "<null>";
}
int displayedBytes;
return GetDebuggerDisplay(out displayedBytes);
}
internal string GetDebuggerDisplay(out int displayedBytes)
{
displayedBytes = Math.Min(Length, 64);
string result = BitConverter.ToString(PeekBytes(0, displayedBytes));
if (displayedBytes < Length)
{
result += "-...";
}
return result;
}
internal string GetDebuggerDisplay(int offset)
{
if (Pointer == null)
{
return "<null>";
}
int displayedBytes;
string display = GetDebuggerDisplay(out displayedBytes);
if (offset < displayedBytes)
{
display = display.Insert(offset * 3, "*");
}
else if (displayedBytes == Length)
{
display += "*";
}
else
{
display += "*...";
}
return display;
}
internal MemoryBlock GetMemoryBlockAt(int offset, int length)
{
CheckBounds(offset, length);
return new MemoryBlock(Pointer + offset, length);
}
internal byte PeekByte(int offset)
{
CheckBounds(offset, sizeof(byte));
return Pointer[offset];
}
internal int PeekInt32(int offset)
{
uint result = PeekUInt32(offset);
if (unchecked((int)result != result))
{
Throw.ValueOverflow();
}
return (int)result;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal uint PeekUInt32(int offset)
{
CheckBounds(offset, sizeof(uint));
unchecked
{
byte* ptr = Pointer + offset;
return (uint)(ptr[0] | (ptr[1] << 8) | (ptr[2] << 16) | (ptr[3] << 24));
}
}
/// <summary>
/// Decodes a compressed integer value starting at offset.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <param name="offset">Offset to the start of the compressed data.</param>
/// <param name="numberOfBytesRead">Bytes actually read.</param>
/// <returns>
/// Value between 0 and 0x1fffffff, or <see cref="BlobReader.InvalidCompressedInteger"/> if the value encoding is invalid.
/// </returns>
internal int PeekCompressedInteger(int offset, out int numberOfBytesRead)
{
CheckBounds(offset, 0);
byte* ptr = Pointer + offset;
long limit = Length - offset;
if (limit == 0)
{
numberOfBytesRead = 0;
return BlobReader.InvalidCompressedInteger;
}
byte headerByte = ptr[0];
if ((headerByte & 0x80) == 0)
{
numberOfBytesRead = 1;
return headerByte;
}
else if ((headerByte & 0x40) == 0)
{
if (limit >= 2)
{
numberOfBytesRead = 2;
return ((headerByte & 0x3f) << 8) | ptr[1];
}
}
else if ((headerByte & 0x20) == 0)
{
if (limit >= 4)
{
numberOfBytesRead = 4;
return ((headerByte & 0x1f) << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];
}
}
numberOfBytesRead = 0;
return BlobReader.InvalidCompressedInteger;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ushort PeekUInt16(int offset)
{
CheckBounds(offset, sizeof(ushort));
unchecked
{
byte* ptr = Pointer + offset;
return (ushort)(ptr[0] | (ptr[1] << 8));
}
}
// When reference has tag bits.
internal uint PeekTaggedReference(int offset, bool smallRefSize)
{
return PeekReferenceUnchecked(offset, smallRefSize);
}
// Use when searching for a tagged or non-tagged reference.
// The result may be an invalid reference and shall only be used to compare with a valid reference.
internal uint PeekReferenceUnchecked(int offset, bool smallRefSize)
{
return smallRefSize ? PeekUInt16(offset) : PeekUInt32(offset);
}
// When reference has at most 24 bits.
internal int PeekReference(int offset, bool smallRefSize)
{
if (smallRefSize)
{
return PeekUInt16(offset);
}
uint value = PeekUInt32(offset);
if (!TokenTypeIds.IsValidRowId(value))
{
Throw.ReferenceOverflow();
}
return (int)value;
}
// #String, #Blob heaps
internal int PeekHeapReference(int offset, bool smallRefSize)
{
if (smallRefSize)
{
return PeekUInt16(offset);
}
uint value = PeekUInt32(offset);
if (!HeapHandleType.IsValidHeapOffset(value))
{
Throw.ReferenceOverflow();
}
return (int)value;
}
internal Guid PeekGuid(int offset)
{
CheckBounds(offset, sizeof(Guid));
byte* ptr = Pointer + offset;
if (BitConverter.IsLittleEndian)
{
return *(Guid*)ptr;
}
else
{
unchecked
{
return new Guid(
(int)(ptr[0] | (ptr[1] << 8) | (ptr[2] << 16) | (ptr[3] << 24)),
(short)(ptr[4] | (ptr[5] << 8)),
(short)(ptr[6] | (ptr[7] << 8)),
ptr[8], ptr[9], ptr[10], ptr[11], ptr[12], ptr[13], ptr[14], ptr[15]);
}
}
}
internal string PeekUtf16(int offset, int byteCount)
{
CheckBounds(offset, byteCount);
byte* ptr = Pointer + offset;
if (BitConverter.IsLittleEndian)
{
// doesn't allocate a new string if byteCount == 0
return new string((char*)ptr, 0, byteCount / sizeof(char));
}
else
{
return Encoding.Unicode.GetString(ptr, byteCount);
}
}
internal string PeekUtf8(int offset, int byteCount)
{
CheckBounds(offset, byteCount);
return Encoding.UTF8.GetString(Pointer + offset, byteCount);
}
/// <summary>
/// Read UTF8 at the given offset up to the given terminator, null terminator, or end-of-block.
/// </summary>
/// <param name="offset">Offset in to the block where the UTF8 bytes start.</param>
/// <param name="prefix">UTF8 encoded prefix to prepend to the bytes at the offset before decoding.</param>
/// <param name="utf8Decoder">The UTF8 decoder to use that allows user to adjust fallback and/or reuse existing strings without allocating a new one.</param>
/// <param name="numberOfBytesRead">The number of bytes read, which includes the terminator if we did not hit the end of the block.</param>
/// <param name="terminator">A character in the ASCII range that marks the end of the string.
/// If a value other than '\0' is passed we still stop at the null terminator if encountered first.</param>
/// <returns>The decoded string.</returns>
internal string PeekUtf8NullTerminated(int offset, byte[] prefix, MetadataStringDecoder utf8Decoder, out int numberOfBytesRead, char terminator = '\0')
{
Debug.Assert(terminator <= 0x7F);
CheckBounds(offset, 0);
int length = GetUtf8NullTerminatedLength(offset, out numberOfBytesRead, terminator);
return EncodingHelper.DecodeUtf8(Pointer + offset, length, prefix, utf8Decoder);
}
/// <summary>
/// Get number of bytes from offset to given terminator, null terminator, or end-of-block (whichever comes first).
/// Returned length does not include the terminator, but numberOfBytesRead out parameter does.
/// </summary>
/// <param name="offset">Offset in to the block where the UTF8 bytes start.</param>
/// <param name="terminator">A character in the ASCII range that marks the end of the string.
/// If a value other than '\0' is passed we still stop at the null terminator if encountered first.</param>
/// <param name="numberOfBytesRead">The number of bytes read, which includes the terminator if we did not hit the end of the block.</param>
/// <returns>Length (byte count) not including terminator.</returns>
internal int GetUtf8NullTerminatedLength(int offset, out int numberOfBytesRead, char terminator = '\0')
{
CheckBounds(offset, 0);
Debug.Assert(terminator <= 0x7f);
byte* start = Pointer + offset;
byte* end = Pointer + Length;
byte* current = start;
while (current < end)
{
byte b = *current;
if (b == 0 || b == terminator)
{
break;
}
current++;
}
int length = (int)(current - start);
numberOfBytesRead = length;
if (current < end)
{
// we also read the terminator
numberOfBytesRead++;
}
return length;
}
internal int Utf8NullTerminatedOffsetOfAsciiChar(int startOffset, char asciiChar)
{
CheckBounds(startOffset, 0);
Debug.Assert(asciiChar != 0 && asciiChar <= 0x7f);
for (int i = startOffset; i < Length; i++)
{
byte b = Pointer[i];
if (b == 0)
{
break;
}
if (b == asciiChar)
{
return i;
}
}
return -1;
}
// comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first.
internal bool Utf8NullTerminatedEquals(int offset, string text, MetadataStringDecoder utf8Decoder, char terminator, bool ignoreCase)
{
int firstDifference;
FastComparisonResult result = Utf8NullTerminatedFastCompare(offset, text, 0, out firstDifference, terminator, ignoreCase);
if (result == FastComparisonResult.Inconclusive)
{
int bytesRead;
string decoded = PeekUtf8NullTerminated(offset, null, utf8Decoder, out bytesRead, terminator);
return decoded.Equals(text, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
return result == FastComparisonResult.Equal;
}
// comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first.
internal bool Utf8NullTerminatedStartsWith(int offset, string text, MetadataStringDecoder utf8Decoder, char terminator, bool ignoreCase)
{
int endIndex;
FastComparisonResult result = Utf8NullTerminatedFastCompare(offset, text, 0, out endIndex, terminator, ignoreCase);
switch (result)
{
case FastComparisonResult.Equal:
case FastComparisonResult.BytesStartWithText:
return true;
case FastComparisonResult.Unequal:
case FastComparisonResult.TextStartsWithBytes:
return false;
default:
Debug.Assert(result == FastComparisonResult.Inconclusive);
int bytesRead;
string decoded = PeekUtf8NullTerminated(offset, null, utf8Decoder, out bytesRead, terminator);
return decoded.StartsWith(text, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
}
internal enum FastComparisonResult
{
Equal,
BytesStartWithText,
TextStartsWithBytes,
Unequal,
Inconclusive
}
// comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first.
internal FastComparisonResult Utf8NullTerminatedFastCompare(int offset, string text, int textStart, out int firstDifferenceIndex, char terminator, bool ignoreCase)
{
CheckBounds(offset, 0);
Debug.Assert(terminator <= 0x7F);
byte* startPointer = Pointer + offset;
byte* endPointer = Pointer + Length;
byte* currentPointer = startPointer;
int ignoreCaseMask = StringUtils.IgnoreCaseMask(ignoreCase);
int currentIndex = textStart;
while (currentIndex < text.Length && currentPointer != endPointer)
{
byte currentByte = *currentPointer;
// note that terminator is not compared case-insensitively even if ignore case is true
if (currentByte == 0 || currentByte == terminator)
{
break;
}
char currentChar = text[currentIndex];
if ((currentByte & 0x80) == 0 && StringUtils.IsEqualAscii(currentChar, currentByte, ignoreCaseMask))
{
currentIndex++;
currentPointer++;
}
else
{
firstDifferenceIndex = currentIndex;
// uncommon non-ascii case --> fall back to slow allocating comparison.
return (currentChar > 0x7F) ? FastComparisonResult.Inconclusive : FastComparisonResult.Unequal;
}
}
firstDifferenceIndex = currentIndex;
bool textTerminated = currentIndex == text.Length;
bool bytesTerminated = currentPointer == endPointer || *currentPointer == 0 || *currentPointer == terminator;
if (textTerminated && bytesTerminated)
{
return FastComparisonResult.Equal;
}
return textTerminated ? FastComparisonResult.BytesStartWithText : FastComparisonResult.TextStartsWithBytes;
}
// comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first.
internal bool Utf8NullTerminatedStringStartsWithAsciiPrefix(int offset, string asciiPrefix)
{
// Assumes stringAscii only contains ASCII characters and no nil characters.
CheckBounds(offset, 0);
// Make sure that we won't read beyond the block even if the block doesn't end with 0 byte.
if (asciiPrefix.Length > Length - offset)
{
return false;
}
byte* p = Pointer + offset;
for (int i = 0; i < asciiPrefix.Length; i++)
{
Debug.Assert(asciiPrefix[i] > 0 && asciiPrefix[i] <= 0x7f);
if (asciiPrefix[i] != *p)
{
return false;
}
p++;
}
return true;
}
internal int CompareUtf8NullTerminatedStringWithAsciiString(int offset, string asciiString)
{
// Assumes stringAscii only contains ASCII characters and no nil characters.
CheckBounds(offset, 0);
byte* p = Pointer + offset;
int limit = Length - offset;
for (int i = 0; i < asciiString.Length; i++)
{
Debug.Assert(asciiString[i] > 0 && asciiString[i] <= 0x7f);
if (i > limit)
{
// Heap value is shorter.
return -1;
}
if (*p != asciiString[i])
{
// If we hit the end of the heap value (*p == 0)
// the heap value is shorter than the string, so we return negative value.
return *p - asciiString[i];
}
p++;
}
// Either the heap value name matches exactly the given string or
// it is longer so it is considered "greater".
return (*p == 0) ? 0 : +1;
}
internal byte[] PeekBytes(int offset, int byteCount)
{
CheckBounds(offset, byteCount);
return BlobUtilities.ReadBytes(Pointer + offset, byteCount);
}
internal int IndexOf(byte b, int start)
{
CheckBounds(start, 0);
return IndexOfUnchecked(b, start);
}
internal int IndexOfUnchecked(byte b, int start)
{
byte* p = Pointer + start;
byte* end = Pointer + Length;
while (p < end)
{
if (*p == b)
{
return (int)(p - Pointer);
}
p++;
}
return -1;
}
// same as Array.BinarySearch, but without using IComparer
internal int BinarySearch(string[] asciiKeys, int offset)
{
var low = 0;
var high = asciiKeys.Length - 1;
while (low <= high)
{
var middle = low + ((high - low) >> 1);
var midValue = asciiKeys[middle];
int comparison = CompareUtf8NullTerminatedStringWithAsciiString(offset, midValue);
if (comparison == 0)
{
return middle;
}
if (comparison < 0)
{
high = middle - 1;
}
else
{
low = middle + 1;
}
}
return ~low;
}
/// <summary>
/// In a table that specifies children via a list field (e.g. TypeDef.FieldList, TypeDef.MethodList),
/// searches for the parent given a reference to a child.
/// </summary>
/// <returns>Returns row number [0..RowCount).</returns>
internal int BinarySearchForSlot(
int rowCount,
int rowSize,
int referenceListOffset,
uint referenceValue,
bool isReferenceSmall)
{
int startRowNumber = 0;
int endRowNumber = rowCount - 1;
uint startValue = PeekReferenceUnchecked(startRowNumber * rowSize + referenceListOffset, isReferenceSmall);
uint endValue = PeekReferenceUnchecked(endRowNumber * rowSize + referenceListOffset, isReferenceSmall);
if (endRowNumber == 1)
{
if (referenceValue >= endValue)
{
return endRowNumber;
}
return startRowNumber;
}
while (endRowNumber - startRowNumber > 1)
{
if (referenceValue <= startValue)
{
return referenceValue == startValue ? startRowNumber : startRowNumber - 1;
}
if (referenceValue >= endValue)
{
return referenceValue == endValue ? endRowNumber : endRowNumber + 1;
}
int midRowNumber = (startRowNumber + endRowNumber) / 2;
uint midReferenceValue = PeekReferenceUnchecked(midRowNumber * rowSize + referenceListOffset, isReferenceSmall);
if (referenceValue > midReferenceValue)
{
startRowNumber = midRowNumber;
startValue = midReferenceValue;
}
else if (referenceValue < midReferenceValue)
{
endRowNumber = midRowNumber;
endValue = midReferenceValue;
}
else
{
return midRowNumber;
}
}
return startRowNumber;
}
/// <summary>
/// In a table ordered by a column containing entity references searches for a row with the specified reference.
/// </summary>
/// <returns>Returns row number [0..RowCount) or -1 if not found.</returns>
internal int BinarySearchReference(
int rowCount,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall)
{
int startRowNumber = 0;
int endRowNumber = rowCount - 1;
while (startRowNumber <= endRowNumber)
{
int midRowNumber = (startRowNumber + endRowNumber) / 2;
uint midReferenceValue = PeekReferenceUnchecked(midRowNumber * rowSize + referenceOffset, isReferenceSmall);
if (referenceValue > midReferenceValue)
{
startRowNumber = midRowNumber + 1;
}
else if (referenceValue < midReferenceValue)
{
endRowNumber = midRowNumber - 1;
}
else
{
return midRowNumber;
}
}
return -1;
}
// Row number [0, ptrTable.Length) or -1 if not found.
internal int BinarySearchReference(
int[] ptrTable,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall)
{
int startRowNumber = 0;
int endRowNumber = ptrTable.Length - 1;
while (startRowNumber <= endRowNumber)
{
int midRowNumber = (startRowNumber + endRowNumber) / 2;
uint midReferenceValue = PeekReferenceUnchecked((ptrTable[midRowNumber] - 1) * rowSize + referenceOffset, isReferenceSmall);
if (referenceValue > midReferenceValue)
{
startRowNumber = midRowNumber + 1;
}
else if (referenceValue < midReferenceValue)
{
endRowNumber = midRowNumber - 1;
}
else
{
return midRowNumber;
}
}
return -1;
}
/// <summary>
/// Calculates a range of rows that have specified value in the specified column in a table that is sorted by that column.
/// </summary>
internal void BinarySearchReferenceRange(
int rowCount,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall,
out int startRowNumber, // [0, rowCount) or -1
out int endRowNumber) // [0, rowCount) or -1
{
int foundRowNumber = BinarySearchReference(
rowCount,
rowSize,
referenceOffset,
referenceValue,
isReferenceSmall
);
if (foundRowNumber == -1)
{
startRowNumber = -1;
endRowNumber = -1;
return;
}
startRowNumber = foundRowNumber;
while (startRowNumber > 0 &&
PeekReferenceUnchecked((startRowNumber - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue)
{
startRowNumber--;
}
endRowNumber = foundRowNumber;
while (endRowNumber + 1 < rowCount &&
PeekReferenceUnchecked((endRowNumber + 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue)
{
endRowNumber++;
}
}
/// <summary>
/// Calculates a range of rows that have specified value in the specified column in a table that is sorted by that column.
/// </summary>
internal void BinarySearchReferenceRange(
int[] ptrTable,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall,
out int startRowNumber, // [0, ptrTable.Length) or -1
out int endRowNumber) // [0, ptrTable.Length) or -1
{
int foundRowNumber = BinarySearchReference(
ptrTable,
rowSize,
referenceOffset,
referenceValue,
isReferenceSmall
);
if (foundRowNumber == -1)
{
startRowNumber = -1;
endRowNumber = -1;
return;
}
startRowNumber = foundRowNumber;
while (startRowNumber > 0 &&
PeekReferenceUnchecked((ptrTable[startRowNumber - 1] - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue)
{
startRowNumber--;
}
endRowNumber = foundRowNumber;
while (endRowNumber + 1 < ptrTable.Length &&
PeekReferenceUnchecked((ptrTable[endRowNumber + 1] - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue)
{
endRowNumber++;
}
}
// Always RowNumber....
internal int LinearSearchReference(
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall)
{
int currOffset = referenceOffset;
int totalSize = this.Length;
while (currOffset < totalSize)
{
uint currReference = PeekReferenceUnchecked(currOffset, isReferenceSmall);
if (currReference == referenceValue)
{
return currOffset / rowSize;
}
currOffset += rowSize;
}
return -1;
}
internal bool IsOrderedByReferenceAscending(
int rowSize,
int referenceOffset,
bool isReferenceSmall)
{
int offset = referenceOffset;
int totalSize = this.Length;
uint previous = 0;
while (offset < totalSize)
{
uint current = PeekReferenceUnchecked(offset, isReferenceSmall);
if (current < previous)
{
return false;
}
previous = current;
offset += rowSize;
}
return true;
}
internal int[] BuildPtrTable(
int numberOfRows,
int rowSize,
int referenceOffset,
bool isReferenceSmall)
{
int[] ptrTable = new int[numberOfRows];
uint[] unsortedReferences = new uint[numberOfRows];
for (int i = 0; i < ptrTable.Length; i++)
{
ptrTable[i] = i + 1;
}
ReadColumn(unsortedReferences, rowSize, referenceOffset, isReferenceSmall);
Array.Sort(ptrTable, (int a, int b) => { return unsortedReferences[a - 1].CompareTo(unsortedReferences[b - 1]); });
return ptrTable;
}
private void ReadColumn(
uint[] result,
int rowSize,
int referenceOffset,
bool isReferenceSmall)
{
int offset = referenceOffset;
int totalSize = this.Length;
int i = 0;
while (offset < totalSize)
{
result[i] = PeekReferenceUnchecked(offset, isReferenceSmall);
offset += rowSize;
i++;
}
Debug.Assert(i == result.Length);
}
internal bool PeekHeapValueOffsetAndSize(int index, out int offset, out int size)
{
int bytesRead;
int numberOfBytes = PeekCompressedInteger(index, out bytesRead);
if (numberOfBytes == BlobReader.InvalidCompressedInteger)
{
offset = 0;
size = 0;
return false;
}
offset = index + bytesRead;
size = numberOfBytes;
return true;
}
}
}
| |
namespace FakeItEasy.Tests.Creation
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection.Emit;
using FakeItEasy.Core;
using FakeItEasy.Creation;
using FluentAssertions;
using NUnit.Framework;
[TestFixture]
public class FakeObjectCreatorTests
{
private IProxyGenerator proxyGenerator;
private FakeObjectCreator fakeObjectCreator;
private IExceptionThrower thrower;
private FakeCallProcessorProvider.Factory fakeCallProcessorProviderFactory;
[SetUp]
public void Setup()
{
this.proxyGenerator = A.Fake<IProxyGenerator>();
this.thrower = A.Fake<IExceptionThrower>();
this.fakeCallProcessorProviderFactory = A.Fake<FakeCallProcessorProvider.Factory>();
this.fakeObjectCreator = new FakeObjectCreator(this.proxyGenerator, this.thrower, this.fakeCallProcessorProviderFactory);
}
[Test]
public void Should_pass_fake_options_to_the_proxy_generator_and_return_the_fake_when_successful()
{
// Arrange
var options = new FakeOptions();
var proxy = A.Fake<IFoo>();
A.CallTo(() => this.proxyGenerator.GenerateProxy(A<Type>._, A<IEnumerable<Type>>._, A<IEnumerable<object>>._, A<IEnumerable<CustomAttributeBuilder>>._, A<IFakeCallProcessorProvider>._))
.Returns(new ProxyGeneratorResult(proxy));
// Act
var createdFake = this.fakeObjectCreator.CreateFake(typeof(IFoo), options, A.Dummy<IDummyValueCreationSession>(), throwOnFailure: false);
// Assert
createdFake.Should().BeSameAs(proxy);
A.CallTo(() => this.proxyGenerator.GenerateProxy(
typeof(IFoo),
options.AdditionalInterfacesToImplement,
options.ArgumentsForConstructor,
options.AdditionalAttributes,
A<IFakeCallProcessorProvider>._))
.MustHaveHappened();
}
[Test]
public void Should_use_new_fake_call_processor_for_the_proxy_generator()
{
// Arrange
var options = new FakeOptions();
var fakeCallProcessorProvider = A.Fake<IFakeCallProcessorProvider>();
A.CallTo(() => this.fakeCallProcessorProviderFactory(A<Type>._, A<FakeOptions>._)).Returns(fakeCallProcessorProvider);
// Act
this.fakeObjectCreator.CreateFake(typeof(IFoo), options, A.Dummy<IDummyValueCreationSession>(), throwOnFailure: false);
// Assert
A.CallTo(() => this.fakeCallProcessorProviderFactory(typeof(IFoo), options)).MustHaveHappened();
A.CallTo(() => this.proxyGenerator.GenerateProxy(A<Type>._, A<IEnumerable<Type>>._, A<IEnumerable<object>>._, A<IEnumerable<CustomAttributeBuilder>>._, fakeCallProcessorProvider))
.MustHaveHappened();
}
[Test]
public void Should_use_new_fake_call_processor_for_every_tried_constructor()
{
// Arrange
var session = A.Fake<IDummyValueCreationSession>();
StubSessionWithDummyValue(session, 1);
StubSessionWithDummyValue(session, "dummy");
this.StubProxyGeneratorToFail();
var options = new FakeOptions();
// Act
this.fakeObjectCreator.CreateFake(typeof(TypeWithMultipleConstructors), options, session, throwOnFailure: false);
// Assert
A.CallTo(() => this.fakeCallProcessorProviderFactory(typeof(TypeWithMultipleConstructors), options))
.MustHaveHappened(Repeated.Exactly.Times(3));
}
[Test]
public void Should_throw_when_generator_fails_and_arguments_for_constructor_are_specified()
{
// Arrange
this.StubProxyGeneratorToFail("fail reason");
var options = new FakeOptions
{
ArgumentsForConstructor = new object[] { "argument for constructor " }
};
// Act
this.fakeObjectCreator.CreateFake(typeof(IFoo), options, A.Dummy<IDummyValueCreationSession>(), throwOnFailure: true);
// Assert
A.CallTo(() => this.thrower.ThrowFailedToGenerateProxyWithArgumentsForConstructor(typeof(IFoo), "fail reason"))
.MustHaveHappened();
}
[Test]
public void Should_return_null_when_unsuccessful_and_throw_on_failure_is_false()
{
// Arrange
this.StubProxyGeneratorToFail();
// Act
var createdFake = this.fakeObjectCreator.CreateFake(typeof(IFoo), new FakeOptions(), A.Dummy<IDummyValueCreationSession>(), throwOnFailure: false);
// Assert
createdFake.Should().BeNull();
}
[Test]
public void Should_not_throw_when_unsuccessful_and_throw_on_failure_is_false()
{
// Arrange
this.StubProxyGeneratorToFail();
// Act
this.fakeObjectCreator.CreateFake(typeof(IFoo), new FakeOptions(), A.Dummy<IDummyValueCreationSession>(), throwOnFailure: false);
// Assert
A.CallTo(this.thrower).MustNotHaveHappened();
}
[Test]
public void Should_try_with_resolved_constructors_incorrect_order()
{
using (var scope = Fake.CreateScope())
{
// Arrange
var session = A.Fake<IDummyValueCreationSession>();
StubSessionWithDummyValue(session, 1);
StubSessionWithDummyValue(session, "dummy");
this.StubProxyGeneratorToFail();
var options = new FakeOptions();
// Act
this.fakeObjectCreator.CreateFake(typeof(TypeWithMultipleConstructors), options, session, throwOnFailure: false);
// Assert
using (scope.OrderedAssertions())
{
A.CallTo(() => this.proxyGenerator.GenerateProxy(typeof(TypeWithMultipleConstructors), options.AdditionalInterfacesToImplement, A<IEnumerable<object>>.That.IsNull(), A<IEnumerable<CustomAttributeBuilder>>._, A<IFakeCallProcessorProvider>._))
.MustHaveHappened();
A.CallTo(() => this.proxyGenerator.GenerateProxy(typeof(TypeWithMultipleConstructors), options.AdditionalInterfacesToImplement, A<IEnumerable<object>>.That.IsThisSequence(1, 1), A<IEnumerable<CustomAttributeBuilder>>._, A<IFakeCallProcessorProvider>._))
.MustHaveHappened();
A.CallTo(() => this.proxyGenerator.GenerateProxy(typeof(TypeWithMultipleConstructors), options.AdditionalInterfacesToImplement, A<IEnumerable<object>>.That.IsThisSequence("dummy"), A<IEnumerable<CustomAttributeBuilder>>._, A<IFakeCallProcessorProvider>._))
.MustHaveHappened();
}
}
}
[Test]
public void Should_not_try_to_resolve_constructors_when_arguments_for_constructor_are_specified()
{
// Arrange
var session = A.Fake<IDummyValueCreationSession>();
StubSessionWithDummyValue(session, 1);
this.StubProxyGeneratorToFail();
var options = new FakeOptions
{
ArgumentsForConstructor = new object[] { 2, 2 }
};
// Act
this.fakeObjectCreator.CreateFake(typeof(TypeWithMultipleConstructors), options, session, throwOnFailure: false);
// Assert
A.CallTo(() => this.proxyGenerator.GenerateProxy(typeof(TypeWithMultipleConstructors), options.AdditionalInterfacesToImplement, A<IEnumerable<object>>.That.Not.IsThisSequence(2, 2), A<IFakeCallProcessorProvider>._))
.MustNotHaveHappened();
}
[Test]
public void Should_return_first_successfully_generated_proxy()
{
// Arrange
var session = A.Fake<IDummyValueCreationSession>();
StubSessionWithDummyValue(session, 1);
var options = new FakeOptions();
var proxy = A.Fake<IFoo>();
this.StubProxyGeneratorToFail();
A.CallTo(() => this.proxyGenerator.GenerateProxy(typeof(TypeWithMultipleConstructors), options.AdditionalInterfacesToImplement, A<IEnumerable<object>>.That.IsThisSequence(1, 1), A<IEnumerable<CustomAttributeBuilder>>._, A<IFakeCallProcessorProvider>._))
.Returns(new ProxyGeneratorResult(proxy));
A.CallTo(() => this.proxyGenerator.GenerateProxy(typeof(TypeWithMultipleConstructors), options.AdditionalInterfacesToImplement, A<IEnumerable<object>>.That.IsThisSequence(1), A<IEnumerable<CustomAttributeBuilder>>._, A<IFakeCallProcessorProvider>._))
.Returns(new ProxyGeneratorResult(new object()));
// Act
var createdFake = this.fakeObjectCreator.CreateFake(typeof(TypeWithMultipleConstructors), options, session, throwOnFailure: false);
// Assert
createdFake.Should().BeSameAs(proxy);
}
[Test]
public void Should_not_try_constructor_where_not_all_arguments_are_resolved()
{
// Arrange
var session = A.Fake<IDummyValueCreationSession>();
StubSessionWithDummyValue(session, 1);
StubSessionToFailForType<string>(session);
// Act
this.fakeObjectCreator.CreateFake(typeof(TypeWithConstructorThatTakesDifferentTypes), new FakeOptions(), session, throwOnFailure: false);
// Assert
A.CallTo(() => this.proxyGenerator.GenerateProxy(A<Type>._, A<IEnumerable<Type>>._, A<IEnumerable<object>>.That.Not.IsNull(), A<IEnumerable<CustomAttributeBuilder>>._, A<IFakeCallProcessorProvider>._))
.MustNotHaveHappened();
}
[Test]
public void Should_try_protected_constructors()
{
// Arrange
var session = A.Fake<IDummyValueCreationSession>();
StubSessionWithDummyValue(session, 1);
this.StubProxyGeneratorToFail();
var options = new FakeOptions();
// Act
this.fakeObjectCreator.CreateFake(typeof(TypeWithProtectedConstructor), options, session, throwOnFailure: false);
// Assert
A.CallTo(() => this.proxyGenerator.GenerateProxy(typeof(TypeWithProtectedConstructor), options.AdditionalInterfacesToImplement, A<IEnumerable<object>>.That.IsThisSequence(1), A<IEnumerable<CustomAttributeBuilder>>._, A<IFakeCallProcessorProvider>._))
.MustHaveHappened();
}
[Test]
public void Should_throw_when_no_resolved_constructor_was_successfully_used()
{
// Arrange
var session = A.Fake<IDummyValueCreationSession>();
StubSessionToFailForType<int>(session);
StubSessionWithDummyValue(session, "dummy");
this.StubProxyGeneratorToFail("failed");
// Act
this.fakeObjectCreator.CreateFake(typeof(TypeWithMultipleConstructors), new FakeOptions(), session, throwOnFailure: true);
// Assert
var expectedConstructors = new[]
{
new ResolvedConstructor
{
Arguments = new[]
{
new ResolvedArgument
{
ArgumentType = typeof(int),
ResolvedValue = null,
WasResolved = false
},
new ResolvedArgument
{
ArgumentType = typeof(int),
ResolvedValue = null,
WasResolved = false
}
}
},
new ResolvedConstructor
{
ReasonForFailure = "failed",
Arguments = new[]
{
new ResolvedArgument
{
ArgumentType = typeof(string),
ResolvedValue = "dummy",
WasResolved = true
}
}
}
};
A.CallTo(() => this.thrower.ThrowFailedToGenerateProxyWithResolvedConstructors(typeof(TypeWithMultipleConstructors), "failed", this.ConstructorsEquivalentTo(expectedConstructors)))
.MustHaveHappened();
}
private static void StubSessionToFailForType<T>(IDummyValueCreationSession session)
{
object outResult;
A.CallTo(() => session.TryResolveDummyValue(typeof(T), out outResult))
.Returns(false);
}
private static void StubSessionWithDummyValue<T>(IDummyValueCreationSession session, T dummyValue)
{
object outResult;
A.CallTo(() => session.TryResolveDummyValue(typeof(T), out outResult))
.Returns(true)
.AssignsOutAndRefParameters(dummyValue);
}
private IEnumerable<ResolvedConstructor> ConstructorsEquivalentTo(IEnumerable<ResolvedConstructor> constructors)
{
return A<IEnumerable<ResolvedConstructor>>.That.Matches(
x =>
{
if (x.Count() != constructors.Count())
{
return false;
}
foreach (var constructorPair in x.Zip(constructors))
{
if (!string.Equals(constructorPair.Item1.ReasonForFailure, constructorPair.Item2.ReasonForFailure))
{
return false;
}
if (constructorPair.Item1.Arguments.Length != constructorPair.Item2.Arguments.Length)
{
return false;
}
foreach (var argumentPair in constructorPair.Item1.Arguments.Zip(constructorPair.Item2.Arguments))
{
var isEqual =
object.Equals(argumentPair.Item1.ArgumentType, argumentPair.Item2.ArgumentType)
&& object.Equals(argumentPair.Item1.ResolvedValue, argumentPair.Item2.ResolvedValue)
&& argumentPair.Item1.WasResolved == argumentPair.Item2.WasResolved;
if (!isEqual)
{
return false;
}
}
}
return true;
},
"Matching constructor");
}
private void StubProxyGeneratorToFail(string failReason)
{
A.CallTo(() => this.proxyGenerator.GenerateProxy(A<Type>._, A<IEnumerable<Type>>._, A<IEnumerable<object>>._, A<IEnumerable<CustomAttributeBuilder>>._, A<IFakeCallProcessorProvider>._))
.Returns(new ProxyGeneratorResult(failReason));
}
private void StubProxyGeneratorToFail()
{
this.StubProxyGeneratorToFail("failed");
}
public class TypeWithMultipleConstructors
{
public TypeWithMultipleConstructors()
{
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument1", Justification = "Required for testing.")]
public TypeWithMultipleConstructors(string argument1)
{
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument1", Justification = "Required for testing.")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument2", Justification = "Required for testing.")]
public TypeWithMultipleConstructors(int argument1, int argument2)
{
}
}
public class TypeWithConstructorThatTakesDifferentTypes
{
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument1", Justification = "Required for testing.")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument2", Justification = "Required for testing.")]
public TypeWithConstructorThatTakesDifferentTypes(int argument1, string argument2)
{
}
}
public class TypeWithProtectedConstructor
{
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument", Justification = "Required for testing.")]
protected TypeWithProtectedConstructor(int argument)
{
}
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using Encog.MathUtil;
using Encog.ML.Data;
using Encog.Util;
namespace Encog.Neural.Networks.Training.Propagation.SCG
{
/// <summary>
/// This is a training class that makes use of scaled conjugate gradient methods.
/// It is a very fast and efficient training algorithm.
/// </summary>
///
public class ScaledConjugateGradient : Propagation
{
/// <summary>
/// The starting value for sigma.
/// </summary>
///
protected internal const double FirstSigma = 1.0E-4D;
/// <summary>
/// The starting value for lambda.
/// </summary>
///
protected internal const double FirstLambda = 1.0E-6D;
/// <summary>
/// The old gradients, used to compare.
/// </summary>
///
private readonly double[] _oldGradient;
/// <summary>
/// The old weight values, used to restore the neural network.
/// </summary>
///
private readonly double[] _oldWeights;
/// <summary>
/// Step direction vector.
/// </summary>
///
private readonly double[] _p;
/// <summary>
/// Step direction vector.
/// </summary>
///
private readonly double[] _r;
/// <summary>
/// The neural network weights.
/// </summary>
///
private readonly double[] _weights;
/// <summary>
/// The current delta.
/// </summary>
///
private double _delta;
/// <summary>
/// The number of iterations. The network will reset when this value
/// increases over the number of weights in the network.
/// </summary>
///
private int _k;
/// <summary>
/// The first lambda value.
/// </summary>
///
private double _lambda;
/// <summary>
/// The second lambda value.
/// </summary>
///
private double _lambda2;
/// <summary>
/// The magnitude of p.
/// </summary>
///
private double _magP;
/// <summary>
/// Should the initial gradients be calculated.
/// </summary>
///
private bool _mustInit;
/// <summary>
/// The old error value, used to make sure an improvement happened.
/// </summary>
///
private double _oldError;
/// <summary>
/// Should we restart?
/// </summary>
///
private bool _restart;
/// <summary>
/// Tracks if the latest training cycle was successful.
/// </summary>
///
private bool _success;
/// <summary>
/// Construct a training class.
/// </summary>
///
/// <param name="network">The network to train.</param>
/// <param name="training">The training data.</param>
public ScaledConjugateGradient(IContainsFlat network,
IMLDataSet training) : base(network, training)
{
_success = true;
_success = true;
_delta = 0;
_lambda2 = 0;
_lambda = FirstLambda;
_oldError = 0;
_magP = 0;
_restart = false;
_weights = EngineArray.ArrayCopy(network.Flat.Weights);
int numWeights = _weights.Length;
_oldWeights = new double[numWeights];
_oldGradient = new double[numWeights];
_p = new double[numWeights];
_r = new double[numWeights];
_mustInit = true;
}
/// <summary>
/// This training type does not support training continue.
/// </summary>
///
/// <returns>Always returns false.</returns>
public override sealed bool CanContinue
{
get { return false; }
}
/// <summary>
/// This training type does not support training continue.
/// </summary>
///
/// <returns>Always returns null.</returns>
public override sealed TrainingContinuation Pause()
{
return null;
}
/// <summary>
/// This training type does not support training continue.
/// </summary>
///
/// <param name="state">Not used.</param>
public override sealed void Resume(TrainingContinuation state)
{
}
/// <summary>
/// Calculate the gradients. They are normalized as well.
/// </summary>
///
public override void CalculateGradients()
{
int outCount = Network.Flat.OutputCount;
base.CalculateGradients();
// normalize
double factor = -2D / Gradients.Length / outCount;
for (int i = 0; i < Gradients.Length; i++)
{
Gradients[i] *= factor;
}
}
/// <summary>
/// Calculate the starting set of gradients.
/// </summary>
///
private void Init()
{
int numWeights = _weights.Length;
CalculateGradients();
_k = 1;
for (int i = 0; i < numWeights; ++i)
{
_p[i] = _r[i] = -Gradients[i];
}
_mustInit = false;
}
/// <summary>
/// Perform one iteration.
/// </summary>
///
public override void Iteration()
{
if (_mustInit)
{
Init();
}
base.PreIteration();
RollIteration();
int numWeights = _weights.Length;
// Storage space for previous iteration values.
if (_restart)
{
// First time through, set initial values for SCG parameters.
_lambda = FirstLambda;
_lambda2 = 0;
_k = 1;
_success = true;
_restart = false;
}
// If an error reduction is possible, calculate 2nd order info.
if (_success)
{
// If the search direction is small, stop.
_magP = EngineArray.VectorProduct(_p, _p);
double sigma = FirstSigma
/ Math.Sqrt(_magP);
// In order to compute the new step, we need a new gradient.
// First, save off the old data.
EngineArray.ArrayCopy(Gradients, _oldGradient);
EngineArray.ArrayCopy(_weights, _oldWeights);
_oldError = Error;
// Now we move to the new point in weight space.
for (int i = 0; i < numWeights; ++i)
{
_weights[i] += sigma * _p[i];
}
EngineArray.ArrayCopy(_weights, Network.Flat.Weights);
// And compute the new gradient.
CalculateGradients();
// Now we have the new gradient, and we continue the step
// computation.
_delta = 0;
for (int i = 0; i < numWeights; ++i)
{
double step = (Gradients[i] - _oldGradient[i])
/ sigma;
_delta += _p[i] * step;
}
}
// Scale delta.
_delta += (_lambda - _lambda2) * _magP;
// If delta <= 0, make Hessian positive definite.
if (_delta <= 0)
{
_lambda2 = 2 * (_lambda - _delta / _magP);
_delta = _lambda * _magP - _delta;
_lambda = _lambda2;
}
// Calculate step size.
double mu = EngineArray.VectorProduct(_p, _r);
double alpha = mu / _delta;
// Calculate the comparison parameter.
// We must compute a new gradient, but this time we do not
// want to keep the old values. They were useful only for
// approximating the Hessian.
for (int i = 0; i < numWeights; ++i)
{
_weights[i] = _oldWeights[i] + alpha * _p[i];
}
EngineArray.ArrayCopy(_weights, Network.Flat.Weights);
CalculateGradients();
double gdelta = 2 * _delta * (_oldError - Error)
/ (mu * mu);
// If gdelta >= 0, a successful reduction in error is possible.
if (gdelta >= 0)
{
// Product of r(k+1) by r(k)
double rsum = 0;
// Now r = r(k+1).
for (int i = 0; i < numWeights; ++i)
{
double tmp = -Gradients[i];
rsum += tmp * _r[i];
_r[i] = tmp;
}
_lambda2 = 0;
_success = true;
// Do we need to restart?
if (_k >= numWeights)
{
_restart = true;
EngineArray.ArrayCopy(_r, _p);
}
else
{
// Compute new conjugate direction.
double beta = (EngineArray.VectorProduct(_r, _r) - rsum)
/ mu;
// Update direction vector.
for (int i = 0; i < numWeights; ++i)
{
_p[i] = _r[i] + beta * _p[i];
}
_restart = false;
}
if (gdelta >= 0.75D)
{
_lambda *= 0.25D;
}
}
else
{
// A reduction in error was not possible.
// under_tolerance = false;
// Go back to w(k) since w(k) + alpha*p(k) is not better.
EngineArray.ArrayCopy(_oldWeights, _weights);
Error = _oldError;
_lambda2 = _lambda;
_success = false;
}
if (gdelta < 0.25D)
{
_lambda += _delta * (1 - gdelta) / _magP;
}
_lambda = BoundNumbers.Bound(_lambda);
++_k;
EngineArray.ArrayCopy(_weights, Network.Flat.Weights);
base.PostIteration();
}
/// <summary>
/// Update the weights.
/// </summary>
///
/// <param name="gradients">The current gradients.</param>
/// <param name="lastGradient">The last gradients.</param>
/// <param name="index">The weight index being updated.</param>
/// <returns>The new weight value.</returns>
public override double UpdateWeight(double[] gradients,
double[] lastGradient, int index)
{
return 0;
}
/// <summary>
/// Not needed for this training type.
/// </summary>
public override void InitOthers()
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Security.Cryptography;
using System.Threading;
using DarkMultiPlayerServer;
using MessageStream2;
namespace DMPServerListReporter
{
public class Main : DMPPlugin
{
//Bump number when we change the format
private const int HEARTBEAT_ID = 0;
private const int REPORTING_PROTOCOL_ID = 2;
//Heartbeat every 10 seconds
private const int CONNECTION_HEARTBEAT = 10000;
//Connection retry attempt every 120s
private const int CONNECTION_RETRY = 60000;
private double lastMessageSendTime = double.NegativeInfinity;
//Settings file name
private const string TOKEN_FILE = "ReportingToken.txt";
private const string DESCRIPTION_FILE = "ReportingDescription.txt";
private const string OLD_SETTINGS_FILE = "ReportingSettings.txt";
private const string NEW_SETTINGS_FILE = "ReportingSettings.xml";
//Plus, we can explicitly terminate the thread to kill the connection upon shutdown.
private Thread reportThread;
TcpClient currentConnection;
private AutoResetEvent sendEvent = new AutoResetEvent(false);
private Queue<byte[]> sendMessages = new Queue<byte[]>();
//Settings
ReportingSettings settingsStore = new ReportingSettings();
//Client state tracking
List<string> connectedPlayers = new List<string>();
public Main()
{
settingsStore.LoadSettings(OLD_SETTINGS_FILE, NEW_SETTINGS_FILE, TOKEN_FILE, DESCRIPTION_FILE);
CommandHandler.RegisterCommand("reloadreporter", ReloadSettings, "Reload the reporting plugin settings");
}
private void ReloadSettings(string commandText)
{
StopReporter();
settingsStore = new ReportingSettings();
settingsStore.LoadSettings(OLD_SETTINGS_FILE, NEW_SETTINGS_FILE, TOKEN_FILE, DESCRIPTION_FILE);
StartReporter();
}
public static string CalculateSHA256Hash(string text)
{
UTF8Encoding encoder = new UTF8Encoding();
byte[] encodedBytes = encoder.GetBytes(text);
StringBuilder sb = new StringBuilder();
using (SHA256Managed sha = new SHA256Managed())
{
byte[] fileHashData = sha.ComputeHash(encodedBytes);
//Byte[] to string conversion adapted from MSDN...
for (int i = 0; i < fileHashData.Length; i++)
{
sb.Append(fileHashData[i].ToString("x2"));
}
}
return sb.ToString();
}
public override void OnServerStart()
{
StartReporter();
}
/*
public override void OnUpdate()
{
if (!connectedStatus && loadedSettings && Server.serverRunning && (Server.serverClock.ElapsedMilliseconds > (lastConnectionTry + CONNECTION_RETRY)))
{
lastConnectionTry = Server.serverClock.ElapsedMilliseconds;
connectThread = new Thread(new ThreadStart(ConnectToServer));
connectThread.Start();
}
}
*/
public override void OnClientAuthenticated(ClientObject client)
{
connectedPlayers.Add(client.playerName);
ReportData();
}
public override void OnClientDisconnect(ClientObject client)
{
connectedPlayers.Remove(client.playerName);
ReportData();
}
public override void OnServerStop()
{
StopReporter();
}
private void StartReporter()
{
reportThread = new Thread(ReporterMain);
reportThread.IsBackground = true;
reportThread.Start();
}
private void ReporterMain()
{
while (true)
{
TcpClient newConnection = ConnectToServer();
if (newConnection != null)
{
currentConnection = newConnection;
try
{
SendReportMain();
}
catch (Exception e)
{
if (!(e is ThreadAbortException))
{
currentConnection = null;
DarkLog.Debug("Disconnected reporter, exception: " + e.Message);
DarkLog.Debug("Reconnecting in 5 seconds...");
Thread.Sleep(5000);
}
}
}
else
{
DarkLog.Debug("All reporters are down, trying again in 60 seconds");
Thread.Sleep(60000);
}
}
}
private void StopReporter()
{
DarkLog.Debug("Stopping reporter");
reportThread.Abort();
try
{
currentConnection.Close();
}
catch
{
//Don't care.
}
}
private TcpClient ConnectToServer()
{
foreach (string currentEndpoint in settingsStore.reportingEndpoint)
{
try
{
string addressString;
string portString;
if (currentEndpoint.Contains("[") || currentEndpoint.Contains("]:"))
{
int startIndex = currentEndpoint.IndexOf("[") + 1;
int endIndex = currentEndpoint.LastIndexOf("]");
addressString = currentEndpoint.Substring(startIndex, endIndex - startIndex);
portString = currentEndpoint.Substring(endIndex + 2);
}
else
{
int portIndex = currentEndpoint.LastIndexOf(":");
addressString = currentEndpoint.Substring(0, portIndex);
portString = currentEndpoint.Substring(portIndex + 1);
}
int port = Int32.Parse(portString);
IPAddress[] connectAddresses = new IPAddress[1];
if (!IPAddress.TryParse(addressString, out connectAddresses[0]))
{
connectAddresses = Dns.GetHostAddresses(addressString);
}
foreach (IPAddress testAddress in connectAddresses)
{
TcpClient newConnection = new TcpClient(testAddress.AddressFamily);
IAsyncResult ar = newConnection.BeginConnect(testAddress, port, null, null);
if (ar.AsyncWaitHandle.WaitOne(5000))
{
if (newConnection.Connected)
{
//Connected!
newConnection.EndConnect(ar);
currentConnection = newConnection;
DarkLog.Debug("Connected to " + currentEndpoint + " (" + testAddress + ")");
return newConnection;
}
else
{
//Failed to connect - try next one
DarkLog.Debug("Failed to connect to " + currentEndpoint + " (" + testAddress + ")");
}
}
else
{
//Failed to connect - try next one
DarkLog.Debug("Failed to connect to " + currentEndpoint + " (" + testAddress + ")");
}
}
}
catch (Exception e)
{
DarkLog.Debug("Error connecting to " + currentEndpoint + ", exception: " + e.Message);
}
}
return null;
}
private void SendReportMain()
{
sendMessages.Clear();
ReportData();
while (true)
{
sendEvent.WaitOne(100);
while (true)
{
byte[] sendBytes = null;
lock (sendMessages)
{
if (sendMessages.Count > 0)
{
sendBytes = sendMessages.Dequeue();
}
}
if (sendBytes != null)
{
SendNetworkMessage(sendBytes);
}
else
{
break;
}
}
if (Server.serverClock.ElapsedMilliseconds > (lastMessageSendTime + CONNECTION_HEARTBEAT))
{
lastMessageSendTime = Server.serverClock.ElapsedMilliseconds;
//Queue a heartbeat to prevent the connection from timing out
QueueHeartbeat();
}
}
}
private void SendNetworkMessage(byte[] data)
{
currentConnection.GetStream().Write(data, 0, data.Length);
}
private void ReportData()
{
string[] currentPlayers = GetServerPlayerArray();
if (currentPlayers.Length == 1)
{
DarkLog.Debug("Sending report: 1 player.");
}
else
{
DarkLog.Debug("Sending report: " + currentPlayers.Length + " players.");
}
using (MessageWriter mw = new MessageWriter())
{
mw.Write<string>(settingsStore.serverHash);
mw.Write<string>(Settings.settingsStore.serverName);
mw.Write<string>(settingsStore.description);
mw.Write<int>(Settings.settingsStore.port);
mw.Write<string>(settingsStore.gameAddress);
//Constants are baked, so we have to reflect them.
int protocolVersion = (int)typeof(DarkMultiPlayerCommon.Common).GetField("PROTOCOL_VERSION").GetValue(null);
mw.Write<int>(protocolVersion);
string programVersion = (string)typeof(DarkMultiPlayerCommon.Common).GetField("PROGRAM_VERSION").GetValue(null);
mw.Write<string>(programVersion);
mw.Write<int>(Settings.settingsStore.maxPlayers);
mw.Write<int>((int)Settings.settingsStore.modControl);
mw.Write<string>(Server.GetModControlSHA());
mw.Write<int>((int)Settings.settingsStore.gameMode);
mw.Write<bool>(Settings.settingsStore.cheats);
mw.Write<int>((int)Settings.settingsStore.warpMode);
mw.Write<long>(Server.GetUniverseSize());
mw.Write<string>(settingsStore.banner);
mw.Write<string>(settingsStore.homepage);
mw.Write<int>(Settings.settingsStore.httpPort);
mw.Write<string>(settingsStore.admin);
mw.Write<string>(settingsStore.team);
mw.Write<string>(settingsStore.location);
mw.Write<bool>(settingsStore.fixedIP);
mw.Write<string[]>(currentPlayers);
QueueNetworkMessage(mw.GetMessageBytes());
}
}
private string[] GetServerPlayerArray()
{
return connectedPlayers.ToArray();
}
private void QueueHeartbeat()
{
byte[] messageBytes = new byte[8];
BitConverter.GetBytes(HEARTBEAT_ID).CopyTo(messageBytes, 0);
BitConverter.GetBytes(0).CopyTo(messageBytes, 4);
lock (sendMessages)
{
sendMessages.Enqueue(messageBytes);
}
sendEvent.Set();
}
private void QueueNetworkMessage(byte[] data)
{
//Prefix the TCP message frame and append the payload.
byte[] messageBytes = new byte[data.Length + 8];
BitConverter.GetBytes(REPORTING_PROTOCOL_ID).CopyTo(messageBytes, 0);
BitConverter.GetBytes(data.Length).CopyTo(messageBytes, 4);
Array.Copy(data, 0, messageBytes, 8, data.Length);
lock (sendMessages)
{
sendMessages.Enqueue(messageBytes);
}
sendEvent.Set();
}
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -----------------------------------------------------------------------------
// The following code is a port of MakeSpriteFont from DirectXTk
// http://go.microsoft.com/fwlink/?LinkId=248929
// -----------------------------------------------------------------------------
// Microsoft Public License (Ms-PL)
//
// This license governs use of the accompanying software. If you use the
// software, you accept this license. If you do not accept the license, do not
// use the software.
//
// 1. Definitions
// The terms "reproduce," "reproduction," "derivative works," and
// "distribution" have the same meaning here as under U.S. copyright law.
// A "contribution" is the original software, or any additions or changes to
// the software.
// A "contributor" is any person that distributes its contribution under this
// license.
// "Licensed patents" are a contributor's patent claims that read directly on
// its contribution.
//
// 2. Grant of Rights
// (A) Copyright Grant- Subject to the terms of this license, including the
// license conditions and limitations in section 3, each contributor grants
// you a non-exclusive, worldwide, royalty-free copyright license to reproduce
// its contribution, prepare derivative works of its contribution, and
// distribute its contribution or any derivative works that you create.
// (B) Patent Grant- Subject to the terms of this license, including the license
// conditions and limitations in section 3, each contributor grants you a
// non-exclusive, worldwide, royalty-free license under its licensed patents to
// make, have made, use, sell, offer for sale, import, and/or otherwise dispose
// of its contribution in the software or derivative works of the contribution
// in the software.
//
// 3. Conditions and Limitations
// (A) No Trademark License- This license does not grant you rights to use any
// contributors' name, logo, or trademarks.
// (B) If you bring a patent claim against any contributor over patents that
// you claim are infringed by the software, your patent license from such
// contributor to the software ends automatically.
// (C) If you distribute any portion of the software, you must retain all
// copyright, patent, trademark, and attribution notices that are present in the
// software.
// (D) If you distribute any portion of the software in source code form, you
// may do so only under this license by including a complete copy of this
// license with your distribution. If you distribute any portion of the software
// in compiled or object code form, you may only do so under a license that
// complies with this license.
// (E) The software is licensed "as-is." You bear the risk of using it. The
// contributors give no express warranties, guarantees or conditions. You may
// have additional consumer rights under your local laws which this license
// cannot change. To the extent permitted under your local laws, the
// contributors exclude the implied warranties of merchantability, fitness for a
// particular purpose and non-infringement.
//--------------------------------------------------------------------
using System;
namespace SharpDX.Toolkit.Graphics
{
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
// Assorted helpers for doing useful things with bitmaps.
internal static class BitmapUtils
{
// Copies a rectangular area from one bitmap to another.
public static void CopyRect(Bitmap source, Rectangle sourceRegion, Bitmap output, Rectangle outputRegion)
{
if (sourceRegion.Width != outputRegion.Width ||
sourceRegion.Height != outputRegion.Height)
{
throw new ArgumentException();
}
using (var sourceData = new PixelAccessor(source, ImageLockMode.ReadOnly, sourceRegion))
using (var outputData = new PixelAccessor(output, ImageLockMode.WriteOnly, outputRegion))
{
for (int y = 0; y < sourceRegion.Height; y++)
{
for (int x = 0; x < sourceRegion.Width; x++)
{
outputData[x, y] = sourceData[x, y];
}
}
}
}
// Checks whether an area of a bitmap contains entirely the specified alpha value.
public static bool IsAlphaEntirely(byte expectedAlpha, Bitmap bitmap, Rectangle? region = null)
{
using (var bitmapData = new PixelAccessor(bitmap, ImageLockMode.ReadOnly, region))
{
for (int y = 0; y < bitmapData.Region.Height; y++)
{
for (int x = 0; x < bitmapData.Region.Width; x++)
{
byte alpha = bitmapData[x, y].A;
if (alpha != expectedAlpha)
return false;
}
}
}
return true;
}
// Checks whether a bitmap contains entirely the specified RGB value.
public static bool IsRgbEntirely(Color expectedRgb, Bitmap bitmap)
{
using (var bitmapData = new PixelAccessor(bitmap, ImageLockMode.ReadOnly))
{
for (int y = 0; y < bitmap.Height; y++)
{
for (int x = 0; x < bitmap.Width; x++)
{
Color color = bitmapData[x, y];
if (color.A == 0)
continue;
if ((color.R != expectedRgb.R) ||
(color.G != expectedRgb.G) ||
(color.B != expectedRgb.B))
{
return false;
}
}
}
}
return true;
}
// Converts greyscale luminosity to alpha data.
public static void ConvertGreyToAlpha(Bitmap bitmap)
{
using (var bitmapData = new PixelAccessor(bitmap, ImageLockMode.ReadWrite))
{
for (int y = 0; y < bitmap.Height; y++)
{
for (int x = 0; x < bitmap.Width; x++)
{
Color color = bitmapData[x, y];
// Average the red, green and blue values to compute brightness.
int alpha = (color.R + color.G + color.B) / 3;
bitmapData[x, y] = Color.FromArgb(alpha, 255, 255, 255);
}
}
}
}
// Converts a bitmap to premultiplied alpha format.
public static void PremultiplyAlphaClearType(Bitmap bitmap)
{
using (var bitmapData = new PixelAccessor(bitmap, ImageLockMode.ReadWrite))
{
for (int y = 0; y < bitmap.Height; y++)
{
for (int x = 0; x < bitmap.Width; x++)
{
Color color = bitmapData[x, y];
int a = (color.R + color.G + color.B) / 3;
int r = color.R;
int g = color.G;
int b = color.B;
bitmapData[x, y] = Color.FromArgb(a, r, g, b);
}
}
}
}
public static void PremultiplyAlpha(Bitmap bitmap)
{
using (var bitmapData = new PixelAccessor(bitmap, ImageLockMode.ReadWrite))
{
for (int y = 0; y < bitmap.Height; y++)
{
for (int x = 0; x < bitmap.Width; x++)
{
Color color = bitmapData[x, y];
int a = color.A;
int r = color.R * a / 255;
int g = color.G * a / 255;
int b = color.B * a / 255;
bitmapData[x, y] = Color.FromArgb(a, r, g, b);
}
}
}
}
// To avoid filtering artifacts when scaling or rotating fonts that do not use premultiplied alpha,
// make sure the one pixel border around each glyph contains the same RGB values as the edge of the
// glyph itself, but with zero alpha. This processing is an elaborate no-op when using premultiplied
// alpha, because the premultiply conversion will change the RGB of all such zero alpha pixels to black.
public static void PadBorderPixels(Bitmap bitmap, Rectangle region)
{
using (var bitmapData = new PixelAccessor(bitmap, ImageLockMode.ReadWrite))
{
// Pad the top and bottom.
for (int x = region.Left; x < region.Right; x++)
{
CopyBorderPixel(bitmapData, x, region.Top, x, region.Top - 1);
CopyBorderPixel(bitmapData, x, region.Bottom - 1, x, region.Bottom);
}
// Pad the left and right.
for (int y = region.Top; y < region.Bottom; y++)
{
CopyBorderPixel(bitmapData, region.Left, y, region.Left - 1, y);
CopyBorderPixel(bitmapData, region.Right - 1, y, region.Right, y);
}
// Pad the four corners.
CopyBorderPixel(bitmapData, region.Left, region.Top, region.Left - 1, region.Top - 1);
CopyBorderPixel(bitmapData, region.Right - 1, region.Top, region.Right, region.Top - 1);
CopyBorderPixel(bitmapData, region.Left, region.Bottom - 1, region.Left - 1, region.Bottom);
CopyBorderPixel(bitmapData, region.Right - 1, region.Bottom - 1, region.Right, region.Bottom);
}
}
// Copies a single pixel within a bitmap, preserving RGB but forcing alpha to zero.
static void CopyBorderPixel(PixelAccessor bitmapData, int sourceX, int sourceY, int destX, int destY)
{
Color color = bitmapData[sourceX, sourceY];
bitmapData[destX, destY] = Color.FromArgb(0, color);
}
// Converts a bitmap to the specified pixel format.
public static Bitmap ChangePixelFormat(Bitmap bitmap, PixelFormat format)
{
Rectangle bounds = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
return bitmap.Clone(bounds, format);
}
// Helper for locking a bitmap and efficiently reading or writing its pixels.
public sealed class PixelAccessor : IDisposable
{
// Constructor locks the bitmap.
public PixelAccessor(Bitmap bitmap, ImageLockMode mode, Rectangle? region = null)
{
this.bitmap = bitmap;
this.Region = region.GetValueOrDefault(new Rectangle(0, 0, bitmap.Width, bitmap.Height));
this.data = bitmap.LockBits(Region, mode, PixelFormat.Format32bppArgb);
}
// Dispose unlocks the bitmap.
public void Dispose()
{
if (data != null)
{
bitmap.UnlockBits(data);
data = null;
}
}
// Query what part of the bitmap is locked.
public Rectangle Region { get; private set; }
// Get or set a pixel value.
public Color this[int x, int y]
{
get
{
return Color.FromArgb(Marshal.ReadInt32(PixelAddress(x, y)));
}
set
{
Marshal.WriteInt32(PixelAddress(x, y), value.ToArgb());
}
}
// Helper computes the address of the specified pixel.
unsafe IntPtr PixelAddress(int x, int y)
{
return new IntPtr((byte*)data.Scan0 + (y * data.Stride) + (x * sizeof(int)));
}
// Fields.
Bitmap bitmap;
BitmapData data;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Reactive.Threading.Tasks;
using System.Security.AccessControl;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Nest;
namespace Tests.Framework.Integration
{
public class ElasticsearchNode : IDisposable
{
private static readonly object _lock = new object();
// <installpath> <> <plugin folder name>
private readonly Dictionary<string, string> SupportedPlugins = new Dictionary<string, string>
{
{ "delete-by-query", "delete-by-query" },
{ "cloud-azure", "cloud-azure" }
};
private readonly bool _doNotSpawnIfAlreadyRunning;
private ObservableProcess _process;
private IDisposable _processListener;
public string Version { get; }
public string Binary { get; }
private string RoamingFolder { get; }
private string RoamingClusterFolder { get; }
public bool Started { get; private set; }
public bool RunningIntegrations { get; private set; }
public string ClusterName { get; } = Guid.NewGuid().ToString("N").Substring(0, 6);
public string NodeName { get; } = Guid.NewGuid().ToString("N").Substring(0, 6);
public string RepositoryPath { get; private set; }
public ElasticsearchNodeInfo Info { get; private set; }
public int Port { get; private set; }
private readonly Subject<ManualResetEvent> _blockingSubject = new Subject<ManualResetEvent>();
public IObservable<ManualResetEvent> BootstrapWork { get; }
public ElasticsearchNode(string elasticsearchVersion, bool runningIntegrations, bool doNotSpawnIfAlreadyRunning)
{
_doNotSpawnIfAlreadyRunning = doNotSpawnIfAlreadyRunning;
this.Version = elasticsearchVersion;
this.RunningIntegrations = runningIntegrations;
this.BootstrapWork = _blockingSubject;
if (!runningIntegrations)
{
this.Port = 9200;
return;
}
var appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
this.RoamingFolder = Path.Combine(appdata, "NEST", this.Version);
this.RoamingClusterFolder = Path.Combine(this.RoamingFolder, "elasticsearch-" + elasticsearchVersion);
this.RepositoryPath = Path.Combine(RoamingFolder, "repositories");
this.Binary = Path.Combine(this.RoamingClusterFolder, "bin", "elasticsearch") + ".bat";
Console.WriteLine("========> {0}", this.RoamingFolder);
this.DownloadAndExtractElasticsearch();
}
public IObservable<ElasticsearchMessage> Start()
{
if (!this.RunningIntegrations) return Observable.Empty<ElasticsearchMessage>();
this.Stop();
var timeout = TimeSpan.FromSeconds(60);
var handle = new ManualResetEvent(false);
if (_doNotSpawnIfAlreadyRunning)
{
var alreadyUp = new ElasticClient().RootNodeInfo();
if (alreadyUp.IsValid)
{
this.Started = true;
this.Port = 9200;
this.Info = new ElasticsearchNodeInfo(alreadyUp.Version.Number, null, alreadyUp.Version.LuceneVersion);
this._blockingSubject.OnNext(handle);
if (!handle.WaitOne(timeout, true))
throw new ApplicationException($"Could launch tests on already running elasticsearch within {timeout}");
return Observable.Empty<ElasticsearchMessage>();
}
}
this._process = new ObservableProcess(this.Binary,
$"-Des.cluster.name={this.ClusterName}",
$"-Des.node.name={this.NodeName}",
$"-Des.path.repo={this.RepositoryPath}",
$"-Des.script.inline=on",
$"-Des.script.indexed=on"
);
var observable = Observable.Using(() => this._process, process => process.Start())
.Select(consoleLine => new ElasticsearchMessage(consoleLine));
this._processListener = observable.Subscribe(onNext: s => HandleConsoleMessage(s, handle));
if (!handle.WaitOne(timeout, true))
{
this.Stop();
throw new ApplicationException($"Could not start elasticsearch within {timeout}");
}
return observable;
}
private void HandleConsoleMessage(ElasticsearchMessage s, ManualResetEvent handle)
{
//no need to snoop for metadata if we already started
if (!this.RunningIntegrations || this.Started) return;
ElasticsearchNodeInfo info;
int port;
if (s.TryParseNodeInfo(out info))
{
this.Info = info;
}
else if (s.TryGetStartedConfirmation())
{
this._blockingSubject.OnNext(handle);
this.Started = true;
}
else if (s.TryGetPortNumber(out port))
{
this.Port = port;
}
}
private void DownloadAndExtractElasticsearch()
{
lock (_lock)
{
var zip = $"elasticsearch-{this.Version}.zip";
var downloadUrl = $"https://download.elasticsearch.org/elasticsearch/release/org/elasticsearch/distribution/zip/elasticsearch/{this.Version}/{zip}";
var localZip = Path.Combine(this.RoamingFolder, zip);
Directory.CreateDirectory(this.RoamingFolder);
if (!File.Exists(localZip))
{
new WebClient().DownloadFile(downloadUrl, localZip);
}
if (!Directory.Exists(this.RoamingClusterFolder))
{
ZipFile.ExtractToDirectory(localZip, this.RoamingFolder);
}
InstallPlugins();
//hunspell config
var hunspellFolder = Path.Combine(this.RoamingClusterFolder, "config", "hunspell", "en_US");
var hunspellPrefix = Path.Combine(hunspellFolder, "en_US");
if (!File.Exists(hunspellPrefix + ".dic"))
{
Directory.CreateDirectory(hunspellFolder);
//File.Create(hunspellPrefix + ".dic");
File.WriteAllText(hunspellPrefix + ".dic", "1\r\nabcdegf");
//File.Create(hunspellPrefix + ".aff");
File.WriteAllText(hunspellPrefix + ".aff", "SET UTF8\r\nSFX P Y 1\r\nSFX P 0 s");
}
var analysFolder = Path.Combine(this.RoamingClusterFolder, "config", "analysis");
if (!Directory.Exists(analysFolder)) Directory.CreateDirectory(analysFolder);
var fopXml = Path.Combine(analysFolder, "fop") + ".xml";
if (!File.Exists(fopXml)) File.WriteAllText(fopXml, "<languages-info />");
var customStems = Path.Combine(analysFolder, "custom_stems") + ".txt";
if (!File.Exists(customStems)) File.WriteAllText(customStems, "");
var stopwords = Path.Combine(analysFolder, "stopwords") + ".txt";
if (!File.Exists(stopwords)) File.WriteAllText(stopwords, "");
}
}
private void InstallPlugins()
{
var pluginBat = Path.Combine(this.RoamingClusterFolder, "bin", "plugin") + ".bat";
foreach (var plugin in SupportedPlugins)
{
var installPath = plugin.Key;
var localPath = plugin.Value;
var pluginFolder = Path.Combine(this.RoamingClusterFolder, "bin", "plugins", localPath);
if (!Directory.Exists(this.RoamingClusterFolder)) continue;
var timeout = TimeSpan.FromSeconds(60);
var handle = new ManualResetEvent(false);
Task.Factory.StartNew(() =>
{
using (var p = new ObservableProcess(pluginBat, "install", installPath))
{
var o = p.Start();
o.Subscribe(Console.WriteLine,
(e) =>
{
handle.Set();
throw e;
},
() => handle.Set()
);
}
});
if (!handle.WaitOne(timeout, true))
throw new ApplicationException($"Could not install ${installPath} within {timeout}");
}
}
public void Stop()
{
if (!this.RunningIntegrations || !this.Started) return;
this.Started = false;
Console.WriteLine($"Stopping... ran integrations: {this.RunningIntegrations}");
Console.WriteLine($"Node started: {this.Started} on port: {this.Port} using PID: {this.Info?.Pid}");
this._process?.Dispose();
this._processListener?.Dispose();
if (this.Info != null && this.Info.Pid.HasValue)
{
var esProcess = Process.GetProcessById(this.Info.Pid.Value);
Console.WriteLine($"Killing elasticsearch PID {this.Info.Pid}");
esProcess.Kill();
esProcess.WaitForExit(5000);
esProcess.Close();
}
if (this._doNotSpawnIfAlreadyRunning) return;
var dataFolder = Path.Combine(this.RoamingClusterFolder, "data", this.ClusterName);
if (Directory.Exists(dataFolder))
{
Console.WriteLine($"attempting to delete cluster data: {dataFolder}");
Directory.Delete(dataFolder, true);
}
var logPath = Path.Combine(this.RoamingClusterFolder, "logs");
var files = Directory.GetFiles(logPath, this.ClusterName + "*.log");
foreach (var f in files)
{
Console.WriteLine($"attempting to delete log file: {f}");
File.Delete(f);
}
if (Directory.Exists(this.RepositoryPath))
{
Console.WriteLine("attempting to delete repositories");
Directory.Delete(this.RepositoryPath, true);
}
}
public void Dispose()
{
this.Stop();
}
}
public class ElasticsearchMessage
{
/*
[2015-05-26 20:05:07,681][INFO ][node ] [Nick Fury] version[1.5.2], pid[7704], build[62ff986/2015-04-27T09:21:06Z]
[2015-05-26 20:05:07,681][INFO ][node ] [Nick Fury] initializing ...
[2015-05-26 20:05:07,681][INFO ][plugins ] [Nick Fury] loaded [], sites []
[2015-05-26 20:05:10,790][INFO ][node ] [Nick Fury] initialized
[2015-05-26 20:05:10,821][INFO ][node ] [Nick Fury] starting ...
[2015-05-26 20:05:11,041][INFO ][transport ] [Nick Fury] bound_address {inet[/0:0:0:0:0:0:0:0:9300]}, publish_address {inet[/192.168.194.146:9300]}
[2015-05-26 20:05:11,056][INFO ][discovery ] [Nick Fury] elasticsearch-martijnl/yuiyXva3Si6sQE5tY_9CHg
[2015-05-26 20:05:14,103][INFO ][cluster.service ] [Nick Fury] new_master [Nick Fury][yuiyXva3Si6sQE5tY_9CHg][WIN-DK60SLEMH8C][inet[/192.168.194.146:9300]], reason: zen-disco-join (elected_as_master)
[2015-05-26 20:05:14,134][INFO ][gateway ] [Nick Fury] recovered [0] indices into cluster_state
[2015-05-26 20:05:14,150][INFO ][http ] [Nick Fury] bound_address {inet[/0:0:0:0:0:0:0:0:9200]}, publish_address {inet[/192.168.194.146:9200]}
[2015-05-26 20:05:14,150][INFO ][node ] [Nick Fury] started
*/
public DateTime Date { get; }
public string Level { get; }
public string Section { get; }
public string Node { get; }
public string Message { get; }
private static readonly Regex ConsoleLineParser =
new Regex(@"\[(?<date>.*?)\]\[(?<level>.*?)\]\[(?<section>.*?)\] \[(?<node>.*?)\] (?<message>.+)");
public ElasticsearchMessage(string consoleLine)
{
Console.WriteLine(consoleLine);
if (string.IsNullOrEmpty(consoleLine)) return;
var match = ConsoleLineParser.Match(consoleLine);
if (!match.Success) return;
var dateString = match.Groups["date"].Value.Trim();
Date = DateTime.ParseExact(dateString, "yyyy-MM-dd HH:mm:ss,fff", CultureInfo.CurrentCulture);
Level = match.Groups["level"].Value.Trim();
Section = match.Groups["section"].Value.Trim().Replace("org.elasticsearch.", "");
Node = match.Groups["node"].Value.Trim();
Message = match.Groups["message"].Value.Trim();
}
private static readonly Regex InfoParser =
new Regex(@"version\[(?<version>.*)\], pid\[(?<pid>.*)\], build\[(?<build>.+)\]");
public bool TryParseNodeInfo(out ElasticsearchNodeInfo nodeInfo)
{
nodeInfo = null;
if (this.Section != "node") return false;
var match = InfoParser.Match(this.Message);
if (!match.Success) return false;
var version = match.Groups["version"].Value.Trim();
var pid = match.Groups["pid"].Value.Trim();
var build = match.Groups["build"].Value.Trim();
nodeInfo = new ElasticsearchNodeInfo(version, pid, build);
return true;
}
public bool TryGetStartedConfirmation()
{
if (this.Section != "node") return false;
return this.Message == "started";
}
private static readonly Regex PortParser =
new Regex(@"bound_address(es)? {.+\:(?<port>\d+)}");
public bool TryGetPortNumber(out int port)
{
port = 0;
if (this.Section != "http") return false;
var match = PortParser.Match(this.Message);
if (!match.Success) return false;
var portString = match.Groups["port"].Value.Trim();
port = int.Parse(portString);
return true;
}
}
public class ElasticsearchNodeInfo
{
public string Version { get; }
public int? Pid { get; }
public string Build { get; }
public ElasticsearchNodeInfo(string version, string pid, string build)
{
this.Version = version;
if (!string.IsNullOrEmpty(pid))
Pid = int.Parse(pid);
Build = build;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Threading.Tasks;
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Diagnostics;
using System.Collections;
using System.Globalization;
using System.Collections.Generic;
// OpenIssue : is it better to cache the current namespace decls for each elem
// as the current code does, or should it just always walk the namespace stack?
namespace System.Xml
{
internal partial class XmlWellFormedWriter : XmlWriter
{
public override Task WriteStartDocumentAsync()
{
return WriteStartDocumentImplAsync(XmlStandalone.Omit);
}
public override Task WriteStartDocumentAsync(bool standalone)
{
return WriteStartDocumentImplAsync(standalone ? XmlStandalone.Yes : XmlStandalone.No);
}
public override async Task WriteEndDocumentAsync()
{
try
{
// auto-close all elements
while (_elemTop > 0)
{
await WriteEndElementAsync().ConfigureAwait(false);
}
State prevState = _currentState;
await AdvanceStateAsync(Token.EndDocument).ConfigureAwait(false);
if (prevState != State.AfterRootEle)
{
throw new ArgumentException(SR.Xml_NoRoot);
}
if (_rawWriter == null)
{
await _writer.WriteEndDocumentAsync().ConfigureAwait(false);
}
}
catch
{
_currentState = State.Error;
throw;
}
}
public override async Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset)
{
try
{
if (name == null || name.Length == 0)
{
throw new ArgumentException(SR.Xml_EmptyName);
}
XmlConvert.VerifyQName(name, ExceptionType.XmlException);
if (_conformanceLevel == ConformanceLevel.Fragment)
{
throw new InvalidOperationException(SR.Xml_DtdNotAllowedInFragment);
}
await AdvanceStateAsync(Token.Dtd).ConfigureAwait(false);
if (_dtdWritten)
{
_currentState = State.Error;
throw new InvalidOperationException(SR.Xml_DtdAlreadyWritten);
}
if (_conformanceLevel == ConformanceLevel.Auto)
{
_conformanceLevel = ConformanceLevel.Document;
_stateTable = s_stateTableDocument;
}
int i;
// check characters
if (_checkCharacters)
{
if (pubid != null)
{
if ((i = _xmlCharType.IsPublicId(pubid)) >= 0)
{
throw new ArgumentException(SR.Format(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(pubid, i)), "pubid");
}
}
if (sysid != null)
{
if ((i = _xmlCharType.IsOnlyCharData(sysid)) >= 0)
{
throw new ArgumentException(SR.Format(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(sysid, i)), "sysid");
}
}
if (subset != null)
{
if ((i = _xmlCharType.IsOnlyCharData(subset)) >= 0)
{
throw new ArgumentException(SR.Format(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(subset, i)), "subset");
}
}
}
// write doctype
await _writer.WriteDocTypeAsync(name, pubid, sysid, subset).ConfigureAwait(false);
_dtdWritten = true;
}
catch
{
_currentState = State.Error;
throw;
}
}
//check if any exception before return the task
private Task TryReturnTask(Task task)
{
if (task.IsSuccess())
{
return Task.CompletedTask;
}
else
{
return _TryReturnTask(task);
}
}
private async Task _TryReturnTask(Task task)
{
try
{
await task.ConfigureAwait(false);
}
catch
{
_currentState = State.Error;
throw;
}
}
//call nextTaskFun after task finish. Check exception.
private Task SequenceRun<TArg>(Task task, Func<TArg, Task> nextTaskFun, TArg arg)
{
if (task.IsSuccess())
{
return TryReturnTask(nextTaskFun(arg));
}
else
{
return _SequenceRun(task, nextTaskFun, arg);
}
}
private async Task _SequenceRun<TArg>(Task task, Func<TArg, Task> nextTaskFun, TArg arg)
{
try
{
await task.ConfigureAwait(false);
await nextTaskFun(arg).ConfigureAwait(false);
}
catch
{
_currentState = State.Error;
throw;
}
}
public override Task WriteStartElementAsync(string prefix, string localName, string ns)
{
try
{
// check local name
if (localName == null || localName.Length == 0)
{
throw new ArgumentException(SR.Xml_EmptyLocalName);
}
CheckNCName(localName);
Task task = AdvanceStateAsync(Token.StartElement);
if (task.IsSuccess())
{
return WriteStartElementAsync_NoAdvanceState(prefix, localName, ns);
}
else
{
return WriteStartElementAsync_NoAdvanceState(task, prefix, localName, ns);
}
}
catch
{
_currentState = State.Error;
throw;
}
}
private Task WriteStartElementAsync_NoAdvanceState(string prefix, string localName, string ns)
{
try
{
// lookup prefix / namespace
if (prefix == null)
{
if (ns != null)
{
prefix = LookupPrefix(ns);
}
if (prefix == null)
{
prefix = string.Empty;
}
}
else if (prefix.Length > 0)
{
CheckNCName(prefix);
if (ns == null)
{
ns = LookupNamespace(prefix);
}
if (ns == null || (ns != null && ns.Length == 0))
{
throw new ArgumentException(SR.Xml_PrefixForEmptyNs);
}
}
if (ns == null)
{
ns = LookupNamespace(prefix);
if (ns == null)
{
Debug.Assert(prefix.Length == 0);
ns = string.Empty;
}
}
if (_elemTop == 0 && _rawWriter != null)
{
// notify the underlying raw writer about the root level element
_rawWriter.OnRootElement(_conformanceLevel);
}
// write start tag
Task task = _writer.WriteStartElementAsync(prefix, localName, ns);
if (task.IsSuccess())
{
WriteStartElementAsync_FinishWrite(prefix, localName, ns);
}
else
{
return WriteStartElementAsync_FinishWrite(task, prefix, localName, ns);
}
return Task.CompletedTask;
}
catch
{
_currentState = State.Error;
throw;
}
}
private async Task WriteStartElementAsync_NoAdvanceState(Task task, string prefix, string localName, string ns)
{
try
{
await task.ConfigureAwait(false);
await WriteStartElementAsync_NoAdvanceState(prefix, localName, ns).ConfigureAwait(false);
}
catch
{
_currentState = State.Error;
throw;
}
}
private void WriteStartElementAsync_FinishWrite(string prefix, string localName, string ns)
{
try
{
// push element on stack and add/check namespace
int top = ++_elemTop;
if (top == _elemScopeStack.Length)
{
ElementScope[] newStack = new ElementScope[top * 2];
Array.Copy(_elemScopeStack, newStack, top);
_elemScopeStack = newStack;
}
_elemScopeStack[top].Set(prefix, localName, ns, _nsTop);
PushNamespaceImplicit(prefix, ns);
if (_attrCount >= MaxAttrDuplWalkCount)
{
_attrHashTable.Clear();
}
_attrCount = 0;
}
catch
{
_currentState = State.Error;
throw;
}
}
private async Task WriteStartElementAsync_FinishWrite(Task t, string prefix, string localName, string ns)
{
try
{
await t.ConfigureAwait(false);
WriteStartElementAsync_FinishWrite(prefix, localName, ns);
}
catch
{
_currentState = State.Error;
throw;
}
}
public override Task WriteEndElementAsync()
{
try
{
Task task = AdvanceStateAsync(Token.EndElement);
return SequenceRun(task, thisRef => thisRef.WriteEndElementAsync_NoAdvanceState(), this);
}
catch
{
_currentState = State.Error;
throw;
}
}
private Task WriteEndElementAsync_NoAdvanceState()
{
try
{
int top = _elemTop;
if (top == 0)
{
throw new XmlException(SR.Xml_NoStartTag, string.Empty);
}
Task task;
// write end tag
if (_rawWriter != null)
{
task = _elemScopeStack[top].WriteEndElementAsync(_rawWriter);
}
else
{
task = _writer.WriteEndElementAsync();
}
return SequenceRun(task, thisRef => thisRef.WriteEndElementAsync_FinishWrite(), this);
}
catch
{
_currentState = State.Error;
throw;
}
}
private Task WriteEndElementAsync_FinishWrite()
{
try
{
int top = _elemTop;
// pop namespaces
int prevNsTop = _elemScopeStack[top].prevNSTop;
if (_useNsHashtable && prevNsTop < _nsTop)
{
PopNamespaces(prevNsTop + 1, _nsTop);
}
_nsTop = prevNsTop;
_elemTop = --top;
// check "one root element" condition for ConformanceLevel.Document
if (top == 0)
{
if (_conformanceLevel == ConformanceLevel.Document)
{
_currentState = State.AfterRootEle;
}
else
{
_currentState = State.TopLevel;
}
}
}
catch
{
_currentState = State.Error;
throw;
}
return Task.CompletedTask;
}
public override Task WriteFullEndElementAsync()
{
try
{
Task task = AdvanceStateAsync(Token.EndElement);
return SequenceRun(task, thisRef => thisRef.WriteFullEndElementAsync_NoAdvanceState(), this);
}
catch
{
_currentState = State.Error;
throw;
}
}
private Task WriteFullEndElementAsync_NoAdvanceState()
{
try
{
int top = _elemTop;
if (top == 0)
{
throw new XmlException(SR.Xml_NoStartTag, string.Empty);
}
Task task;
// write end tag
if (_rawWriter != null)
{
task = _elemScopeStack[top].WriteFullEndElementAsync(_rawWriter);
}
else
{
task = _writer.WriteFullEndElementAsync();
}
return SequenceRun(task, thisRef => thisRef.WriteEndElementAsync_FinishWrite(), this);
}
catch
{
_currentState = State.Error;
throw;
}
}
protected internal override Task WriteStartAttributeAsync(string prefix, string localName, string namespaceName)
{
try
{
// check local name
if (localName == null || localName.Length == 0)
{
if (prefix == "xmlns")
{
localName = "xmlns";
prefix = string.Empty;
}
else
{
throw new ArgumentException(SR.Xml_EmptyLocalName);
}
}
CheckNCName(localName);
Task task = AdvanceStateAsync(Token.StartAttribute);
if (task.IsSuccess())
{
return WriteStartAttributeAsync_NoAdvanceState(prefix, localName, namespaceName);
}
else
{
return WriteStartAttributeAsync_NoAdvanceState(task, prefix, localName, namespaceName);
}
}
catch
{
_currentState = State.Error;
throw;
}
}
private Task WriteStartAttributeAsync_NoAdvanceState(string prefix, string localName, string namespaceName)
{
try
{
// lookup prefix / namespace
if (prefix == null)
{
if (namespaceName != null)
{
// special case prefix=null/localname=xmlns
if (!(localName == "xmlns" && namespaceName == XmlReservedNs.NsXmlNs))
prefix = LookupPrefix(namespaceName);
}
if (prefix == null)
{
prefix = string.Empty;
}
}
if (namespaceName == null)
{
if (prefix != null && prefix.Length > 0)
{
namespaceName = LookupNamespace(prefix);
}
if (namespaceName == null)
{
namespaceName = string.Empty;
}
}
if (prefix.Length == 0)
{
if (localName[0] == 'x' && localName == "xmlns")
{
if (namespaceName.Length > 0 && namespaceName != XmlReservedNs.NsXmlNs)
{
throw new ArgumentException(SR.Xml_XmlnsPrefix);
}
_curDeclPrefix = String.Empty;
SetSpecialAttribute(SpecialAttribute.DefaultXmlns);
goto SkipPushAndWrite;
}
else if (namespaceName.Length > 0)
{
prefix = LookupPrefix(namespaceName);
if (prefix == null || prefix.Length == 0)
{
prefix = GeneratePrefix();
}
}
}
else
{
if (prefix[0] == 'x')
{
if (prefix == "xmlns")
{
if (namespaceName.Length > 0 && namespaceName != XmlReservedNs.NsXmlNs)
{
throw new ArgumentException(SR.Xml_XmlnsPrefix);
}
_curDeclPrefix = localName;
SetSpecialAttribute(SpecialAttribute.PrefixedXmlns);
goto SkipPushAndWrite;
}
else if (prefix == "xml")
{
if (namespaceName.Length > 0 && namespaceName != XmlReservedNs.NsXml)
{
throw new ArgumentException(SR.Xml_XmlPrefix);
}
switch (localName)
{
case "space":
SetSpecialAttribute(SpecialAttribute.XmlSpace);
goto SkipPushAndWrite;
case "lang":
SetSpecialAttribute(SpecialAttribute.XmlLang);
goto SkipPushAndWrite;
}
}
}
CheckNCName(prefix);
if (namespaceName.Length == 0)
{
// attributes cannot have default namespace
prefix = string.Empty;
}
else
{
string definedNs = LookupLocalNamespace(prefix);
if (definedNs != null && definedNs != namespaceName)
{
prefix = GeneratePrefix();
}
}
}
if (prefix.Length != 0)
{
PushNamespaceImplicit(prefix, namespaceName);
}
SkipPushAndWrite:
// add attribute to the list and check for duplicates
AddAttribute(prefix, localName, namespaceName);
if (_specAttr == SpecialAttribute.No)
{
// write attribute name
return TryReturnTask(_writer.WriteStartAttributeAsync(prefix, localName, namespaceName));
}
return Task.CompletedTask;
}
catch
{
_currentState = State.Error;
throw;
}
}
private async Task WriteStartAttributeAsync_NoAdvanceState(Task task, string prefix, string localName, string namespaceName)
{
try
{
await task.ConfigureAwait(false);
await WriteStartAttributeAsync_NoAdvanceState(prefix, localName, namespaceName).ConfigureAwait(false);
}
catch
{
_currentState = State.Error;
throw;
}
}
protected internal override Task WriteEndAttributeAsync()
{
try
{
Task task = AdvanceStateAsync(Token.EndAttribute);
return SequenceRun(task, thisRef => thisRef.WriteEndAttributeAsync_NoAdvance(), this);
}
catch
{
_currentState = State.Error;
throw;
}
}
private Task WriteEndAttributeAsync_NoAdvance()
{
try
{
if (_specAttr != SpecialAttribute.No)
{
return WriteEndAttributeAsync_SepcialAtt();
}
else
{
return TryReturnTask(_writer.WriteEndAttributeAsync());
}
}
catch
{
_currentState = State.Error;
throw;
}
}
private async Task WriteEndAttributeAsync_SepcialAtt()
{
try
{
string value;
switch (_specAttr)
{
case SpecialAttribute.DefaultXmlns:
value = _attrValueCache.StringValue;
if (PushNamespaceExplicit(string.Empty, value))
{ // returns true if the namespace declaration should be written out
if (_rawWriter != null)
{
if (_rawWriter.SupportsNamespaceDeclarationInChunks)
{
await _rawWriter.WriteStartNamespaceDeclarationAsync(string.Empty).ConfigureAwait(false);
await _attrValueCache.ReplayAsync(_rawWriter).ConfigureAwait(false);
await _rawWriter.WriteEndNamespaceDeclarationAsync().ConfigureAwait(false);
}
else
{
await _rawWriter.WriteNamespaceDeclarationAsync(string.Empty, value).ConfigureAwait(false);
}
}
else
{
await _writer.WriteStartAttributeAsync(string.Empty, "xmlns", XmlReservedNs.NsXmlNs).ConfigureAwait(false);
await _attrValueCache.ReplayAsync(_writer).ConfigureAwait(false);
await _writer.WriteEndAttributeAsync().ConfigureAwait(false);
}
}
_curDeclPrefix = null;
break;
case SpecialAttribute.PrefixedXmlns:
value = _attrValueCache.StringValue;
if (value.Length == 0)
{
throw new ArgumentException(SR.Xml_PrefixForEmptyNs);
}
if (value == XmlReservedNs.NsXmlNs || (value == XmlReservedNs.NsXml && _curDeclPrefix != "xml"))
{
throw new ArgumentException(SR.Xml_CanNotBindToReservedNamespace);
}
if (PushNamespaceExplicit(_curDeclPrefix, value))
{ // returns true if the namespace declaration should be written out
if (_rawWriter != null)
{
if (_rawWriter.SupportsNamespaceDeclarationInChunks)
{
await _rawWriter.WriteStartNamespaceDeclarationAsync(_curDeclPrefix).ConfigureAwait(false);
await _attrValueCache.ReplayAsync(_rawWriter).ConfigureAwait(false);
await _rawWriter.WriteEndNamespaceDeclarationAsync().ConfigureAwait(false);
}
else
{
await _rawWriter.WriteNamespaceDeclarationAsync(_curDeclPrefix, value).ConfigureAwait(false);
}
}
else
{
await _writer.WriteStartAttributeAsync("xmlns", _curDeclPrefix, XmlReservedNs.NsXmlNs).ConfigureAwait(false);
await _attrValueCache.ReplayAsync(_writer).ConfigureAwait(false);
await _writer.WriteEndAttributeAsync().ConfigureAwait(false);
}
}
_curDeclPrefix = null;
break;
case SpecialAttribute.XmlSpace:
_attrValueCache.Trim();
value = _attrValueCache.StringValue;
if (value == "default")
{
_elemScopeStack[_elemTop].xmlSpace = XmlSpace.Default;
}
else if (value == "preserve")
{
_elemScopeStack[_elemTop].xmlSpace = XmlSpace.Preserve;
}
else
{
throw new ArgumentException(SR.Xml_InvalidXmlSpace, value);
}
await _writer.WriteStartAttributeAsync("xml", "space", XmlReservedNs.NsXml).ConfigureAwait(false);
await _attrValueCache.ReplayAsync(_writer).ConfigureAwait(false);
await _writer.WriteEndAttributeAsync().ConfigureAwait(false);
break;
case SpecialAttribute.XmlLang:
value = _attrValueCache.StringValue;
_elemScopeStack[_elemTop].xmlLang = value;
await _writer.WriteStartAttributeAsync("xml", "lang", XmlReservedNs.NsXml).ConfigureAwait(false);
await _attrValueCache.ReplayAsync(_writer).ConfigureAwait(false);
await _writer.WriteEndAttributeAsync().ConfigureAwait(false);
break;
}
_specAttr = SpecialAttribute.No;
_attrValueCache.Clear();
}
catch
{
_currentState = State.Error;
throw;
}
}
public override async Task WriteCDataAsync(string text)
{
try
{
if (text == null)
{
text = string.Empty;
}
await AdvanceStateAsync(Token.CData).ConfigureAwait(false);
await _writer.WriteCDataAsync(text).ConfigureAwait(false);
}
catch
{
_currentState = State.Error;
throw;
}
}
public override async Task WriteCommentAsync(string text)
{
try
{
if (text == null)
{
text = string.Empty;
}
await AdvanceStateAsync(Token.Comment).ConfigureAwait(false);
await _writer.WriteCommentAsync(text).ConfigureAwait(false);
}
catch
{
_currentState = State.Error;
throw;
}
}
public override async Task WriteProcessingInstructionAsync(string name, string text)
{
try
{
// check name
if (name == null || name.Length == 0)
{
throw new ArgumentException(SR.Xml_EmptyName);
}
CheckNCName(name);
// check text
if (text == null)
{
text = string.Empty;
}
// xml declaration is a special case (not a processing instruction, but we allow WriteProcessingInstruction as a convenience)
if (name.Length == 3 && string.Equals(name, "xml", StringComparison.OrdinalIgnoreCase))
{
if (_currentState != State.Start)
{
throw new ArgumentException(_conformanceLevel == ConformanceLevel.Document ? SR.Xml_DupXmlDecl : SR.Xml_CannotWriteXmlDecl);
}
_xmlDeclFollows = true;
await AdvanceStateAsync(Token.PI).ConfigureAwait(false);
if (_rawWriter != null)
{
// Translate PI into an xml declaration
await _rawWriter.WriteXmlDeclarationAsync(text).ConfigureAwait(false);
}
else
{
await _writer.WriteProcessingInstructionAsync(name, text).ConfigureAwait(false);
}
}
else
{
await AdvanceStateAsync(Token.PI).ConfigureAwait(false);
await _writer.WriteProcessingInstructionAsync(name, text).ConfigureAwait(false);
}
}
catch
{
_currentState = State.Error;
throw;
}
}
public override async Task WriteEntityRefAsync(string name)
{
try
{
// check name
if (name == null || name.Length == 0)
{
throw new ArgumentException(SR.Xml_EmptyName);
}
CheckNCName(name);
await AdvanceStateAsync(Token.Text).ConfigureAwait(false);
if (SaveAttrValue)
{
_attrValueCache.WriteEntityRef(name);
}
else
{
await _writer.WriteEntityRefAsync(name).ConfigureAwait(false);
}
}
catch
{
_currentState = State.Error;
throw;
}
}
public override async Task WriteCharEntityAsync(char ch)
{
try
{
if (Char.IsSurrogate(ch))
{
throw new ArgumentException(SR.Xml_InvalidSurrogateMissingLowChar);
}
await AdvanceStateAsync(Token.Text).ConfigureAwait(false);
if (SaveAttrValue)
{
_attrValueCache.WriteCharEntity(ch);
}
else
{
await _writer.WriteCharEntityAsync(ch).ConfigureAwait(false);
}
}
catch
{
_currentState = State.Error;
throw;
}
}
public override async Task WriteSurrogateCharEntityAsync(char lowChar, char highChar)
{
try
{
if (!Char.IsSurrogatePair(highChar, lowChar))
{
throw XmlConvert.CreateInvalidSurrogatePairException(lowChar, highChar);
}
await AdvanceStateAsync(Token.Text).ConfigureAwait(false);
if (SaveAttrValue)
{
_attrValueCache.WriteSurrogateCharEntity(lowChar, highChar);
}
else
{
await _writer.WriteSurrogateCharEntityAsync(lowChar, highChar).ConfigureAwait(false);
}
}
catch
{
_currentState = State.Error;
throw;
}
}
public override async Task WriteWhitespaceAsync(string ws)
{
try
{
if (ws == null)
{
ws = string.Empty;
}
if (!XmlCharType.Instance.IsOnlyWhitespace(ws))
{
throw new ArgumentException(SR.Xml_NonWhitespace);
}
await AdvanceStateAsync(Token.Whitespace).ConfigureAwait(false);
if (SaveAttrValue)
{
_attrValueCache.WriteWhitespace(ws);
}
else
{
await _writer.WriteWhitespaceAsync(ws).ConfigureAwait(false);
}
}
catch
{
_currentState = State.Error;
throw;
}
}
public override Task WriteStringAsync(string text)
{
try
{
if (text == null)
{
return Task.CompletedTask;
}
Task task = AdvanceStateAsync(Token.Text);
if (task.IsSuccess())
{
return WriteStringAsync_NoAdvanceState(text);
}
else
{
return WriteStringAsync_NoAdvanceState(task, text);
}
}
catch
{
_currentState = State.Error;
throw;
}
}
private Task WriteStringAsync_NoAdvanceState(string text)
{
try
{
if (SaveAttrValue)
{
_attrValueCache.WriteString(text);
return Task.CompletedTask;
}
else
{
return TryReturnTask(_writer.WriteStringAsync(text));
}
}
catch
{
_currentState = State.Error;
throw;
}
}
private async Task WriteStringAsync_NoAdvanceState(Task task, string text)
{
try
{
await task.ConfigureAwait(false);
await WriteStringAsync_NoAdvanceState(text).ConfigureAwait(false);
}
catch
{
_currentState = State.Error;
throw;
}
}
public override async Task WriteCharsAsync(char[] buffer, int index, int count)
{
try
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("index");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if (count > buffer.Length - index)
{
throw new ArgumentOutOfRangeException("count");
}
await AdvanceStateAsync(Token.Text).ConfigureAwait(false);
if (SaveAttrValue)
{
_attrValueCache.WriteChars(buffer, index, count);
}
else
{
await _writer.WriteCharsAsync(buffer, index, count).ConfigureAwait(false);
}
}
catch
{
_currentState = State.Error;
throw;
}
}
public override async Task WriteRawAsync(char[] buffer, int index, int count)
{
try
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("index");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if (count > buffer.Length - index)
{
throw new ArgumentOutOfRangeException("count");
}
await AdvanceStateAsync(Token.RawData).ConfigureAwait(false);
if (SaveAttrValue)
{
_attrValueCache.WriteRaw(buffer, index, count);
}
else
{
await _writer.WriteRawAsync(buffer, index, count).ConfigureAwait(false);
}
}
catch
{
_currentState = State.Error;
throw;
}
}
public override async Task WriteRawAsync(string data)
{
try
{
if (data == null)
{
return;
}
await AdvanceStateAsync(Token.RawData).ConfigureAwait(false);
if (SaveAttrValue)
{
_attrValueCache.WriteRaw(data);
}
else
{
await _writer.WriteRawAsync(data).ConfigureAwait(false);
}
}
catch
{
_currentState = State.Error;
throw;
}
}
public override Task WriteBase64Async(byte[] buffer, int index, int count)
{
try
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("index");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if (count > buffer.Length - index)
{
throw new ArgumentOutOfRangeException("count");
}
Task task = AdvanceStateAsync(Token.Base64);
if (task.IsSuccess())
{
return TryReturnTask(_writer.WriteBase64Async(buffer, index, count));
}
else
{
return WriteBase64Async_NoAdvanceState(task, buffer, index, count);
}
}
catch
{
_currentState = State.Error;
throw;
}
}
private async Task WriteBase64Async_NoAdvanceState(Task task, byte[] buffer, int index, int count)
{
try
{
await task.ConfigureAwait(false);
await _writer.WriteBase64Async(buffer, index, count).ConfigureAwait(false);
}
catch
{
_currentState = State.Error;
throw;
}
}
public override async Task FlushAsync()
{
try
{
await _writer.FlushAsync().ConfigureAwait(false);
}
catch
{
_currentState = State.Error;
throw;
}
}
public override async Task WriteQualifiedNameAsync(string localName, string ns)
{
try
{
if (localName == null || localName.Length == 0)
{
throw new ArgumentException(SR.Xml_EmptyLocalName);
}
CheckNCName(localName);
await AdvanceStateAsync(Token.Text).ConfigureAwait(false);
string prefix = String.Empty;
if (ns != null && ns.Length != 0)
{
prefix = LookupPrefix(ns);
if (prefix == null)
{
if (_currentState != State.Attribute)
{
throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns));
}
prefix = GeneratePrefix();
PushNamespaceImplicit(prefix, ns);
}
}
// if this is a special attribute, then just convert this to text
// otherwise delegate to raw-writer
if (SaveAttrValue || _rawWriter == null)
{
if (prefix.Length != 0)
{
await WriteStringAsync(prefix).ConfigureAwait(false);
await WriteStringAsync(":").ConfigureAwait(false);
}
await WriteStringAsync(localName).ConfigureAwait(false);
}
else
{
await _rawWriter.WriteQualifiedNameAsync(prefix, localName, ns).ConfigureAwait(false);
}
}
catch
{
_currentState = State.Error;
throw;
}
}
public override async Task WriteBinHexAsync(byte[] buffer, int index, int count)
{
if (IsClosedOrErrorState)
{
throw new InvalidOperationException(SR.Xml_ClosedOrError);
}
try
{
await AdvanceStateAsync(Token.Text).ConfigureAwait(false);
await base.WriteBinHexAsync(buffer, index, count).ConfigureAwait(false);
}
catch
{
_currentState = State.Error;
throw;
}
}
private async Task WriteStartDocumentImplAsync(XmlStandalone standalone)
{
try
{
await AdvanceStateAsync(Token.StartDocument).ConfigureAwait(false);
if (_conformanceLevel == ConformanceLevel.Auto)
{
_conformanceLevel = ConformanceLevel.Document;
_stateTable = s_stateTableDocument;
}
else if (_conformanceLevel == ConformanceLevel.Fragment)
{
throw new InvalidOperationException(SR.Xml_CannotStartDocumentOnFragment);
}
if (_rawWriter != null)
{
if (!_xmlDeclFollows)
{
await _rawWriter.WriteXmlDeclarationAsync(standalone).ConfigureAwait(false);
}
}
else
{
// We do not pass the standalone value here
await _writer.WriteStartDocumentAsync().ConfigureAwait(false);
}
}
catch
{
_currentState = State.Error;
throw;
}
}
//call taskFun and change state in sequence
private Task AdvanceStateAsync_ReturnWhenFinish(Task task, State newState)
{
if (task.IsSuccess())
{
_currentState = newState;
return Task.CompletedTask;
}
else
{
return _AdvanceStateAsync_ReturnWhenFinish(task, newState);
}
}
private async Task _AdvanceStateAsync_ReturnWhenFinish(Task task, State newState)
{
await task.ConfigureAwait(false);
_currentState = newState;
}
private Task AdvanceStateAsync_ContinueWhenFinish(Task task, State newState, Token token)
{
if (task.IsSuccess())
{
_currentState = newState;
return AdvanceStateAsync(token);
}
else
{
return _AdvanceStateAsync_ContinueWhenFinish(task, newState, token);
}
}
private async Task _AdvanceStateAsync_ContinueWhenFinish(Task task, State newState, Token token)
{
await task.ConfigureAwait(false);
_currentState = newState;
await AdvanceStateAsync(token).ConfigureAwait(false);
}
// Advance the state machine
private Task AdvanceStateAsync(Token token)
{
if ((int)_currentState >= (int)State.Closed)
{
if (_currentState == State.Closed || _currentState == State.Error)
{
throw new InvalidOperationException(SR.Xml_ClosedOrError);
}
else
{
throw new InvalidOperationException(SR.Format(SR.Xml_WrongToken, tokenName[(int)token], GetStateName(_currentState)));
}
}
Advance:
State newState = _stateTable[((int)token << 4) + (int)_currentState];
// [ (int)token * 16 + (int)currentState ];
Task task;
if ((int)newState >= (int)State.Error)
{
switch (newState)
{
case State.Error:
ThrowInvalidStateTransition(token, _currentState);
break;
case State.StartContent:
return AdvanceStateAsync_ReturnWhenFinish(StartElementContentAsync(), State.Content);
case State.StartContentEle:
return AdvanceStateAsync_ReturnWhenFinish(StartElementContentAsync(), State.Element);
case State.StartContentB64:
return AdvanceStateAsync_ReturnWhenFinish(StartElementContentAsync(), State.B64Content);
case State.StartDoc:
return AdvanceStateAsync_ReturnWhenFinish(WriteStartDocumentAsync(), State.Document);
case State.StartDocEle:
return AdvanceStateAsync_ReturnWhenFinish(WriteStartDocumentAsync(), State.Element);
case State.EndAttrSEle:
task = SequenceRun(WriteEndAttributeAsync(), thisRef => thisRef.StartElementContentAsync(), this);
return AdvanceStateAsync_ReturnWhenFinish(task, State.Element);
case State.EndAttrEEle:
task = SequenceRun(WriteEndAttributeAsync(), thisRef => thisRef.StartElementContentAsync(), this);
return AdvanceStateAsync_ReturnWhenFinish(task, State.Content);
case State.EndAttrSCont:
task = SequenceRun(WriteEndAttributeAsync(), thisRef => thisRef.StartElementContentAsync(), this);
return AdvanceStateAsync_ReturnWhenFinish(task, State.Content);
case State.EndAttrSAttr:
return AdvanceStateAsync_ReturnWhenFinish(WriteEndAttributeAsync(), State.Attribute);
case State.PostB64Cont:
if (_rawWriter != null)
{
return AdvanceStateAsync_ContinueWhenFinish(_rawWriter.WriteEndBase64Async(), State.Content, token);
}
_currentState = State.Content;
goto Advance;
case State.PostB64Attr:
if (_rawWriter != null)
{
return AdvanceStateAsync_ContinueWhenFinish(_rawWriter.WriteEndBase64Async(), State.Attribute, token);
}
_currentState = State.Attribute;
goto Advance;
case State.PostB64RootAttr:
if (_rawWriter != null)
{
return AdvanceStateAsync_ContinueWhenFinish(_rawWriter.WriteEndBase64Async(), State.RootLevelAttr, token);
}
_currentState = State.RootLevelAttr;
goto Advance;
case State.StartFragEle:
StartFragment();
newState = State.Element;
break;
case State.StartFragCont:
StartFragment();
newState = State.Content;
break;
case State.StartFragB64:
StartFragment();
newState = State.B64Content;
break;
case State.StartRootLevelAttr:
return AdvanceStateAsync_ReturnWhenFinish(WriteEndAttributeAsync(), State.RootLevelAttr);
default:
Debug.Assert(false, "We should not get to this point.");
break;
}
}
_currentState = newState;
return Task.CompletedTask;
}
// write namespace declarations
private async Task StartElementContentAsync_WithNS()
{
int start = _elemScopeStack[_elemTop].prevNSTop;
for (int i = _nsTop; i > start; i--)
{
if (_nsStack[i].kind == NamespaceKind.NeedToWrite)
{
await _nsStack[i].WriteDeclAsync(_writer, _rawWriter).ConfigureAwait(false);
}
}
if (_rawWriter != null)
{
_rawWriter.StartElementContent();
}
}
private Task StartElementContentAsync()
{
if (_nsTop > _elemScopeStack[_elemTop].prevNSTop)
{
return StartElementContentAsync_WithNS();
}
if (_rawWriter != null)
{
_rawWriter.StartElementContent();
}
return Task.CompletedTask;
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using key = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLString;
using rotation = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.Quaternion;
using vector = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.Vector3;
using LSL_List = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.list;
using LSL_String = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLString;
using LSL_Integer = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLInteger;
using LSL_Float = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLFloat;
using LSL_Key = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLString;
namespace Aurora.ScriptEngine.AuroraDotNetEngine.APIs.Interfaces
{
public interface IOSSL_Api
{
//OpenSim functions
string osSetDynamicTextureURL(string dynamicID, string contentType, string url, string extraParams, int timer);
string osSetDynamicTextureURLBlend(string dynamicID, string contentType, string url, string extraParams,
int timer, int alpha);
string osSetDynamicTextureURLBlendFace(string dynamicID, string contentType, string url, string extraParams,
bool blend, int disp, int timer, int alpha, int face);
string osSetDynamicTextureData(string dynamicID, string contentType, string data, string extraParams, int timer);
string osSetDynamicTextureDataBlend(string dynamicID, string contentType, string data, string extraParams,
int timer, int alpha);
string osSetDynamicTextureDataBlendFace(string dynamicID, string contentType, string data, string extraParams,
bool blend, int disp, int timer, int alpha, int face);
LSL_Float osGetTerrainHeight(int x, int y);
LSL_Integer osSetTerrainHeight(int x, int y, double val);
void osTerrainFlush();
int osRegionRestart(double seconds);
void osRegionNotice(string msg);
bool osConsoleCommand(string Command);
void osSetParcelMediaURL(string url);
void osSetPrimFloatOnWater(int floatYN);
void osSetParcelSIPAddress(string SIPAddress);
// Avatar Info Commands
LSL_String osGetAgentIP(string agent);
LSL_List osGetAgents();
// Teleport commands
DateTime osTeleportAgent(string agent, string regionName, vector position, vector lookat);
DateTime osTeleportAgent(string agent, int regionX, int regionY, vector position, vector lookat);
DateTime osTeleportAgent(string agent, vector position, vector lookat);
// Animation commands
void osAvatarPlayAnimation(string avatar, string animation);
void osAvatarStopAnimation(string avatar, string animation);
void osSetTerrainTexture(int level, LSL_Key texture);
void osSetTerrainTextureHeight(int corner, double low, double high);
// Attachment commands
/// <summary>
/// Attach the object containing this script to the avatar that owns it without checking for PERMISSION_ATTACH
/// </summary>
/// <param name='attachment'>The attachment point. For example, ATTACH_CHEST</param>
void osForceAttachToAvatar(int attachment);
/// <summary>
/// Detach the object containing this script from the avatar it is attached to without checking for PERMISSION_ATTACH
/// </summary>
/// <remarks>Nothing happens if the object is not attached.</remarks>
void osForceDetachFromAvatar();
//texture draw functions
string osMovePen(string drawList, int x, int y);
string osDrawLine(string drawList, int startX, int startY, int endX, int endY);
string osDrawLine(string drawList, int endX, int endY);
string osDrawText(string drawList, string text);
string osDrawEllipse(string drawList, int width, int height);
string osDrawRectangle(string drawList, int width, int height);
string osDrawFilledRectangle(string drawList, int width, int height);
string osDrawPolygon(string drawList, LSL_List x, LSL_List y);
string osDrawFilledPolygon(string drawList, LSL_List x, LSL_List y);
string osSetFontName(string drawList, string fontName);
string osSetFontSize(string drawList, int fontSize);
string osSetPenSize(string drawList, int penSize);
string osSetPenColor(string drawList, string colour);
string osSetPenCap(string drawList, string direction, string type);
string osDrawImage(string drawList, int width, int height, string imageUrl);
vector osGetDrawStringSize(string contentType, string text, string fontName, int fontSize);
double osList2Double(LSL_List src, int index);
void osSetRegionWaterHeight(double height);
void osSetRegionSunSettings(bool useEstateSun, bool sunFixed, double sunHour);
void osSetEstateSunSettings(bool sunFixed, double sunHour);
double osGetCurrentSunHour();
double osSunGetParam(string param);
void osSunSetParam(string param, double value);
// Wind Module Functions
string osWindActiveModelPluginName();
void osSetWindParam(string plugin, string param, LSL_Float value);
LSL_Float osGetWindParam(string plugin, string param);
// Parcel commands
void osParcelJoin(vector pos1, vector pos2);
void osParcelSubdivide(vector pos1, vector pos2);
void osSetParcelDetails(vector pos, LSL_List rules);
string osGetScriptEngineName();
string osGetSimulatorVersion();
Hashtable osParseJSON(string JSON);
void osMessageObject(key objectUUID, string message);
void osMakeNotecard(string notecardName, LSL_List contents);
string osGetNotecardLine(string name, int line);
string osGetNotecard(string name);
int osGetNumberOfNotecardLines(string name);
string osAvatarName2Key(string firstname, string lastname);
string osKey2Name(string id);
// Grid Info Functions
string osGetGridNick();
string osGetGridName();
string osGetGridLoginURI();
LSL_String osFormatString(string str, LSL_List strings);
LSL_List osMatchString(string src, string pattern, int start);
// Information about data loaded into the region
string osLoadedCreationDate();
string osLoadedCreationTime();
string osLoadedCreationID();
LSL_List osGetLinkPrimitiveParams(int linknumber, LSL_List rules);
key osGetMapTexture();
key osGetRegionMapTexture(string regionName);
LSL_List osGetRegionStats();
int osGetSimulatorMemory();
void osKickAvatar(LSL_String FirstName, LSL_String SurName, LSL_String alert);
void osSetSpeed(LSL_Key UUID, LSL_Float SpeedModifier);
LSL_List osGetPrimitiveParams(LSL_Key prim, LSL_List rules);
void osSetPrimitiveParams(LSL_Key prim, LSL_List rules);
void osSetProjectionParams(bool projection, LSL_Key texture, double fov, double focus, double amb);
void osSetProjectionParams(LSL_Key prim, bool projection, LSL_Key texture, double fov, double focus, double amb);
LSL_List osGetAvatarList();
void osReturnObject(LSL_Key userID);
void osReturnObjects(LSL_Float Parameter);
void osShutDown();
LSL_Integer osAddAgentToGroup(LSL_Key AgentID, LSL_String GroupName, LSL_String RequestedRole);
DateTime osRezObject(string inventory, vector pos, vector vel, rotation rot, int param, LSL_Integer isRezAtRoot,
LSL_Integer doRecoil, LSL_Integer SetDieAtEdge, LSL_Integer CheckPos);
LSL_String osUnixTimeToTimestamp(long time);
DateTime osTeleportOwner(string regionName, vector position, vector lookat);
DateTime osTeleportOwner(int regionX, int regionY, vector position, vector lookat);
DateTime osTeleportOwner(vector position, vector lookat);
void osCauseDamage(string avatar, double damage, string regionName, vector position, vector lookat);
void osCauseHealing(string avatar, double healing);
void osCauseDamage(string avatar, double damage);
LSL_String osGetInventoryDesc(string item);
LSL_Integer osInviteToGroup(LSL_Key agentId);
LSL_Integer osEjectFromGroup(LSL_Key agentId);
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Razor.Editor;
using Microsoft.AspNet.Razor.Generator;
using Microsoft.AspNet.Razor.Parser;
using Microsoft.AspNet.Razor.Parser.SyntaxTree;
using Microsoft.AspNet.Razor.Test.Framework;
using Microsoft.AspNet.Razor.Text;
using Xunit;
namespace Microsoft.AspNet.Razor.Test.Parser.Html
{
public class HtmlAttributeTest : CsHtmlMarkupParserTestBase
{
[Fact]
public void SimpleLiteralAttribute()
{
ParseBlockTest("<a href='Foo' />",
new MarkupBlock(
Factory.Markup("<a"),
new MarkupBlock(new AttributeBlockCodeGenerator(name: "href", prefix: new LocationTagged<string>(" href='", 2, 0, 2), suffix: new LocationTagged<string>("'", 12, 0, 12)),
Factory.Markup(" href='").With(SpanCodeGenerator.Null),
Factory.Markup("Foo").With(new LiteralAttributeCodeGenerator(prefix: new LocationTagged<string>(string.Empty, 9, 0, 9), value: new LocationTagged<string>("Foo", 9, 0, 9))),
Factory.Markup("'").With(SpanCodeGenerator.Null)),
Factory.Markup(" />").Accepts(AcceptedCharacters.None)));
}
[Fact]
public void MultiPartLiteralAttribute()
{
ParseBlockTest("<a href='Foo Bar Baz' />",
new MarkupBlock(
Factory.Markup("<a"),
new MarkupBlock(new AttributeBlockCodeGenerator(name: "href", prefix: new LocationTagged<string>(" href='", 2, 0, 2), suffix: new LocationTagged<string>("'", 20, 0, 20)),
Factory.Markup(" href='").With(SpanCodeGenerator.Null),
Factory.Markup("Foo").With(new LiteralAttributeCodeGenerator(prefix: new LocationTagged<string>(string.Empty, 9, 0, 9), value: new LocationTagged<string>("Foo", 9, 0, 9))),
Factory.Markup(" Bar").With(new LiteralAttributeCodeGenerator(prefix: new LocationTagged<string>(" ", 12, 0, 12), value: new LocationTagged<string>("Bar", 13, 0, 13))),
Factory.Markup(" Baz").With(new LiteralAttributeCodeGenerator(prefix: new LocationTagged<string>(" ", 16, 0, 16), value: new LocationTagged<string>("Baz", 17, 0, 17))),
Factory.Markup("'").With(SpanCodeGenerator.Null)),
Factory.Markup(" />").Accepts(AcceptedCharacters.None)));
}
[Fact]
public void DoubleQuotedLiteralAttribute()
{
ParseBlockTest("<a href=\"Foo Bar Baz\" />",
new MarkupBlock(
Factory.Markup("<a"),
new MarkupBlock(new AttributeBlockCodeGenerator(name: "href", prefix: new LocationTagged<string>(" href=\"", 2, 0, 2), suffix: new LocationTagged<string>("\"", 20, 0, 20)),
Factory.Markup(" href=\"").With(SpanCodeGenerator.Null),
Factory.Markup("Foo").With(new LiteralAttributeCodeGenerator(prefix: new LocationTagged<string>(string.Empty, 9, 0, 9), value: new LocationTagged<string>("Foo", 9, 0, 9))),
Factory.Markup(" Bar").With(new LiteralAttributeCodeGenerator(prefix: new LocationTagged<string>(" ", 12, 0, 12), value: new LocationTagged<string>("Bar", 13, 0, 13))),
Factory.Markup(" Baz").With(new LiteralAttributeCodeGenerator(prefix: new LocationTagged<string>(" ", 16, 0, 16), value: new LocationTagged<string>("Baz", 17, 0, 17))),
Factory.Markup("\"").With(SpanCodeGenerator.Null)),
Factory.Markup(" />").Accepts(AcceptedCharacters.None)));
}
[Fact]
public void UnquotedLiteralAttribute()
{
ParseBlockTest("<a href=Foo Bar Baz />",
new MarkupBlock(
Factory.Markup("<a"),
new MarkupBlock(new AttributeBlockCodeGenerator(name: "href", prefix: new LocationTagged<string>(" href=", 2, 0, 2), suffix: new LocationTagged<string>(string.Empty, 11, 0, 11)),
Factory.Markup(" href=").With(SpanCodeGenerator.Null),
Factory.Markup("Foo").With(new LiteralAttributeCodeGenerator(prefix: new LocationTagged<string>(string.Empty, 8, 0, 8), value: new LocationTagged<string>("Foo", 8, 0, 8)))),
Factory.Markup(" Bar Baz />").Accepts(AcceptedCharacters.None)));
}
[Fact]
public void SimpleExpressionAttribute()
{
ParseBlockTest("<a href='@foo' />",
new MarkupBlock(
Factory.Markup("<a"),
new MarkupBlock(new AttributeBlockCodeGenerator(name: "href", prefix: new LocationTagged<string>(" href='", 2, 0, 2), suffix: new LocationTagged<string>("'", 13, 0, 13)),
Factory.Markup(" href='").With(SpanCodeGenerator.Null),
new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(string.Empty, 9, 0, 9), 9, 0, 9),
new ExpressionBlock(
Factory.CodeTransition(),
Factory.Code("foo")
.AsImplicitExpression(CSharpCodeParser.DefaultKeywords)
.Accepts(AcceptedCharacters.NonWhiteSpace))),
Factory.Markup("'").With(SpanCodeGenerator.Null)),
Factory.Markup(" />").Accepts(AcceptedCharacters.None)));
}
[Fact]
public void MultiValueExpressionAttribute()
{
ParseBlockTest("<a href='@foo bar @baz' />",
new MarkupBlock(
Factory.Markup("<a"),
new MarkupBlock(new AttributeBlockCodeGenerator(name: "href", prefix: new LocationTagged<string>(" href='", 2, 0, 2), suffix: new LocationTagged<string>("'", 22, 0, 22)),
Factory.Markup(" href='").With(SpanCodeGenerator.Null),
new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(string.Empty, 9, 0, 9), 9, 0, 9),
new ExpressionBlock(
Factory.CodeTransition(),
Factory.Code("foo")
.AsImplicitExpression(CSharpCodeParser.DefaultKeywords)
.Accepts(AcceptedCharacters.NonWhiteSpace))),
Factory.Markup(" bar").With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(" ", 13, 0, 13), new LocationTagged<string>("bar", 14, 0, 14))),
new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(" ", 17, 0, 17), 18, 0, 18),
Factory.Markup(" ").With(SpanCodeGenerator.Null),
new ExpressionBlock(
Factory.CodeTransition(),
Factory.Code("baz")
.AsImplicitExpression(CSharpCodeParser.DefaultKeywords)
.Accepts(AcceptedCharacters.NonWhiteSpace))),
Factory.Markup("'").With(SpanCodeGenerator.Null)),
Factory.Markup(" />").Accepts(AcceptedCharacters.None)));
}
[Fact]
public void VirtualPathAttributesWorkWithConditionalAttributes()
{
ParseBlockTest("<a href='@foo ~/Foo/Bar' />",
new MarkupBlock(
Factory.Markup("<a"),
new MarkupBlock(new AttributeBlockCodeGenerator(name: "href", prefix: new LocationTagged<string>(" href='", 2, 0, 2), suffix: new LocationTagged<string>("'", 23, 0, 23)),
Factory.Markup(" href='").With(SpanCodeGenerator.Null),
new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(string.Empty, 9, 0, 9), 9, 0, 9),
new ExpressionBlock(
Factory.CodeTransition(),
Factory.Code("foo")
.AsImplicitExpression(CSharpCodeParser.DefaultKeywords)
.Accepts(AcceptedCharacters.NonWhiteSpace))),
Factory.Markup(" ~/Foo/Bar")
.WithEditorHints(EditorHints.VirtualPath)
.With(new LiteralAttributeCodeGenerator(
new LocationTagged<string>(" ", 13, 0, 13),
new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 14, 0, 14))),
Factory.Markup("'").With(SpanCodeGenerator.Null)),
Factory.Markup(" />").Accepts(AcceptedCharacters.None)));
}
[Fact]
public void UnquotedAttributeWithCodeWithSpacesInBlock()
{
ParseBlockTest("<input value=@foo />",
new MarkupBlock(
Factory.Markup("<input"),
new MarkupBlock(new AttributeBlockCodeGenerator(name: "value", prefix: new LocationTagged<string>(" value=", 6, 0, 6), suffix: new LocationTagged<string>(string.Empty, 17, 0, 17)),
Factory.Markup(" value=").With(SpanCodeGenerator.Null),
new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(string.Empty, 13, 0, 13), 13, 0, 13),
new ExpressionBlock(
Factory.CodeTransition(),
Factory.Code("foo")
.AsImplicitExpression(CSharpCodeParser.DefaultKeywords)
.Accepts(AcceptedCharacters.NonWhiteSpace)))),
Factory.Markup(" />").Accepts(AcceptedCharacters.None)));
}
[Fact]
public void UnquotedAttributeWithCodeWithSpacesInDocument()
{
ParseDocumentTest("<input value=@foo />",
new MarkupBlock(
Factory.Markup("<input"),
new MarkupBlock(new AttributeBlockCodeGenerator(name: "value", prefix: new LocationTagged<string>(" value=", 6, 0, 6), suffix: new LocationTagged<string>(string.Empty, 17, 0, 17)),
Factory.Markup(" value=").With(SpanCodeGenerator.Null),
new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(string.Empty, 13, 0, 13), 13, 0, 13),
new ExpressionBlock(
Factory.CodeTransition(),
Factory.Code("foo")
.AsImplicitExpression(CSharpCodeParser.DefaultKeywords)
.Accepts(AcceptedCharacters.NonWhiteSpace)))),
Factory.Markup(" />")));
}
[Fact]
public void ConditionalAttributeCollapserDoesNotRemoveUrlAttributeValues()
{
// Act
ParserResults results = ParseDocument("<a href='~/Foo/Bar' />");
Block rewritten = new ConditionalAttributeCollapser(new HtmlMarkupParser().BuildSpan).Rewrite(results.Document);
rewritten = new MarkupCollapser(new HtmlMarkupParser().BuildSpan).Rewrite(rewritten);
// Assert
Assert.Equal(0, results.ParserErrors.Count);
EvaluateParseTree(rewritten,
new MarkupBlock(
Factory.Markup("<a"),
new MarkupBlock(new AttributeBlockCodeGenerator(name: "href", prefix: new LocationTagged<string>(" href='", 2, 0, 2), suffix: new LocationTagged<string>("'", 18, 0, 18)),
Factory.Markup(" href='").With(SpanCodeGenerator.Null),
Factory.Markup("~/Foo/Bar")
.WithEditorHints(EditorHints.VirtualPath)
.With(new LiteralAttributeCodeGenerator(
new LocationTagged<string>(string.Empty, 9, 0, 9),
new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 9, 0, 9))),
Factory.Markup("'").With(SpanCodeGenerator.Null)),
Factory.Markup(" />")));
}
[Fact]
public void ConditionalAttributesDoNotCreateExtraDataForEntirelyLiteralAttribute()
{
// Arrange
const string code =
@"<div class=""sidebar"">
<h1>Title</h1>
<p>
As the author, you can <a href=""/Photo/Edit/photoId"">edit</a>
or <a href=""/Photo/Remove/photoId"">remove</a> this photo.
</p>
<dl>
<dt class=""description"">Description</dt>
<dd class=""description"">
The uploader did not provide a description for this photo.
</dd>
<dt class=""uploaded-by"">Uploaded by</dt>
<dd class=""uploaded-by""><a href=""/User/View/user.UserId"">user.DisplayName</a></dd>
<dt class=""upload-date"">Upload date</dt>
<dd class=""upload-date"">photo.UploadDate</dd>
<dt class=""part-of-gallery"">Gallery</dt>
<dd><a href=""/View/gallery.Id"" title=""View gallery.Name gallery"">gallery.Name</a></dd>
<dt class=""tags"">Tags</dt>
<dd class=""tags"">
<ul class=""tags"">
<li>This photo has no tags.</li>
</ul>
<a href=""/Photo/EditTags/photoId"">edit tags</a>
</dd>
</dl>
<p>
<a class=""download"" href=""/Photo/Full/photoId"" title=""Download: (photo.FileTitle + photo.FileExtension)"">Download full photo</a> ((photo.FileSize / 1024) KB)
</p>
</div>
<div class=""main"">
<img class=""large-photo"" alt=""photo.FileTitle"" src=""/Photo/Thumbnail"" />
<h2>Nobody has commented on this photo</h2>
<ol class=""comments"">
<li>
<h3 class=""comment-header"">
<a href=""/User/View/comment.UserId"" title=""View comment.DisplayName's profile"">comment.DisplayName</a> commented at comment.CommentDate:
</h3>
<p class=""comment-body"">comment.CommentText</p>
</li>
</ol>
<form method=""post"" action="""">
<fieldset id=""addComment"">
<legend>Post new comment</legend>
<ol>
<li>
<label for=""newComment"">Comment</label>
<textarea id=""newComment"" name=""newComment"" title=""Your comment"" rows=""6"" cols=""70""></textarea>
</li>
</ol>
<p class=""form-actions"">
<input type=""submit"" title=""Add comment"" value=""Add comment"" />
</p>
</fieldset>
</form>
</div>";
// Act
ParserResults results = ParseDocument(code);
Block rewritten = new ConditionalAttributeCollapser(new HtmlMarkupParser().BuildSpan).Rewrite(results.Document);
rewritten = new MarkupCollapser(new HtmlMarkupParser().BuildSpan).Rewrite(rewritten);
// Assert
Assert.Equal(0, results.ParserErrors.Count);
EvaluateParseTree(rewritten, new MarkupBlock(Factory.Markup(code)));
}
[Fact]
public void ConditionalAttributesAreDisabledForDataAttributesInBlock()
{
ParseBlockTest("<span data-foo='@foo'></span>",
new MarkupBlock(
Factory.Markup("<span"),
new MarkupBlock(
Factory.Markup(" data-foo='"),
new ExpressionBlock(
Factory.CodeTransition(),
Factory.Code("foo")
.AsImplicitExpression(CSharpCodeParser.DefaultKeywords)
.Accepts(AcceptedCharacters.NonWhiteSpace)),
Factory.Markup("'")),
Factory.Markup("></span>").Accepts(AcceptedCharacters.None)));
}
[Fact]
public void ConditionalAttributesAreDisabledForDataAttributesInDocument()
{
ParseDocumentTest("<span data-foo='@foo'></span>",
new MarkupBlock(
Factory.Markup("<span"),
new MarkupBlock(
Factory.Markup(" data-foo='"),
new ExpressionBlock(
Factory.CodeTransition(),
Factory.Code("foo")
.AsImplicitExpression(CSharpCodeParser.DefaultKeywords)
.Accepts(AcceptedCharacters.NonWhiteSpace)),
Factory.Markup("'")),
Factory.Markup("></span>")));
}
}
}
| |
// Copyright (c) Pomelo Foundation. All rights reserved.
// Licensed under the MIT. See LICENSE in the project root for license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
// ReSharper disable once CheckNamespace
namespace System
{
[DebuggerStepThrough]
internal static class SharedTypeExtensions
{
public static Type UnwrapNullableType(this Type type) => Nullable.GetUnderlyingType(type) ?? type;
public static bool IsNullableType(this Type type)
{
var typeInfo = type.GetTypeInfo();
return !typeInfo.IsValueType
|| (typeInfo.IsGenericType
&& typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>));
}
public static Type MakeNullable(this Type type)
=> type.IsNullableType()
? type
: typeof(Nullable<>).MakeGenericType(type);
public static bool IsInteger(this Type type)
{
type = type.UnwrapNullableType();
return type == typeof(int)
|| type == typeof(long)
|| type == typeof(short)
|| type == typeof(byte)
|| type == typeof(uint)
|| type == typeof(ulong)
|| type == typeof(ushort)
|| type == typeof(sbyte);
}
public static bool IsIntegerForSerial(this Type type)
{
type = type.UnwrapNullableType();
return type == typeof(int)
|| type == typeof(long)
|| type == typeof(short);
}
public static PropertyInfo GetAnyProperty(this Type type, string name)
{
var props = type.GetRuntimeProperties().Where(p => p.Name == name).ToList();
if (props.Count() > 1)
{
throw new AmbiguousMatchException();
}
return props.SingleOrDefault();
}
private static bool IsNonIntegerPrimitive(this Type type)
{
type = type.UnwrapNullableType();
return type == typeof(bool)
|| type == typeof(byte[])
|| type == typeof(char)
|| type == typeof(DateTime)
|| type == typeof(DateTimeOffset)
|| type == typeof(decimal)
|| type == typeof(double)
|| type == typeof(float)
|| type == typeof(Guid)
|| type == typeof(string)
|| type == typeof(TimeSpan)
|| type.GetTypeInfo().IsEnum;
}
public static bool IsPrimitive(this Type type)
=> type.IsInteger()
|| type.IsNonIntegerPrimitive();
public static Type UnwrapEnumType(this Type type)
=> type.GetTypeInfo().IsEnum ? Enum.GetUnderlyingType(type) : type;
public static Type GetSequenceType(this Type type)
{
var sequenceType = TryGetSequenceType(type);
if (sequenceType == null)
{
throw new ArgumentException();
}
return sequenceType;
}
public static Type TryGetSequenceType(this Type type)
=> type.TryGetElementType(typeof(IEnumerable<>))
?? type.TryGetElementType(typeof(IAsyncEnumerable<>));
public static Type TryGetElementType(this Type type, Type interfaceOrBaseType)
{
if (type.GetTypeInfo().IsGenericTypeDefinition)
{
return null;
}
var types = GetGenericTypeImplementations(type, interfaceOrBaseType);
Type singleImplementation = null;
foreach (var impelementation in types)
{
if (singleImplementation == null)
{
singleImplementation = impelementation;
}
else
{
singleImplementation = null;
break;
}
}
return singleImplementation?.GetTypeInfo().GenericTypeArguments.FirstOrDefault();
}
public static IEnumerable<Type> GetGenericTypeImplementations(this Type type, Type interfaceOrBaseType)
{
var typeInfo = type.GetTypeInfo();
if (!typeInfo.IsGenericTypeDefinition)
{
var baseTypes = interfaceOrBaseType.GetTypeInfo().IsInterface
? typeInfo.ImplementedInterfaces
: type.GetBaseTypes();
foreach (var baseType in baseTypes)
{
if (baseType.GetTypeInfo().IsGenericType
&& baseType.GetGenericTypeDefinition() == interfaceOrBaseType)
{
yield return baseType;
}
}
if (type.GetTypeInfo().IsGenericType
&& type.GetGenericTypeDefinition() == interfaceOrBaseType)
{
yield return type;
}
}
}
public static IEnumerable<Type> GetBaseTypes(this Type type)
{
type = type.GetTypeInfo().BaseType;
while (type != null)
{
yield return type;
type = type.GetTypeInfo().BaseType;
}
}
public static ConstructorInfo GetDeclaredConstructor(this Type type, Type[] types)
{
types = types ?? Array.Empty<Type>();
return type.GetTypeInfo().DeclaredConstructors
.SingleOrDefault(
c => !c.IsStatic
&& c.GetParameters().Select(p => p.ParameterType).SequenceEqual(types));
}
public static IEnumerable<PropertyInfo> GetPropertiesInHierarchy(this Type type, string name)
{
do
{
var typeInfo = type.GetTypeInfo();
foreach (var propertyInfo in typeInfo.DeclaredProperties)
{
if (propertyInfo.Name.Equals(name, StringComparison.Ordinal)
&& !(propertyInfo.GetMethod ?? propertyInfo.SetMethod).IsStatic)
{
yield return propertyInfo;
}
}
type = typeInfo.BaseType;
}
while (type != null);
}
// Looking up the members through the whole hierarchy allows to find inherited private members.
public static IEnumerable<MemberInfo> GetMembersInHierarchy(this Type type)
{
do
{
// Do the whole hierarchy for properties first since looking for fields is slower.
foreach (var propertyInfo in type.GetRuntimeProperties().Where(pi => !(pi.GetMethod ?? pi.SetMethod).IsStatic))
{
yield return propertyInfo;
}
foreach (var fieldInfo in type.GetRuntimeFields().Where(f => !f.IsStatic))
{
yield return fieldInfo;
}
type = type.BaseType;
}
while (type != null);
}
public static IEnumerable<MemberInfo> GetMembersInHierarchy(this Type type, string name)
=> type.GetMembersInHierarchy().Where(m => m.Name == name);
private static readonly Dictionary<Type, object> _commonTypeDictionary = new Dictionary<Type, object>
{
#pragma warning disable IDE0034 // Simplify 'default' expression - default causes default(object)
{ typeof(int), default(int) },
{ typeof(Guid), default(Guid) },
{ typeof(DateOnly), default(DateOnly) },
{ typeof(DateTime), default(DateTime) },
{ typeof(DateTimeOffset), default(DateTimeOffset) },
{ typeof(TimeOnly), default(TimeOnly) },
{ typeof(long), default(long) },
{ typeof(bool), default(bool) },
{ typeof(double), default(double) },
{ typeof(short), default(short) },
{ typeof(float), default(float) },
{ typeof(byte), default(byte) },
{ typeof(char), default(char) },
{ typeof(uint), default(uint) },
{ typeof(ushort), default(ushort) },
{ typeof(ulong), default(ulong) },
{ typeof(sbyte), default(sbyte) }
#pragma warning restore IDE0034 // Simplify 'default' expression
};
public static object GetDefaultValue(this Type type)
{
if (!type.GetTypeInfo().IsValueType)
{
return null;
}
// A bit of perf code to avoid calling Activator.CreateInstance for common types and
// to avoid boxing on every call. This is about 50% faster than just calling CreateInstance
// for all value types.
return _commonTypeDictionary.TryGetValue(type, out var value)
? value
: Activator.CreateInstance(type);
}
public static MethodInfo GetRequiredRuntimeMethod(this Type type, string name, params Type[] parameters)
=> type.GetTypeInfo().GetRuntimeMethod(name, parameters)
?? throw new InvalidOperationException($"Could not find method '{name}' on type '{type}'");
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace XenAPI
{
/// <summary>
/// A long-running asynchronous task
/// First published in XenServer 4.0.
/// </summary>
public partial class Task : XenObject<Task>
{
public Task()
{
}
public Task(string uuid,
string name_label,
string name_description,
List<task_allowed_operations> allowed_operations,
Dictionary<string, task_allowed_operations> current_operations,
DateTime created,
DateTime finished,
task_status_type status,
XenRef<Host> resident_on,
double progress,
string type,
string result,
string[] error_info,
Dictionary<string, string> other_config,
XenRef<Task> subtask_of,
List<XenRef<Task>> subtasks,
string backtrace)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.allowed_operations = allowed_operations;
this.current_operations = current_operations;
this.created = created;
this.finished = finished;
this.status = status;
this.resident_on = resident_on;
this.progress = progress;
this.type = type;
this.result = result;
this.error_info = error_info;
this.other_config = other_config;
this.subtask_of = subtask_of;
this.subtasks = subtasks;
this.backtrace = backtrace;
}
/// <summary>
/// Creates a new Task from a Proxy_Task.
/// </summary>
/// <param name="proxy"></param>
public Task(Proxy_Task proxy)
{
this.UpdateFromProxy(proxy);
}
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Task.
/// </summary>
public override void UpdateFrom(Task update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
allowed_operations = update.allowed_operations;
current_operations = update.current_operations;
created = update.created;
finished = update.finished;
status = update.status;
resident_on = update.resident_on;
progress = update.progress;
type = update.type;
result = update.result;
error_info = update.error_info;
other_config = update.other_config;
subtask_of = update.subtask_of;
subtasks = update.subtasks;
backtrace = update.backtrace;
}
internal void UpdateFromProxy(Proxy_Task proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
name_label = proxy.name_label == null ? null : (string)proxy.name_label;
name_description = proxy.name_description == null ? null : (string)proxy.name_description;
allowed_operations = proxy.allowed_operations == null ? null : Helper.StringArrayToEnumList<task_allowed_operations>(proxy.allowed_operations);
current_operations = proxy.current_operations == null ? null : Maps.convert_from_proxy_string_task_allowed_operations(proxy.current_operations);
created = proxy.created;
finished = proxy.finished;
status = proxy.status == null ? (task_status_type) 0 : (task_status_type)Helper.EnumParseDefault(typeof(task_status_type), (string)proxy.status);
resident_on = proxy.resident_on == null ? null : XenRef<Host>.Create(proxy.resident_on);
progress = Convert.ToDouble(proxy.progress);
type = proxy.type == null ? null : (string)proxy.type;
result = proxy.result == null ? null : (string)proxy.result;
error_info = proxy.error_info == null ? new string[] {} : (string [])proxy.error_info;
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
subtask_of = proxy.subtask_of == null ? null : XenRef<Task>.Create(proxy.subtask_of);
subtasks = proxy.subtasks == null ? null : XenRef<Task>.Create(proxy.subtasks);
backtrace = proxy.backtrace == null ? null : (string)proxy.backtrace;
}
public Proxy_Task ToProxy()
{
Proxy_Task result_ = new Proxy_Task();
result_.uuid = uuid ?? "";
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.allowed_operations = (allowed_operations != null) ? Helper.ObjectListToStringArray(allowed_operations) : new string[] {};
result_.current_operations = Maps.convert_to_proxy_string_task_allowed_operations(current_operations);
result_.created = created;
result_.finished = finished;
result_.status = task_status_type_helper.ToString(status);
result_.resident_on = resident_on ?? "";
result_.progress = progress;
result_.type = type ?? "";
result_.result = result ?? "";
result_.error_info = error_info;
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.subtask_of = subtask_of ?? "";
result_.subtasks = (subtasks != null) ? Helper.RefListToStringArray(subtasks) : new string[] {};
result_.backtrace = backtrace ?? "";
return result_;
}
/// <summary>
/// Creates a new Task from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Task(Hashtable table) : this()
{
UpdateFrom(table);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Task
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("allowed_operations"))
allowed_operations = Helper.StringArrayToEnumList<task_allowed_operations>(Marshalling.ParseStringArray(table, "allowed_operations"));
if (table.ContainsKey("current_operations"))
current_operations = Maps.convert_from_proxy_string_task_allowed_operations(Marshalling.ParseHashTable(table, "current_operations"));
if (table.ContainsKey("created"))
created = Marshalling.ParseDateTime(table, "created");
if (table.ContainsKey("finished"))
finished = Marshalling.ParseDateTime(table, "finished");
if (table.ContainsKey("status"))
status = (task_status_type)Helper.EnumParseDefault(typeof(task_status_type), Marshalling.ParseString(table, "status"));
if (table.ContainsKey("resident_on"))
resident_on = Marshalling.ParseRef<Host>(table, "resident_on");
if (table.ContainsKey("progress"))
progress = Marshalling.ParseDouble(table, "progress");
if (table.ContainsKey("type"))
type = Marshalling.ParseString(table, "type");
if (table.ContainsKey("result"))
result = Marshalling.ParseString(table, "result");
if (table.ContainsKey("error_info"))
error_info = Marshalling.ParseStringArray(table, "error_info");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
if (table.ContainsKey("subtask_of"))
subtask_of = Marshalling.ParseRef<Task>(table, "subtask_of");
if (table.ContainsKey("subtasks"))
subtasks = Marshalling.ParseSetRef<Task>(table, "subtasks");
if (table.ContainsKey("backtrace"))
backtrace = Marshalling.ParseString(table, "backtrace");
}
public bool DeepEquals(Task other, bool ignoreCurrentOperations)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations))
return false;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._allowed_operations, other._allowed_operations) &&
Helper.AreEqual2(this._created, other._created) &&
Helper.AreEqual2(this._finished, other._finished) &&
Helper.AreEqual2(this._status, other._status) &&
Helper.AreEqual2(this._resident_on, other._resident_on) &&
Helper.AreEqual2(this._progress, other._progress) &&
Helper.AreEqual2(this._type, other._type) &&
Helper.AreEqual2(this._result, other._result) &&
Helper.AreEqual2(this._error_info, other._error_info) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._subtask_of, other._subtask_of) &&
Helper.AreEqual2(this._subtasks, other._subtasks) &&
Helper.AreEqual2(this._backtrace, other._backtrace);
}
internal static List<Task> ProxyArrayToObjectList(Proxy_Task[] input)
{
var result = new List<Task>();
foreach (var item in input)
result.Add(new Task(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, Task server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Task.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static Task get_record(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_record(session.opaque_ref, _task);
else
return new Task((Proxy_Task)session.proxy.task_get_record(session.opaque_ref, _task ?? "").parse());
}
/// <summary>
/// Get a reference to the task instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Task> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<Task>.Create(session.proxy.task_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get all the task instances with the given label.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<Task>> get_by_name_label(Session session, string _label)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_by_name_label(session.opaque_ref, _label);
else
return XenRef<Task>.Create(session.proxy.task_get_by_name_label(session.opaque_ref, _label ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static string get_uuid(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_uuid(session.opaque_ref, _task);
else
return (string)session.proxy.task_get_uuid(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Get the name/label field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static string get_name_label(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_name_label(session.opaque_ref, _task);
else
return (string)session.proxy.task_get_name_label(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Get the name/description field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static string get_name_description(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_name_description(session.opaque_ref, _task);
else
return (string)session.proxy.task_get_name_description(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Get the allowed_operations field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static List<task_allowed_operations> get_allowed_operations(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_allowed_operations(session.opaque_ref, _task);
else
return Helper.StringArrayToEnumList<task_allowed_operations>(session.proxy.task_get_allowed_operations(session.opaque_ref, _task ?? "").parse());
}
/// <summary>
/// Get the current_operations field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static Dictionary<string, task_allowed_operations> get_current_operations(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_current_operations(session.opaque_ref, _task);
else
return Maps.convert_from_proxy_string_task_allowed_operations(session.proxy.task_get_current_operations(session.opaque_ref, _task ?? "").parse());
}
/// <summary>
/// Get the created field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static DateTime get_created(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_created(session.opaque_ref, _task);
else
return session.proxy.task_get_created(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Get the finished field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static DateTime get_finished(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_finished(session.opaque_ref, _task);
else
return session.proxy.task_get_finished(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Get the status field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static task_status_type get_status(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_status(session.opaque_ref, _task);
else
return (task_status_type)Helper.EnumParseDefault(typeof(task_status_type), (string)session.proxy.task_get_status(session.opaque_ref, _task ?? "").parse());
}
/// <summary>
/// Get the resident_on field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static XenRef<Host> get_resident_on(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_resident_on(session.opaque_ref, _task);
else
return XenRef<Host>.Create(session.proxy.task_get_resident_on(session.opaque_ref, _task ?? "").parse());
}
/// <summary>
/// Get the progress field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static double get_progress(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_progress(session.opaque_ref, _task);
else
return Convert.ToDouble(session.proxy.task_get_progress(session.opaque_ref, _task ?? "").parse());
}
/// <summary>
/// Get the type field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static string get_type(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_type(session.opaque_ref, _task);
else
return (string)session.proxy.task_get_type(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Get the result field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static string get_result(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_result(session.opaque_ref, _task);
else
return (string)session.proxy.task_get_result(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Get the error_info field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static string[] get_error_info(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_error_info(session.opaque_ref, _task);
else
return (string [])session.proxy.task_get_error_info(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Get the other_config field of the given task.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static Dictionary<string, string> get_other_config(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_other_config(session.opaque_ref, _task);
else
return Maps.convert_from_proxy_string_string(session.proxy.task_get_other_config(session.opaque_ref, _task ?? "").parse());
}
/// <summary>
/// Get the subtask_of field of the given task.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static XenRef<Task> get_subtask_of(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_subtask_of(session.opaque_ref, _task);
else
return XenRef<Task>.Create(session.proxy.task_get_subtask_of(session.opaque_ref, _task ?? "").parse());
}
/// <summary>
/// Get the subtasks field of the given task.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static List<XenRef<Task>> get_subtasks(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_subtasks(session.opaque_ref, _task);
else
return XenRef<Task>.Create(session.proxy.task_get_subtasks(session.opaque_ref, _task ?? "").parse());
}
/// <summary>
/// Get the backtrace field of the given task.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static string get_backtrace(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_backtrace(session.opaque_ref, _task);
else
return (string)session.proxy.task_get_backtrace(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Set the other_config field of the given task.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _task, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.task_set_other_config(session.opaque_ref, _task, _other_config);
else
session.proxy.task_set_other_config(session.opaque_ref, _task ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given task.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _task, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.task_add_to_other_config(session.opaque_ref, _task, _key, _value);
else
session.proxy.task_add_to_other_config(session.opaque_ref, _task ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given task. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _task, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.task_remove_from_other_config(session.opaque_ref, _task, _key);
else
session.proxy.task_remove_from_other_config(session.opaque_ref, _task ?? "", _key ?? "").parse();
}
/// <summary>
/// Create a new task object which must be manually destroyed.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">short label for the new task</param>
/// <param name="_description">longer description for the new task</param>
public static XenRef<Task> create(Session session, string _label, string _description)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_create(session.opaque_ref, _label, _description);
else
return XenRef<Task>.Create(session.proxy.task_create(session.opaque_ref, _label ?? "", _description ?? "").parse());
}
/// <summary>
/// Destroy the task object
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static void destroy(Session session, string _task)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.task_destroy(session.opaque_ref, _task);
else
session.proxy.task_destroy(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Request that a task be cancelled. Note that a task may fail to be cancelled and may complete or fail normally and note that, even when a task does cancel, it might take an arbitrary amount of time.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static void cancel(Session session, string _task)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.task_cancel(session.opaque_ref, _task);
else
session.proxy.task_cancel(session.opaque_ref, _task ?? "").parse();
}
/// <summary>
/// Request that a task be cancelled. Note that a task may fail to be cancelled and may complete or fail normally and note that, even when a task does cancel, it might take an arbitrary amount of time.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static XenRef<Task> async_cancel(Session session, string _task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_task_cancel(session.opaque_ref, _task);
else
return XenRef<Task>.Create(session.proxy.async_task_cancel(session.opaque_ref, _task ?? "").parse());
}
/// <summary>
/// Set the task status
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
/// <param name="_value">task status value to be set</param>
public static void set_status(Session session, string _task, task_status_type _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.task_set_status(session.opaque_ref, _task, _value);
else
session.proxy.task_set_status(session.opaque_ref, _task ?? "", task_status_type_helper.ToString(_value)).parse();
}
/// <summary>
/// Return a list of all the tasks known to the system.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Task>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_all(session.opaque_ref);
else
return XenRef<Task>.Create(session.proxy.task_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the task Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Task>, Task> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.task_get_all_records(session.opaque_ref);
else
return XenRef<Task>.Create<Proxy_Task>(session.proxy.task_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
Changed = true;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
Changed = true;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client.
/// </summary>
public virtual List<task_allowed_operations> allowed_operations
{
get { return _allowed_operations; }
set
{
if (!Helper.AreEqual(value, _allowed_operations))
{
_allowed_operations = value;
Changed = true;
NotifyPropertyChanged("allowed_operations");
}
}
}
private List<task_allowed_operations> _allowed_operations = new List<task_allowed_operations>() {};
/// <summary>
/// links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task.
/// </summary>
public virtual Dictionary<string, task_allowed_operations> current_operations
{
get { return _current_operations; }
set
{
if (!Helper.AreEqual(value, _current_operations))
{
_current_operations = value;
Changed = true;
NotifyPropertyChanged("current_operations");
}
}
}
private Dictionary<string, task_allowed_operations> _current_operations = new Dictionary<string, task_allowed_operations>() {};
/// <summary>
/// Time task was created
/// </summary>
[JsonConverter(typeof(XenDateTimeConverter))]
public virtual DateTime created
{
get { return _created; }
set
{
if (!Helper.AreEqual(value, _created))
{
_created = value;
Changed = true;
NotifyPropertyChanged("created");
}
}
}
private DateTime _created;
/// <summary>
/// Time task finished (i.e. succeeded or failed). If task-status is pending, then the value of this field has no meaning
/// </summary>
[JsonConverter(typeof(XenDateTimeConverter))]
public virtual DateTime finished
{
get { return _finished; }
set
{
if (!Helper.AreEqual(value, _finished))
{
_finished = value;
Changed = true;
NotifyPropertyChanged("finished");
}
}
}
private DateTime _finished;
/// <summary>
/// current status of the task
/// </summary>
[JsonConverter(typeof(task_status_typeConverter))]
public virtual task_status_type status
{
get { return _status; }
set
{
if (!Helper.AreEqual(value, _status))
{
_status = value;
Changed = true;
NotifyPropertyChanged("status");
}
}
}
private task_status_type _status;
/// <summary>
/// the host on which the task is running
/// </summary>
[JsonConverter(typeof(XenRefConverter<Host>))]
public virtual XenRef<Host> resident_on
{
get { return _resident_on; }
set
{
if (!Helper.AreEqual(value, _resident_on))
{
_resident_on = value;
Changed = true;
NotifyPropertyChanged("resident_on");
}
}
}
private XenRef<Host> _resident_on = new XenRef<Host>(Helper.NullOpaqueRef);
/// <summary>
/// This field contains the estimated fraction of the task which is complete. This field should not be used to determine whether the task is complete - for this the status field of the task should be used.
/// </summary>
public virtual double progress
{
get { return _progress; }
set
{
if (!Helper.AreEqual(value, _progress))
{
_progress = value;
Changed = true;
NotifyPropertyChanged("progress");
}
}
}
private double _progress;
/// <summary>
/// if the task has completed successfully, this field contains the type of the encoded result (i.e. name of the class whose reference is in the result field). Undefined otherwise.
/// </summary>
public virtual string type
{
get { return _type; }
set
{
if (!Helper.AreEqual(value, _type))
{
_type = value;
Changed = true;
NotifyPropertyChanged("type");
}
}
}
private string _type = "";
/// <summary>
/// if the task has completed successfully, this field contains the result value (either Void or an object reference). Undefined otherwise.
/// </summary>
public virtual string result
{
get { return _result; }
set
{
if (!Helper.AreEqual(value, _result))
{
_result = value;
Changed = true;
NotifyPropertyChanged("result");
}
}
}
private string _result = "";
/// <summary>
/// if the task has failed, this field contains the set of associated error strings. Undefined otherwise.
/// </summary>
public virtual string[] error_info
{
get { return _error_info; }
set
{
if (!Helper.AreEqual(value, _error_info))
{
_error_info = value;
Changed = true;
NotifyPropertyChanged("error_info");
}
}
}
private string[] _error_info = {};
/// <summary>
/// additional configuration
/// First published in XenServer 4.1.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
/// <summary>
/// Ref pointing to the task this is a substask of.
/// First published in XenServer 5.0.
/// </summary>
[JsonConverter(typeof(XenRefConverter<Task>))]
public virtual XenRef<Task> subtask_of
{
get { return _subtask_of; }
set
{
if (!Helper.AreEqual(value, _subtask_of))
{
_subtask_of = value;
Changed = true;
NotifyPropertyChanged("subtask_of");
}
}
}
private XenRef<Task> _subtask_of = new XenRef<Task>(Helper.NullOpaqueRef);
/// <summary>
/// List pointing to all the substasks.
/// First published in XenServer 5.0.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<Task>))]
public virtual List<XenRef<Task>> subtasks
{
get { return _subtasks; }
set
{
if (!Helper.AreEqual(value, _subtasks))
{
_subtasks = value;
Changed = true;
NotifyPropertyChanged("subtasks");
}
}
}
private List<XenRef<Task>> _subtasks = new List<XenRef<Task>>() {};
/// <summary>
/// Function call trace for debugging.
/// First published in XenServer 7.0.
/// </summary>
public virtual string backtrace
{
get { return _backtrace; }
set
{
if (!Helper.AreEqual(value, _backtrace))
{
_backtrace = value;
Changed = true;
NotifyPropertyChanged("backtrace");
}
}
}
private string _backtrace = "()";
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
#if SERIALIZATION
using System.Runtime.Serialization;
#endif
namespace Wire.Extensions
{
public static class TypeEx
{
//Why not inline typeof you ask?
//Because it actually generates calls to get the type.
//We prefetch all primitives here
public static readonly Type SystemObject = typeof(object);
public static readonly Type Int32Type = typeof(int);
public static readonly Type Int64Type = typeof(long);
public static readonly Type Int16Type = typeof(short);
public static readonly Type UInt32Type = typeof(uint);
public static readonly Type UInt64Type = typeof(ulong);
public static readonly Type UInt16Type = typeof(ushort);
public static readonly Type ByteType = typeof(byte);
public static readonly Type SByteType = typeof(sbyte);
public static readonly Type BoolType = typeof(bool);
public static readonly Type DateTimeType = typeof(DateTime);
public static readonly Type StringType = typeof(string);
public static readonly Type GuidType = typeof(Guid);
public static readonly Type FloatType = typeof(float);
public static readonly Type DoubleType = typeof(double);
public static readonly Type DecimalType = typeof(decimal);
public static readonly Type CharType = typeof(char);
public static readonly Type ByteArrayType = typeof(byte[]);
public static readonly Type TypeType = typeof(Type);
public static readonly Type RuntimeType = Type.GetType("System.RuntimeType");
public static bool IsWirePrimitive(this Type type)
{
return type == Int32Type ||
type == Int64Type ||
type == Int16Type ||
type == UInt32Type ||
type == UInt64Type ||
type == UInt16Type ||
type == ByteType ||
type == SByteType ||
type == DateTimeType ||
type == BoolType ||
type == StringType ||
type == GuidType ||
type == FloatType ||
type == DoubleType ||
type == DecimalType ||
type == CharType;
//add TypeSerializer with null support
}
#if !SERIALIZATION
//HACK: the GetUnitializedObject actually exists in .NET Core, its just not public
private static readonly Func<Type, object> getUninitializedObjectDelegate = (Func<Type, object>)
typeof(string)
.GetTypeInfo()
.Assembly
.GetType("System.Runtime.Serialization.FormatterServices")
?.GetTypeInfo()
?.GetMethod("GetUninitializedObject", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)
?.CreateDelegate(typeof(Func<Type, object>));
public static object GetEmptyObject(this Type type)
{
return getUninitializedObjectDelegate(type);
}
#else
public static object GetEmptyObject(this Type type)
{
return FormatterServices.GetUninitializedObject(type);
}
#endif
public static bool IsOneDimensionalArray(this Type type)
{
return type.IsArray && type.GetArrayRank() == 1;
}
public static bool IsOneDimensionalPrimitiveArray(this Type type)
{
return type.IsArray && type.GetArrayRank() == 1 && type.GetElementType().IsWirePrimitive();
}
private static readonly ConcurrentDictionary<ByteArrayKey, Type> TypeNameLookup =
new ConcurrentDictionary<ByteArrayKey, Type>(ByteArrayKeyComparer.Instance);
public static byte[] GetTypeManifest(IReadOnlyCollection<byte[]> fieldNames)
{
IEnumerable<byte> result = new[] { (byte)fieldNames.Count };
foreach (var name in fieldNames)
{
var encodedLength = BitConverter.GetBytes(name.Length);
result = result.Concat(encodedLength);
result = result.Concat(name);
}
var versionTolerantHeader = result.ToArray();
return versionTolerantHeader;
}
private static Type GetTypeFromManifestName(Stream stream, DeserializerSession session)
{
var bytes = stream.ReadLengthEncodedByteArray(session);
var byteArr = ByteArrayKey.Create(bytes);
return TypeNameLookup.GetOrAdd(byteArr, b =>
{
var shortName = StringEx.FromUtf8Bytes(b.Bytes, 0, b.Bytes.Length);
var typename = ToQualifiedAssemblyName(shortName);
return Type.GetType(typename, true);
});
}
public static Type GetTypeFromManifestFull(Stream stream, DeserializerSession session)
{
var type = GetTypeFromManifestName(stream, session);
session.TrackDeserializedType(type);
return type;
}
public static Type GetTypeFromManifestVersion(Stream stream, DeserializerSession session)
{
var type = GetTypeFromManifestName(stream, session);
var fieldCount = stream.ReadByte();
for (var i = 0; i < fieldCount; i++)
{
var fieldName = stream.ReadLengthEncodedByteArray(session);
}
session.TrackDeserializedTypeWithVersion(type, null);
return type;
}
public static Type GetTypeFromManifestIndex(int typeId, DeserializerSession session)
{
var type = session.GetTypeFromTypeId(typeId);
return type;
}
public static bool IsNullable(this Type type)
{
return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
public static Type GetNullableElement(this Type type)
{
return type.GetTypeInfo().GetGenericArguments()[0];
}
public static bool IsFixedSizeType(this Type type)
{
return type == Int16Type ||
type == Int32Type ||
type == Int64Type ||
type == BoolType ||
type == UInt16Type ||
type == UInt32Type ||
type == UInt64Type ||
type == CharType;
}
public static int GetTypeSize(this Type type)
{
if (type == Int16Type)
return sizeof(short);
if (type == Int32Type)
return sizeof (int);
if (type == Int64Type)
return sizeof (long);
if (type == BoolType)
return sizeof (bool);
if (type == UInt16Type)
return sizeof (ushort);
if (type == UInt32Type)
return sizeof (uint);
if (type == UInt64Type)
return sizeof (ulong);
if (type == CharType)
return sizeof(char);
throw new NotSupportedException();
}
private static readonly string CoreAssemblyName = GetCoreAssemblyName();
private static string GetCoreAssemblyName()
{
var name = 1.GetType().AssemblyQualifiedName;
var part = name.Substring( name.IndexOf(", Version", StringComparison.Ordinal));
return part;
}
public static string GetShortAssemblyQualifiedName(this Type self)
{
var name = self.AssemblyQualifiedName;
name = name.Replace(CoreAssemblyName, ",%core%");
name = name.Replace(", Culture=neutral", "");
name = name.Replace(", PublicKeyToken=null", "");
name = name.Replace(", Version=1.0.0.0", ""); //TODO: regex or whatever...
return name;
}
public static string ToQualifiedAssemblyName(string shortName)
{
var res = shortName.Replace(",%core%", CoreAssemblyName);
return res;
}
}
}
| |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using NUnit.Framework;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestHelper
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Superclass of all Unit Tests for DiagnosticAnalyzers
/// </summary>
[TestFixture]
public abstract partial class DiagnosticVerifier
{
#region To be implemented by Test classes
/// <summary>
/// Get the CSharp analyzer being tested - to be implemented in non-abstract class
/// </summary>
protected virtual DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return null;
}
/// <summary>
/// Get the Visual Basic analyzer being tested (C#) - to be implemented in non-abstract class
/// </summary>
protected virtual DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return null;
}
#endregion
#region Verifier wrappers
/// <summary>
/// Called to test a C# DiagnosticAnalyzer when applied on the single inputted string as a source
/// Note: input a DiagnosticResult for each Diagnostic expected
/// </summary>
/// <param name="source">A class in the form of a string to run the analyzer on</param>
/// <param name="expected"> DiagnosticResults that should appear after the analyzer is run on the source</param>
protected void VerifyCSharpDiagnostic(string source, params DiagnosticResult[] expected)
{
VerifyDiagnostics(new[] { source }, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), expected);
}
/// <summary>
/// Called to test a VB DiagnosticAnalyzer when applied on the single inputted string as a source
/// Note: input a DiagnosticResult for each Diagnostic expected
/// </summary>
/// <param name="source">A class in the form of a string to run the analyzer on</param>
/// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the source</param>
protected void VerifyBasicDiagnostic(string source, params DiagnosticResult[] expected)
{
VerifyDiagnostics(new[] { source }, LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), expected);
}
/// <summary>
/// Called to test a C# DiagnosticAnalyzer when applied on the inputted strings as a source
/// Note: input a DiagnosticResult for each Diagnostic expected
/// </summary>
/// <param name="sources">An array of strings to create source documents from to run the analyzers on</param>
/// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources</param>
protected void VerifyCSharpDiagnostic(string[] sources, params DiagnosticResult[] expected)
{
VerifyDiagnostics(sources, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), expected);
}
/// <summary>
/// Called to test a VB DiagnosticAnalyzer when applied on the inputted strings as a source
/// Note: input a DiagnosticResult for each Diagnostic expected
/// </summary>
/// <param name="sources">An array of strings to create source documents from to run the analyzers on</param>
/// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources</param>
protected void VerifyBasicDiagnostic(string[] sources, params DiagnosticResult[] expected)
{
VerifyDiagnostics(sources, LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), expected);
}
/// <summary>
/// General method that gets a collection of actual diagnostics found in the source after the analyzer is run,
/// then verifies each of them.
/// </summary>
/// <param name="sources">An array of strings to create source documents from to run the analyzers on</param>
/// <param name="language">The language of the classes represented by the source strings</param>
/// <param name="analyzer">The analyzer to be run on the source code</param>
/// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources</param>
private static void VerifyDiagnostics(string[] sources, string language, DiagnosticAnalyzer analyzer, params DiagnosticResult[] expected)
{
var diagnostics = GetSortedDiagnostics(sources, language, analyzer);
VerifyDiagnosticResults(diagnostics, analyzer, expected);
}
#endregion
#region Actual comparisons and verifications
/// <summary>
/// Checks each of the actual Diagnostics found and compares them with the corresponding DiagnosticResult in the array of expected results.
/// Diagnostics are considered equal only if the DiagnosticResultLocation, Id, Severity, and Message of the DiagnosticResult match the actual diagnostic.
/// </summary>
/// <param name="actualResults">The Diagnostics found by the compiler after running the analyzer on the source code</param>
/// <param name="analyzer">The analyzer that was being run on the sources</param>
/// <param name="expectedResults">Diagnostic Results that should have appeared in the code</param>
private static void VerifyDiagnosticResults(IEnumerable<Diagnostic> actualResults, DiagnosticAnalyzer analyzer, params DiagnosticResult[] expectedResults)
{
int expectedCount = expectedResults.Count();
int actualCount = actualResults.Count();
if (expectedCount != actualCount)
{
string diagnosticsOutput = actualResults.Any() ? FormatDiagnostics(analyzer, actualResults.ToArray()) : " NONE.";
Assert.IsTrue(false,
string.Format("Mismatch between number of diagnostics returned, expected \"{0}\" actual \"{1}\"\r\n\r\nDiagnostics:\r\n{2}\r\n", expectedCount, actualCount, diagnosticsOutput));
}
for (int i = 0; i < expectedResults.Length; i++)
{
var actual = actualResults.ElementAt(i);
var expected = expectedResults[i];
if (expected.Line == -1 && expected.Column == -1)
{
if (actual.Location != Location.None)
{
Assert.IsTrue(false,
string.Format("Expected:\nA project diagnostic with No location\nActual:\n{0}",
FormatDiagnostics(analyzer, actual)));
}
}
else
{
VerifyDiagnosticLocation(analyzer, actual, actual.Location, expected.Locations.First());
var additionalLocations = actual.AdditionalLocations.ToArray();
if (additionalLocations.Length != expected.Locations.Length - 1)
{
Assert.IsTrue(false,
string.Format("Expected {0} additional locations but got {1} for Diagnostic:\r\n {2}\r\n",
expected.Locations.Length - 1, additionalLocations.Length,
FormatDiagnostics(analyzer, actual)));
}
for (int j = 0; j < additionalLocations.Length; ++j)
{
VerifyDiagnosticLocation(analyzer, actual, additionalLocations[j], expected.Locations[j + 1]);
}
}
if (actual.Id != expected.Id)
{
Assert.IsTrue(false,
string.Format("Expected diagnostic id to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
expected.Id, actual.Id, FormatDiagnostics(analyzer, actual)));
}
if (actual.Severity != expected.Severity)
{
Assert.IsTrue(false,
string.Format("Expected diagnostic severity to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
expected.Severity, actual.Severity, FormatDiagnostics(analyzer, actual)));
}
if (actual.GetMessage() != expected.Message)
{
Assert.IsTrue(false,
string.Format("Expected diagnostic message to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
expected.Message, actual.GetMessage(), FormatDiagnostics(analyzer, actual)));
}
}
}
/// <summary>
/// Helper method to VerifyDiagnosticResult that checks the location of a diagnostic and compares it with the location in the expected DiagnosticResult.
/// </summary>
/// <param name="analyzer">The analyzer that was being run on the sources</param>
/// <param name="diagnostic">The diagnostic that was found in the code</param>
/// <param name="actual">The Location of the Diagnostic found in the code</param>
/// <param name="expected">The DiagnosticResultLocation that should have been found</param>
private static void VerifyDiagnosticLocation(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, Location actual, DiagnosticResultLocation expected)
{
var actualSpan = actual.GetLineSpan();
Assert.IsTrue(actualSpan.Path == expected.Path || (actualSpan.Path != null && actualSpan.Path.Contains("Test0.") && expected.Path.Contains("Test.")),
string.Format("Expected diagnostic to be in file \"{0}\" was actually in file \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
expected.Path, actualSpan.Path, FormatDiagnostics(analyzer, diagnostic)));
var actualLinePosition = actualSpan.StartLinePosition;
// Only check line position if there is an actual line in the real diagnostic
if (actualLinePosition.Line > 0)
{
if (actualLinePosition.Line + 1 != expected.Line)
{
Assert.IsTrue(false,
string.Format("Expected diagnostic to be on line \"{0}\" was actually on line \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
expected.Line, actualLinePosition.Line + 1, FormatDiagnostics(analyzer, diagnostic)));
}
}
// Only check column position if there is an actual column position in the real diagnostic
if (actualLinePosition.Character > 0)
{
if (actualLinePosition.Character + 1 != expected.Column)
{
Assert.IsTrue(false,
string.Format("Expected diagnostic to start at column \"{0}\" was actually at column \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
expected.Column, actualLinePosition.Character + 1, FormatDiagnostics(analyzer, diagnostic)));
}
}
}
#endregion
#region Formatting Diagnostics
/// <summary>
/// Helper method to format a Diagnostic into an easily readable string
/// </summary>
/// <param name="analyzer">The analyzer that this verifier tests</param>
/// <param name="diagnostics">The Diagnostics to be formatted</param>
/// <returns>The Diagnostics formatted as a string</returns>
private static string FormatDiagnostics(DiagnosticAnalyzer analyzer, params Diagnostic[] diagnostics)
{
var builder = new StringBuilder();
for (int i = 0; i < diagnostics.Length; ++i)
{
builder.AppendLine("// " + diagnostics[i].ToString());
var analyzerType = analyzer.GetType();
var rules = analyzer.SupportedDiagnostics;
foreach (var rule in rules)
{
if (rule != null && rule.Id == diagnostics[i].Id)
{
var location = diagnostics[i].Location;
if (location == Location.None)
{
builder.AppendFormat("GetGlobalResult({0}.{1})", analyzerType.Name, rule.Id);
}
else
{
Assert.IsTrue(location.IsInSource,
$"Test base does not currently handle diagnostics in metadata locations. Diagnostic in metadata: {diagnostics[i]}\r\n");
string resultMethodName = diagnostics[i].Location.SourceTree.FilePath.EndsWith(".cs") ? "GetCSharpResultAt" : "GetBasicResultAt";
var linePosition = diagnostics[i].Location.GetLineSpan().StartLinePosition;
builder.AppendFormat("{0}({1}, {2}, {3}.{4})",
resultMethodName,
linePosition.Line + 1,
linePosition.Character + 1,
analyzerType.Name,
rule.Id);
}
if (i != diagnostics.Length - 1)
{
builder.Append(',');
}
builder.AppendLine();
break;
}
}
}
return builder.ToString();
}
#endregion
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Diagnostics.Debug.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Diagnostics
{
static public partial class Debug
{
#region Methods and constructors
public static void Assert(bool condition, string message)
{
}
public static void Assert(bool condition, string message, string detailMessage)
{
}
public static void Assert(bool condition)
{
}
public static void Assert(bool condition, string message, string detailMessageFormat, Object[] args)
{
}
public static void Close()
{
}
public static void Fail(string message, string detailMessage)
{
}
public static void Fail(string message)
{
}
public static void Flush()
{
}
public static void Indent()
{
}
public static void Print(string format, Object[] args)
{
}
public static void Print(string message)
{
}
public static void Unindent()
{
}
public static void Write(string message)
{
}
public static void Write(string message, string category)
{
}
public static void Write(Object value, string category)
{
}
public static void Write(Object value)
{
}
public static void WriteIf(bool condition, Object value, string category)
{
}
public static void WriteIf(bool condition, string message, string category)
{
}
public static void WriteIf(bool condition, string message)
{
}
public static void WriteIf(bool condition, Object value)
{
}
public static void WriteLine(Object value, string category)
{
}
public static void WriteLine(string format, Object[] args)
{
}
public static void WriteLine(string message)
{
}
public static void WriteLine(Object value)
{
}
public static void WriteLine(string message, string category)
{
}
public static void WriteLineIf(bool condition, Object value)
{
}
public static void WriteLineIf(bool condition, string message)
{
}
public static void WriteLineIf(bool condition, Object value, string category)
{
}
public static void WriteLineIf(bool condition, string message, string category)
{
}
#endregion
#region Properties and indexers
public static bool AutoFlush
{
get
{
return default(bool);
}
set
{
}
}
public static int IndentLevel
{
get
{
return default(int);
}
set
{
}
}
public static int IndentSize
{
get
{
return default(int);
}
set
{
}
}
public static TraceListenerCollection Listeners
{
get
{
Contract.Ensures(Contract.Result<System.Diagnostics.TraceListenerCollection>() != null);
return default(TraceListenerCollection);
}
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="MobileCapabilities.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Mobile
{
using System.Web;
using System.Collections;
using System.Configuration;
using System.Reflection;
using System.Diagnostics;
using System.ComponentModel;
using System.Globalization;
using System.Security.Permissions;
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities"]/*' />
[AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)]
[Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
public class MobileCapabilities : HttpBrowserCapabilities
{
internal delegate bool EvaluateCapabilitiesDelegate(MobileCapabilities capabilities,
String evalParameter);
private Hashtable _evaluatorResults = Hashtable.Synchronized(new Hashtable());
private const String _kDeviceFiltersConfig = "system.web/deviceFilters";
private static readonly object _staticLock = new object();
[AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[ConfigurationPermission(SecurityAction.Assert, Unrestricted = true)]
private DeviceFilterDictionary GetCurrentFilters()
{
object config = ConfigurationManager.GetSection(_kDeviceFiltersConfig);
DeviceFiltersSection controlSection = config as DeviceFiltersSection;
if (controlSection != null)
{
return controlSection.GetDeviceFilters();
}
return (DeviceFilterDictionary)config;
}
private bool HasComparisonEvaluator(String evaluatorName, out bool result)
{
result = false;
String evaluator;
String argument;
DeviceFilterDictionary currentFilters = GetCurrentFilters();
if(currentFilters == null)
{
return false;
}
if(!currentFilters.FindComparisonEvaluator(evaluatorName, out evaluator, out argument))
{
return false;
}
result = HasCapability(evaluator, argument);
return true;
}
private bool HasDelegatedEvaluator(String evaluatorName, String parameter,
out bool result)
{
result = false;
EvaluateCapabilitiesDelegate evaluator;
DeviceFilterDictionary currentFilters = GetCurrentFilters();
if(currentFilters == null)
{
return false;
}
if(!currentFilters.FindDelegateEvaluator(evaluatorName, out evaluator))
{
return false;
}
result = evaluator(this, parameter);
return true;
}
private bool HasItem(String evaluatorName, String parameter,
out bool result)
{
result = false;
String item;
item = this[evaluatorName];
if(item == null)
{
return false;
}
result = (item == parameter);
return true;
}
private bool HasProperty(String evaluatorName, String parameter,
out bool result)
{
result = false;
PropertyDescriptor propertyDescriptor =
TypeDescriptor.GetProperties(this)[evaluatorName];
if(propertyDescriptor == null)
{
return false;
}
String propertyValue = propertyDescriptor.GetValue(this).ToString();
bool invariantCultureIgnoreCase = (propertyDescriptor.PropertyType == typeof(bool) && parameter != null);
StringComparison compareOption = invariantCultureIgnoreCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.CurrentCulture;
result = (String.Equals(propertyValue, parameter, compareOption));
return true;
}
private bool IsComparisonEvaluator(String evaluatorName)
{
DeviceFilterDictionary currentFilters = GetCurrentFilters();
if(currentFilters == null)
{
return false;
}
else
{
return currentFilters.IsComparisonEvaluator(evaluatorName) &&
!currentFilters.IsDelegateEvaluator(evaluatorName);
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.HasCapability"]/*' />
public bool HasCapability(String delegateName, String optionalParameter)
{
bool result;
bool resultFound;
if(String.IsNullOrEmpty(delegateName))
{
throw new ArgumentException(SR.GetString(SR.MobCap_DelegateNameNoValue),
"delegateName");
}
// Check for cached results
DeviceFilterDictionary currentFilters = GetCurrentFilters();
String hashKey = ((currentFilters == null) ? "null" : currentFilters.GetHashCode().ToString(CultureInfo.InvariantCulture))
+ delegateName;
if(optionalParameter != null && !IsComparisonEvaluator(delegateName))
{
hashKey += optionalParameter;
}
if (_evaluatorResults.Contains(hashKey))
{
return (bool)_evaluatorResults[hashKey];
}
lock (_staticLock)
{
if (_evaluatorResults.Contains(hashKey))
{
return (bool)_evaluatorResults[hashKey];
}
// Note: The fact that delegate evaluators are checked before comparison evaluators
// determines the implementation of IsComparisonEvaluator above.
resultFound = HasDelegatedEvaluator(delegateName, optionalParameter, out result);
if (!resultFound)
{
resultFound = HasComparisonEvaluator(delegateName, out result);
if (!resultFound)
{
resultFound = HasProperty(delegateName, optionalParameter, out result);
if (!resultFound)
{
resultFound = HasItem(delegateName, optionalParameter, out result);
}
}
}
if (resultFound)
{
_evaluatorResults.Add(hashKey, result);
}
else
{
throw new ArgumentOutOfRangeException(
"delegateName",
SR.GetString(SR.MobCap_CantFindCapability, delegateName));
}
return result;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.MobileDeviceManufacturer"]/*' />
/* public virtual String MobileDeviceManufacturer
{
get
{
if(!_haveMobileDeviceManufacturer)
{
_mobileDeviceManufacturer = this["mobileDeviceManufacturer"];
_haveMobileDeviceManufacturer = true;
}
return _mobileDeviceManufacturer;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.MobileDeviceModel"]/*' />
public virtual String MobileDeviceModel
{
get
{
if(!_haveMobileDeviceModel)
{
_mobileDeviceModel = this["mobileDeviceModel"];
_haveMobileDeviceModel = true;
}
return _mobileDeviceModel;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.GatewayVersion"]/*' />
public virtual String GatewayVersion
{
get
{
if(!_haveGatewayVersion)
{
_gatewayVersion = this["gatewayVersion"];
_haveGatewayVersion = true;
}
return _gatewayVersion;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.GatewayMajorVersion"]/*' />
public virtual int GatewayMajorVersion
{
get
{
if(!_haveGatewayMajorVersion)
{
_gatewayMajorVersion = Convert.ToInt32(this["gatewayMajorVersion"]);
_haveGatewayMajorVersion = true;
}
return _gatewayMajorVersion;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.GatewayMinorVersion"]/*' />
public virtual double GatewayMinorVersion
{
get
{
if(!_haveGatewayMinorVersion)
{
// The conversion below does not use Convert.ToDouble()
// because it depends on the current locale. So a german machine it would look for
// a comma as a seperator "1,5" where all user-agent strings use english
// decimal points "1.5". URT11176
//
_gatewayMinorVersion = double.Parse(
this["gatewayMinorVersion"],
NumberStyles.Float | NumberStyles.AllowDecimalPoint,
NumberFormatInfo.InvariantInfo);
_haveGatewayMinorVersion = true;
}
return _gatewayMinorVersion;
}
}
*/
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.PreferredRenderingTypeHtml32"]/*' />
public static readonly String PreferredRenderingTypeHtml32 = "html32";
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.PreferredRenderingTypeWml11"]/*' />
public static readonly String PreferredRenderingTypeWml11 = "wml11";
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.PreferredRenderingTypeWml12"]/*' />
public static readonly String PreferredRenderingTypeWml12 = "wml12";
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.PreferredRenderingTypeChtml10"]/*' />
public static readonly String PreferredRenderingTypeChtml10 = "chtml10";
/*
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.PreferredRenderingType"]/*' />
public virtual String PreferredRenderingType
{
get
{
if(!_havePreferredRenderingType)
{
_preferredRenderingType = this["preferredRenderingType"];
_havePreferredRenderingType = true;
}
return _preferredRenderingType;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.PreferredRenderingMime"]/*' />
public virtual String PreferredRenderingMime
{
get
{
if(!_havePreferredRenderingMime)
{
_preferredRenderingMime = this["preferredRenderingMime"];
_havePreferredRenderingMime = true;
}
return _preferredRenderingMime;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.PreferredImageMime"]/*' />
public virtual String PreferredImageMime
{
get
{
if(!_havePreferredImageMime)
{
_preferredImageMime = this["preferredImageMime"];
_havePreferredImageMime = true;
}
return _preferredImageMime;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.ScreenCharactersWidth"]/*' />
public virtual int ScreenCharactersWidth
{
get
{
if(!_haveScreenCharactersWidth)
{
if(this["screenCharactersWidth"] == null)
{
// calculate from best partial information
int screenPixelsWidthToUse = 640;
int characterWidthToUse = 8;
if(this["screenPixelsWidth"] != null && this["characterWidth"] != null)
{
screenPixelsWidthToUse = Convert.ToInt32(this["screenPixelsWidth"]);
characterWidthToUse = Convert.ToInt32(this["characterWidth"]);
}
else if(this["screenPixelsWidth"] != null)
{
screenPixelsWidthToUse = Convert.ToInt32(this["screenPixelsWidth"]);
characterWidthToUse = Convert.ToInt32(this["defaultCharacterWidth"]);
}
else if(this["characterWidth"] != null)
{
screenPixelsWidthToUse = Convert.ToInt32(this["defaultScreenPixelsWidth"]);
characterWidthToUse = Convert.ToInt32(this["characterWidth"]);
}
else if(this["defaultScreenCharactersWidth"] != null)
{
screenPixelsWidthToUse = Convert.ToInt32(this["defaultScreenCharactersWidth"]);
characterWidthToUse = 1;
}
_screenCharactersWidth = screenPixelsWidthToUse / characterWidthToUse;
}
else
{
_screenCharactersWidth = Convert.ToInt32(this["screenCharactersWidth"]);
}
_haveScreenCharactersWidth = true;
}
return _screenCharactersWidth;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.ScreenCharactersHeight"]/*' />
public virtual int ScreenCharactersHeight
{
get
{
if(!_haveScreenCharactersHeight)
{
if(this["screenCharactersHeight"] == null)
{
// calculate from best partial information
int screenPixelHeightToUse = 480;
int characterHeightToUse = 12;
if(this["screenPixelsHeight"] != null && this["characterHeight"] != null)
{
screenPixelHeightToUse = Convert.ToInt32(this["screenPixelsHeight"]);
characterHeightToUse = Convert.ToInt32(this["characterHeight"]);
}
else if(this["screenPixelsHeight"] != null)
{
screenPixelHeightToUse = Convert.ToInt32(this["screenPixelsHeight"]);
characterHeightToUse = Convert.ToInt32(this["defaultCharacterHeight"]);
}
else if(this["characterHeight"] != null)
{
screenPixelHeightToUse = Convert.ToInt32(this["defaultScreenPixelsHeight"]);
characterHeightToUse = Convert.ToInt32(this["characterHeight"]);
}
else if(this["defaultScreenCharactersHeight"] != null)
{
screenPixelHeightToUse = Convert.ToInt32(this["defaultScreenCharactersHeight"]);
characterHeightToUse = 1;
}
_screenCharactersHeight = screenPixelHeightToUse / characterHeightToUse;
}
else
{
_screenCharactersHeight = Convert.ToInt32(this["screenCharactersHeight"]);
}
_haveScreenCharactersHeight = true;
}
return _screenCharactersHeight;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.ScreenPixelsWidth"]/*' />
public virtual int ScreenPixelsWidth
{
get
{
if(!_haveScreenPixelsWidth)
{
if(this["screenPixelsWidth"] == null)
{
// calculate from best partial information
int screenCharactersWidthToUse = 80;
int characterWidthToUse = 8;
if(this["screenCharactersWidth"] != null && this["characterWidth"] != null)
{
screenCharactersWidthToUse = Convert.ToInt32(this["screenCharactersWidth"]);
characterWidthToUse = Convert.ToInt32(this["characterWidth"]);
}
else if(this["screenCharactersWidth"] != null)
{
screenCharactersWidthToUse = Convert.ToInt32(this["screenCharactersWidth"]);
characterWidthToUse = Convert.ToInt32(this["defaultCharacterWidth"]);
}
else if(this["characterWidth"] != null)
{
screenCharactersWidthToUse = Convert.ToInt32(this["defaultScreenCharactersWidth"]);
characterWidthToUse = Convert.ToInt32(this["characterWidth"]);
}
else if(this["defaultScreenPixelsWidth"] != null)
{
screenCharactersWidthToUse = Convert.ToInt32(this["defaultScreenPixelsWidth"]);
characterWidthToUse = 1;
}
_screenPixelsWidth = screenCharactersWidthToUse * characterWidthToUse;
}
else
{
_screenPixelsWidth = Convert.ToInt32(this["screenPixelsWidth"]);
}
_haveScreenPixelsWidth = true;
}
return _screenPixelsWidth;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.ScreenPixelsHeight"]/*' />
public virtual int ScreenPixelsHeight
{
get
{
if(!_haveScreenPixelsHeight)
{
if(this["screenPixelsHeight"] == null)
{
int screenCharactersHeightToUse = 480 / 12;
int characterHeightToUse = 12;
if(this["screenCharactersHeight"] != null && this["characterHeight"] != null)
{
screenCharactersHeightToUse = Convert.ToInt32(this["screenCharactersHeight"]);
characterHeightToUse = Convert.ToInt32(this["characterHeight"]);
}
else if(this["screenCharactersHeight"] != null)
{
screenCharactersHeightToUse = Convert.ToInt32(this["screenCharactersHeight"]);
characterHeightToUse = Convert.ToInt32(this["defaultCharacterHeight"]);
}
else if(this["characterHeight"] != null)
{
screenCharactersHeightToUse = Convert.ToInt32(this["defaultScreenCharactersHeight"]);
characterHeightToUse = Convert.ToInt32(this["characterHeight"]);
}
else if(this["defaultScreenPixelsHeight"] != null)
{
screenCharactersHeightToUse = Convert.ToInt32(this["defaultScreenPixelsHeight"]);
characterHeightToUse = 1;
}
_screenPixelsHeight = screenCharactersHeightToUse * characterHeightToUse;
}
else
{
_screenPixelsHeight = Convert.ToInt32(this["screenPixelsHeight"]);
}
_haveScreenPixelsHeight = true;
}
return _screenPixelsHeight;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.ScreenBitDepth"]/*' />
public virtual int ScreenBitDepth
{
get
{
if(!_haveScreenBitDepth)
{
_screenBitDepth = Convert.ToInt32(this["screenBitDepth"]);
_haveScreenBitDepth = true;
}
return _screenBitDepth;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.IsColor"]/*' />
public virtual bool IsColor
{
get
{
if(!_haveIsColor)
{
String isColorString = this["isColor"];
if(isColorString == null)
{
_isColor = false;
}
else
{
_isColor = Convert.ToBoolean(this["isColor"]);
}
_haveIsColor = true;
}
return _isColor;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.InputType"]/*' />
public virtual String InputType
{
get
{
if(!_haveInputType)
{
_inputType = this["inputType"];
_haveInputType = true;
}
return _inputType;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.NumberOfSoftkeys"]/*' />
public virtual int NumberOfSoftkeys
{
get
{
if(!_haveNumberOfSoftkeys)
{
_numberOfSoftkeys = Convert.ToInt32(this["numberOfSoftkeys"]);
_haveNumberOfSoftkeys = true;
}
return _numberOfSoftkeys;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.MaximumSoftkeyLabelLength"]/*' />
public virtual int MaximumSoftkeyLabelLength
{
get
{
if(!_haveMaximumSoftkeyLabelLength)
{
_maximumSoftkeyLabelLength = Convert.ToInt32(this["maximumSoftkeyLabelLength"]);
_haveMaximumSoftkeyLabelLength = true;
}
return _maximumSoftkeyLabelLength;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.CanInitiateVoiceCall"]/*' />
public virtual bool CanInitiateVoiceCall
{
get
{
if(!_haveCanInitiateVoiceCall)
{
String canInitiateVoiceCallString = this["canInitiateVoiceCall"];
if(canInitiateVoiceCallString == null)
{
_canInitiateVoiceCall = false;
}
else
{
_canInitiateVoiceCall = Convert.ToBoolean(canInitiateVoiceCallString);
}
_haveCanInitiateVoiceCall = true;
}
return _canInitiateVoiceCall;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.CanSendMail"]/*' />
public virtual bool CanSendMail
{
get
{
if(!_haveCanSendMail)
{
String canSendMailString = this["canSendMail"];
if(canSendMailString == null)
{
_canSendMail = true;
}
else
{
_canSendMail = Convert.ToBoolean(canSendMailString);
}
_haveCanSendMail = true;
}
return _canSendMail;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.HasBackButton"]/*' />
public virtual bool HasBackButton
{
get
{
if(!_haveHasBackButton)
{
String hasBackButtonString = this["hasBackButton"];
if(hasBackButtonString == null)
{
_hasBackButton = true;
}
else
{
_hasBackButton = Convert.ToBoolean(hasBackButtonString);
}
_haveHasBackButton = true;
}
return _hasBackButton;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.RendersWmlDoAcceptsInline"]/*' />
public virtual bool RendersWmlDoAcceptsInline
{
get
{
if(!_haveRendersWmlDoAcceptsInline)
{
String rendersWmlDoAcceptsInlineString = this["rendersWmlDoAcceptsInline"];
if(rendersWmlDoAcceptsInlineString == null)
{
_rendersWmlDoAcceptsInline = true;
}
else
{
_rendersWmlDoAcceptsInline = Convert.ToBoolean(rendersWmlDoAcceptsInlineString);
}
_haveRendersWmlDoAcceptsInline = true;
}
return _rendersWmlDoAcceptsInline;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.RendersWmlSelectsAsMenuCards"]/*' />
public virtual bool RendersWmlSelectsAsMenuCards
{
get
{
if(!_haveRendersWmlSelectsAsMenuCards)
{
String rendersWmlSelectsAsMenuCardsString = this["rendersWmlSelectsAsMenuCards"];
if(rendersWmlSelectsAsMenuCardsString == null)
{
_rendersWmlSelectsAsMenuCards = false;
}
else
{
_rendersWmlSelectsAsMenuCards = Convert.ToBoolean(rendersWmlSelectsAsMenuCardsString);
}
_haveRendersWmlSelectsAsMenuCards = true;
}
return _rendersWmlSelectsAsMenuCards;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.RendersBreaksAfterWmlAnchor"]/*' />
public virtual bool RendersBreaksAfterWmlAnchor
{
get
{
if(!_haveRendersBreaksAfterWmlAnchor)
{
String rendersBreaksAfterWmlAnchorString = this["rendersBreaksAfterWmlAnchor"];
if(rendersBreaksAfterWmlAnchorString == null)
{
_rendersBreaksAfterWmlAnchor = true;
}
else
{
_rendersBreaksAfterWmlAnchor = Convert.ToBoolean(rendersBreaksAfterWmlAnchorString);
}
_haveRendersBreaksAfterWmlAnchor = true;
}
return _rendersBreaksAfterWmlAnchor;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.RendersBreaksAfterWmlInput"]/*' />
public virtual bool RendersBreaksAfterWmlInput
{
get
{
if(!_haveRendersBreaksAfterWmlInput)
{
String rendersBreaksAfterWmlInputString = this["rendersBreaksAfterWmlInput"];
if(rendersBreaksAfterWmlInputString == null)
{
_rendersBreaksAfterWmlInput = true;
}
else
{
_rendersBreaksAfterWmlInput = Convert.ToBoolean(rendersBreaksAfterWmlInputString);
}
_haveRendersBreaksAfterWmlInput = true;
}
return _rendersBreaksAfterWmlInput;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.RendersBreakBeforeWmlSelectAndInput"]/*' />
public virtual bool RendersBreakBeforeWmlSelectAndInput
{
get
{
if(!_haveRendersBreakBeforeWmlSelectAndInput)
{
String rendersBreaksBeforeWmlSelectAndInputString = this["rendersBreakBeforeWmlSelectAndInput"];
if(rendersBreaksBeforeWmlSelectAndInputString == null)
{
_rendersBreakBeforeWmlSelectAndInput = false;
}
else
{
_rendersBreakBeforeWmlSelectAndInput = Convert.ToBoolean(rendersBreaksBeforeWmlSelectAndInputString);
}
_haveRendersBreakBeforeWmlSelectAndInput = true;
}
return _rendersBreakBeforeWmlSelectAndInput;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.RequiresPhoneNumbersAsPlainText"]/*' />
public virtual bool RequiresPhoneNumbersAsPlainText
{
get
{
if(!_haveRequiresPhoneNumbersAsPlainText)
{
String requiresPhoneNumbersAsPlainTextString = this["requiresPhoneNumbersAsPlainText"];
if(requiresPhoneNumbersAsPlainTextString == null)
{
_requiresPhoneNumbersAsPlainText = false;
}
else
{
_requiresPhoneNumbersAsPlainText = Convert.ToBoolean(requiresPhoneNumbersAsPlainTextString);
}
_haveRequiresPhoneNumbersAsPlainText = true;
}
return _requiresPhoneNumbersAsPlainText;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.RequiresUrlEncodedPostfieldValues"]/*' />
public virtual bool RequiresUrlEncodedPostfieldValues
{
get
{
if(!_haveRequiresUrlEncodedPostfieldValues)
{
String requiresUrlEncodedPostfieldValuesString = this["requiresUrlEncodedPostfieldValues"];
if(requiresUrlEncodedPostfieldValuesString == null)
{
_requiresUrlEncodedPostfieldValues = true;
}
else
{
_requiresUrlEncodedPostfieldValues = Convert.ToBoolean(requiresUrlEncodedPostfieldValuesString);
}
_haveRequiresUrlEncodedPostfieldValues = true;
}
return _requiresUrlEncodedPostfieldValues;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.RequiredMetaTagNameValue"]/*' />
public virtual String RequiredMetaTagNameValue
{
get
{
if(!_haveRequiredMetaTagNameValue)
{
String value = this["requiredMetaTagNameValue"];
if(value == null || value == String.Empty)
{
_requiredMetaTagNameValue = null;
}
else
{
_requiredMetaTagNameValue = value;
}
_haveRequiredMetaTagNameValue = true;
}
return _requiredMetaTagNameValue;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.RendersBreaksAfterHtmlLists"]/*' />
public virtual bool RendersBreaksAfterHtmlLists
{
get
{
if(!_haveRendersBreaksAfterHtmlLists)
{
String rendersBreaksAfterHtmlListsString = this["rendersBreaksAfterHtmlLists"];
if(rendersBreaksAfterHtmlListsString == null)
{
_rendersBreaksAfterHtmlLists = true;
}
else
{
_rendersBreaksAfterHtmlLists = Convert.ToBoolean(rendersBreaksAfterHtmlListsString);
}
_haveRendersBreaksAfterHtmlLists = true;
}
return _rendersBreaksAfterHtmlLists;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.RequiresUniqueHtmlInputNames"]/*' />
public virtual bool RequiresUniqueHtmlInputNames
{
get
{
if(!_haveRequiresUniqueHtmlInputNames)
{
String requiresUniqueHtmlInputNamesString = this["requiresUniqueHtmlInputNames"];
if(requiresUniqueHtmlInputNamesString == null)
{
_requiresUniqueHtmlInputNames = false;
}
else
{
_requiresUniqueHtmlInputNames = Convert.ToBoolean(requiresUniqueHtmlInputNamesString);
}
_haveRequiresUniqueHtmlInputNames = true;
}
return _requiresUniqueHtmlInputNames;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.RequiresUniqueHtmlCheckboxNames"]/*' />
public virtual bool RequiresUniqueHtmlCheckboxNames
{
get
{
if(!_haveRequiresUniqueHtmlCheckboxNames)
{
String requiresUniqueHtmlCheckboxNamesString = this["requiresUniqueHtmlCheckboxNames"];
if(requiresUniqueHtmlCheckboxNamesString == null)
{
_requiresUniqueHtmlCheckboxNames = false;
}
else
{
_requiresUniqueHtmlCheckboxNames = Convert.ToBoolean(requiresUniqueHtmlCheckboxNamesString);
}
_haveRequiresUniqueHtmlCheckboxNames = true;
}
return _requiresUniqueHtmlCheckboxNames;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsCss"]/*' />
public virtual bool SupportsCss
{
get
{
if(!_haveSupportsCss)
{
String supportsCssString = this["supportsCss"];
if(supportsCssString == null)
{
_supportsCss = false;
}
else
{
_supportsCss = Convert.ToBoolean(supportsCssString);
}
_haveSupportsCss = true;
}
return _supportsCss;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.HidesRightAlignedMultiselectScrollbars"]/*' />
public virtual bool HidesRightAlignedMultiselectScrollbars
{
get
{
if(!_haveHidesRightAlignedMultiselectScrollbars)
{
String hidesRightAlignedMultiselectScrollbarsString = this["hidesRightAlignedMultiselectScrollbars"];
if(hidesRightAlignedMultiselectScrollbarsString == null)
{
_hidesRightAlignedMultiselectScrollbars = false;
}
else
{
_hidesRightAlignedMultiselectScrollbars = Convert.ToBoolean(hidesRightAlignedMultiselectScrollbarsString);
}
_haveHidesRightAlignedMultiselectScrollbars = true;
}
return _hidesRightAlignedMultiselectScrollbars;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.IsMobileDevice"]/*' />
public virtual bool IsMobileDevice
{
get
{
if(!_haveIsMobileDevice)
{
String isMobileDeviceString = this["isMobileDevice"];
if(isMobileDeviceString == null)
{
_isMobileDevice = false;
}
else
{
_isMobileDevice = Convert.ToBoolean(isMobileDeviceString);
}
_haveIsMobileDevice = true;
}
return _isMobileDevice;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.RequiresAttributeColonSubstitution"]/*' />
public virtual bool RequiresAttributeColonSubstitution
{
get
{
if(!_haveRequiresAttributeColonSubstitution)
{
String requiresAttributeColonSubstitution = this["requiresAttributeColonSubstitution"];
if(requiresAttributeColonSubstitution == null)
{
_requiresAttributeColonSubstitution = false;
}
else
{
_requiresAttributeColonSubstitution = Convert.ToBoolean(requiresAttributeColonSubstitution);
}
_haveRequiresAttributeColonSubstitution = true;
}
return _requiresAttributeColonSubstitution;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.CanRenderOneventAndPrevElementsTogether"]/*' />
public virtual bool CanRenderOneventAndPrevElementsTogether
{
get
{
if(!_haveCanRenderOneventAndPrevElementsTogether)
{
String canRenderOneventAndPrevElementsTogetherString = this["canRenderOneventAndPrevElementsTogether"];
if(canRenderOneventAndPrevElementsTogetherString == null)
{
_canRenderOneventAndPrevElementsTogether = true;
}
else
{
_canRenderOneventAndPrevElementsTogether = Convert.ToBoolean(canRenderOneventAndPrevElementsTogetherString);
}
_haveCanRenderOneventAndPrevElementsTogether = true;
}
return _canRenderOneventAndPrevElementsTogether;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.CanRenderInputAndSelectElementsTogether"]/*' />
public virtual bool CanRenderInputAndSelectElementsTogether
{
get
{
if(!_haveCanRenderInputAndSelectElementsTogether)
{
String canRenderInputAndSelectElementsTogetherString = this["canRenderInputAndSelectElementsTogether"];
if(canRenderInputAndSelectElementsTogetherString == null)
{
_canRenderInputAndSelectElementsTogether = true;
}
else
{
_canRenderInputAndSelectElementsTogether = Convert.ToBoolean(canRenderInputAndSelectElementsTogetherString);
}
_haveCanRenderInputAndSelectElementsTogether = true;
}
return _canRenderInputAndSelectElementsTogether;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.CanRenderAfterInputOrSelectElement"]/*' />
public virtual bool CanRenderAfterInputOrSelectElement
{
get
{
if(!_haveCanRenderAfterInputOrSelectElement)
{
String canRenderAfterInputOrSelectElementString = this["canRenderAfterInputOrSelectElement"];
if(canRenderAfterInputOrSelectElementString == null)
{
_canRenderAfterInputOrSelectElement = true;
}
else
{
_canRenderAfterInputOrSelectElement = Convert.ToBoolean(canRenderAfterInputOrSelectElementString);
}
_haveCanRenderAfterInputOrSelectElement = true;
}
return _canRenderAfterInputOrSelectElement;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.CanRenderPostBackCards"]/*' />
public virtual bool CanRenderPostBackCards
{
get
{
if(!_haveCanRenderPostBackCards)
{
String canRenderPostBackCardsString = this["canRenderPostBackCards"];
if(canRenderPostBackCardsString == null)
{
_canRenderPostBackCards = true;
}
else
{
_canRenderPostBackCards = Convert.ToBoolean(canRenderPostBackCardsString);
}
_haveCanRenderPostBackCards = true;
}
return _canRenderPostBackCards;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.CanRenderMixedSelects"]/*' />
public virtual bool CanRenderMixedSelects
{
get
{
if(!_haveCanRenderMixedSelects)
{
String canRenderMixedSelectsString = this["canRenderMixedSelects"];
if(canRenderMixedSelectsString == null)
{
_canRenderMixedSelects = true;
}
else
{
_canRenderMixedSelects = Convert.ToBoolean(canRenderMixedSelectsString);
}
_haveCanRenderMixedSelects = true;
}
return _canRenderMixedSelects;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.CanCombineFormsInDeck"]/*' />
public virtual bool CanCombineFormsInDeck
{
get
{
if(!_haveCanCombineFormsInDeck)
{
String canCombineFormsInDeckString = this["canCombineFormsInDeck"];
if(canCombineFormsInDeckString == null)
{
_canCombineFormsInDeck = true;
}
else
{
_canCombineFormsInDeck = Convert.ToBoolean(canCombineFormsInDeckString);
}
_haveCanCombineFormsInDeck = true;
}
return _canCombineFormsInDeck;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.CanRenderSetvarZeroWithMultiSelectionList"]/*' />
public virtual bool CanRenderSetvarZeroWithMultiSelectionList
{
get
{
if(!_haveCanRenderSetvarZeroWithMultiSelectionList)
{
String canRenderSetvarZeroWithMultiSelectionListString = this["canRenderSetvarZeroWithMultiSelectionList"];
if(canRenderSetvarZeroWithMultiSelectionListString == null)
{
_canRenderSetvarZeroWithMultiSelectionList = true;
}
else
{
_canRenderSetvarZeroWithMultiSelectionList = Convert.ToBoolean(canRenderSetvarZeroWithMultiSelectionListString);
}
_haveCanRenderSetvarZeroWithMultiSelectionList = true;
}
return _canRenderSetvarZeroWithMultiSelectionList;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsImageSubmit"]/*' />
public virtual bool SupportsImageSubmit
{
get
{
if(!_haveSupportsImageSubmit)
{
String supportsImageSubmitString = this["supportsImageSubmit"];
if(supportsImageSubmitString == null)
{
_supportsImageSubmit = false;
}
else
{
_supportsImageSubmit = Convert.ToBoolean(supportsImageSubmitString);
}
_haveSupportsImageSubmit = true;
}
return _supportsImageSubmit;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.RequiresUniqueFilePathSuffix"]/*' />
public virtual bool RequiresUniqueFilePathSuffix
{
get
{
if(!_haveRequiresUniqueFilePathSuffix)
{
String requiresUniqueFilePathSuffixString = this["requiresUniqueFilePathSuffix"];
if(requiresUniqueFilePathSuffixString == null)
{
_requiresUniqueFilePathSuffix = false;
}
else
{
_requiresUniqueFilePathSuffix = Convert.ToBoolean(requiresUniqueFilePathSuffixString);
}
_haveRequiresUniqueFilePathSuffix = true;
}
return _requiresUniqueFilePathSuffix;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.RequiresNoBreakInFormatting"]/*' />
public virtual bool RequiresNoBreakInFormatting
{
get
{
if(!_haveRequiresNoBreakInFormatting)
{
String requiresNoBreakInFormatting = this["requiresNoBreakInFormatting"];
if(requiresNoBreakInFormatting == null)
{
_requiresNoBreakInFormatting = false;
}
else
{
_requiresNoBreakInFormatting = Convert.ToBoolean(requiresNoBreakInFormatting);
}
_haveRequiresNoBreakInFormatting = true;
}
return _requiresNoBreakInFormatting;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.RequiresLeadingPageBreak"]/*' />
public virtual bool RequiresLeadingPageBreak
{
get
{
if(!_haveRequiresLeadingPageBreak)
{
String requiresLeadingPageBreak = this["requiresLeadingPageBreak"];
if(requiresLeadingPageBreak == null)
{
_requiresLeadingPageBreak = false;
}
else
{
_requiresLeadingPageBreak = Convert.ToBoolean(requiresLeadingPageBreak);
}
_haveRequiresLeadingPageBreak = true;
}
return _requiresLeadingPageBreak;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsSelectMultiple"]/*' />
public virtual bool SupportsSelectMultiple
{
get
{
if(!_haveSupportsSelectMultiple)
{
String supportsSelectMultipleString = this["supportsSelectMultiple"];
if(supportsSelectMultipleString == null)
{
_supportsSelectMultiple = false;
}
else
{
_supportsSelectMultiple = Convert.ToBoolean(supportsSelectMultipleString);
}
_haveSupportsSelectMultiple = true;
}
return _supportsSelectMultiple;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsBold"]/*' />
public new virtual bool SupportsBold
{
get
{
if(!_haveSupportsBold)
{
String supportsBold = this["supportsBold"];
if(supportsBold == null)
{
_supportsBold = false;
}
else
{
_supportsBold = Convert.ToBoolean(supportsBold);
}
_haveSupportsBold = true;
}
return _supportsBold;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsItalic"]/*' />
public new virtual bool SupportsItalic
{
get
{
if(!_haveSupportsItalic)
{
String supportsItalic = this["supportsItalic"];
if(supportsItalic == null)
{
_supportsItalic = false;
}
else
{
_supportsItalic = Convert.ToBoolean(supportsItalic);
}
_haveSupportsItalic = true;
}
return _supportsItalic;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsFontSize"]/*' />
public virtual bool SupportsFontSize
{
get
{
if(!_haveSupportsFontSize)
{
String supportsFontSize = this["supportsFontSize"];
if(supportsFontSize == null)
{
_supportsFontSize = false;
}
else
{
_supportsFontSize = Convert.ToBoolean(supportsFontSize);
}
_haveSupportsFontSize = true;
}
return _supportsFontSize;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsFontName"]/*' />
public virtual bool SupportsFontName
{
get
{
if(!_haveSupportsFontName)
{
String supportsFontName = this["supportsFontName"];
if(supportsFontName == null)
{
_supportsFontName = false;
}
else
{
_supportsFontName = Convert.ToBoolean(supportsFontName);
}
_haveSupportsFontName = true;
}
return _supportsFontName;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsFontColor"]/*' />
public virtual bool SupportsFontColor
{
get
{
if(!_haveSupportsFontColor)
{
String supportsFontColor = this["supportsFontColor"];
if(supportsFontColor == null)
{
_supportsFontColor = false;
}
else
{
_supportsFontColor = Convert.ToBoolean(supportsFontColor);
}
_haveSupportsFontColor = true;
}
return _supportsFontColor;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsBodyColor"]/*' />
public virtual bool SupportsBodyColor
{
get
{
if(!_haveSupportsBodyColor)
{
String supportsBodyColor = this["supportsBodyColor"];
if(supportsBodyColor == null)
{
_supportsBodyColor = false;
}
else
{
_supportsBodyColor = Convert.ToBoolean(supportsBodyColor);
}
_haveSupportsBodyColor = true;
}
return _supportsBodyColor;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsDivAlign"]/*' />
public virtual bool SupportsDivAlign
{
get
{
if(!_haveSupportsDivAlign)
{
String supportsDivAlign = this["supportsDivAlign"];
if(supportsDivAlign == null)
{
_supportsDivAlign = false;
}
else
{
_supportsDivAlign = Convert.ToBoolean(supportsDivAlign);
}
_haveSupportsDivAlign = true;
}
return _supportsDivAlign;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsDivNoWrap"]/*' />
public virtual bool SupportsDivNoWrap
{
get
{
if(!_haveSupportsDivNoWrap)
{
String supportsDivNoWrap = this["supportsDivNoWrap"];
if(supportsDivNoWrap == null)
{
_supportsDivNoWrap = false;
}
else
{
_supportsDivNoWrap = Convert.ToBoolean(supportsDivNoWrap);
}
_haveSupportsDivNoWrap = true;
}
return _supportsDivNoWrap;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.RequiresContentTypeMetaTag"]/*' />
public virtual bool RequiresContentTypeMetaTag
{
get
{
if(!_haveRequiresContentTypeMetaTag)
{
String requiresContentTypeMetaTag = this["requiresContentTypeMetaTag"];
if(requiresContentTypeMetaTag == null)
{
_requiresContentTypeMetaTag = false;
}
else
{
_requiresContentTypeMetaTag =
Convert.ToBoolean(requiresContentTypeMetaTag);
}
_haveRequiresContentTypeMetaTag = true;
}
return _requiresContentTypeMetaTag;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.RequiresDBCSCharacter"]/*' />
public virtual bool RequiresDBCSCharacter
{
get
{
if(!_haveRequiresDBCSCharacter)
{
String requiresDBCSCharacter = this["requiresDBCSCharacter"];
if(requiresDBCSCharacter == null)
{
_requiresDBCSCharacter = false;
}
else
{
_requiresDBCSCharacter =
Convert.ToBoolean(requiresDBCSCharacter);
}
_haveRequiresDBCSCharacter = true;
}
return _requiresDBCSCharacter;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.RequiresHtmlAdaptiveErrorReporting"]/*' />
public virtual bool RequiresHtmlAdaptiveErrorReporting
{
get
{
if(!_haveRequiresHtmlAdaptiveErrorReporting)
{
String requiresHtmlAdaptiveErrorReporting = this["requiresHtmlAdaptiveErrorReporting"];
if(requiresHtmlAdaptiveErrorReporting == null)
{
_requiresHtmlAdaptiveErrorReporting = false;
}
else
{
_requiresHtmlAdaptiveErrorReporting =
Convert.ToBoolean(requiresHtmlAdaptiveErrorReporting);
}
_haveRequiresHtmlAdaptiveErrorReporting = true;
}
return _requiresHtmlAdaptiveErrorReporting;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.RequiresOutputOptimization"]/*' />
public virtual bool RequiresOutputOptimization
{
get
{
if(!_haveRequiresOutputOptimization)
{
String RequiresOutputOptimizationString = this["requiresOutputOptimization"];
if(RequiresOutputOptimizationString == null)
{
_requiresOutputOptimization = false;
}
else
{
_requiresOutputOptimization = Convert.ToBoolean(RequiresOutputOptimizationString);
}
_haveRequiresOutputOptimization = true;
}
return _requiresOutputOptimization;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsAccesskeyAttribute"]/*' />
public virtual bool SupportsAccesskeyAttribute
{
get
{
if(!_haveSupportsAccesskeyAttribute)
{
String SupportsAccesskeyAttributeString = this["supportsAccesskeyAttribute"];
if(SupportsAccesskeyAttributeString == null)
{
_supportsAccesskeyAttribute = false;
}
else
{
_supportsAccesskeyAttribute = Convert.ToBoolean(SupportsAccesskeyAttributeString);
}
_haveSupportsAccesskeyAttribute = true;
}
return _supportsAccesskeyAttribute;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsInputIStyle"]/*' />
public virtual bool SupportsInputIStyle
{
get
{
if(!_haveSupportsInputIStyle)
{
String SupportsInputIStyleString = this["supportsInputIStyle"];
if(SupportsInputIStyleString == null)
{
_supportsInputIStyle = false;
}
else
{
_supportsInputIStyle = Convert.ToBoolean(SupportsInputIStyleString);
}
_haveSupportsInputIStyle = true;
}
return _supportsInputIStyle;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsInputMode"]/*' />
public virtual bool SupportsInputMode
{
get
{
if(!_haveSupportsInputMode)
{
String SupportsInputModeString = this["supportsInputMode"];
if(SupportsInputModeString == null)
{
_supportsInputMode = false;
}
else
{
_supportsInputMode = Convert.ToBoolean(SupportsInputModeString);
}
_haveSupportsInputMode = true;
}
return _supportsInputMode;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsIModeSymbols"]/*' />
public virtual bool SupportsIModeSymbols
{
get
{
if(!_haveSupportsIModeSymbols)
{
String SupportsIModeSymbolsString = this["supportsIModeSymbols"];
if(SupportsIModeSymbolsString == null)
{
_supportsIModeSymbols = false;
}
else
{
_supportsIModeSymbols = Convert.ToBoolean(SupportsIModeSymbolsString);
}
_haveSupportsIModeSymbols = true;
}
return _supportsIModeSymbols;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsJPhoneSymbols"]/*' />
public virtual bool SupportsJPhoneSymbols
{
get
{
if(!_haveSupportsJPhoneSymbols)
{
String SupportsJPhoneSymbolsString = this["supportsJPhoneSymbols"];
if(SupportsJPhoneSymbolsString == null)
{
_supportsJPhoneSymbols = false;
}
else
{
_supportsJPhoneSymbols = Convert.ToBoolean(SupportsJPhoneSymbolsString);
}
_haveSupportsJPhoneSymbols = true;
}
return _supportsJPhoneSymbols;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsJPhoneMultiMediaAttributes"]/*' />
public virtual bool SupportsJPhoneMultiMediaAttributes
{
get
{
if(!_haveSupportsJPhoneMultiMediaAttributes)
{
String SupportsJPhoneMultiMediaAttributesString = this["supportsJPhoneMultiMediaAttributes"];
if(SupportsJPhoneMultiMediaAttributesString == null)
{
_supportsJPhoneMultiMediaAttributes = false;
}
else
{
_supportsJPhoneMultiMediaAttributes = Convert.ToBoolean(SupportsJPhoneMultiMediaAttributesString);
}
_haveSupportsJPhoneMultiMediaAttributes = true;
}
return _supportsJPhoneMultiMediaAttributes;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.MaximumRenderedPageSize"]/*' />
public virtual int MaximumRenderedPageSize
{
get
{
if(!_haveMaximumRenderedPageSize)
{
_maximumRenderedPageSize = Convert.ToInt32(this["maximumRenderedPageSize"]);
_haveMaximumRenderedPageSize = true;
}
return _maximumRenderedPageSize;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.RequiresSpecialViewStateEncoding"]/*' />
public virtual bool RequiresSpecialViewStateEncoding
{
get
{
if(!_haveRequiresSpecialViewStateEncoding)
{
String RequiresSpecialViewStateEncodingString = this["requiresSpecialViewStateEncoding"];
if(RequiresSpecialViewStateEncodingString == null)
{
_requiresSpecialViewStateEncoding = false;
}
else
{
_requiresSpecialViewStateEncoding = Convert.ToBoolean(RequiresSpecialViewStateEncodingString);
}
_haveRequiresSpecialViewStateEncoding = true;
}
return _requiresSpecialViewStateEncoding;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsQueryStringInFormAction"]/*' />
public virtual bool SupportsQueryStringInFormAction
{
get
{
if(!_haveSupportsQueryStringInFormAction)
{
String SupportsQueryStringInFormActionString = this["supportsQueryStringInFormAction"];
if(SupportsQueryStringInFormActionString == null)
{
_supportsQueryStringInFormAction = true;
}
else
{
_supportsQueryStringInFormAction = Convert.ToBoolean(SupportsQueryStringInFormActionString);
}
_haveSupportsQueryStringInFormAction = true;
}
return _supportsQueryStringInFormAction;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsCacheControlMetaTag"]/*' />
public virtual bool SupportsCacheControlMetaTag
{
get
{
if(!_haveSupportsCacheControlMetaTag)
{
String SupportsCacheControlMetaTagString = this["supportsCacheControlMetaTag"];
if(SupportsCacheControlMetaTagString == null)
{
_supportsCacheControlMetaTag = true;
}
else
{
_supportsCacheControlMetaTag = Convert.ToBoolean(SupportsCacheControlMetaTagString);
}
_haveSupportsCacheControlMetaTag = true;
}
return _supportsCacheControlMetaTag;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsUncheck"]/*' />
public virtual bool SupportsUncheck
{
get
{
if(!_haveSupportsUncheck)
{
String SupportsUncheckString = this["supportsUncheck"];
if(SupportsUncheckString == null)
{
_supportsUncheck = true;
}
else
{
_supportsUncheck = Convert.ToBoolean(SupportsUncheckString);
}
_haveSupportsUncheck = true;
}
return _supportsUncheck;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.CanRenderEmptySelects"]/*' />
public virtual bool CanRenderEmptySelects
{
get
{
if(!_haveCanRenderEmptySelects)
{
String CanRenderEmptySelectsString = this["canRenderEmptySelects"];
if(CanRenderEmptySelectsString == null)
{
_canRenderEmptySelects = true;
}
else
{
_canRenderEmptySelects = Convert.ToBoolean(CanRenderEmptySelectsString);
}
_haveCanRenderEmptySelects = true;
}
return _canRenderEmptySelects;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsRedirectWithCookie"]/*' />
public virtual bool SupportsRedirectWithCookie
{
get
{
if(!_haveSupportsRedirectWithCookie)
{
String supportsRedirectWithCookie = this["supportsRedirectWithCookie"];
if(supportsRedirectWithCookie == null)
{
_supportsRedirectWithCookie = true;
}
else
{
_supportsRedirectWithCookie = Convert.ToBoolean(supportsRedirectWithCookie);
}
_haveSupportsRedirectWithCookie = true;
}
return _supportsRedirectWithCookie;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.SupportsEmptyStringInCookieValue"]/*' />
public virtual bool SupportsEmptyStringInCookieValue
{
get
{
if (!_haveSupportsEmptyStringInCookieValue)
{
String supportsEmptyStringInCookieValue = this["supportsEmptyStringInCookieValue"];
if (supportsEmptyStringInCookieValue == null)
{
_supportsEmptyStringInCookieValue = true;
}
else
{
_supportsEmptyStringInCookieValue =
Convert.ToBoolean (supportsEmptyStringInCookieValue);
}
_haveSupportsEmptyStringInCookieValue = true;
}
return _supportsEmptyStringInCookieValue;
}
}
/// <include file='doc\MobileCapabilities.uex' path='docs/doc[@for="MobileCapabilities.DefaultSubmitButtonLimit"]/*' />
public virtual int DefaultSubmitButtonLimit
{
get
{
if(!_haveDefaultSubmitButtonLimit)
{
String s = this["defaultSubmitButtonLimit"];
_defaultSubmitButtonLimit = s != null ? Convert.ToInt32(this["defaultSubmitButtonLimit"]) : 1;
_haveDefaultSubmitButtonLimit = true;
}
return _defaultSubmitButtonLimit;
}
}
private String _mobileDeviceManufacturer;
private String _mobileDeviceModel;
private String _gatewayVersion;
private int _gatewayMajorVersion;
private double _gatewayMinorVersion;
private String _preferredRenderingType; //
*/
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using NuGet;
using NuGet.Frameworks;
using NuGet.Packaging.Core;
using NuGet.Packaging;
using NuGet.Versioning;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Versioning;
using System.Text;
namespace Microsoft.DotNet.Build.Tasks.Packaging
{
public class GenerateNuSpec : Task
{
private const string NuSpecXmlNamespace = @"http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd";
public string InputFileName { get; set; }
[Required]
public string OutputFileName { get; set; }
public string MinClientVersion { get; set; }
[Required]
public string Id { get; set; }
[Required]
public string Version { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Authors { get; set; }
[Required]
public string Owners { get; set; }
[Required]
public string Description { get; set; }
public string ReleaseNotes { get; set; }
public string Summary { get; set; }
public string Language { get; set; }
public string ProjectUrl { get; set; }
public string IconUrl { get; set; }
public string LicenseUrl { get; set; }
public string Copyright { get; set; }
public bool RequireLicenseAcceptance { get; set; }
public bool DevelopmentDependency { get; set; }
public bool Serviceable { get; set; }
public string Tags { get; set; }
public ITaskItem[] Dependencies { get; set; }
public ITaskItem[] References { get; set; }
public ITaskItem[] FrameworkReferences { get; set; }
public ITaskItem[] Files { get; set; }
public override bool Execute()
{
try
{
WriteNuSpecFile();
}
catch (Exception ex)
{
Log.LogError(ex.ToString());
Log.LogErrorFromException(ex);
}
return !Log.HasLoggedErrors;
}
private void WriteNuSpecFile()
{
var manifest = CreateManifest();
if (!IsDifferent(manifest))
{
Log.LogMessage("Skipping generation of .nuspec because contents are identical.");
return;
}
var directory = Path.GetDirectoryName(OutputFileName);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
using (var file = File.Create(OutputFileName))
{
manifest.Save(file, false);
}
}
private bool IsDifferent(Manifest newManifest)
{
if (!File.Exists(OutputFileName))
return true;
var oldSource = File.ReadAllText(OutputFileName);
var newSource = "";
using (var stream = new MemoryStream())
{
newManifest.Save(stream);
stream.Seek(0, SeekOrigin.Begin);
newSource = Encoding.UTF8.GetString(stream.ToArray());
}
return oldSource != newSource;
}
private Manifest CreateManifest()
{
Manifest manifest;
ManifestMetadata manifestMetadata;
if (!string.IsNullOrEmpty(InputFileName))
{
using (var stream = File.OpenRead(InputFileName))
{
manifest = Manifest.ReadFrom(stream, false);
}
if (manifest.Metadata == null)
{
manifest = new Manifest(new ManifestMetadata(), manifest.Files);
}
}
else
{
manifest = new Manifest(new ManifestMetadata());
}
manifestMetadata = manifest.Metadata;
manifestMetadata.UpdateMember(x => x.Authors, Authors?.Split(';'));
manifestMetadata.UpdateMember(x => x.Copyright, Copyright);
manifestMetadata.UpdateMember(x => x.DependencyGroups, GetDependencySets());
manifestMetadata.UpdateMember(x => x.Description, Description);
manifestMetadata.DevelopmentDependency |= DevelopmentDependency;
manifestMetadata.UpdateMember(x => x.FrameworkReferences, GetFrameworkAssemblies());
if (IconUrl != null)
{
manifestMetadata.SetIconUrl(IconUrl);
}
manifestMetadata.UpdateMember(x => x.Id, Id);
manifestMetadata.UpdateMember(x => x.Language, Language);
if (LicenseUrl != null)
{
manifestMetadata.SetLicenseUrl(LicenseUrl);
}
manifestMetadata.UpdateMember(x => x.MinClientVersionString, MinClientVersion);
manifestMetadata.UpdateMember(x => x.Owners, Owners?.Split(';'));
if (ProjectUrl != null)
{
manifestMetadata.SetProjectUrl(ProjectUrl);
}
manifestMetadata.UpdateMember(x => x.PackageAssemblyReferences, GetReferenceSets());
manifestMetadata.UpdateMember(x => x.ReleaseNotes, ReleaseNotes);
manifestMetadata.RequireLicenseAcceptance |= RequireLicenseAcceptance;
manifestMetadata.UpdateMember(x => x.Summary, Summary);
manifestMetadata.UpdateMember(x => x.Tags, Tags);
manifestMetadata.UpdateMember(x => x.Title, Title);
manifestMetadata.UpdateMember(x => x.Version, Version != null ? new NuGetVersion(Version) : null);
manifestMetadata.Serviceable |= Serviceable;
manifest.AddRangeToMember(x => x.Files, GetManifestFiles());
return manifest;
}
private List<ManifestFile> GetManifestFiles()
{
return (from f in Files.NullAsEmpty()
where !f.GetMetadata(Metadata.FileTarget).StartsWith("$none$", StringComparison.OrdinalIgnoreCase)
select new ManifestFile()
{
Source = f.GetMetadata(Metadata.FileSource),
// Pattern matching in PathResolver requires that we standardize to OS specific directory separator characters
Target = f.GetMetadata(Metadata.FileTarget).Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar),
Exclude = f.GetMetadata(Metadata.FileExclude)
}).OrderBy(f => f.Target, StringComparer.OrdinalIgnoreCase).ToList();
}
static FrameworkAssemblyReferenceComparer frameworkAssemblyReferenceComparer = new FrameworkAssemblyReferenceComparer();
private List<FrameworkAssemblyReference> GetFrameworkAssemblies()
{
return (from fr in FrameworkReferences.NullAsEmpty()
orderby fr.ItemSpec, StringComparer.Ordinal
select new FrameworkAssemblyReference(fr.ItemSpec, new[] { fr.GetTargetFramework() })
).Distinct(frameworkAssemblyReferenceComparer).ToList();
}
private class FrameworkAssemblyReferenceComparer : EqualityComparer<FrameworkAssemblyReference>
{
public override bool Equals(FrameworkAssemblyReference x, FrameworkAssemblyReference y)
{
return Object.Equals(x, y) ||
( x != null && y != null &&
x.AssemblyName.Equals(y.AssemblyName) &&
x.SupportedFrameworks.SequenceEqual(y.SupportedFrameworks, NuGetFramework.Comparer)
);
}
public override int GetHashCode(FrameworkAssemblyReference obj)
{
return obj.AssemblyName.GetHashCode();
}
}
private List<PackageDependencyGroup> GetDependencySets()
{
var dependencies = from d in Dependencies.NullAsEmpty()
select new Dependency
{
Id = d.ItemSpec,
Version = d.GetVersion(),
TargetFramework = d.GetTargetFramework() ?? NuGetFramework.AnyFramework,
Include = d.GetValueList("Include"),
Exclude = d.GetValueList("Exclude")
};
return (from dependency in dependencies
group dependency by dependency.TargetFramework into dependenciesByFramework
select new PackageDependencyGroup(
dependenciesByFramework.Key,
from dependency in dependenciesByFramework
where dependency.Id != "_._"
orderby dependency.Id, StringComparer.Ordinal
group dependency by dependency.Id into dependenciesById
select new PackageDependency(
dependenciesById.Key,
VersionRange.Parse(
dependenciesById.Select(x => x.Version)
.Aggregate(AggregateVersions)
.ToStringSafe()),
dependenciesById.Select(x => x.Include).Aggregate(AggregateInclude),
dependenciesById.Select(x => x.Exclude).Aggregate(AggregateExclude)
))).OrderBy(s => s?.TargetFramework?.GetShortFolderName(), StringComparer.Ordinal)
.ToList();
}
private IEnumerable<PackageReferenceSet> GetReferenceSets()
{
var references = from r in References.NullAsEmpty()
select new
{
File = r.ItemSpec,
TargetFramework = r.GetTargetFramework(),
};
return (from reference in references
group reference by reference.TargetFramework into referencesByFramework
select new PackageReferenceSet(
referencesByFramework.Key,
from reference in referencesByFramework
orderby reference.File, StringComparer.Ordinal
select reference.File
)
).ToList();
}
private static VersionRange AggregateVersions(VersionRange aggregate, VersionRange next)
{
var versionRange = new VersionRange();
SetMinVersion(ref versionRange, aggregate);
SetMinVersion(ref versionRange, next);
SetMaxVersion(ref versionRange, aggregate);
SetMaxVersion(ref versionRange, next);
if (versionRange.MinVersion == null && versionRange.MaxVersion == null)
{
versionRange = null;
}
return versionRange;
}
private static IReadOnlyList<string> AggregateInclude(IReadOnlyList<string> aggregate, IReadOnlyList<string> next)
{
// include is a union
if (aggregate == null)
{
return next;
}
if (next == null)
{
return aggregate;
}
return aggregate.Union(next).ToArray();
}
private static IReadOnlyList<string> AggregateExclude(IReadOnlyList<string> aggregate, IReadOnlyList<string> next)
{
// exclude is an intersection
if (aggregate == null || next == null)
{
return null;
}
return aggregate.Intersect(next).ToArray();
}
private static void SetMinVersion(ref VersionRange target, VersionRange source)
{
if (source == null || source.MinVersion == null)
{
return;
}
bool update = false;
NuGetVersion minVersion = target.MinVersion;
bool includeMinVersion = target.IsMinInclusive;
if (target.MinVersion == null)
{
update = true;
minVersion = source.MinVersion;
includeMinVersion = source.IsMinInclusive;
}
if (target.MinVersion < source.MinVersion)
{
update = true;
minVersion = source.MinVersion;
includeMinVersion = source.IsMinInclusive;
}
if (target.MinVersion == source.MinVersion)
{
update = true;
includeMinVersion = target.IsMinInclusive && source.IsMinInclusive;
}
if (update)
{
target = new VersionRange(minVersion, includeMinVersion, target.MaxVersion, target.IsMaxInclusive, target.Float, target.OriginalString);
}
}
private static void SetMaxVersion(ref VersionRange target, VersionRange source)
{
if (source == null || source.MaxVersion == null)
{
return;
}
bool update = false;
NuGetVersion maxVersion = target.MaxVersion;
bool includeMaxVersion = target.IsMaxInclusive;
if (target.MaxVersion == null)
{
update = true;
maxVersion = source.MaxVersion;
includeMaxVersion = source.IsMaxInclusive;
}
if (target.MaxVersion > source.MaxVersion)
{
update = true;
maxVersion = source.MaxVersion;
includeMaxVersion = source.IsMaxInclusive;
}
if (target.MaxVersion == source.MaxVersion)
{
update = true;
includeMaxVersion = target.IsMaxInclusive && source.IsMaxInclusive;
}
if (update)
{
target = new VersionRange(target.MinVersion, target.IsMinInclusive, maxVersion, includeMaxVersion, target.Float, target.OriginalString);
}
}
private class Dependency
{
public string Id { get; set; }
public NuGetFramework TargetFramework { get; set; }
public VersionRange Version { get; set; }
public IReadOnlyList<string> Exclude { get; set; }
public IReadOnlyList<string> Include { get; set; }
}
}
}
| |
// Copyright 2004 Armand du Plessis <armand@dotnet.org.za>
// http://dotnet.org.za/armand/articles/2453.aspx
// Thanks to Joe Cataford and Friedrich Brunzema.
// Also see MSDN: http://msdn2.microsoft.com/en-us/library/ms675899.aspx
// Enhancements by sgryphon@computer.org (PACOM):
// - Integrated with the CommonDialog API, e.g. returns a DialogResult, changed namespace, etc.
// - Marked COM interop code as internal; only the main dialog (and related classes) are public.
// - Added basic scope (location) and filter (object type) control, plus multi-select flag.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.ComponentModel;
namespace Tulpep.ActiveDirectoryObjectPicker
{
/// <summary>
/// Represents a common dialog that allows a user to select directory objects.
/// </summary>
/// <remarks>
/// <para>
/// The directory object picker dialog box enables a user to select one or more objects
/// from either the global catalog, a Microsoft Windows 2000 domain or computer,
/// a Microsoft Windows NT 4.0 domain or computer, or a workgroup. The object types
/// from which a user can select include user, contact, group, and computer objects.
/// </para>
/// <para>
/// This managed class wraps the Directory Object Picker common dialog from
/// the Active Directory UI.
/// </para>
/// <para>
/// It simplifies the scope (Locations) and filter (ObjectTypes) selection by allowing a single filter to be
/// specified which applies to all scopes (translating to both up-level and down-level
/// filter flags as necessary).
/// </para>
/// <para>
/// The object type filter is also simplified by combining different types of groups (local, global, etc)
/// and not using individual well known types in down-level scopes (only all well known types
/// can be specified).
/// </para>
/// <para>
/// The scope location is also simplified by combining down-level and up-level variations
/// into a single locations flag, e.g. external domains.
/// </para>
/// </remarks>
public class DirectoryObjectPickerDialog : CommonDialog
{
private DirectoryObject[] selectedObjects;
private string userName, password;
/// <summary>
/// Constructor. Sets all properties to their default values.
/// </summary>
/// <remarks>
/// <para>
/// The default values for the DirectoryObjectPickerDialog properties are:
/// </para>
/// <para>
/// <list type="table">
/// <listheader><term>Property</term><description>Default value</description></listheader>
/// <item><term>AllowedLocations</term><description>All locations.</description></item>
/// <item><term>AllowedObjectTypes</term><description>All object types.</description></item>
/// <item><term>DefaultLocations</term><description>None. (Will default to first location.)</description></item>
/// <item><term>DefaultObjectTypes</term><description>All object types.</description></item>
/// <item><term>Providers</term><description><see cref="ADsPathsProviders.Default"/>.</description></item>
/// <item><term>MultiSelect</term><description>false.</description></item>
/// <item><term>SkipDomainControllerCheck</term><description>false.</description></item>
/// <item><term>AttributesToFetch</term><description>Empty list.</description></item>
/// <item><term>SelectedObject</term><description>null.</description></item>
/// <item><term>SelectedObjects</term><description>Empty array.</description></item>
/// <item><term>ShowAdvancedView</term><description>false.</description></item>
/// <item><term>TargetComputer</term><description>null.</description></item>
/// </list>
/// </para>
/// </remarks>
public DirectoryObjectPickerDialog()
{
ResetInner();
}
/// <summary>
/// Gets or sets the scopes the DirectoryObjectPickerDialog is allowed to search.
/// </summary>
public Locations AllowedLocations { get; set; }
/// <summary>
/// Gets or sets the types of objects the DirectoryObjectPickerDialog is allowed to search for.
/// </summary>
public ObjectTypes AllowedObjectTypes { get; set; }
/// <summary>
/// Gets or sets the initially selected scope in the DirectoryObjectPickerDialog.
/// </summary>
public Locations DefaultLocations { get; set; }
/// <summary>
/// Gets or sets the initially seleted types of objects in the DirectoryObjectPickerDialog.
/// </summary>
public ObjectTypes DefaultObjectTypes { get; set; }
/// <summary>
/// Gets or sets the providers affecting the ADPath returned in objects.
/// </summary>
public ADsPathsProviders Providers { get; set; }
/// <summary>
/// Gets or sets whether the user can select multiple objects.
/// </summary>
/// <remarks>
/// <para>
/// If this flag is false, the user can select only one object.
/// </para>
/// </remarks>
public bool MultiSelect { get; set; }
/// <summary>
/// Gets or sets the whether to check whether the target is a Domain Controller and hide the "Local Computer" scope
/// </summary>
/// <remarks>
/// <para>
/// From MSDN:
///
/// If this flag is NOT set, then the DSOP_SCOPE_TYPE_TARGET_COMPUTER flag
/// will be ignored if the target computer is a DC. This flag has no effect
/// unless DSOP_SCOPE_TYPE_TARGET_COMPUTER is specified.
/// </para>
/// </remarks>
public bool SkipDomainControllerCheck { get; set; }
/// <summary>
/// An list of LDAP attribute names that will be retrieved for picked objects
/// </summary>
public IList<string> AttributesToFetch { get; set; }
/// <summary>
/// Gets the directory object selected in the dialog, or null if no object was selected.
/// </summary>
/// <remarks>
/// <para>
/// If MultiSelect is enabled, then this property returns only the first selected object.
/// Use SelectedObjects to get an array of all objects selected.
/// </para>
/// </remarks>
public DirectoryObject SelectedObject
{
get
{
if (selectedObjects == null || selectedObjects.Length == 0)
{
return null;
}
return selectedObjects[0];
}
}
/// <summary>
/// Gets an array of the directory objects selected in the dialog.
/// </summary>
public DirectoryObject[] SelectedObjects
{
get
{
if (selectedObjects == null)
{
return new DirectoryObject[0];
}
return (DirectoryObject[])selectedObjects.Clone();
}
}
/// <summary>
/// Gets or sets whether objects flagged as show in advanced view only are displayed (up-level).
/// </summary>
public bool ShowAdvancedView { get; set; }
/// <summary>
/// Gets or sets the name of the target computer.
/// </summary>
/// <remarks>
/// <para>
/// The dialog box operates as if it is running on the target computer, using the target computer
/// to determine the joined domain and enterprise. If this value is null or empty, the target computer
/// is the local computer.
/// </para>
/// </remarks>
public string TargetComputer { get; set; }
/// <summary>
/// Resets all properties to their default values.
/// </summary>
public override void Reset()
{
ResetInner();
}
/// <summary>Use this method to override the user credentials, passing new credentials for the account profile to be used.</summary>
/// <param name="userName">Name of the user.</param>
/// <param name="password">The password for the user.</param>
public void SetCredentials(string userName, string password)
{
this.userName = userName;
this.password = password;
}
private void ResetInner() // can be called from constructor without a "Virtual member call in constructor" warning
{
AllowedLocations = Locations.All;
AllowedObjectTypes = ObjectTypes.All;
DefaultLocations = Locations.None;
DefaultObjectTypes = ObjectTypes.All;
Providers = ADsPathsProviders.Default;
MultiSelect = false;
SkipDomainControllerCheck = false;
AttributesToFetch = new List<string>();
selectedObjects = null;
ShowAdvancedView = false;
TargetComputer = null;
}
/// <summary>
/// Displays the Directory Object Picker (Active Directory) common dialog, when called by ShowDialog.
/// </summary>
/// <param name="hwndOwner">Handle to the window that owns the dialog.</param>
/// <returns>If the user clicks the OK button of the Directory Object Picker dialog that is displayed, true is returned;
/// otherwise, false.</returns>
protected override bool RunDialog(IntPtr hwndOwner)
{
IDsObjectPicker ipicker = Initialize();
if (ipicker == null)
{
selectedObjects = null;
return false;
}
try
{
IDataObject dataObj = null;
int hresult = ipicker.InvokeDialog(hwndOwner, out dataObj);
if (hresult == HRESULT.S_OK)
{
selectedObjects = ProcessSelections(dataObj);
Marshal.ReleaseComObject(dataObj);
return true;
}
if (hresult == HRESULT.S_FALSE)
{
selectedObjects = null;
return false;
}
throw new COMException("IDsObjectPicker.InvokeDialog failed", hresult);
}
finally
{
Marshal.ReleaseComObject(ipicker);
}
}
#region Private implementation
// Convert ObjectTypes to DSCOPE_SCOPE_INIT_INFO_FLAGS
private uint GetDefaultFilter()
{
uint defaultFilter = 0;
if (((DefaultObjectTypes & ObjectTypes.Users) == ObjectTypes.Users) ||
((DefaultObjectTypes & ObjectTypes.WellKnownPrincipals) == ObjectTypes.WellKnownPrincipals))
{
defaultFilter |= DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_DEFAULT_FILTER_USERS;
}
if (((DefaultObjectTypes & ObjectTypes.Groups) == ObjectTypes.Groups) ||
((DefaultObjectTypes & ObjectTypes.BuiltInGroups) == ObjectTypes.BuiltInGroups))
{
defaultFilter |= DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_DEFAULT_FILTER_GROUPS;
}
if ((DefaultObjectTypes & ObjectTypes.Computers) == ObjectTypes.Computers)
{
defaultFilter |= DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_DEFAULT_FILTER_COMPUTERS;
}
if ((DefaultObjectTypes & ObjectTypes.Contacts) == ObjectTypes.Contacts)
{
defaultFilter |= DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_DEFAULT_FILTER_CONTACTS;
}
if ((DefaultObjectTypes & ObjectTypes.ServiceAccounts) == ObjectTypes.ServiceAccounts)
{
defaultFilter |= DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_DEFAULT_FILTER_SERVICE_ACCOUNTS;
}
return defaultFilter;
}
// Convert ObjectTypes to DSOP_DOWNLEVEL_FLAGS
private uint GetDownLevelFilter()
{
uint downlevelFilter = 0;
if ((AllowedObjectTypes & ObjectTypes.Users) == ObjectTypes.Users)
{
downlevelFilter |= DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_USERS;
}
if ((AllowedObjectTypes & ObjectTypes.Groups) == ObjectTypes.Groups)
{
downlevelFilter |= DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_LOCAL_GROUPS |
DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_GLOBAL_GROUPS;
}
if ((AllowedObjectTypes & ObjectTypes.Computers) == ObjectTypes.Computers)
{
downlevelFilter |= DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_COMPUTERS;
}
// Contacts not available in downlevel scopes
//if ((allowedTypes & ObjectTypes.Contacts) == ObjectTypes.Contacts)
// Exclude build in groups if not selected
if ((AllowedObjectTypes & ObjectTypes.BuiltInGroups) == 0)
{
downlevelFilter |= DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_EXCLUDE_BUILTIN_GROUPS;
}
if ((AllowedObjectTypes & ObjectTypes.WellKnownPrincipals) == ObjectTypes.WellKnownPrincipals)
{
downlevelFilter |= DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_ALL_WELLKNOWN_SIDS;
// This includes all the following:
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_WORLD |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_AUTHENTICATED_USER |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_ANONYMOUS |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_BATCH |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_CREATOR_OWNER |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_CREATOR_GROUP |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_DIALUP |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_INTERACTIVE |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_NETWORK |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_SERVICE |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_SYSTEM |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_TERMINAL_SERVER |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_LOCAL_SERVICE |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_NETWORK_SERVICE |
//DSOP_DOWNLEVEL_FLAGS.DSOP_DOWNLEVEL_FILTER_REMOTE_LOGON;
}
return downlevelFilter;
}
// Convert ObjectTypes to DSOP_FILTER_FLAGS_FLAGS
private uint GetUpLevelFilter()
{
uint uplevelFilter = 0;
if ((AllowedObjectTypes & ObjectTypes.Users) == ObjectTypes.Users)
{
uplevelFilter |= DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_USERS;
}
if ((AllowedObjectTypes & ObjectTypes.Groups) == ObjectTypes.Groups)
{
uplevelFilter |= DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_UNIVERSAL_GROUPS_DL |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_UNIVERSAL_GROUPS_SE |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_GLOBAL_GROUPS_DL |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_GLOBAL_GROUPS_SE |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_DOMAIN_LOCAL_GROUPS_DL |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_DOMAIN_LOCAL_GROUPS_SE;
}
if ((AllowedObjectTypes & ObjectTypes.Computers) == ObjectTypes.Computers)
{
uplevelFilter |= DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_COMPUTERS;
}
if ((AllowedObjectTypes & ObjectTypes.Contacts) == ObjectTypes.Contacts)
{
uplevelFilter |= DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_CONTACTS;
}
if ((AllowedObjectTypes & ObjectTypes.BuiltInGroups) == ObjectTypes.BuiltInGroups)
{
uplevelFilter |= DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_BUILTIN_GROUPS;
}
if ((AllowedObjectTypes & ObjectTypes.WellKnownPrincipals) == ObjectTypes.WellKnownPrincipals)
{
uplevelFilter |= DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_WELL_KNOWN_PRINCIPALS;
}
if ((AllowedObjectTypes & ObjectTypes.ServiceAccounts) == ObjectTypes.ServiceAccounts)
{
uplevelFilter |= DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_SERVICE_ACCOUNTS;
}
if ( ShowAdvancedView ) {
uplevelFilter |= DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_INCLUDE_ADVANCED_VIEW;
}
return uplevelFilter;
}
// Convert Locations to DSOP_SCOPE_TYPE_FLAGS
private static uint GetScope( Locations locations )
{
uint scope = 0;
if ((locations & Locations.LocalComputer) == Locations.LocalComputer)
{
scope |= DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_TARGET_COMPUTER;
}
if ((locations & Locations.JoinedDomain) == Locations.JoinedDomain)
{
scope |= DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_DOWNLEVEL_JOINED_DOMAIN |
DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_UPLEVEL_JOINED_DOMAIN;
}
if ((locations & Locations.EnterpriseDomain) == Locations.EnterpriseDomain)
{
scope |= DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_ENTERPRISE_DOMAIN;
}
if ((locations & Locations.GlobalCatalog) == Locations.GlobalCatalog)
{
scope |= DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_GLOBAL_CATALOG;
}
if ((locations & Locations.ExternalDomain) == Locations.ExternalDomain)
{
scope |= DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_EXTERNAL_DOWNLEVEL_DOMAIN |
DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_EXTERNAL_UPLEVEL_DOMAIN;
}
if ((locations & Locations.Workgroup) == Locations.Workgroup)
{
scope |= DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_WORKGROUP;
}
if ((locations & Locations.UserEntered) == Locations.UserEntered)
{
scope |= DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_USER_ENTERED_DOWNLEVEL_SCOPE |
DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_USER_ENTERED_UPLEVEL_SCOPE;
}
return scope;
}
// Convert ADsPathsProviders to DSOP_SCOPE_INIT_INFO_FLAGS
private uint GetProviderFlags()
{
uint scope = 0;
if ((Providers & ADsPathsProviders.WinNT) == ADsPathsProviders.WinNT)
scope |= DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_WANT_PROVIDER_WINNT;
if ((Providers & ADsPathsProviders.LDAP) == ADsPathsProviders.LDAP)
scope |= DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_WANT_PROVIDER_LDAP;
if ((Providers & ADsPathsProviders.GC) == ADsPathsProviders.GC)
scope |= DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_WANT_PROVIDER_GC;
if ((Providers & ADsPathsProviders.SIDPath) == ADsPathsProviders.SIDPath)
scope |= DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_WANT_SID_PATH;
if ((Providers & ADsPathsProviders.DownlevelBuiltinPath) == ADsPathsProviders.DownlevelBuiltinPath)
scope |= DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_WANT_DOWNLEVEL_BUILTIN_PATH;
return scope;
}
private IDsObjectPicker Initialize()
{
DSObjectPicker picker = new DSObjectPicker();
IDsObjectPicker ipicker = (IDsObjectPicker)picker;
List<DSOP_SCOPE_INIT_INFO> scopeInitInfoList = new List<DSOP_SCOPE_INIT_INFO>();
// Note the same default and filters are used by all scopes
uint defaultFilter = GetDefaultFilter();
uint upLevelFilter = GetUpLevelFilter();
uint downLevelFilter = GetDownLevelFilter();
uint providerFlags = GetProviderFlags ();
// Internall, use one scope for the default (starting) locations.
uint startingScope = GetScope(DefaultLocations);
if (startingScope > 0)
{
DSOP_SCOPE_INIT_INFO startingScopeInfo = new DSOP_SCOPE_INIT_INFO();
startingScopeInfo.cbSize = (uint)Marshal.SizeOf(typeof(DSOP_SCOPE_INIT_INFO));
startingScopeInfo.flType = startingScope;
startingScopeInfo.flScope = DSOP_SCOPE_INIT_INFO_FLAGS.DSOP_SCOPE_FLAG_STARTING_SCOPE | defaultFilter | providerFlags;
startingScopeInfo.FilterFlags.Uplevel.flBothModes = upLevelFilter;
startingScopeInfo.FilterFlags.flDownlevel = downLevelFilter;
startingScopeInfo.pwzADsPath = null;
startingScopeInfo.pwzDcName = null;
startingScopeInfo.hr = 0;
scopeInitInfoList.Add(startingScopeInfo);
}
// And another scope for all other locations (AllowedLocation values not in DefaultLocation)
Locations otherLocations = AllowedLocations & (~DefaultLocations);
uint otherScope = GetScope(otherLocations);
if (otherScope > 0)
{
DSOP_SCOPE_INIT_INFO otherScopeInfo = new DSOP_SCOPE_INIT_INFO();
otherScopeInfo.cbSize = (uint)Marshal.SizeOf(typeof(DSOP_SCOPE_INIT_INFO));
otherScopeInfo.flType = otherScope;
otherScopeInfo.flScope = defaultFilter | providerFlags;
otherScopeInfo.FilterFlags.Uplevel.flBothModes = upLevelFilter;
otherScopeInfo.FilterFlags.flDownlevel = downLevelFilter;
otherScopeInfo.pwzADsPath = null;
otherScopeInfo.pwzDcName = null;
otherScopeInfo.hr = 0;
scopeInitInfoList.Add(otherScopeInfo);
}
DSOP_SCOPE_INIT_INFO[] scopeInitInfo = scopeInitInfoList.ToArray();
// TODO: Scopes for alternate ADs, alternate domains, alternate computers, etc
// Allocate memory from the unmananged mem of the process, this should be freed later!??
IntPtr refScopeInitInfo = Marshal.AllocHGlobal
(Marshal.SizeOf(typeof(DSOP_SCOPE_INIT_INFO)) * scopeInitInfo.Length);
// Marshal structs to pointers
for (int index = 0; index < scopeInitInfo.Length; index++)
{
Marshal.StructureToPtr(scopeInitInfo[index],
refScopeInitInfo.OffsetWith(index * Marshal.SizeOf(typeof(DSOP_SCOPE_INIT_INFO))),
false);
}
// Initialize structure with data to initialize an object picker dialog box.
DSOP_INIT_INFO initInfo = new DSOP_INIT_INFO ();
initInfo.cbSize = (uint) Marshal.SizeOf (initInfo);
initInfo.pwzTargetComputer = TargetComputer;
initInfo.cDsScopeInfos = (uint)scopeInitInfo.Length;
initInfo.aDsScopeInfos = refScopeInitInfo;
// Flags that determine the object picker options.
uint flOptions = 0;
if (MultiSelect)
{
flOptions |= DSOP_INIT_INFO_FLAGS.DSOP_FLAG_MULTISELECT;
}
// Only set DSOP_INIT_INFO_FLAGS.DSOP_FLAG_SKIP_TARGET_COMPUTER_DC_CHECK
// if we know target is not a DC (which then saves initialization time).
if (SkipDomainControllerCheck)
{
flOptions |= DSOP_INIT_INFO_FLAGS.DSOP_FLAG_SKIP_TARGET_COMPUTER_DC_CHECK;
}
initInfo.flOptions = flOptions;
// there's a (seeming?) bug on my Windows XP when fetching the objectClass attribute - the pwzClass field is corrupted...
// plus, it returns a multivalued array for this attribute. In Windows 2008 R2, however, only last value is returned,
// just as in pwzClass. So won't actually be retrieving __objectClass__ - will give pwzClass instead
List<string> goingToFetch = new List<string>(AttributesToFetch);
for (int i = 0; i < goingToFetch.Count; i++)
{
if (goingToFetch[i].Equals("objectClass", StringComparison.OrdinalIgnoreCase))
goingToFetch[i] = "__objectClass__";
}
initInfo.cAttributesToFetch = (uint)goingToFetch.Count;
UnmanagedArrayOfStrings unmanagedAttributesToFetch = new UnmanagedArrayOfStrings(goingToFetch);
initInfo.apwzAttributeNames = unmanagedAttributesToFetch.ArrayPtr;
// If the user has defined new credentials, set them now
if (!string.IsNullOrEmpty(userName))
{
var cred = (IDsObjectPickerCredentials)ipicker;
cred.SetCredentials(userName, password);
}
try
{
// Initialize the Object Picker Dialog Box with our options
int hresult = ipicker.Initialize (ref initInfo);
if (hresult != HRESULT.S_OK)
{
Marshal.ReleaseComObject(ipicker);
throw new COMException("IDsObjectPicker.Initialize failed", hresult);
}
return ipicker;
}
finally
{
/*
from MSDN (http://msdn.microsoft.com/en-us/library/ms675899(VS.85).aspx):
Initialize can be called multiple times, but only the last call has effect.
Be aware that object picker makes its own copy of InitInfo.
*/
Marshal.FreeHGlobal(refScopeInitInfo);
unmanagedAttributesToFetch.Dispose();
}
}
private DirectoryObject[] ProcessSelections(IDataObject dataObj)
{
if(dataObj == null)
return null;
DirectoryObject[] selections = null;
// The STGMEDIUM structure is a generalized global memory handle used for data transfer operations
STGMEDIUM stg = new STGMEDIUM();
stg.tymed = (uint)TYMED.TYMED_HGLOBAL;
stg.hGlobal = IntPtr.Zero;
stg.pUnkForRelease = IntPtr.Zero;
// The FORMATETC structure is a generalized Clipboard format.
FORMATETC fe = new FORMATETC();
fe.cfFormat = DataFormats.GetFormat(CLIPBOARD_FORMAT.CFSTR_DSOP_DS_SELECTION_LIST).Id;
// The CFSTR_DSOP_DS_SELECTION_LIST clipboard format is provided by the IDataObject obtained
// by calling IDsObjectPicker::InvokeDialog
fe.ptd = IntPtr.Zero;
fe.dwAspect = 1; //DVASPECT.DVASPECT_CONTENT = 1,
fe.lindex = -1; // all of the data
fe.tymed = (uint)TYMED.TYMED_HGLOBAL; //The storage medium is a global memory handle (HGLOBAL)
int hresult = dataObj.GetData(ref fe, ref stg);
if (hresult != HRESULT.S_OK) throw new COMException("IDataObject.GetData failed", hresult);
IntPtr pDsSL = PInvoke.GlobalLock(stg.hGlobal);
if (pDsSL == IntPtr.Zero) throw new Win32Exception("GlobalLock(stg.hGlobal) failed");
try
{
// the start of our structure
IntPtr current = pDsSL;
// get the # of items selected
int cnt = Marshal.ReadInt32(current);
int cFetchedAttributes = Marshal.ReadInt32(current, Marshal.SizeOf(typeof(uint)));
// if we selected at least 1 object
if (cnt > 0)
{
selections = new DirectoryObject[cnt];
// increment the pointer so we can read the DS_SELECTION structure
current = current.OffsetWith(Marshal.SizeOf(typeof(uint))*2);
// now loop through the structures
for (int i = 0; i < cnt; i++)
{
// marshal the pointer to the structure
DS_SELECTION s = (DS_SELECTION)Marshal.PtrToStructure(current, typeof(DS_SELECTION));
// increment the position of our pointer by the size of the structure
current = current.OffsetWith(Marshal.SizeOf(typeof(DS_SELECTION)));
string name = s.pwzName;
string path = s.pwzADsPath;
string schemaClassName = s.pwzClass;
string upn = s.pwzUPN;
object[] fetchedAttributes = GetFetchedAttributes(s.pvarFetchedAttributes, cFetchedAttributes, schemaClassName);
selections[i] = new DirectoryObject(name, path, schemaClassName, upn, fetchedAttributes);
}
}
}
finally
{
PInvoke.GlobalUnlock(pDsSL);
PInvoke.ReleaseStgMedium(ref stg);
}
return selections;
}
private Object[] GetFetchedAttributes(IntPtr pvarFetchedAttributes, int cFetchedAttributes, string schemaClassName)
{
object[] fetchedAttributes;
if (cFetchedAttributes > 0)
fetchedAttributes = Marshal.GetObjectsForNativeVariants(pvarFetchedAttributes, cFetchedAttributes);
else
fetchedAttributes = new Object[0];
for (int i = 0; i < fetchedAttributes.Length; i++)
{
var largeInteger = fetchedAttributes[i] as IAdsLargeInteger;
if (largeInteger != null)
{
long l = (largeInteger.HighPart * 0x100000000L) + ((uint) largeInteger.LowPart);
fetchedAttributes[i] = l;
}
if (AttributesToFetch[i].Equals("objectClass", StringComparison.OrdinalIgnoreCase)) // see comments in Initialize() function
fetchedAttributes[i] = schemaClassName;
}
return fetchedAttributes;
}
#endregion
}
}
| |
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Text;
namespace Meziantou.Framework.Html;
internal static class Utilities
{
[Pure]
public static bool EqualsIgnoreCase(this string? str1, string? str2)
{
return string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase);
}
[Pure]
public static string? Nullify(string? str, bool trim)
{
if (str == null)
return null;
if (trim)
{
str = str.Trim();
}
if (string.IsNullOrEmpty(str))
return null;
return str;
}
[Pure]
public static bool StartsWith(this string str, char c)
{
if (str.Length == 0)
return false;
return str[0] == c;
}
[Pure]
public static bool EndsWith(this string str, char c)
{
if (str.Length == 0)
return false;
return str[^1] == c;
}
public static Encoding GetDefaultEncoding()
{
return Encoding.GetEncoding(0);
}
public static StreamReader OpenReader(string filePath)
{
var stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
return new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, 0x400, leaveOpen: false);
}
public static StreamReader OpenReader(string filePath, Encoding encoding)
{
var stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
return new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true, 0x400, leaveOpen: false);
}
public static StreamReader OpenReader(string filePath, Encoding encoding, bool detectEncodingFromByteOrderMarks)
{
var stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
return new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks, 0x400, leaveOpen: false);
}
public static StreamReader OpenReader(string filePath, bool detectEncodingFromByteOrderMarks)
{
var stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
return new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks, 0x400, leaveOpen: false);
}
public static StreamReader OpenReader(string filePath, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
{
var stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
return new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize, leaveOpen: false);
}
public static StreamWriter OpenWriter(string filePath, bool append, Encoding encoding, int bufferSize)
{
var stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.Read);
if (append)
{
stream.Seek(0, SeekOrigin.End);
}
return new StreamWriter(stream, encoding, bufferSize, leaveOpen: false);
}
public static StreamWriter OpenWriter(string filePath, bool append, Encoding encoding)
{
var stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.Read);
if (append)
{
stream.Seek(0, SeekOrigin.End);
}
return new StreamWriter(stream, encoding, 0x400, leaveOpen: false);
}
public static StreamWriter OpenWriter(string filePath)
{
var stream = File.Open(filePath, FileMode.Create, FileAccess.Write, FileShare.Read);
var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
return new StreamWriter(stream, encoding, 0x400, leaveOpen: false);
}
public static string? GetAttributeFromHeader(string? header, string name!!)
{
int index;
if (header == null)
return null;
var startIndex = 1;
while (startIndex < header.Length)
{
startIndex = CultureInfo.InvariantCulture.CompareInfo.IndexOf(header, name, startIndex, CompareOptions.IgnoreCase);
if (startIndex < 0 || (startIndex + name.Length) >= header.Length)
break;
var c1 = header[startIndex - 1];
var c2 = header[startIndex + name.Length];
if ((c1 == ';' || c1 == ',' || char.IsWhiteSpace(c1)) && (c2 == '=' || char.IsWhiteSpace(c2)))
break;
startIndex += name.Length;
}
if (startIndex < 0 || startIndex >= header.Length)
return null;
startIndex += name.Length;
while (startIndex < header.Length && char.IsWhiteSpace(header[startIndex]))
{
startIndex++;
}
if (startIndex >= header.Length || header[startIndex] != '=')
return null;
startIndex++;
while (startIndex < header.Length && char.IsWhiteSpace(header[startIndex]))
{
startIndex++;
}
if (startIndex >= header.Length)
return null;
if (startIndex < header.Length && header[startIndex] == '"')
{
if (startIndex == (header.Length - 1))
return null;
index = header.IndexOf('"', startIndex + 1);
if (index < 0 || index == (startIndex + 1))
return null;
return header.Substring(startIndex + 1, index - startIndex - 1).Trim();
}
index = startIndex;
while (index < header.Length)
{
if (header[index] == ' ' || header[index] == ',')
break;
index++;
}
if (index == startIndex)
return null;
return header[startIndex..index].Trim();
}
public static string GetValidXmlName(string text)
{
if ((text == null) || (text.Trim().Length == 0))
throw new ArgumentNullException(nameof(text));
var sb = new StringBuilder(text.Length);
if (IsValidXmlNameStart(text[0]))
{
sb.Append(text[0]);
}
else
{
sb.Append(GetXmlNameEscape(text[0]));
}
for (var i = 1; i < text.Length; i++)
{
if (IsValidXmlNamePart(text[i]))
{
sb.Append(text[i]);
}
else
{
sb.Append(GetXmlNameEscape(text[i]));
}
}
return sb.ToString();
}
private static string GetXmlNameEscape(char c)
{
return "_x" + ((int)c).ToString("x4", CultureInfo.InvariantCulture) + "_";
}
// http://www.w3.org/TR/REC-xml/#NT-Letter
// valids are Lu, Ll, Lt, Lo, Nl
private static bool IsValidXmlNameStart(char c)
{
if (c == '_')
return true;
if ((c == 0x20DD) || (c == 0x20E0))
return false;
if ((c > 0xF900) && (c < 0xFFFE))
return false;
var category = CharUnicodeInfo.GetUnicodeCategory(c);
return category == UnicodeCategory.UppercaseLetter
|| category == UnicodeCategory.LowercaseLetter
|| category == UnicodeCategory.TitlecaseLetter
|| category == UnicodeCategory.LetterNumber
|| category == UnicodeCategory.OtherLetter;
}
// valids are Lu, Ll, Lt, Lo, Nl, Mc, Me, Mn, Lm, or Nd
[SuppressMessage("Style", "IDE0066:Convert switch statement to expression", Justification = "Better readability")]
private static bool IsValidXmlNamePart(char c)
{
if ((c == '_') || (c == '.'))
return true;
if (c == 0x0387)
return true;
if ((c == 0x20DD) || (c == 0x20E0))
return false;
if ((c > 0xF900) && (c < 0xFFFE))
return false;
var category = CharUnicodeInfo.GetUnicodeCategory(c);
switch (category)
{
case UnicodeCategory.UppercaseLetter://Lu
case UnicodeCategory.LowercaseLetter://Ll
case UnicodeCategory.TitlecaseLetter://Lt
case UnicodeCategory.LetterNumber://Nl
case UnicodeCategory.OtherLetter://Lo
case UnicodeCategory.ModifierLetter://Lm
case UnicodeCategory.NonSpacingMark://Mn
case UnicodeCategory.SpacingCombiningMark://Mc
case UnicodeCategory.EnclosingMark://Me
case UnicodeCategory.DecimalDigitNumber://Nd
return true;
default:
return false;
}
}
public static string? GetServerPath(string path)
{
return GetServerPath(path, out _, out _, out _);
}
public static string? GetServerPath(string path!!, out string? serverName, out string? shareName, out string? sharePath)
{
serverName = null;
shareName = null;
sharePath = null;
if (path.Length < 5 || !path.StartsWith(@"\\", StringComparison.Ordinal)) // min is \\x\y (5 chars)
return null;
if (path[2] == Path.DirectorySeparatorChar)
return null;
var pos = path.IndexOf(Path.DirectorySeparatorChar, 3); // \\\ is invalid
if (pos < 0)
{
serverName = path[2..];
return path;
}
var pos2 = path.IndexOf(Path.DirectorySeparatorChar, pos + 2); // \\server\\ is invalid
if (pos2 < 0)
{
serverName = path[2..pos];
shareName = path[(pos + 1)..];
return path;
}
serverName = path[2..pos];
shareName = path[(pos + 1)..pos2];
sharePath = path[(pos2 + 1)..];
return @"\\" + serverName + @"\" + shareName;
}
private const string Prefix = @"\\?\";
public static bool IsRooted(string? path)
{
if (path == null)
return false;
if (path.StartsWith(Prefix, StringComparison.Ordinal))
{
path = path[Prefix.Length..];
}
var spath = GetServerPath(path);
if (spath != null)
return true;
if (path.Length >= 1 && path[0] == Path.DirectorySeparatorChar)
return true;
if (path.Length >= 2 && path[1] == Path.VolumeSeparatorChar)
return true;
return false;
}
public static string EnsureTerminatingSeparator(string? path)
{
if (string.IsNullOrEmpty(path))
return Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture);
if (path[^1] != Path.DirectorySeparatorChar)
return path + Path.DirectorySeparatorChar;
return path;
}
}
| |
#region License
//
// Copyright (c) 2018, Fluent Migrator Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System.Data;
using FluentMigrator.Runner.Generators.Oracle;
using NUnit.Framework;
using Shouldly;
namespace FluentMigrator.Tests.Unit.Generators.Oracle
{
[TestFixture]
public class OracleConstraintsTests : BaseConstraintsTests
{
protected OracleGenerator Generator;
[SetUp]
public void Setup()
{
Generator = new OracleGenerator();
}
[Test]
public override void CanCreateForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
expression.ForeignKey.PrimaryTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT FK_TestTable1_TestColumn1_TestTable2_TestColumn2 FOREIGN KEY (TestColumn1) REFERENCES TestSchema.TestTable2 (TestColumn2)");
}
[Test]
public override void CanCreateForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT FK_TestTable1_TestColumn1_TestTable2_TestColumn2 FOREIGN KEY (TestColumn1) REFERENCES TestTable2 (TestColumn2)");
}
[Test]
public override void CanCreateForeignKeyWithDifferentSchemas()
{
var expression = GeneratorTestHelper.GetCreateForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT FK_TestTable1_TestColumn1_TestTable2_TestColumn2 FOREIGN KEY (TestColumn1) REFERENCES TestTable2 (TestColumn2)");
}
[Test]
public override void CanCreateMultiColumnForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
expression.ForeignKey.PrimaryTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT FK_TestTable1_TestColumn1_TestColumn3_TestTable2_TestColumn2_TestColumn4 FOREIGN KEY (TestColumn1, TestColumn3) REFERENCES TestSchema.TestTable2 (TestColumn2, TestColumn4)");
}
[Test]
public override void CanCreateMultiColumnForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT FK_TestTable1_TestColumn1_TestColumn3_TestTable2_TestColumn2_TestColumn4 FOREIGN KEY (TestColumn1, TestColumn3) REFERENCES TestTable2 (TestColumn2, TestColumn4)");
}
[Test]
public override void CanCreateMultiColumnForeignKeyWithDifferentSchemas()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT FK_TestTable1_TestColumn1_TestColumn3_TestTable2_TestColumn2_TestColumn4 FOREIGN KEY (TestColumn1, TestColumn3) REFERENCES TestTable2 (TestColumn2, TestColumn4)");
}
[Test]
public override void CanCreateMultiColumnPrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnPrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT PK_TestTable1_TestColumn1_TestColumn2 PRIMARY KEY (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateMultiColumnPrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT PK_TestTable1_TestColumn1_TestColumn2 PRIMARY KEY (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateMultiColumnUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT UC_TestTable1_TestColumn1_TestColumn2 UNIQUE (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateMultiColumnUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT UC_TestTable1_TestColumn1_TestColumn2 UNIQUE (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateNamedForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
expression.ForeignKey.PrimaryTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1) REFERENCES TestSchema.TestTable2 (TestColumn2)");
}
[Test]
public override void CanCreateNamedForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1) REFERENCES TestTable2 (TestColumn2)");
}
[Test]
public override void CanCreateNamedForeignKeyWithDifferentSchemas()
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1) REFERENCES TestTable2 (TestColumn2)");
}
[Test]
public override void CanCreateNamedForeignKeyWithOnDeleteAndOnUpdateOptions()
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.OnDelete = Rule.Cascade;
expression.ForeignKey.OnUpdate = Rule.SetDefault;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1) REFERENCES TestTable2 (TestColumn2) ON DELETE CASCADE ON UPDATE SET DEFAULT");
}
[TestCase(Rule.SetDefault, "SET DEFAULT"), TestCase(Rule.SetNull, "SET NULL"), TestCase(Rule.Cascade, "CASCADE")]
public override void CanCreateNamedForeignKeyWithOnDeleteOptions(Rule rule, string output)
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.OnDelete = rule;
var result = Generator.Generate(expression);
result.ShouldBe(string.Format("ALTER TABLE TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1) REFERENCES TestTable2 (TestColumn2) ON DELETE {0}", output));
}
[TestCase(Rule.SetDefault, "SET DEFAULT"), TestCase(Rule.SetNull, "SET NULL"), TestCase(Rule.Cascade, "CASCADE")]
public override void CanCreateNamedForeignKeyWithOnUpdateOptions(Rule rule, string output)
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.OnUpdate = rule;
var result = Generator.Generate(expression);
result.ShouldBe(string.Format("ALTER TABLE TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1) REFERENCES TestTable2 (TestColumn2) ON UPDATE {0}", output));
}
[Test]
public override void CanCreateNamedMultiColumnForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
expression.ForeignKey.PrimaryTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1, TestColumn3) REFERENCES TestSchema.TestTable2 (TestColumn2, TestColumn4)");
}
[Test]
public override void CanCreateNamedMultiColumnForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1, TestColumn3) REFERENCES TestTable2 (TestColumn2, TestColumn4)");
}
[Test]
public override void CanCreateNamedMultiColumnForeignKeyWithDifferentSchemas()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1, TestColumn3) REFERENCES TestTable2 (TestColumn2, TestColumn4)");
}
[Test]
public override void CanCreateNamedMultiColumnPrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnPrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TESTPRIMARYKEY PRIMARY KEY (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateNamedMultiColumnPrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT TESTPRIMARYKEY PRIMARY KEY (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateNamedMultiColumnUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TESTUNIQUECONSTRAINT UNIQUE (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateNamedMultiColumnUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT TESTUNIQUECONSTRAINT UNIQUE (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateNamedPrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedPrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TESTPRIMARYKEY PRIMARY KEY (TestColumn1)");
}
[Test]
public override void CanCreateNamedPrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT TESTPRIMARYKEY PRIMARY KEY (TestColumn1)");
}
[Test]
public override void CanCreateNamedUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TESTUNIQUECONSTRAINT UNIQUE (TestColumn1)");
}
[Test]
public override void CanCreateNamedUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT TESTUNIQUECONSTRAINT UNIQUE (TestColumn1)");
}
[Test]
public override void CanCreatePrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreatePrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT PK_TestTable1_TestColumn1 PRIMARY KEY (TestColumn1)");
}
[Test]
public override void CanCreatePrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreatePrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT PK_TestTable1_TestColumn1 PRIMARY KEY (TestColumn1)");
}
[Test]
public override void CanCreateUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT UC_TestTable1_TestColumn1 UNIQUE (TestColumn1)");
}
[Test]
public override void CanCreateUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT UC_TestTable1_TestColumn1 UNIQUE (TestColumn1)");
}
[Test]
public override void CanDropForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 DROP CONSTRAINT FK_Test");
}
[Test]
public override void CanDropForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 DROP CONSTRAINT FK_Test");
}
[Test]
public override void CanDropPrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeletePrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 DROP CONSTRAINT TESTPRIMARYKEY");
}
[Test]
public override void CanDropPrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeletePrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 DROP CONSTRAINT TESTPRIMARYKEY");
}
[Test]
public override void CanDropUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 DROP CONSTRAINT TESTUNIQUECONSTRAINT");
}
[Test]
public override void CanDropUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 DROP CONSTRAINT TESTUNIQUECONSTRAINT");
}
[Test]
public void CanAlterDefaultConstraintWithValueAsDefault()
{
var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 MODIFY TestColumn1 DEFAULT 1");
}
[Test]
public void CanAlterDefaultConstraintWithStringValueAsDefault()
{
var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
expression.DefaultValue = "1";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 MODIFY TestColumn1 DEFAULT '1'");
}
[Test]
public void CanAlterDefaultConstraintWithDefaultSystemMethodNewGuid()
{
var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
expression.DefaultValue = SystemMethods.NewGuid;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 MODIFY TestColumn1 DEFAULT sys_guid()");
}
[Test]
public void CanAlterDefaultConstraintWithDefaultSystemMethodCurrentDateTime()
{
var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
expression.DefaultValue = SystemMethods.CurrentDateTime;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 MODIFY TestColumn1 DEFAULT LOCALTIMESTAMP");
}
[Test]
public void CanAlterDefaultConstraintWithDefaultSystemMethodCurrentUser()
{
var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
expression.DefaultValue = SystemMethods.CurrentUser;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 MODIFY TestColumn1 DEFAULT USER");
}
[Test]
public void CanRemoveDefaultConstraint()
{
var expression = GeneratorTestHelper.GetDeleteDefaultConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 MODIFY TestColumn1 DEFAULT NULL");
}
}
}
| |
// 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.ExceptionServices;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
// The System.Net.Sockets.TcpClient class provide TCP services at a higher level
// of abstraction than the System.Net.Sockets.Socket class. System.Net.Sockets.TcpClient
// is used to create a Client connection to a remote host.
public class TcpClient : IDisposable
{
private AddressFamily _family;
private Socket _clientSocket;
private NetworkStream _dataStream;
private bool _cleanedUp;
private bool _active;
// Initializes a new instance of the System.Net.Sockets.TcpClient class.
public TcpClient() : this(AddressFamily.Unknown)
{
}
// Initializes a new instance of the System.Net.Sockets.TcpClient class.
public TcpClient(AddressFamily family)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, family);
// Validate parameter
if (family != AddressFamily.InterNetwork &&
family != AddressFamily.InterNetworkV6 &&
family != AddressFamily.Unknown)
{
throw new ArgumentException(SR.Format(SR.net_protocol_invalid_family, "TCP"), nameof(family));
}
_family = family;
InitializeClientSocket();
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
// Initializes a new instance of the System.Net.Sockets.TcpClient class with the specified end point.
public TcpClient(IPEndPoint localEP)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, localEP);
if (localEP == null)
{
throw new ArgumentNullException(nameof(localEP));
}
_family = localEP.AddressFamily; // set before calling CreateSocket
InitializeClientSocket();
_clientSocket.Bind(localEP);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
// Initializes a new instance of the System.Net.Sockets.TcpClient class and connects to the specified port on
// the specified host.
public TcpClient(string hostname, int port)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, hostname);
if (hostname == null)
{
throw new ArgumentNullException(nameof(hostname));
}
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
}
try
{
Connect(hostname, port);
}
catch
{
_clientSocket?.Close();
throw;
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
// Used by TcpListener.Accept().
internal TcpClient(Socket acceptedSocket)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, acceptedSocket);
_clientSocket = acceptedSocket;
_active = true;
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
// Used by the class to indicate that a connection has been made.
protected bool Active
{
get { return _active; }
set { _active = value; }
}
public int Available => _clientSocket?.Available ?? 0;
// Used by the class to provide the underlying network socket.
public Socket Client
{
get { return _clientSocket; }
set
{
_clientSocket = value;
_family = _clientSocket?.AddressFamily ?? AddressFamily.Unknown;
}
}
public bool Connected => _clientSocket?.Connected ?? false;
public bool ExclusiveAddressUse
{
get { return _clientSocket?.ExclusiveAddressUse ?? false; }
set
{
if (_clientSocket != null)
{
_clientSocket.ExclusiveAddressUse = value;
}
}
}
// Connects the Client to the specified port on the specified host.
public void Connect(string hostname, int port)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, hostname);
if (_cleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (hostname == null)
{
throw new ArgumentNullException(nameof(hostname));
}
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
}
// Check for already connected and throw here. This check
// is not required in the other connect methods as they
// will throw from WinSock. Here, the situation is more
// complex since we have to resolve a hostname so it's
// easier to simply block the request up front.
if (_active)
{
throw new SocketException((int)SocketError.IsConnected);
}
// IPv6: We need to process each of the addresses returned from
// DNS when trying to connect. Use of AddressList[0] is
// bad form.
IPAddress[] addresses = Dns.GetHostAddresses(hostname);
ExceptionDispatchInfo lastex = null;
try
{
foreach (IPAddress address in addresses)
{
Socket tmpSocket = null;
try
{
if (_clientSocket == null)
{
// We came via the <hostname,port> constructor. Set the address family appropriately,
// create the socket and try to connect.
Debug.Assert(address.AddressFamily == AddressFamily.InterNetwork || address.AddressFamily == AddressFamily.InterNetworkV6);
if ((address.AddressFamily == AddressFamily.InterNetwork && Socket.OSSupportsIPv4) || Socket.OSSupportsIPv6)
{
tmpSocket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
tmpSocket.Connect(address, port);
_clientSocket = tmpSocket;
tmpSocket = null;
}
_family = address.AddressFamily;
_active = true;
break;
}
else if (address.AddressFamily == _family || _family == AddressFamily.Unknown)
{
// Only use addresses with a matching family
Connect(new IPEndPoint(address, port));
_active = true;
break;
}
}
catch (Exception ex) when (!(ex is OutOfMemoryException))
{
if (tmpSocket != null)
{
tmpSocket.Dispose();
tmpSocket = null;
}
lastex = ExceptionDispatchInfo.Capture(ex);
}
}
}
finally
{
if (!_active)
{
// The connect failed - rethrow the last error we had
lastex?.Throw();
throw new SocketException((int)SocketError.NotConnected);
}
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
// Connects the Client to the specified port on the specified host.
public void Connect(IPAddress address, int port)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, address);
if (_cleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
}
IPEndPoint remoteEP = new IPEndPoint(address, port);
Connect(remoteEP);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
// Connect the Client to the specified end point.
public void Connect(IPEndPoint remoteEP)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, remoteEP);
if (_cleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (remoteEP == null)
{
throw new ArgumentNullException(nameof(remoteEP));
}
Client.Connect(remoteEP);
_family = Client.AddressFamily;
_active = true;
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
public void Connect(IPAddress[] ipAddresses, int port)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, ipAddresses);
Client.Connect(ipAddresses, port);
_family = Client.AddressFamily;
_active = true;
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
public Task ConnectAsync(IPAddress address, int port) =>
Task.Factory.FromAsync(
(targetAddess, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetAddess, targetPort, callback, state),
asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult),
address, port, state: this);
public Task ConnectAsync(string host, int port) =>
Task.Factory.FromAsync(
(targetHost, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetHost, targetPort, callback, state),
asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult),
host, port, state: this);
public Task ConnectAsync(IPAddress[] addresses, int port) =>
Task.Factory.FromAsync(
(targetAddresses, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetAddresses, targetPort, callback, state),
asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult),
addresses, port, state: this);
public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, address);
IAsyncResult result = Client.BeginConnect(address, port, requestCallback, state);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
return result;
}
public IAsyncResult BeginConnect(string host, int port, AsyncCallback requestCallback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, (string)host);
IAsyncResult result = Client.BeginConnect(host, port, requestCallback, state);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
return result;
}
public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback requestCallback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, addresses);
IAsyncResult result = Client.BeginConnect(addresses, port, requestCallback, state);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
return result;
}
public void EndConnect(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, asyncResult);
Socket s = Client;
if (s == null)
{
// Dispose nulls out the client socket field.
throw new ObjectDisposedException(GetType().Name);
}
s.EndConnect(asyncResult);
_active = true;
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
// Returns the stream used to read and write data to the remote host.
public NetworkStream GetStream()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (_cleanedUp)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (!Connected)
{
throw new InvalidOperationException(SR.net_notconnected);
}
if (_dataStream == null)
{
_dataStream = new NetworkStream(Client, true);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, _dataStream);
return _dataStream;
}
public void Close() => Dispose();
// Disposes the Tcp connection.
protected virtual void Dispose(bool disposing)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (_cleanedUp)
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
return;
}
if (disposing)
{
IDisposable dataStream = _dataStream;
if (dataStream != null)
{
dataStream.Dispose();
}
else
{
// If the NetworkStream wasn't created, the Socket might
// still be there and needs to be closed. In the case in which
// we are bound to a local IPEndPoint this will remove the
// binding and free up the IPEndPoint for later uses.
Socket chkClientSocket = _clientSocket;
if (chkClientSocket != null)
{
try
{
chkClientSocket.InternalShutdown(SocketShutdown.Both);
}
finally
{
chkClientSocket.Close();
_clientSocket = null;
}
}
}
GC.SuppressFinalize(this);
}
_cleanedUp = true;
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
public void Dispose() => Dispose(true);
~TcpClient()
{
#if DEBUG
DebugThreadTracking.SetThreadSource(ThreadKinds.Finalization);
using (DebugThreadTracking.SetThreadKind(ThreadKinds.System | ThreadKinds.Async))
{
#endif
Dispose(false);
#if DEBUG
}
#endif
}
// Gets or sets the size of the receive buffer in bytes.
public int ReceiveBufferSize
{
get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer); }
set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value); }
}
// Gets or sets the size of the send buffer in bytes.
public int SendBufferSize
{
get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer); }
set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, value); }
}
// Gets or sets the receive time out value of the connection in milliseconds.
public int ReceiveTimeout
{
get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); }
set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, value); }
}
// Gets or sets the send time out value of the connection in milliseconds.
public int SendTimeout
{
get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout); }
set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, value); }
}
// Gets or sets the value of the connection's linger option.
public LingerOption LingerState
{
get { return Client.LingerState; }
set { Client.LingerState = value; }
}
// Enables or disables delay when send or receive buffers are full.
public bool NoDelay
{
get { return Client.NoDelay; }
set { Client.NoDelay = value; }
}
private void InitializeClientSocket()
{
Debug.Assert(_clientSocket == null);
if (_family == AddressFamily.Unknown)
{
// If AF was not explicitly set try to initialize dual mode socket or fall-back to IPv4.
_clientSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
if (_clientSocket.AddressFamily == AddressFamily.InterNetwork)
{
_family = AddressFamily.InterNetwork;
}
}
else
{
_clientSocket = new Socket(_family, SocketType.Stream, ProtocolType.Tcp);
}
}
}
}
| |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Runtime.InteropServices;
namespace SharpDX.DirectInput
{
public partial class EffectFile
{
/// <summary>
/// Initializes a new instance of the <see cref="EffectFile"/> class.
/// </summary>
public EffectFile()
{
unsafe
{
Size = sizeof(__Native);
}
}
/// <summary>
/// Gets or sets the parameters.
/// </summary>
/// <value>The parameters.</value>
public EffectParameters Parameters { get; set; }
internal static __Native __NewNative()
{
unsafe
{
__Native temp = default(__Native);
temp.Size = sizeof(__Native);
return temp;
}
}
// Internal native struct used for marshalling
[StructLayout(LayoutKind.Sequential, Pack = 0)]
internal partial struct __Native
{
public int Size;
public System.Guid Guid;
public System.IntPtr EffectParametersPointer;
public byte Name;
public byte _Name2;
public byte _Name3;
public byte _Name4;
public byte _Name5;
public byte _Name6;
public byte _Name7;
public byte _Name8;
public byte _Name9;
public byte _Name10;
public byte _Name11;
public byte _Name12;
public byte _Name13;
public byte _Name14;
public byte _Name15;
public byte _Name16;
public byte _Name17;
public byte _Name18;
public byte _Name19;
public byte _Name20;
public byte _Name21;
public byte _Name22;
public byte _Name23;
public byte _Name24;
public byte _Name25;
public byte _Name26;
public byte _Name27;
public byte _Name28;
public byte _Name29;
public byte _Name30;
public byte _Name31;
public byte _Name32;
public byte _Name33;
public byte _Name34;
public byte _Name35;
public byte _Name36;
public byte _Name37;
public byte _Name38;
public byte _Name39;
public byte _Name40;
public byte _Name41;
public byte _Name42;
public byte _Name43;
public byte _Name44;
public byte _Name45;
public byte _Name46;
public byte _Name47;
public byte _Name48;
public byte _Name49;
public byte _Name50;
public byte _Name51;
public byte _Name52;
public byte _Name53;
public byte _Name54;
public byte _Name55;
public byte _Name56;
public byte _Name57;
public byte _Name58;
public byte _Name59;
public byte _Name60;
public byte _Name61;
public byte _Name62;
public byte _Name63;
public byte _Name64;
public byte _Name65;
public byte _Name66;
public byte _Name67;
public byte _Name68;
public byte _Name69;
public byte _Name70;
public byte _Name71;
public byte _Name72;
public byte _Name73;
public byte _Name74;
public byte _Name75;
public byte _Name76;
public byte _Name77;
public byte _Name78;
public byte _Name79;
public byte _Name80;
public byte _Name81;
public byte _Name82;
public byte _Name83;
public byte _Name84;
public byte _Name85;
public byte _Name86;
public byte _Name87;
public byte _Name88;
public byte _Name89;
public byte _Name90;
public byte _Name91;
public byte _Name92;
public byte _Name93;
public byte _Name94;
public byte _Name95;
public byte _Name96;
public byte _Name97;
public byte _Name98;
public byte _Name99;
public byte _Name100;
public byte _Name101;
public byte _Name102;
public byte _Name103;
public byte _Name104;
public byte _Name105;
public byte _Name106;
public byte _Name107;
public byte _Name108;
public byte _Name109;
public byte _Name110;
public byte _Name111;
public byte _Name112;
public byte _Name113;
public byte _Name114;
public byte _Name115;
public byte _Name116;
public byte _Name117;
public byte _Name118;
public byte _Name119;
public byte _Name120;
public byte _Name121;
public byte _Name122;
public byte _Name123;
public byte _Name124;
public byte _Name125;
public byte _Name126;
public byte _Name127;
public byte _Name128;
public byte _Name129;
public byte _Name130;
public byte _Name131;
public byte _Name132;
public byte _Name133;
public byte _Name134;
public byte _Name135;
public byte _Name136;
public byte _Name137;
public byte _Name138;
public byte _Name139;
public byte _Name140;
public byte _Name141;
public byte _Name142;
public byte _Name143;
public byte _Name144;
public byte _Name145;
public byte _Name146;
public byte _Name147;
public byte _Name148;
public byte _Name149;
public byte _Name150;
public byte _Name151;
public byte _Name152;
public byte _Name153;
public byte _Name154;
public byte _Name155;
public byte _Name156;
public byte _Name157;
public byte _Name158;
public byte _Name159;
public byte _Name160;
public byte _Name161;
public byte _Name162;
public byte _Name163;
public byte _Name164;
public byte _Name165;
public byte _Name166;
public byte _Name167;
public byte _Name168;
public byte _Name169;
public byte _Name170;
public byte _Name171;
public byte _Name172;
public byte _Name173;
public byte _Name174;
public byte _Name175;
public byte _Name176;
public byte _Name177;
public byte _Name178;
public byte _Name179;
public byte _Name180;
public byte _Name181;
public byte _Name182;
public byte _Name183;
public byte _Name184;
public byte _Name185;
public byte _Name186;
public byte _Name187;
public byte _Name188;
public byte _Name189;
public byte _Name190;
public byte _Name191;
public byte _Name192;
public byte _Name193;
public byte _Name194;
public byte _Name195;
public byte _Name196;
public byte _Name197;
public byte _Name198;
public byte _Name199;
public byte _Name200;
public byte _Name201;
public byte _Name202;
public byte _Name203;
public byte _Name204;
public byte _Name205;
public byte _Name206;
public byte _Name207;
public byte _Name208;
public byte _Name209;
public byte _Name210;
public byte _Name211;
public byte _Name212;
public byte _Name213;
public byte _Name214;
public byte _Name215;
public byte _Name216;
public byte _Name217;
public byte _Name218;
public byte _Name219;
public byte _Name220;
public byte _Name221;
public byte _Name222;
public byte _Name223;
public byte _Name224;
public byte _Name225;
public byte _Name226;
public byte _Name227;
public byte _Name228;
public byte _Name229;
public byte _Name230;
public byte _Name231;
public byte _Name232;
public byte _Name233;
public byte _Name234;
public byte _Name235;
public byte _Name236;
public byte _Name237;
public byte _Name238;
public byte _Name239;
public byte _Name240;
public byte _Name241;
public byte _Name242;
public byte _Name243;
public byte _Name244;
public byte _Name245;
public byte _Name246;
public byte _Name247;
public byte _Name248;
public byte _Name249;
public byte _Name250;
public byte _Name251;
public byte _Name252;
public byte _Name253;
public byte _Name254;
public byte _Name255;
public byte _Name256;
public byte _Name257;
public byte _Name258;
public byte _Name259;
public byte _Name260;
// Method to free native struct
internal unsafe void __MarshalFree()
{
if (EffectParametersPointer != IntPtr.Zero)
Marshal.FreeHGlobal(EffectParametersPointer);
}
}
internal unsafe void __MarshalFree(ref __Native @ref)
{
// Free Parameters
if (Parameters != null && @ref.EffectParametersPointer != IntPtr.Zero)
Parameters.__MarshalFree(ref *((EffectParameters.__Native*)@ref.EffectParametersPointer));
@ref.__MarshalFree();
}
// Method to marshal from native to managed struct
internal unsafe void __MarshalFrom(ref __Native @ref)
{
this.Size = @ref.Size;
this.Guid = @ref.Guid;
this.EffectParametersPointer = @ref.EffectParametersPointer;
fixed (void* __ptr = &@ref.Name) this.Name = Utilities.PtrToStringAnsi((IntPtr)__ptr, 260);
if (this.EffectParametersPointer != IntPtr.Zero)
{
Parameters = new EffectParameters();
Parameters.__MarshalFrom(ref *(EffectParameters.__Native*)EffectParametersPointer);
EffectParametersPointer = IntPtr.Zero;
}
}
// Method to marshal from managed struct tot native
internal unsafe void __MarshalTo(ref __Native @ref)
{
@ref.Size = this.Size;
@ref.Guid = this.Guid;
IntPtr effectParameters = IntPtr.Zero;
if ( Parameters != null)
{
effectParameters = Marshal.AllocHGlobal(sizeof (EffectParameters.__Native));
var nativeParameters = default(EffectParameters.__Native);
Parameters.__MarshalTo(ref nativeParameters);
*((EffectParameters.__Native*) effectParameters) = nativeParameters;
}
@ref.EffectParametersPointer = effectParameters;
IntPtr Name_ = Marshal.StringToHGlobalAnsi(this.Name);
fixed (void* __ptr = &@ref.Name) Utilities.CopyMemory((IntPtr)__ptr, Name_, this.Name.Length);
Marshal.FreeHGlobal(Name_);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.UseExpressionBody;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
{
public class UseExpressionBodyForPropertiesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
=> new Tuple<DiagnosticAnalyzer, CodeFixProvider>(
new UseExpressionBodyForPropertiesDiagnosticAnalyzer(),
new UseExpressionBodyForPropertiesCodeFixProvider());
private static readonly Dictionary<OptionKey, object> UseExpressionBody =
new Dictionary<OptionKey, object>
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CodeStyleOptions.TrueWithNoneEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CodeStyleOptions.FalseWithNoneEnforcement },
};
private static readonly Dictionary<OptionKey, object> UseBlockBody =
new Dictionary<OptionKey, object>
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CodeStyleOptions.FalseWithNoneEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CodeStyleOptions.FalseWithNoneEnforcement }
};
private static readonly Dictionary<OptionKey, object> UseBlockBodyExceptAccessor =
new Dictionary<OptionKey, object>
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CodeStyleOptions.FalseWithNoneEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CodeStyleOptions.TrueWithNoneEnforcement }
};
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseExpressionBody1()
{
await TestAsync(
@"class C
{
int Foo
{
get
{
[|return|] Bar();
}
}
}",
@"class C
{
int Foo => Bar();
}", options: UseExpressionBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestMissingWithSetter()
{
await TestMissingAsync(
@"class C
{
int Foo
{
get
{
[|return|] Bar();
}
set
{
}
}
}", options: UseExpressionBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestMissingWithAttribute()
{
await TestMissingAsync(
@"class C
{
int Foo
{
[A]
get
{
[|return|] Bar();
}
}
}", options: UseExpressionBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestMissingOnSetter1()
{
await TestMissingAsync(
@"class C
{
int Foo
{
set
{
[|Bar|]();
}
}
}", options: UseExpressionBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseExpressionBody3()
{
await TestAsync(
@"class C
{
int Foo
{
get
{
[|throw|] new NotImplementedException();
}
}
}",
@"class C
{
int Foo => throw new NotImplementedException();
}", options: UseExpressionBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseExpressionBody4()
{
await TestAsync(
@"class C
{
int Foo
{
get
{
[|throw|] new NotImplementedException(); // comment
}
}
}",
@"class C
{
int Foo => throw new NotImplementedException(); // comment
}", compareTokens: false, options: UseExpressionBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseBlockBody1()
{
await TestAsync(
@"class C
{
int Foo [|=>|] Bar();
}",
@"class C
{
int Foo
{
get
{
return Bar();
}
}
}", options: UseBlockBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseBlockBodyIfAccessorWantExpression1()
{
await TestAsync(
@"class C
{
int Foo [|=>|] Bar();
}",
@"class C
{
int Foo
{
get => Bar();
}
}", options: UseBlockBodyExceptAccessor);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseBlockBody3()
{
await TestAsync(
@"class C
{
int Foo [|=>|] throw new NotImplementedException();
}",
@"class C
{
int Foo
{
get
{
throw new NotImplementedException();
}
}
}", options: UseBlockBody);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseBlockBody4()
{
await TestAsync(
@"class C
{
int Foo [|=>|] throw new NotImplementedException(); // comment
}",
@"class C
{
int Foo
{
get
{
throw new NotImplementedException(); // comment
}
}
}", compareTokens: false, options: UseBlockBody);
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Abstract;
using System.Globalization;
using Microsoft.Practices.SharePoint.Common.Logging;
using Microsoft.SharePoint.Administration;
namespace Contoso.Abstract
{
/// <summary>
/// ISPDeveloperServiceLog
/// </summary>
public interface ISPDeveloperServiceLog : IServiceLog
{
/// <summary>
/// Gets the log.
/// </summary>
ILogger Log { get; }
/// <summary>
/// Gets the event ID.
/// </summary>
int EventID { get; }
/// <summary>
/// Gets the name of the area.
/// </summary>
/// <value>
/// The name of the area.
/// </value>
string AreaName { get; }
/// <summary>
/// Gets the category.
/// </summary>
string Category { get; }
}
/// <summary>
/// SPDeveloperServiceLog
/// </summary>
public class SPDeveloperServiceLog : ISPDeveloperServiceLog, ServiceLogManager.ISetupRegistration
{
static SPDeveloperServiceLog() { ServiceLogManager.EnsureRegistration(); }
/// <summary>
/// Initializes a new instance of the <see cref="SPDeveloperServiceLog"/> class.
/// </summary>
public SPDeveloperServiceLog()
: this(new SharePointLogger(), 0, "SharePoint Foundation", "General") { }
/// <summary>
/// Initializes a new instance of the <see cref="SPDeveloperServiceLog"/> class.
/// </summary>
/// <param name="areaName">Name of the area.</param>
/// <param name="category">The category.</param>
public SPDeveloperServiceLog(string areaName, string category)
: this(new SharePointLogger(), 0, areaName, category) { }
/// <summary>
/// Initializes a new instance of the <see cref="SPDeveloperServiceLog"/> class.
/// </summary>
/// <param name="eventID">The event ID.</param>
public SPDeveloperServiceLog(int eventID)
: this(new SharePointLogger(), eventID, "SharePoint Foundation", "General") { }
/// <summary>
/// Initializes a new instance of the <see cref="SPDeveloperServiceLog"/> class.
/// </summary>
/// <param name="eventID">The event ID.</param>
/// <param name="areaName">Name of the area.</param>
/// <param name="category">The category.</param>
public SPDeveloperServiceLog(int eventID, string areaName, string category)
: this(new SharePointLogger(), eventID, areaName, category) { }
/// <summary>
/// Initializes a new instance of the <see cref="SPDeveloperServiceLog"/> class.
/// </summary>
/// <param name="log">The log.</param>
/// <param name="eventID">The event ID.</param>
/// <param name="areaName">Name of the area.</param>
/// <param name="category">The category.</param>
public SPDeveloperServiceLog(ILogger log, int eventID, string areaName, string category)
{
if (log == null)
throw new ArgumentNullException("log");
if (string.IsNullOrEmpty(areaName))
throw new ArgumentNullException("areaName");
if (string.IsNullOrEmpty(category))
throw new ArgumentNullException("category");
Log = log;
EventID = eventID;
AreaName = areaName;
Category = category;
}
Action<IServiceLocator, string> ServiceLogManager.ISetupRegistration.DefaultServiceRegistrar
{
get { return (locator, name) => ServiceLogManager.RegisterInstance<ISPDeveloperServiceLog>(this, locator, name); }
}
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <param name="serviceType">An object that specifies the type of service object to get.</param>
/// <returns>
/// A service object of type <paramref name="serviceType"/>.
/// -or-
/// null if there is no service object of type <paramref name="serviceType"/>.
/// </returns>
public object GetService(Type serviceType) { throw new NotImplementedException(); }
// get
/// <summary>
/// Gets the name.
/// </summary>
public string Name
{
get { return AreaName + "/" + Category; }
}
/// <summary>
/// Gets the specified name.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public IServiceLog Get(string name)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
return new SPServiceLog(Log, EventID, AreaName, Name);
}
/// <summary>
/// Gets the specified name.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public IServiceLog Get(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
return new SPServiceLog(Log, EventID, AreaName, type.Name);
}
// log
/// <summary>
/// Writes the specified level.
/// </summary>
/// <param name="level">The level.</param>
/// <param name="ex">The ex.</param>
/// <param name="s">The s.</param>
public void Write(ServiceLog.LogLevel level, Exception ex, string s)
{
if (Log == null)
throw new NullReferenceException("Log");
if (ex == null)
switch (level)
{
case ServiceLog.LogLevel.Fatal: Log.TraceToDeveloper(s, EventID, TraceSeverity.Unexpected, Name); return;
case ServiceLog.LogLevel.Error: Log.TraceToDeveloper(s, EventID, TraceSeverity.High, Name); return;
case ServiceLog.LogLevel.Warning: Log.TraceToDeveloper(s, EventID, TraceSeverity.Medium, Name); return;
case ServiceLog.LogLevel.Information: Log.TraceToDeveloper(s, EventID, TraceSeverity.Monitorable, Name); return;
case ServiceLog.LogLevel.Debug: Log.TraceToDeveloper(s, EventID, TraceSeverity.Verbose, Name); return;
default: return;
}
else
switch (level)
{
case ServiceLog.LogLevel.Fatal: Log.TraceToDeveloper(ex, s, EventID, TraceSeverity.Unexpected, Name); return;
case ServiceLog.LogLevel.Error: Log.TraceToDeveloper(ex, s, EventID, TraceSeverity.High, Name); return;
case ServiceLog.LogLevel.Warning: Log.TraceToDeveloper(ex, s, EventID, TraceSeverity.Medium, Name); return;
case ServiceLog.LogLevel.Information: Log.TraceToDeveloper(ex, s, EventID, TraceSeverity.Monitorable, Name); return;
case ServiceLog.LogLevel.Debug: Log.TraceToDeveloper(ex, s, EventID, TraceSeverity.Verbose, Name); return;
default: return;
}
}
#region Domain-specific
/// <summary>
/// Gets the log.
/// </summary>
public ILogger Log { get; private set; }
/// <summary>
/// Gets the event ID.
/// </summary>
public int EventID { get; private set; }
/// <summary>
/// Gets the name of the area.
/// </summary>
/// <value>
/// The name of the area.
/// </value>
public string AreaName { get; private set; }
/// <summary>
/// Gets the category.
/// </summary>
public string Category { get; private set; }
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Content;
namespace XNA3
{
/// <summary>
/// This is a game component that implements IUpdateable.
/// </summary>
public class BossZombie : Microsoft.Xna.Framework.DrawableGameComponent
{
protected Texture2D texture;
protected Rectangle spriteRectangle;
protected Vector2 position;
protected Vector2 velocity;
float rotation;
protected const int PLAYERWIDTH = 100;
protected const int PLAYERHEIGHT = 100;
protected const int speed = 4;
protected Rectangle screenBounds;
protected bool show = true;
Random random;
Survivor survivor;
//MouseComponent myMouse;
public BossZombie(Game game, ref Texture2D theTexture, ref Survivor s)
: base(game)
{
// TODO: Construct any child components here
texture = theTexture;
position = new Vector2();
random = new Random(this.GetHashCode());
survivor = s;
spriteRectangle = new Rectangle(0, 0, PLAYERWIDTH, PLAYERHEIGHT);
screenBounds = new Rectangle(0, 0, Game.Window.ClientBounds.Width, Game.Window.ClientBounds.Height);
//myMouse = mouse;
}
public void PutinStartPosition(int x, int y)
{
position.X = x;
position.Y = y;
}
public void PutonRandomWall()
{
int wall = random.Next(4);
if (wall == 0)
PutRandomNorthWall();
else if (wall == 1)
PutRandomSouthWall();
else if (wall == 2)
PutRandomEastWall();
else if (wall == 3)
PutRandomWestWall();
}
public void PutinRandomPosition()
{
int x = random.Next(Game.Window.ClientBounds.Width - PLAYERWIDTH);
int y = random.Next(Game.Window.ClientBounds.Height - PLAYERHEIGHT);
position.X = x;
position.Y = y;
}
public void PutRandomNorthWall()
{
int x = random.Next(Game.Window.ClientBounds.Width - PLAYERWIDTH);
int y = 0;
position.X = x;
position.Y = y;
}
public void PutRandomSouthWall()
{
int x = random.Next(Game.Window.ClientBounds.Width - PLAYERWIDTH);
int y = Game.Window.ClientBounds.Height - PLAYERHEIGHT;
position.X = x;
position.Y = y;
}
public void PutRandomEastWall()
{
int x = Game.Window.ClientBounds.Width - PLAYERWIDTH;
int y = random.Next(Game.Window.ClientBounds.Height - PLAYERHEIGHT);
position.X = x;
position.Y = y;
}
public void PutRandomWestWall()
{
int x = 0;
int y = random.Next(Game.Window.ClientBounds.Height - PLAYERHEIGHT);
position.X = x;
position.Y = y;
}
public void setPos(BossZombie s)
{
position.X = s.position.X;
position.Y = s.position.Y;
}
/// <summary>
/// Allows the game component to perform any initialization it needs to before starting
/// to run. This is where it can query for any required services and load content.
/// </summary>
public override void Initialize()
{
// TODO: Add your initialization code here
random = new Random(this.GetHashCode());
base.Initialize();
}
/// <summary>
/// Allows the game component to update itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public override void Update(GameTime gameTime)
{
// TODO: Add your update code here
if(show)
{
float XDistance = position.X - survivor.getPosition().X;
float YDistance = position.Y - survivor.getPosition().Y;
rotation = (float)Math.Atan2(YDistance, XDistance);
double angle = Math.Atan2(((double)(survivor.getPosition().Y - position.Y)), (double)(survivor.getPosition().X - position.X));
velocity = new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle));
velocity.X = velocity.X * speed;
velocity.Y = velocity.Y * speed;
position += velocity;
}
base.Update(gameTime);
}
public override void Draw(GameTime gameTime)
{
//get current sprite batch
SpriteBatch sBatch = (SpriteBatch)Game.Services.GetService(typeof(SpriteBatch));
//Draw the survivor
if (show)
{
//Draw the sprite with required rotation and origin (centre of rotation) set to the centre of the sprite
sBatch.Draw(texture, position, spriteRectangle, Color.White, rotation, new Vector2(texture.Width / 2, texture.Height / 2), 1, SpriteEffects.None, 0);
}
base.Draw(gameTime);
}
public Rectangle GetBounds()
{
return new Rectangle((int)position.X, (int)position.Y, PLAYERWIDTH, PLAYERHEIGHT);
}
public bool CheckCollision(Rectangle rect)
{
Rectangle spriterect = new Rectangle((int)position.X, (int)position.Y, PLAYERWIDTH, PLAYERHEIGHT);
return spriterect.Intersects(rect);
}
public void Show()
{
show = true;
}
public void Hide()
{
show = false;
}
public void goAway()
{
position.X = 5000;
position.Y = 5000;
Hide();
}
public Vector2 getPosition()
{
return position;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Windows;
using System.Windows.Threading;
using StructureMap;
using TypeVisualiser.Messaging;
using TypeVisualiser.Model;
using TypeVisualiser.Model.Persistence;
using TypeVisualiser.Properties;
using TypeVisualiser.Startup;
using TypeVisualiser.UI.Views;
using TypeVisualiser.UI.WpfUtilities;
namespace TypeVisualiser.UI
{
public class ViewportController : TypeVisualiserControllerBase, IDiagramController, IDiagramCommandsNeedsRefactor
{
private readonly ObservableCollection<DiagramElement> diagramElements = new ObservableCollection<DiagramElement>();
private bool clean;
private IVisualisableTypeWithAssociations currentSubject;
private IContainer doNotUseFactory;
private ClassUmlDrawingEngine drawingEngine;
private ViewportControllerFilter filter;
private bool hideBackground;
private Diagram hostDiagram;
private DiagramElement subjectDiagramElement;
public ViewportController(IContainer factory)
{
this.doNotUseFactory = factory;
}
/// <summary>
/// Raised when the diagram has finished loading and positioning all diagram elements.
/// </summary>
public event EventHandler DiagramLoaded;
/// <summary>
/// Raised when data bound objects have changed that affect the overall size of the diagram.
/// This signals the view to recalculate the canvas size.
/// </summary>
public event EventHandler ExpandCanvasRequested;
/// <summary>
/// Gets the diagram caption to appear in the diagram tab.
/// </summary>
public string DiagramCaption
{
get { return Subject != null ? Subject.Name : "[New]"; }
}
public ObservableCollection<DiagramElement> DiagramElements
{
get { return this.diagramElements; }
}
/// <summary>
/// Gets the full name of the diagram to appear as the tool tip for the diagram tab.
/// </summary>
/// <value>
/// The full name of the diagram.
/// </value>
public string DiagramFullName
{
get { return Subject != null ? Subject.AssemblyQualifiedName : string.Empty; }
}
/// <summary>
/// A unique identifier for this diagram instance.
/// </summary>
public Guid DiagramId { get; set; }
public bool HideBackground
{
get { return this.hideBackground; }
set
{
if (this.hideBackground != value)
{
this.hideBackground = value;
VerifyPropertyName("HideBackground");
RaisePropertyChanged("HideBackground");
}
}
}
public IVisualisableTypeWithAssociations Subject
{
get { return this.currentSubject; }
private set
{
if (this.currentSubject != value)
{
this.currentSubject = value;
VerifyPropertyName("Subject");
OnMySubjectChanged();
RaisePropertyChanged("Subject");
}
}
}
public DiagramElement SubjectDiagramElement
{
get { return this.subjectDiagramElement; }
}
protected IContainer Factory
{
get { return this.doNotUseFactory ?? (this.doNotUseFactory = IoC.Default); }
}
private static bool IsLoading
{
get { return ShellController.Current.IsLoading; }
}
public static bool AddToTrivialListCanExecute(object parameter)
{
return !IsLoading && parameter is Association && !(parameter is SubjectAssociation);
}
public static bool AnnotateCanExecute()
{
return true;
}
public static bool NavigateToAssociationCanExecute(object parameter)
{
return !IsLoading && parameter != null && !(parameter is IVisualisableTypeWithAssociations);
}
public static bool ShowAllAssociationsCanExecute()
{
return !IsLoading;
}
public static bool TemporarilyHideAssociationCanExecute(object parameter)
{
var type = parameter as Association;
return !IsLoading && type != null && !(type is SubjectAssociation);
}
public override void Cleanup()
{
if (this.clean)
{
return;
}
this.clean = true;
DiagramElements.ToList().ForEach(x => x.Cleanup());
DiagramElements.Clear();
this.filter.Clear();
Messenger.Send(new CloseDiagramMessage(DiagramId));
base.Cleanup();
}
/// <summary>
/// Activates the diagram after it has been in the background of the tab control and now has been selected by the user.
/// </summary>
public void ActivateDiagram()
{
if (this.filter == null)
{
return;
}
this.filter.ApplyTypeFilter(this.currentSubject);
}
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "Multi-CLR Language not needed")]
public void AddAnnotation(Point where, AnnotationData annotation = null)
{
if (where == default(Point))
{
return;
}
if (annotation == null)
{
annotation = new AnnotationData();
}
annotation.Text = EditAnnotationText(annotation);
if (string.IsNullOrWhiteSpace(annotation.Text))
{
return;
}
var diagramElement = new DiagramElement(DiagramId, annotation) { TopLeft = where };
DiagramElements.Add(diagramElement);
}
public void AddToTrivialList(Association association)
{
if (association == null)
{
throw new ArgumentNullResourceException("association", Resources.General_Given_Parameter_Cannot_Be_Null);
}
this.Factory.GetInstance<ITrivialFilter>().AddToTrivialTypeList(association.AssociatedTo);
this.filter.ApplyTypeFilter(this.currentSubject);
}
/// <summary>
/// Assigns the diagram data.
/// This is the main entry point to display something into the diagram visual tree.
/// </summary>
/// <param name="bindableDiagramData">The data to load into the diagram visual.</param>
public void AssignDiagramData(object bindableDiagramData)
{
var subject = bindableDiagramData as IVisualisableTypeWithAssociations;
if (subject == null)
{
throw new InvalidOperationException("Code Error: Invalid type given to Viewport Controller: " + bindableDiagramData);
}
Subject = subject;
Subject.DiscoverSecondaryAssociationsInModel(); // This enables lines on the diagram other than those involving the subject.
DiagramElements.Clear();
this.drawingEngine = new ClassUmlDrawingEngine(DiagramId, subject);
foreach (DiagramElement element in this.drawingEngine.DrawAllBoxes())
{
DiagramElements.Add(element);
}
}
/// <summary>
/// Clears all diagram visual elements.
/// </summary>
public void Clear()
{
Subject = null;
this.subjectDiagramElement = null;
this.drawingEngine = null;
DiagramElements.ToList().ForEach(x => x.Cleanup());
DiagramElements.Clear();
}
public DiagramElement DeleteAnnotation(AnnotationData annotation)
{
DiagramElement found = DiagramElements.FirstOrDefault(x => x.DiagramContent is AnnotationData && ((AnnotationData)x.DiagramContent).Id == annotation.Id);
if (found != null)
{
DiagramElements.Remove(found);
return found;
}
return null;
}
public void EditAnnotation(AnnotationData annotation)
{
if (annotation == null)
{
throw new ArgumentNullResourceException("annotation", Resources.General_Given_Parameter_Cannot_Be_Null);
}
annotation.Text = EditAnnotationText(annotation);
if (string.IsNullOrWhiteSpace(annotation.Text))
{
DeleteAnnotation(annotation);
}
}
public IPersistentFileData GatherPersistentData()
{
var canvasLayoutData = new CanvasLayoutData();
foreach (DiagramElement element in DiagramElements)
{
if (Attribute.GetCustomAttribute(element.DiagramContent.GetType(), typeof(PersistentAttribute)) == null)
{
// Only Diagram Content that is decorated with Persistent will get saved into the Layout collection.
continue;
}
var layoutData = new TypeLayoutData { ContentType = element.DiagramContent.GetType().FullName, TopLeft = element.TopLeft, Id = element.DiagramContent.Id, Visible = element.Show, };
var diagramContent = element.DiagramContent as AnnotationData;
if (diagramContent != null)
{
layoutData.Data = diagramContent.Text;
}
canvasLayoutData.Types.Add(layoutData);
}
var saveData = new TypeVisualiserLayoutFile
{
CanvasLayout = canvasLayoutData,
Subject = (VisualisableTypeSubjectData)Subject.ExtractPersistentData(),
AssemblyFullName = Subject.AssemblyFullName,
AssemblyFileName = Subject.AssemblyFileName,
FileVersion = GetType().Assembly.GetName().Version.ToString(),
};
saveData.AssemblyFileName = saveData.Subject.AssemblyFileName ?? GetType().Assembly.Location;
return saveData;
}
public void HideSecondaryAssociations()
{
this.filter.ApplyTypeFilter(this.currentSubject);
}
public void HideSystemTypes()
{
this.filter.ApplyTypeFilter(this.currentSubject);
}
public void HideTrivialTypes()
{
this.filter.ApplyTypeFilter(this.currentSubject);
}
/// <summary>
/// Loads the diagram data from file after the subject has already been set by <see cref="AssignDiagramData"/>.
/// At this stage the diagram has already been loaded and is displayed on screen.
/// This method ensures all diagram elements have been positioned where the file specifies their co-ordinates.
/// Also will provide feedback on any mismatches, ie the type has changed and there are more or less associations.
/// </summary>
/// <param name="deserializedDataFile">The deserialised data file.</param>
public void LoadDiagramDataFromFile(object deserializedDataFile)
{
var data = deserializedDataFile as TypeVisualiserLayoutFile;
if (data == null)
{
throw new InvalidOperationException("Code Error: Attempt to load data from a type which is not an instance of Type Visualiser Layout File.");
}
var typesNoLongerInDiagram = new List<VisualisableTypeData>();
foreach (TypeLayoutData layoutData in data.CanvasLayout.Types)
{
// Deal with annotations first - these have not been loaded by setting the subject.
if (layoutData.ContentType == typeof(AnnotationData).FullName)
{
var annotation = new AnnotationData { Id = layoutData.Id, Text = layoutData.Data, };
var annotationElement = new DiagramElement(DiagramId, annotation) { Show = layoutData.Visible, TopLeft = layoutData.TopLeft };
DiagramElements.Add(annotationElement);
continue;
}
DiagramElement element = DiagramElements.FirstOrDefault(x => x.DiagramContent.Id == layoutData.Id);
if (element == null)
{
VisualisableTypeData type = FindTypeInFile(data, layoutData.Id);
if (type == null)
{
throw new InvalidOperationException("Code error: there is a layout data element without a matching association. " + layoutData.Id);
}
typesNoLongerInDiagram.Add(type);
continue;
}
element.TopLeft = layoutData.TopLeft;
element.Show = layoutData.Visible;
}
RaiseExpandCanvasRequested();
if (typesNoLongerInDiagram.Any())
{
UserPrompt.Show(Resources.ViewportController_Error_in_diagram_file,
Resources.ViewportController_Some_types_are_not_in_assembly_anymore + string.Join(", ", typesNoLongerInDiagram.Select(x => x.Name)));
}
}
/// <summary>
/// Begins the navigating to the chosen type asynchronously.
/// Called by the view.
/// </summary>
/// <param name="association">The association.</param>
public void NavigateToAssociation(IVisualisableType association)
{
// Notify the File Manager that a new type needs to be loaded.
Messenger.Send(new NavigateToDiagramAssociationMessage(DiagramId, association));
}
/// <summary>
/// Positions the diagram elements. Is called by the View when all elements have been loaded onto the canvas.
/// </summary>
public void PositionDiagramElements()
{
// It is invalid to invoke this when lines have already been drawn.
if (DiagramElements.Any(x => x.DiagramContent is ConnectionLine))
{
throw new InvalidOperationException("Code error: it is invalid to call View Loaded twice for one diagram.");
}
// By default the view will have loaded all visual controls for the diagram elements and positioned them at 0,0. All Actual width and height properties are now set.
this.drawingEngine.PositionMainSubject(this.hostDiagram);
this.drawingEngine.PositionAllOtherAssociations(DiagramElements);
// This needs to be queued to allow the expand canvas to fire and reposition all controls in positive space. After that then connect them with lines.
this.filter = this.Factory.GetInstance<ViewportControllerFilter>();
this.filter.Dispatcher = this.Dispatcher;
Dispatcher.BeginInvoke(() =>
{
var secondaryElements = DrawConnectingLines(false);
this.filter.SecondaryAssociationElements = secondaryElements;
this.filter.DiagramElements = DiagramElements;
this.filter.ApplyTypeFilter(this.currentSubject);
EventHandler handler = DiagramLoaded; // intended for the ShellController
if (handler != null)
{
handler(this.hostDiagram, EventArgs.Empty);
}
},
DispatcherPriority.ContextIdle);
}
private Dictionary<string, DiagramElement> DrawConnectingLines(bool redraw)
{
if (redraw)
{
// First remove the existing lines from the Diagram Element collection.
foreach (var element in DiagramElements.Where(e => !(e.DiagramContent is Association)).ToList())
{
DiagramElements.Remove(element);
}
}
Dictionary<string, DiagramElement> secondaryElements;
IEnumerable<DiagramElement> drawnElements = this.drawingEngine.DrawConnectingLines(
DiagramElements,
this.filter.ShouldThisSecondaryElementBeVisible,
out secondaryElements);
drawnElements.ToList().ForEach(e => DiagramElements.Add(e));
return secondaryElements;
}
public void DrawConnectingLines()
{
if (DiagramElements.Any())
{
// Otherwise nothing to redraw
DrawConnectingLines(true);
}
}
public void Refresh(IFileManager fileManager)
{
if (fileManager == null)
{
throw new ArgumentNullResourceException("fileManager", Resources.General_Given_Parameter_Cannot_Be_Null);
}
Type t = fileManager.RefreshType(Subject.AssemblyQualifiedName, Subject.AssemblyFileName);
IVisualisableTypeWithAssociations subject = fileManager.RefreshSubject(t);
Clear();
AssignDiagramData(subject);
Dispatcher.BeginInvoke(() =>
{
PositionDiagramElements();
RaiseExpandCanvasRequested();
},
DispatcherPriority.ContextIdle);
}
/// <summary>
/// Gives a reference of the diagram container to the controller. This must be called prior to loading any content in the diagram.
/// Should not be used externally, the diagram constructor must be the only caller of this.
/// </summary>
/// <param name="diagram">The new host diagram.</param>
public void SetHostDiagram(Diagram diagram)
{
if (this.hostDiagram != null)
{
throw new InvalidOperationException("Code Error: You cannot call Set Host Diagram twice.");
}
this.hostDiagram = diagram;
}
public void ShowAllAssociations()
{
this.filter.ApplyTypeFilter(this.currentSubject);
}
public void TemporarilyHideAssociation(Association association)
{
DiagramElement diagramElement = DiagramElements.FirstOrDefault(x => x.DiagramContent.Equals(association));
if (diagramElement != null)
{
diagramElement.Show = false;
}
}
internal void ShowLineDetails(DiagramElement arrowheadOrLine)
{
FieldAssociation pointingAtAssociation = ClassDiagramSearchTool.FindAssociationTarget(arrowheadOrLine);
if (pointingAtAssociation == null)
{
return;
}
new UsageDialog().ShowDialog(Resources.ApplicationName, Subject.Name, Subject.Modifiers.TypeTextName, pointingAtAssociation);
}
private static string EditAnnotationText(AnnotationData annotation)
{
var inputBox = new AnnotationInputBox { InputText = annotation.Text };
inputBox.ShowDialog();
if (string.IsNullOrWhiteSpace(inputBox.InputText))
{
return null;
}
return inputBox.InputText;
}
private static VisualisableTypeData FindTypeInFile(TypeVisualiserLayoutFile data, string id)
{
if (data.Subject.Id == id)
{
return data.Subject;
}
if (data.Subject.Parent != null && data.Subject.Parent.AssociatedTo.Id == id)
{
return data.Subject;
}
AssociationData type = data.Subject.Associations.FirstOrDefault(x => x.AssociatedTo.Id == id);
if (type != null)
{
return type.AssociatedTo;
}
type = data.Subject.Implements.FirstOrDefault(x => x.AssociatedTo.Id == id);
if (type != null)
{
return type.AssociatedTo;
}
return null;
}
private void OnMySubjectChanged()
{
if (Subject != null)
{
Factory.GetInstance<IDiagramDimensions>().Initialise(Subject.FilteredAssociations.Count(), true);
}
}
private void RaiseExpandCanvasRequested()
{
// Expand canvas needs to be manually triggered when navigating to a type on an open diagram. When a new tab opens expand canvas is triggered by view events otherwise.
Dispatcher.BeginInvoke(() =>
{
EventHandler handler = ExpandCanvasRequested;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
},
DispatcherPriority.ContextIdle);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="OutOfProcSessionStateStore.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.SessionState {
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.Configuration;
using System.Web.Management;
using System.Web.Security.Cryptography;
using System.Web.Util;
internal sealed class OutOfProcSessionStateStore : SessionStateStoreProviderBase {
internal static readonly IntPtr INVALID_SOCKET = UnsafeNativeMethods.INVALID_HANDLE_VALUE;
internal static readonly int WHIDBEY_MAJOR_VERSION = 2;
internal const int STATE_NETWORK_TIMEOUT_DEFAULT = 10; // in sec
static string s_uribase;
static int s_networkTimeout;
#pragma warning disable 0649
static ReadWriteSpinLock s_lock;
#pragma warning restore 0649
static bool s_oneTimeInited;
static StateServerPartitionInfo s_singlePartitionInfo;
static PartitionManager s_partitionManager;
static bool s_usePartition;
static EventHandler s_onAppDomainUnload;
// We keep these info because we don't want to hold on to the config object.
static string s_configPartitionResolverType;
static string s_configStateConnectionString;
static string s_configStateConnectionStringFileName;
static int s_configStateConnectionStringLineNumber;
static bool s_configCompressionEnabled;
// Per request info
IPartitionResolver _partitionResolver;
StateServerPartitionInfo _partitionInfo;
internal override void Initialize(string name, NameValueCollection config, IPartitionResolver partitionResolver) {
_partitionResolver = partitionResolver;
Initialize(name, config);
}
public override void Initialize(string name, NameValueCollection config) {
if (String.IsNullOrEmpty(name))
name = "State Server Session State Provider";
base.Initialize(name, config);
if (!s_oneTimeInited) {
s_lock.AcquireWriterLock();
try {
if (!s_oneTimeInited) {
OneTimeInit();
}
}
finally {
s_lock.ReleaseWriterLock();
}
}
if (!s_usePartition) {
// For single partition, the connection info won't change from request to request
Debug.Assert(s_partitionManager == null);
_partitionInfo = s_singlePartitionInfo;
}
}
void OneTimeInit() {
SessionStateSection config = RuntimeConfig.GetAppConfig().SessionState;
s_configPartitionResolverType = config.PartitionResolverType;
s_configStateConnectionString = config.StateConnectionString;
s_configStateConnectionStringFileName = config.ElementInformation.Properties["stateConnectionString"].Source;
s_configStateConnectionStringLineNumber = config.ElementInformation.Properties["stateConnectionString"].LineNumber;
s_configCompressionEnabled = config.CompressionEnabled;
if (_partitionResolver == null) {
String stateConnectionString = config.StateConnectionString;
SessionStateModule.ReadConnectionString(config, ref stateConnectionString, "stateConnectionString");
s_singlePartitionInfo = (StateServerPartitionInfo)CreatePartitionInfo(stateConnectionString);
}
else {
s_usePartition = true;
s_partitionManager = new PartitionManager(new CreatePartitionInfo(CreatePartitionInfo));
}
s_networkTimeout = (int)config.StateNetworkTimeout.TotalSeconds;
string appId = HttpRuntime.AppDomainAppId;
string idHash = Convert.ToBase64String(CryptoUtil.ComputeSHA256Hash(Encoding.UTF8.GetBytes(appId)));
// Make sure that we have a absolute URI, some hosts(Cassini) don't provide this.
if (appId.StartsWith("/", StringComparison.Ordinal)) {
s_uribase = appId + "(" + idHash + ")/";
}
else {
s_uribase = "/" + appId + "(" + idHash + ")/";
}
// We only need to do this in one instance
s_onAppDomainUnload = new EventHandler(OnAppDomainUnload);
Thread.GetDomain().DomainUnload += s_onAppDomainUnload;
s_oneTimeInited = true;
}
void OnAppDomainUnload(Object unusedObject, EventArgs unusedEventArgs) {
Debug.Trace("OutOfProcSessionStateStore", "OnAppDomainUnload called");
Thread.GetDomain().DomainUnload -= s_onAppDomainUnload;
if (_partitionResolver == null) {
if (s_singlePartitionInfo != null) {
s_singlePartitionInfo.Dispose();
}
}
else {
if (s_partitionManager != null) {
s_partitionManager.Dispose();
}
}
}
internal IPartitionInfo CreatePartitionInfo(string stateConnectionString) {
string server;
bool serverIsIpv6NumericAddress;
int port;
int hr;
try {
ParseStateConnectionString(stateConnectionString, out server, out serverIsIpv6NumericAddress, out port);
// At v1, we won't accept server name that has non-ascii characters
for (int i = 0; i < server.Length; ++i) {
if (server[i] > 0x7F) {
throw new ArgumentException("stateConnectionString");
}
}
}
catch {
if (s_usePartition) {
throw new HttpException(
SR.GetString(SR.Error_parsing_state_server_partition_resolver_string, s_configPartitionResolverType));
}
else {
throw new ConfigurationErrorsException(
SR.GetString(SR.Invalid_value_for_sessionstate_stateConnectionString, s_configStateConnectionString),
s_configStateConnectionStringFileName, s_configStateConnectionStringLineNumber);
}
}
hr = UnsafeNativeMethods.SessionNDConnectToService(server);
if (hr != 0) {
throw CreateConnectionException(server, port, hr);
}
return new StateServerPartitionInfo(
new ResourcePool(new TimeSpan(0, 0, 5), int.MaxValue),
server: server,
serverIsIPv6NumericAddress: serverIsIpv6NumericAddress,
port: port);
}
private static Regex _ipv6ConnectionStringFormat = new Regex(@"^\[(?<ipv6Address>.*)\]:(?<port>\d*)$");
[SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = @"The exception is never bubbled up to the user.")]
internal static void ParseStateConnectionString(string stateConnectionString, out string server, out bool serverIsIPv6NumericAddress, out int port) {
/*
* stateConnection string has the following format:
*
* "tcpip=<server>:<port>"
* "tcpip=[IPv6-address]:port", per RFC 3986, Sec. 3.2.2
*/
// chop off the "tcpip=" part
if (!stateConnectionString.StartsWith("tcpip=", StringComparison.Ordinal)) {
throw new ArgumentException("stateConnectionString");
}
stateConnectionString = stateConnectionString.Substring("tcpip=".Length);
// is this an IPv6 address?
Match ipv6RegexMatch = _ipv6ConnectionStringFormat.Match(stateConnectionString);
if (ipv6RegexMatch != null && ipv6RegexMatch.Success) {
string ipv6AddressString = ipv6RegexMatch.Groups["ipv6Address"].Value;
IPAddress ipv6Address = IPAddress.Parse(ipv6AddressString);
if (ipv6Address.AddressFamily != AddressFamily.InterNetworkV6) {
throw new ArgumentException("stateConnectionString");
}
server = ipv6AddressString;
serverIsIPv6NumericAddress = true;
port = UInt16.Parse(ipv6RegexMatch.Groups["port"].Value, CultureInfo.InvariantCulture);
return;
}
// not an IPv6 address; assume "host:port"
string[] parts = stateConnectionString.Split(':');
if (parts.Length != 2) {
throw new ArgumentException("stateConnectionString");
}
server = parts[0];
serverIsIPv6NumericAddress = false;
port = UInt16.Parse(parts[1], CultureInfo.InvariantCulture);
}
internal static HttpException CreateConnectionException(string server, int port, int hr) {
if (s_usePartition) {
return new HttpException(
SR.GetString(SR.Cant_make_session_request_partition_resolver,
s_configPartitionResolverType, server, port.ToString(CultureInfo.InvariantCulture)), hr);
}
else {
return new HttpException(
SR.GetString(SR.Cant_make_session_request), hr);
}
}
public override bool SetItemExpireCallback(SessionStateItemExpireCallback expireCallback) {
return false;
}
public override void Dispose() {
}
public override void InitializeRequest(HttpContext context) {
if (s_usePartition) {
// For multiple partition case, the connection info can change from request to request
Debug.Assert(_partitionResolver != null);
_partitionInfo = null;
}
}
void MakeRequest(
UnsafeNativeMethods.StateProtocolVerb verb,
String id,
UnsafeNativeMethods.StateProtocolExclusive exclusiveAccess,
int extraFlags,
int timeout,
int lockCookie,
byte[] buf,
int cb,
int networkTimeout,
out UnsafeNativeMethods.SessionNDMakeRequestResults results) {
int hr;
string uri;
OutOfProcConnection conn = null;
HandleRef socketHandle;
bool checkVersion = false;
Debug.Assert(timeout <= SessionStateModule.MAX_CACHE_BASED_TIMEOUT_MINUTES, "item.Timeout <= SessionStateModule.MAX_CACHE_BASED_TIMEOUT_MINUTES");
SessionIDManager.CheckIdLength(id, true /* throwOnFail */);
if (_partitionInfo == null) {
Debug.Assert(s_partitionManager != null);
Debug.Assert(_partitionResolver != null);
_partitionInfo = (StateServerPartitionInfo)s_partitionManager.GetPartition(_partitionResolver, id);
// If its still null, we give up
if (_partitionInfo == null) {
throw new HttpException(SR.GetString(SR.Bad_partition_resolver_connection_string, "PartitionManager"));
}
}
// Need to make sure we dispose the connection if anything goes wrong
try {
conn = (OutOfProcConnection)_partitionInfo.RetrieveResource();
if (conn != null) {
socketHandle = new HandleRef(this, conn._socketHandle.Handle);
}
else {
socketHandle = new HandleRef(this, INVALID_SOCKET);
}
if (_partitionInfo.StateServerVersion == -1) {
// We don't need locking here because it's okay to have two
// requests initializing s_stateServerVersion.
checkVersion = true;
}
Debug.Trace("OutOfProcSessionStateStoreMakeRequest",
"Calling MakeRequest, " +
"socket=" + (IntPtr)socketHandle.Handle +
"verb=" + verb +
" id=" + id +
" exclusiveAccess=" + exclusiveAccess +
" timeout=" + timeout +
" buf=" + ((buf != null) ? "non-null" : "null") +
" cb=" + cb +
" checkVersion=" + checkVersion +
" extraFlags=" + extraFlags);
// Have to UrlEncode id because it may contain non-URL-safe characters
uri = HttpUtility.UrlEncode(s_uribase + id);
hr = UnsafeNativeMethods.SessionNDMakeRequest(
socketHandle, _partitionInfo.Server, _partitionInfo.Port, _partitionInfo.ServerIsIPv6NumericAddress /* forceIPv6 */, networkTimeout, verb, uri,
exclusiveAccess, extraFlags, timeout, lockCookie,
buf, cb, checkVersion, out results);
Debug.Trace("OutOfProcSessionStateStoreMakeRequest", "MakeRequest returned: " +
"hr=" + hr +
" socket=" + (IntPtr)results.socket +
" httpstatus=" + results.httpStatus +
" timeout=" + results.timeout +
" contentlength=" + results.contentLength +
" uri=" + (IntPtr)results.content +
" lockCookie=" + results.lockCookie +
" lockDate=" + string.Format("{0:x}", results.lockDate) +
" lockAge=" + results.lockAge +
" stateServerMajVer=" + results.stateServerMajVer +
" actionFlags=" + results.actionFlags);
if (conn != null) {
if (results.socket == INVALID_SOCKET) {
conn.Detach();
conn = null;
}
else if (results.socket != socketHandle.Handle) {
// The original socket is no good. We've got a new one.
// Pleae note that EnsureConnected has closed the bad
// one already.
conn._socketHandle = new HandleRef(this, results.socket);
}
}
else if (results.socket != INVALID_SOCKET) {
conn = new OutOfProcConnection(results.socket);
}
if (conn != null) {
_partitionInfo.StoreResource(conn);
}
}
catch {
// We just need to dispose the connection if anything bad happened
if (conn != null) {
conn.Dispose();
}
throw;
}
if (hr != 0) {
HttpException e = CreateConnectionException(_partitionInfo.Server, _partitionInfo.Port, hr);
string phase = null;
switch (results.lastPhase) {
case (int)UnsafeNativeMethods.SessionNDMakeRequestPhase.Initialization:
phase = SR.GetString(SR.State_Server_detailed_error_phase0);
break;
case (int)UnsafeNativeMethods.SessionNDMakeRequestPhase.Connecting:
phase = SR.GetString(SR.State_Server_detailed_error_phase1);
break;
case (int)UnsafeNativeMethods.SessionNDMakeRequestPhase.SendingRequest:
phase = SR.GetString(SR.State_Server_detailed_error_phase2);
break;
case (int)UnsafeNativeMethods.SessionNDMakeRequestPhase.ReadingResponse:
phase = SR.GetString(SR.State_Server_detailed_error_phase3);
break;
default:
Debug.Assert(false, "Unknown results.lastPhase: " + results.lastPhase);
break;
}
WebBaseEvent.RaiseSystemEvent(SR.GetString(SR.State_Server_detailed_error,
phase,
"0x" + hr.ToString("X08", CultureInfo.InvariantCulture),
cb.ToString(CultureInfo.InvariantCulture)),
this, WebEventCodes.WebErrorOtherError, WebEventCodes.StateServerConnectionError, e);
throw e;
}
if (results.httpStatus == 400) {
if (s_usePartition) {
throw new HttpException(
SR.GetString(SR.Bad_state_server_request_partition_resolver,
s_configPartitionResolverType, _partitionInfo.Server, _partitionInfo.Port.ToString(CultureInfo.InvariantCulture)));
}
else {
throw new HttpException(
SR.GetString(SR.Bad_state_server_request));
}
}
if (checkVersion) {
_partitionInfo.StateServerVersion = results.stateServerMajVer;
if (_partitionInfo.StateServerVersion < WHIDBEY_MAJOR_VERSION) {
// We won't work with versions lower than Whidbey
if (s_usePartition) {
throw new HttpException(
SR.GetString(SR.Need_v2_State_Server_partition_resolver,
s_configPartitionResolverType, _partitionInfo.Server, _partitionInfo.Port.ToString(CultureInfo.InvariantCulture)));
}
else {
throw new HttpException(
SR.GetString(SR.Need_v2_State_Server));
}
}
}
}
[SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)]
internal SessionStateStoreData DoGet(HttpContext context,
String id,
UnsafeNativeMethods.StateProtocolExclusive exclusiveAccess,
out bool locked,
out TimeSpan lockAge,
out object lockId,
out SessionStateActions actionFlags) {
SessionStateStoreData item = null;
UnmanagedMemoryStream stream = null;
int contentLength;
UnsafeNativeMethods.SessionNDMakeRequestResults results;
// Set default return values
locked = false;
lockId = null;
lockAge = TimeSpan.Zero;
actionFlags = 0;
results.content = IntPtr.Zero;
try {
MakeRequest(UnsafeNativeMethods.StateProtocolVerb.GET,
id, exclusiveAccess, 0, 0, 0,
null, 0, s_networkTimeout, out results);
switch (results.httpStatus) {
case 200:
/* item found, deserialize it */
contentLength = results.contentLength;
if (contentLength > 0) {
try {
unsafe {
stream = new UnmanagedMemoryStream((byte*)results.content, contentLength);
}
item = SessionStateUtility.DeserializeStoreData(context, stream, s_configCompressionEnabled);
}
finally {
if(stream != null) {
stream.Close();
}
}
lockId = results.lockCookie;
actionFlags = (SessionStateActions) results.actionFlags;
}
break;
case 423:
/* state locked, return lock information */
if (0 <= results.lockAge) {
if (results.lockAge < Sec.ONE_YEAR) {
lockAge = new TimeSpan(0, 0, results.lockAge);
}
else {
lockAge = TimeSpan.Zero;
}
}
else {
DateTime now = DateTime.Now;
if (0 < results.lockDate && results.lockDate < now.Ticks) {
lockAge = now - new DateTime(results.lockDate);
}
else {
lockAge = TimeSpan.Zero;
}
}
locked = true;
lockId = results.lockCookie;
Debug.Assert((results.actionFlags & (int)SessionStateActions.InitializeItem) == 0,
"(results.actionFlags & (int)SessionStateActions.InitializeItem) == 0; uninitialized item cannot be locked");
break;
}
}
finally {
if (results.content != IntPtr.Zero) {
UnsafeNativeMethods.SessionNDFreeBody(new HandleRef(this, results.content));
}
}
return item;
}
public override SessionStateStoreData GetItem(HttpContext context,
String id,
out bool locked,
out TimeSpan lockAge,
out object lockId,
out SessionStateActions actionFlags) {
Debug.Trace("OutOfProcSessionStateStore", "Calling Get, id=" + id);
return DoGet(context, id, UnsafeNativeMethods.StateProtocolExclusive.NONE,
out locked, out lockAge, out lockId, out actionFlags);
}
public override SessionStateStoreData GetItemExclusive(HttpContext context,
String id,
out bool locked,
out TimeSpan lockAge,
out object lockId,
out SessionStateActions actionFlags) {
Debug.Trace("OutOfProcSessionStateStore", "Calling GetExlusive, id=" + id);
return DoGet(context, id, UnsafeNativeMethods.StateProtocolExclusive.ACQUIRE,
out locked, out lockAge, out lockId, out actionFlags);
}
public override void ReleaseItemExclusive(HttpContext context,
String id,
object lockId) {
Debug.Assert(lockId != null, "lockId != null");
UnsafeNativeMethods.SessionNDMakeRequestResults results;
int lockCookie = (int)lockId;
Debug.Trace("OutOfProcSessionStateStore", "Calling ReleaseExclusive, id=" + id);
MakeRequest(UnsafeNativeMethods.StateProtocolVerb.GET, id,
UnsafeNativeMethods.StateProtocolExclusive.RELEASE, 0, 0,
lockCookie, null, 0, s_networkTimeout, out results);
}
public override void SetAndReleaseItemExclusive(HttpContext context,
String id,
SessionStateStoreData item,
object lockId,
bool newItem) {
UnsafeNativeMethods.SessionNDMakeRequestResults results;
byte[] buf;
int length;
int lockCookie;
Debug.Assert(item.Items != null, "item.Items != null");
Debug.Assert(item.StaticObjects != null, "item.StaticObjects != null");
Debug.Trace("OutOfProcSessionStateStore", "Calling Set, id=" + id + " sessionItems=" + item.Items + " timeout=" + item.Timeout);
try {
SessionStateUtility.SerializeStoreData(item, 0, out buf, out length, s_configCompressionEnabled);
}
catch {
if (!newItem) {
((SessionStateStoreProviderBase)this).ReleaseItemExclusive(context, id, lockId);
}
throw;
}
// Save it to the store
if (lockId == null) {
lockCookie = 0;
}
else {
lockCookie = (int)lockId;
}
MakeRequest(UnsafeNativeMethods.StateProtocolVerb.PUT, id,
UnsafeNativeMethods.StateProtocolExclusive.NONE, 0, item.Timeout, lockCookie,
buf, length, s_networkTimeout, out results);
}
public override void RemoveItem(HttpContext context,
String id,
object lockId,
SessionStateStoreData item) {
Debug.Assert(lockId != null, "lockId != null");
Debug.Trace("OutOfProcSessionStateStore", "Calling Remove, id=" + id);
UnsafeNativeMethods.SessionNDMakeRequestResults results;
int lockCookie = (int)lockId;
MakeRequest(UnsafeNativeMethods.StateProtocolVerb.DELETE, id,
UnsafeNativeMethods.StateProtocolExclusive.NONE, 0, 0, lockCookie,
null, 0, s_networkTimeout, out results);
}
public override void ResetItemTimeout(HttpContext context, String id) {
UnsafeNativeMethods.SessionNDMakeRequestResults results;
Debug.Trace("OutOfProcSessionStateStore", "Calling ResetTimeout, id=" + id);
MakeRequest(UnsafeNativeMethods.StateProtocolVerb.HEAD, id,
UnsafeNativeMethods.StateProtocolExclusive.NONE, 0, 0, 0,
null, 0, s_networkTimeout, out results);
}
public override SessionStateStoreData CreateNewStoreData(HttpContext context, int timeout)
{
Debug.Assert(timeout <= SessionStateModule.MAX_CACHE_BASED_TIMEOUT_MINUTES, "item.Timeout <= SessionStateModule.MAX_CACHE_BASED_TIMEOUT_MINUTES");
return SessionStateUtility.CreateLegitStoreData(context, null, null, timeout);
}
public override void CreateUninitializedItem(HttpContext context, String id, int timeout) {
UnsafeNativeMethods.SessionNDMakeRequestResults results;
byte[] buf;
int length;
Debug.Trace("OutOfProcSessionStateStore", "Calling CreateUninitializedItem, id=" + id + " timeout=" + timeout);
// Create an empty item
SessionStateUtility.SerializeStoreData(CreateNewStoreData(context, timeout), 0, out buf, out length, s_configCompressionEnabled);
// Save it to the store
MakeRequest(UnsafeNativeMethods.StateProtocolVerb.PUT, id,
UnsafeNativeMethods.StateProtocolExclusive.NONE,
(int)SessionStateItemFlags.Uninitialized, timeout, 0,
buf, length, s_networkTimeout, out results);
}
// Called during EndRequest event
public override void EndRequest(HttpContext context) {
}
class StateServerPartitionInfo : PartitionInfo {
string _server;
bool _serverIsIPv6NumericAddress;
int _port;
int _stateServerVersion;
internal StateServerPartitionInfo(ResourcePool rpool, string server, bool serverIsIPv6NumericAddress, int port) : base(rpool) {
_server = server;
_serverIsIPv6NumericAddress = serverIsIPv6NumericAddress;
_port = port;
_stateServerVersion = -1;
Debug.Trace("PartitionInfo", "Created a new info, server=" + server + ", port=" + port);
}
internal string Server {
get { return _server; }
}
internal bool ServerIsIPv6NumericAddress {
get { return _serverIsIPv6NumericAddress; }
}
internal int Port {
get { return _port; }
}
internal int StateServerVersion {
get { return _stateServerVersion; }
set { _stateServerVersion = value; }
}
protected override string TracingPartitionString {
get {
// only add the brackets if the server is an IPv6 address, per the URI specification
string formatString = (ServerIsIPv6NumericAddress) ? "[{0}]:{1}" : "{0}:{1}";
return String.Format(CultureInfo.InvariantCulture, formatString, Server, Port);
}
}
}
class OutOfProcConnection : IDisposable {
internal HandleRef _socketHandle;
internal OutOfProcConnection(IntPtr socket) {
Debug.Assert(socket != OutOfProcSessionStateStore.INVALID_SOCKET,
"socket != OutOfProcSessionStateStore.INVALID_SOCKET");
_socketHandle = new HandleRef(this, socket);
PerfCounters.IncrementCounter(AppPerfCounter.SESSION_STATE_SERVER_CONNECTIONS);
}
~OutOfProcConnection() {
Dispose(false);
}
public void Dispose() {
Debug.Trace("ResourcePool", "Disposing OutOfProcConnection");
Dispose(true);
System.GC.SuppressFinalize(this);
}
private void Dispose(bool dummy) {
if (_socketHandle.Handle != OutOfProcSessionStateStore.INVALID_SOCKET) {
UnsafeNativeMethods.SessionNDCloseConnection(_socketHandle);
_socketHandle = new HandleRef(this, OutOfProcSessionStateStore.INVALID_SOCKET);
PerfCounters.DecrementCounter(AppPerfCounter.SESSION_STATE_SERVER_CONNECTIONS);
}
}
internal void Detach() {
_socketHandle = new HandleRef(this, OutOfProcSessionStateStore.INVALID_SOCKET);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Signum.Utilities;
#pragma warning disable CS8618 // Non-nullable field is uninitialized.
namespace Signum.Entities.DynamicQuery
{
[Serializable]
public abstract class BaseQueryRequest
{
public object QueryName { get; set; }
public List<Filter> Filters { get; set; }
public string QueryUrl { get; set; }
public override string ToString()
{
return "{0} {1}".FormatWith(GetType().Name, QueryName);
}
}
[Serializable]
public class QueryRequest : BaseQueryRequest
{
public bool GroupResults { get; set; }
public List<Column> Columns { get; set; }
public List<Order> Orders { get; set; }
public Pagination Pagination { get; set; }
public SystemTime? SystemTime { get; set; }
public List<CollectionElementToken> Multiplications()
{
HashSet<QueryToken> allTokens = new HashSet<QueryToken>(this.AllTokens());
return CollectionElementToken.GetElements(allTokens);
}
public List<QueryToken> AllTokens()
{
var allTokens = Columns.Select(a => a.Token).ToList();
if (Filters != null)
allTokens.AddRange(Filters.SelectMany(a => a.GetFilterConditions()).Select(a => a.Token));
if (Orders != null)
allTokens.AddRange(Orders.Select(a => a.Token));
return allTokens;
}
}
[DescriptionOptions(DescriptionOptions.Members), InTypeScript(true)]
public enum PaginationMode
{
All,
Firsts,
Paginate
}
[DescriptionOptions(DescriptionOptions.Members), InTypeScript(true)]
public enum SystemTimeMode
{
AsOf,
Between,
ContainedIn,
All
}
[DescriptionOptions(DescriptionOptions.Members)]
public enum SystemTimeProperty
{
SystemValidFrom,
SystemValidTo,
}
[Serializable]
public abstract class Pagination
{
public abstract PaginationMode GetMode();
public abstract int? GetElementsPerPage();
public abstract int? MaxElementIndex { get; }
[Serializable]
public class All : Pagination
{
public override int? MaxElementIndex
{
get { return null; }
}
public override PaginationMode GetMode()
{
return PaginationMode.All;
}
public override int? GetElementsPerPage()
{
return null;
}
}
[Serializable]
public class Firsts : Pagination
{
public static int DefaultTopElements = 20;
public Firsts(int topElements)
{
this.TopElements = topElements;
}
public int TopElements { get; private set; }
public override int? MaxElementIndex
{
get { return TopElements; }
}
public override PaginationMode GetMode()
{
return PaginationMode.Firsts;
}
public override int? GetElementsPerPage()
{
return TopElements;
}
}
[Serializable]
public class Paginate : Pagination
{
public static int DefaultElementsPerPage = 20;
public Paginate(int elementsPerPage, int currentPage = 1)
{
if (elementsPerPage <= 0)
throw new InvalidOperationException("elementsPerPage should be greater than zero");
if (currentPage <= 0)
throw new InvalidOperationException("currentPage should be greater than zero");
this.ElementsPerPage = elementsPerPage;
this.CurrentPage = currentPage;
}
public int ElementsPerPage { get; private set; }
public int CurrentPage { get; private set; }
public int StartElementIndex()
{
return (ElementsPerPage * (CurrentPage - 1)) + 1;
}
public int EndElementIndex(int rows)
{
return StartElementIndex() + rows - 1;
}
public int TotalPages(int totalElements)
{
return (totalElements + ElementsPerPage - 1) / ElementsPerPage; //Round up
}
public override int? MaxElementIndex
{
get { return (ElementsPerPage * (CurrentPage + 1)) - 1; }
}
public override PaginationMode GetMode()
{
return PaginationMode.Paginate;
}
public override int? GetElementsPerPage()
{
return ElementsPerPage;
}
public Paginate WithCurrentPage(int newPage)
{
return new Paginate(this.ElementsPerPage, newPage);
}
}
}
[Serializable]
public class QueryValueRequest : BaseQueryRequest
{
public QueryToken? ValueToken { get; set; }
public SystemTime? SystemTime { get; set; }
public List<CollectionElementToken> Multiplications
{
get
{
return CollectionElementToken.GetElements(Filters
.SelectMany(a => a.GetFilterConditions())
.Select(fc => fc.Token)
.PreAnd(ValueToken)
.NotNull()
.ToHashSet());
}
}
}
[Serializable]
public class UniqueEntityRequest : BaseQueryRequest
{
List<Order> orders;
public List<Order> Orders
{
get { return orders; }
set { orders = value; }
}
UniqueType uniqueType;
public UniqueType UniqueType
{
get { return uniqueType; }
set { uniqueType = value; }
}
public List<CollectionElementToken> Multiplications
{
get
{
var allTokens = Filters
.SelectMany(a => a.GetFilterConditions())
.Select(a => a.Token)
.Concat(Orders.Select(a => a.Token))
.ToHashSet();
return CollectionElementToken.GetElements(allTokens);
}
}
}
[Serializable]
public class QueryEntitiesRequest: BaseQueryRequest
{
List<Order> orders = new List<Order>();
public List<Order> Orders
{
get { return orders; }
set { orders = value; }
}
public List<CollectionElementToken> Multiplications
{
get
{
var allTokens = Filters.SelectMany(a=>a.GetFilterConditions()).Select(a => a.Token)
.Concat(Orders.Select(a => a.Token)).ToHashSet();
return CollectionElementToken.GetElements(allTokens);
}
}
public int? Count { get; set; }
public override string ToString() => QueryName.ToString()!;
}
[Serializable]
public class DQueryableRequest : BaseQueryRequest
{
List<Order> orders = new List<Order>();
public List<Order> Orders
{
get { return orders; }
set { orders = value; }
}
List<Column> columns = new List<Column>();
public List<Column> Columns
{
get { return columns; }
set { columns = value; }
}
public List<CollectionElementToken> Multiplications
{
get
{
HashSet<QueryToken> allTokens =
Filters.SelectMany(a => a.GetFilterConditions()).Select(a => a.Token)
.Concat(Columns.Select(a => a.Token))
.Concat(Orders.Select(a => a.Token)).ToHashSet();
return CollectionElementToken.GetElements(allTokens);
}
}
public int? Count { get; set; }
public override string ToString() => QueryName.ToString()!;
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Conn.Scheme.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Org.Apache.Http.Conn.Scheme
{
/// <summary>
/// <para>The default class for creating sockets.</para><para><para> </para><simplesectsep></simplesectsep><para>Michael Becke </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/scheme/PlainSocketFactory
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/scheme/PlainSocketFactory", AccessFlags = 49)]
public sealed partial class PlainSocketFactory : global::Org.Apache.Http.Conn.Scheme.ISocketFactory
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/conn/scheme/HostNameResolver;)V", AccessFlags = 1)]
public PlainSocketFactory(global::Org.Apache.Http.Conn.Scheme.IHostNameResolver nameResolver) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public PlainSocketFactory() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the singleton instance of this class. </para>
/// </summary>
/// <returns>
/// <para>the one and only plain socket factory </para>
/// </returns>
/// <java-name>
/// getSocketFactory
/// </java-name>
[Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/scheme/PlainSocketFactory;", AccessFlags = 9)]
public static global::Org.Apache.Http.Conn.Scheme.PlainSocketFactory GetSocketFactory() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Scheme.PlainSocketFactory);
}
/// <summary>
/// <para>Creates a new, unconnected socket. The socket should subsequently be passed to connectSocket.</para><para></para>
/// </summary>
/// <returns>
/// <para>a new socket</para>
/// </returns>
/// <java-name>
/// createSocket
/// </java-name>
[Dot42.DexImport("createSocket", "()Ljava/net/Socket;", AccessFlags = 1)]
public global::Java.Net.Socket CreateSocket() /* MethodBuilder.Create */
{
return default(global::Java.Net.Socket);
}
/// <summary>
/// <para>Connects a socket to the given host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the connected socket. The returned object may be different from the <code>sock</code> argument if this factory supports a layered protocol.</para>
/// </returns>
/// <java-name>
/// connectSocket
/// </java-name>
[Dot42.DexImport("connectSocket", "(Ljava/net/Socket;Ljava/lang/String;ILjava/net/InetAddress;ILorg/apache/http/para" +
"ms/HttpParams;)Ljava/net/Socket;", AccessFlags = 1)]
public global::Java.Net.Socket ConnectSocket(global::Java.Net.Socket sock, string host, int port, global::Java.Net.InetAddress localAddress, int localPort, global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(global::Java.Net.Socket);
}
/// <summary>
/// <para>Checks whether a socket connection is secure. This factory creates plain socket connections which are not considered secure.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>false</code></para>
/// </returns>
/// <java-name>
/// isSecure
/// </java-name>
[Dot42.DexImport("isSecure", "(Ljava/net/Socket;)Z", AccessFlags = 17)]
public bool IsSecure(global::Java.Net.Socket sock) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Compares this factory with an object. There is only one instance of this class.</para><para></para>
/// </summary>
/// <returns>
/// <para>iff the argument is this object </para>
/// </returns>
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)]
public override bool Equals(object obj) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Obtains a hash code for this object. All instances of this class have the same hash code. There is only one instance of this class. </para>
/// </summary>
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "()I", AccessFlags = 1)]
public override int GetHashCode() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Gets the singleton instance of this class. </para>
/// </summary>
/// <returns>
/// <para>the one and only plain socket factory </para>
/// </returns>
/// <java-name>
/// getSocketFactory
/// </java-name>
public static global::Org.Apache.Http.Conn.Scheme.PlainSocketFactory SocketFactory
{
[Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/scheme/PlainSocketFactory;", AccessFlags = 9)]
get{ return GetSocketFactory(); }
}
}
/// <summary>
/// <para>A set of supported protocol schemes. Schemes are identified by lowercase names.</para><para><para></para><para></para><title>Revision:</title><para>648356 </para><title>Date:</title><para>2008-04-15 10:57:53 -0700 (Tue, 15 Apr 2008) </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/scheme/SchemeRegistry
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/scheme/SchemeRegistry", AccessFlags = 49)]
public sealed partial class SchemeRegistry
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new, empty scheme registry. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public SchemeRegistry() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Obtains the scheme for a host. Convenience method for <code>getScheme(host.getSchemeName())</code></para><para><code> </code></para>
/// </summary>
/// <returns>
/// <para>the scheme for the given host, never <code>null</code></para>
/// </returns>
/// <java-name>
/// getScheme
/// </java-name>
[Dot42.DexImport("getScheme", "(Ljava/lang/String;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)]
public global::Org.Apache.Http.Conn.Scheme.Scheme GetScheme(string host) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Scheme.Scheme);
}
/// <summary>
/// <para>Obtains the scheme for a host. Convenience method for <code>getScheme(host.getSchemeName())</code></para><para><code> </code></para>
/// </summary>
/// <returns>
/// <para>the scheme for the given host, never <code>null</code></para>
/// </returns>
/// <java-name>
/// getScheme
/// </java-name>
[Dot42.DexImport("getScheme", "(Lorg/apache/http/HttpHost;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)]
public global::Org.Apache.Http.Conn.Scheme.Scheme GetScheme(global::Org.Apache.Http.HttpHost host) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Scheme.Scheme);
}
/// <summary>
/// <para>Obtains a scheme by name, if registered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the scheme, or <code>null</code> if there is none by this name </para>
/// </returns>
/// <java-name>
/// get
/// </java-name>
[Dot42.DexImport("get", "(Ljava/lang/String;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)]
public global::Org.Apache.Http.Conn.Scheme.Scheme Get(string name) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Scheme.Scheme);
}
/// <summary>
/// <para>Registers a scheme. The scheme can later be retrieved by its name using getScheme or get.</para><para></para>
/// </summary>
/// <returns>
/// <para>the scheme previously registered with that name, or <code>null</code> if none was registered </para>
/// </returns>
/// <java-name>
/// register
/// </java-name>
[Dot42.DexImport("register", "(Lorg/apache/http/conn/scheme/Scheme;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)]
public global::Org.Apache.Http.Conn.Scheme.Scheme Register(global::Org.Apache.Http.Conn.Scheme.Scheme sch) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Scheme.Scheme);
}
/// <summary>
/// <para>Unregisters a scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para>the unregistered scheme, or <code>null</code> if there was none </para>
/// </returns>
/// <java-name>
/// unregister
/// </java-name>
[Dot42.DexImport("unregister", "(Ljava/lang/String;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)]
public global::Org.Apache.Http.Conn.Scheme.Scheme Unregister(string name) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Scheme.Scheme);
}
/// <summary>
/// <para>Obtains the names of the registered schemes in their default order.</para><para></para>
/// </summary>
/// <returns>
/// <para>List containing registered scheme names. </para>
/// </returns>
/// <java-name>
/// getSchemeNames
/// </java-name>
[Dot42.DexImport("getSchemeNames", "()Ljava/util/List;", AccessFlags = 49, Signature = "()Ljava/util/List<Ljava/lang/String;>;")]
public global::Java.Util.IList<string> GetSchemeNames() /* MethodBuilder.Create */
{
return default(global::Java.Util.IList<string>);
}
/// <summary>
/// <para>Populates the internal collection of registered protocol schemes with the content of the map passed as a parameter.</para><para></para>
/// </summary>
/// <java-name>
/// setItems
/// </java-name>
[Dot42.DexImport("setItems", "(Ljava/util/Map;)V", AccessFlags = 33, Signature = "(Ljava/util/Map<Ljava/lang/String;Lorg/apache/http/conn/scheme/Scheme;>;)V")]
public void SetItems(global::Java.Util.IMap<string, global::Org.Apache.Http.Conn.Scheme.Scheme> map) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Obtains the names of the registered schemes in their default order.</para><para></para>
/// </summary>
/// <returns>
/// <para>List containing registered scheme names. </para>
/// </returns>
/// <java-name>
/// getSchemeNames
/// </java-name>
public global::Java.Util.IList<string> SchemeNames
{
[Dot42.DexImport("getSchemeNames", "()Ljava/util/List;", AccessFlags = 49, Signature = "()Ljava/util/List<Ljava/lang/String;>;")]
get{ return GetSchemeNames(); }
}
}
/// <summary>
/// <para>Encapsulates specifics of a protocol scheme such as "http" or "https". Schemes are identified by lowercase names. Supported schemes are typically collected in a SchemeRegistry.</para><para>For example, to configure support for "https://" URLs, you could write code like the following: </para><para><pre>
/// Scheme https = new Scheme("https", new MySecureSocketFactory(), 443);
/// SchemeRegistry.DEFAULT.register(https);
/// </pre></para><para><para> </para><simplesectsep></simplesectsep><para>Michael Becke </para><simplesectsep></simplesectsep><para>Jeff Dever </para><simplesectsep></simplesectsep><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/scheme/Scheme
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/scheme/Scheme", AccessFlags = 49)]
public sealed partial class Scheme
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new scheme. Whether the created scheme allows for layered connections depends on the class of <code>factory</code>.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Lorg/apache/http/conn/scheme/SocketFactory;I)V", AccessFlags = 1)]
public Scheme(string name, global::Org.Apache.Http.Conn.Scheme.ISocketFactory factory, int port) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Obtains the default port.</para><para></para>
/// </summary>
/// <returns>
/// <para>the default port for this scheme </para>
/// </returns>
/// <java-name>
/// getDefaultPort
/// </java-name>
[Dot42.DexImport("getDefaultPort", "()I", AccessFlags = 17)]
public int GetDefaultPort() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Obtains the socket factory. If this scheme is layered, the factory implements LayeredSocketFactory.</para><para></para>
/// </summary>
/// <returns>
/// <para>the socket factory for this scheme </para>
/// </returns>
/// <java-name>
/// getSocketFactory
/// </java-name>
[Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/scheme/SocketFactory;", AccessFlags = 17)]
public global::Org.Apache.Http.Conn.Scheme.ISocketFactory GetSocketFactory() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Scheme.ISocketFactory);
}
/// <summary>
/// <para>Obtains the scheme name.</para><para></para>
/// </summary>
/// <returns>
/// <para>the name of this scheme, in lowercase </para>
/// </returns>
/// <java-name>
/// getName
/// </java-name>
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 17)]
public string GetName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Indicates whether this scheme allows for layered connections.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if layered connections are possible, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isLayered
/// </java-name>
[Dot42.DexImport("isLayered", "()Z", AccessFlags = 17)]
public bool IsLayered() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Resolves the correct port for this scheme. Returns the given port if it is valid, the default port otherwise.</para><para></para>
/// </summary>
/// <returns>
/// <para>the given port or the defaultPort </para>
/// </returns>
/// <java-name>
/// resolvePort
/// </java-name>
[Dot42.DexImport("resolvePort", "(I)I", AccessFlags = 17)]
public int ResolvePort(int port) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Return a string representation of this object.</para><para></para>
/// </summary>
/// <returns>
/// <para>a human-readable string description of this scheme </para>
/// </returns>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 17)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Compares this scheme to an object.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> iff the argument is equal to this scheme </para>
/// </returns>
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 17)]
public override bool Equals(object obj) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Obtains a hash code for this scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para>the hash code </para>
/// </returns>
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "()I", AccessFlags = 1)]
public override int GetHashCode() /* MethodBuilder.Create */
{
return default(int);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal Scheme() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Obtains the default port.</para><para></para>
/// </summary>
/// <returns>
/// <para>the default port for this scheme </para>
/// </returns>
/// <java-name>
/// getDefaultPort
/// </java-name>
public int DefaultPort
{
[Dot42.DexImport("getDefaultPort", "()I", AccessFlags = 17)]
get{ return GetDefaultPort(); }
}
/// <summary>
/// <para>Obtains the socket factory. If this scheme is layered, the factory implements LayeredSocketFactory.</para><para></para>
/// </summary>
/// <returns>
/// <para>the socket factory for this scheme </para>
/// </returns>
/// <java-name>
/// getSocketFactory
/// </java-name>
public global::Org.Apache.Http.Conn.Scheme.ISocketFactory SocketFactory
{
[Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/scheme/SocketFactory;", AccessFlags = 17)]
get{ return GetSocketFactory(); }
}
/// <summary>
/// <para>Obtains the scheme name.</para><para></para>
/// </summary>
/// <returns>
/// <para>the name of this scheme, in lowercase </para>
/// </returns>
/// <java-name>
/// getName
/// </java-name>
public string Name
{
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 17)]
get{ return GetName(); }
}
}
/// <summary>
/// <para>A factory for creating and connecting sockets. The factory encapsulates the logic for establishing a socket connection. <br></br> Both Object.equals() and Object.hashCode() must be overridden for the correct operation of some connection managers.</para><para><para> </para><simplesectsep></simplesectsep><para>Michael Becke </para><simplesectsep></simplesectsep><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/scheme/SocketFactory
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/scheme/SocketFactory", AccessFlags = 1537)]
public partial interface ISocketFactory
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new, unconnected socket. The socket should subsequently be passed to connectSocket.</para><para></para>
/// </summary>
/// <returns>
/// <para>a new socket</para>
/// </returns>
/// <java-name>
/// createSocket
/// </java-name>
[Dot42.DexImport("createSocket", "()Ljava/net/Socket;", AccessFlags = 1025)]
global::Java.Net.Socket CreateSocket() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Connects a socket to the given host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the connected socket. The returned object may be different from the <code>sock</code> argument if this factory supports a layered protocol.</para>
/// </returns>
/// <java-name>
/// connectSocket
/// </java-name>
[Dot42.DexImport("connectSocket", "(Ljava/net/Socket;Ljava/lang/String;ILjava/net/InetAddress;ILorg/apache/http/para" +
"ms/HttpParams;)Ljava/net/Socket;", AccessFlags = 1025)]
global::Java.Net.Socket ConnectSocket(global::Java.Net.Socket sock, string host, int port, global::Java.Net.InetAddress localAddress, int localPort, global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Checks whether a socket provides a secure connection. The socket must be connected by this factory. The factory will <b>not</b> perform I/O operations in this method. <br></br> As a rule of thumb, plain sockets are not secure and TLS/SSL sockets are secure. However, there may be application specific deviations. For example, a plain socket to a host in the same intranet ("trusted zone") could be considered secure. On the other hand, a TLS/SSL socket could be considered insecure based on the cypher suite chosen for the connection.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the connection of the socket should be considered secure, or <code>false</code> if it should not</para>
/// </returns>
/// <java-name>
/// isSecure
/// </java-name>
[Dot42.DexImport("isSecure", "(Ljava/net/Socket;)Z", AccessFlags = 1025)]
bool IsSecure(global::Java.Net.Socket sock) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>A SocketFactory for layered sockets (SSL/TLS). See there for things to consider when implementing a socket factory.</para><para><para>Michael Becke </para><simplesectsep></simplesectsep><para> </para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/scheme/LayeredSocketFactory
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/scheme/LayeredSocketFactory", AccessFlags = 1537)]
public partial interface ILayeredSocketFactory : global::Org.Apache.Http.Conn.Scheme.ISocketFactory
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns a socket connected to the given host that is layered over an existing socket. Used primarily for creating secure sockets through proxies.</para><para></para>
/// </summary>
/// <returns>
/// <para>Socket a new socket</para>
/// </returns>
/// <java-name>
/// createSocket
/// </java-name>
[Dot42.DexImport("createSocket", "(Ljava/net/Socket;Ljava/lang/String;IZ)Ljava/net/Socket;", AccessFlags = 1025)]
global::Java.Net.Socket CreateSocket(global::Java.Net.Socket socket, string host, int port, bool autoClose) /* MethodBuilder.Create */ ;
}
/// <java-name>
/// org/apache/http/conn/scheme/HostNameResolver
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/scheme/HostNameResolver", AccessFlags = 1537)]
public partial interface IHostNameResolver
/* scope: __dot42__ */
{
/// <java-name>
/// resolve
/// </java-name>
[Dot42.DexImport("resolve", "(Ljava/lang/String;)Ljava/net/InetAddress;", AccessFlags = 1025)]
global::Java.Net.InetAddress Resolve(string hostname) /* MethodBuilder.Create */ ;
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Input.Platform;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Controls.Utils;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Metadata;
using Avalonia.Data;
namespace Avalonia.Controls
{
public class TextBox : TemplatedControl, UndoRedoHelper<TextBox.UndoRedoState>.IUndoRedoHost
{
public static readonly StyledProperty<bool> AcceptsReturnProperty =
AvaloniaProperty.Register<TextBox, bool>("AcceptsReturn");
public static readonly StyledProperty<bool> AcceptsTabProperty =
AvaloniaProperty.Register<TextBox, bool>("AcceptsTab");
public static readonly DirectProperty<TextBox, bool> CanScrollHorizontallyProperty =
AvaloniaProperty.RegisterDirect<TextBox, bool>("CanScrollHorizontally", o => o.CanScrollHorizontally);
public static readonly DirectProperty<TextBox, int> CaretIndexProperty =
AvaloniaProperty.RegisterDirect<TextBox, int>(
nameof(CaretIndex),
o => o.CaretIndex,
(o, v) => o.CaretIndex = v);
public static readonly DirectProperty<TextBox, int> SelectionStartProperty =
AvaloniaProperty.RegisterDirect<TextBox, int>(
nameof(SelectionStart),
o => o.SelectionStart,
(o, v) => o.SelectionStart = v);
public static readonly DirectProperty<TextBox, int> SelectionEndProperty =
AvaloniaProperty.RegisterDirect<TextBox, int>(
nameof(SelectionEnd),
o => o.SelectionEnd,
(o, v) => o.SelectionEnd = v);
public static readonly DirectProperty<TextBox, string> TextProperty =
TextBlock.TextProperty.AddOwner<TextBox>(
o => o.Text,
(o, v) => o.Text = v,
defaultBindingMode: BindingMode.TwoWay);
public static readonly StyledProperty<TextAlignment> TextAlignmentProperty =
TextBlock.TextAlignmentProperty.AddOwner<TextBox>();
public static readonly StyledProperty<TextWrapping> TextWrappingProperty =
TextBlock.TextWrappingProperty.AddOwner<TextBox>();
public static readonly StyledProperty<string> WatermarkProperty =
AvaloniaProperty.Register<TextBox, string>("Watermark");
public static readonly StyledProperty<bool> UseFloatingWatermarkProperty =
AvaloniaProperty.Register<TextBox, bool>("UseFloatingWatermark");
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextBox, bool>(nameof(IsReadOnly));
struct UndoRedoState : IEquatable<UndoRedoState>
{
public string Text { get; }
public int CaretPosition { get; }
public UndoRedoState(string text, int caretPosition)
{
Text = text;
CaretPosition = caretPosition;
}
public bool Equals(UndoRedoState other) => ReferenceEquals(Text, other.Text) || Equals(Text, other.Text);
}
private string _text;
private int _caretIndex;
private int _selectionStart;
private int _selectionEnd;
private bool _canScrollHorizontally;
private TextPresenter _presenter;
private UndoRedoHelper<UndoRedoState> _undoRedoHelper;
static TextBox()
{
FocusableProperty.OverrideDefaultValue(typeof(TextBox), true);
}
public TextBox()
{
var canScrollHorizontally = this.GetObservable(TextWrappingProperty)
.Select(x => x == TextWrapping.NoWrap)
.Subscribe(x => CanScrollHorizontally = x);
var horizontalScrollBarVisibility = this.GetObservable(AcceptsReturnProperty)
.Select(x => x ? ScrollBarVisibility.Auto : ScrollBarVisibility.Hidden);
Bind(
ScrollViewer.HorizontalScrollBarVisibilityProperty,
horizontalScrollBarVisibility,
BindingPriority.Style);
_undoRedoHelper = new UndoRedoHelper<UndoRedoState>(this);
}
public bool AcceptsReturn
{
get { return GetValue(AcceptsReturnProperty); }
set { SetValue(AcceptsReturnProperty, value); }
}
public bool AcceptsTab
{
get { return GetValue(AcceptsTabProperty); }
set { SetValue(AcceptsTabProperty, value); }
}
public bool CanScrollHorizontally
{
get { return _canScrollHorizontally; }
private set { SetAndRaise(CanScrollHorizontallyProperty, ref _canScrollHorizontally, value); }
}
public int CaretIndex
{
get
{
return _caretIndex;
}
set
{
value = CoerceCaretIndex(value);
SetAndRaise(CaretIndexProperty, ref _caretIndex, value);
if (_undoRedoHelper.IsLastState && _undoRedoHelper.LastState.Text == Text)
_undoRedoHelper.UpdateLastState();
}
}
public int SelectionStart
{
get
{
return _selectionStart;
}
set
{
value = CoerceCaretIndex(value);
SetAndRaise(SelectionStartProperty, ref _selectionStart, value);
}
}
public int SelectionEnd
{
get
{
return _selectionEnd;
}
set
{
value = CoerceCaretIndex(value);
SetAndRaise(SelectionEndProperty, ref _selectionEnd, value);
}
}
[Content]
public string Text
{
get { return _text; }
set { SetAndRaise(TextProperty, ref _text, value); }
}
public TextAlignment TextAlignment
{
get { return GetValue(TextAlignmentProperty); }
set { SetValue(TextAlignmentProperty, value); }
}
public string Watermark
{
get { return GetValue(WatermarkProperty); }
set { SetValue(WatermarkProperty, value); }
}
public bool UseFloatingWatermark
{
get { return GetValue(UseFloatingWatermarkProperty); }
set { SetValue(UseFloatingWatermarkProperty, value); }
}
public bool IsReadOnly
{
get { return GetValue(IsReadOnlyProperty); }
set { SetValue(IsReadOnlyProperty, value); }
}
public TextWrapping TextWrapping
{
get { return GetValue(TextWrappingProperty); }
set { SetValue(TextWrappingProperty, value); }
}
protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
{
_presenter = e.NameScope.Get<TextPresenter>("PART_TextPresenter");
_presenter.Cursor = new Cursor(StandardCursorType.Ibeam);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
_presenter.ShowCaret();
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
SelectionStart = 0;
SelectionEnd = 0;
_presenter.HideCaret();
}
protected override void OnTextInput(TextInputEventArgs e)
{
HandleTextInput(e.Text);
}
protected override void DataValidationChanged(AvaloniaProperty property, IValidationStatus status)
{
if (property == TextProperty)
{
UpdateValidationState(status);
}
}
private void HandleTextInput(string input)
{
if (!IsReadOnly)
{
string text = Text ?? string.Empty;
int caretIndex = CaretIndex;
if (!string.IsNullOrEmpty(input))
{
DeleteSelection();
caretIndex = CaretIndex;
text = Text ?? string.Empty;
Text = text.Substring(0, caretIndex) + input + text.Substring(caretIndex);
CaretIndex += input.Length;
SelectionStart = SelectionEnd = CaretIndex;
_undoRedoHelper.DiscardRedo();
}
}
}
private async void Copy()
{
await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard)))
.SetTextAsync(GetSelection());
}
private async void Paste()
{
var text = await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard))).GetTextAsync();
if (text == null)
{
return;
}
_undoRedoHelper.Snapshot();
HandleTextInput(text);
}
protected override void OnKeyDown(KeyEventArgs e)
{
string text = Text ?? string.Empty;
int caretIndex = CaretIndex;
bool movement = false;
bool handled = true;
var modifiers = e.Modifiers;
switch (e.Key)
{
case Key.A:
if (modifiers == InputModifiers.Control)
{
SelectAll();
}
break;
case Key.C:
if (modifiers == InputModifiers.Control)
{
Copy();
}
break;
case Key.X:
if(modifiers == InputModifiers.Control)
{
Copy();
DeleteSelection();
}
break;
case Key.V:
if (modifiers == InputModifiers.Control)
{
Paste();
}
break;
case Key.Z:
if (modifiers == InputModifiers.Control)
_undoRedoHelper.Undo();
break;
case Key.Y:
if (modifiers == InputModifiers.Control)
_undoRedoHelper.Redo();
break;
case Key.Left:
MoveHorizontal(-1, modifiers);
movement = true;
break;
case Key.Right:
MoveHorizontal(1, modifiers);
movement = true;
break;
case Key.Up:
MoveVertical(-1, modifiers);
movement = true;
break;
case Key.Down:
MoveVertical(1, modifiers);
movement = true;
break;
case Key.Home:
MoveHome(modifiers);
movement = true;
break;
case Key.End:
MoveEnd(modifiers);
movement = true;
break;
case Key.Back:
if (!DeleteSelection() && CaretIndex > 0)
{
Text = text.Substring(0, caretIndex - 1) + text.Substring(caretIndex);
--CaretIndex;
}
break;
case Key.Delete:
if (!DeleteSelection() && caretIndex < text.Length)
{
Text = text.Substring(0, caretIndex) + text.Substring(caretIndex + 1);
}
break;
case Key.Enter:
if (AcceptsReturn)
{
HandleTextInput("\r\n");
}
break;
case Key.Tab:
if (AcceptsTab)
{
HandleTextInput("\t");
}
else
{
base.OnKeyDown(e);
handled = false;
}
break;
default:
handled = false;
break;
}
if (movement && ((modifiers & InputModifiers.Shift) != 0))
{
SelectionEnd = CaretIndex;
}
else if (movement)
{
SelectionStart = SelectionEnd = CaretIndex;
}
if (handled)
{
e.Handled = true;
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
if (e.Source == _presenter)
{
var point = e.GetPosition(_presenter);
var index = CaretIndex = _presenter.GetCaretIndex(point);
var text = Text;
if (text != null)
{
switch (e.ClickCount)
{
case 1:
SelectionStart = SelectionEnd = index;
break;
case 2:
if (!StringUtils.IsStartOfWord(text, index))
{
SelectionStart = StringUtils.PreviousWord(text, index, false);
}
SelectionEnd = StringUtils.NextWord(text, index, false);
break;
case 3:
SelectionStart = 0;
SelectionEnd = text.Length;
break;
}
}
e.Device.Capture(_presenter);
e.Handled = true;
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
if (_presenter != null && e.Device.Captured == _presenter)
{
var point = e.GetPosition(_presenter);
CaretIndex = SelectionEnd = _presenter.GetCaretIndex(point);
}
}
protected override void OnPointerReleased(PointerEventArgs e)
{
if (_presenter != null && e.Device.Captured == _presenter)
{
e.Device.Capture(null);
}
}
private int CoerceCaretIndex(int value)
{
var text = Text;
var length = text?.Length ?? 0;
return Math.Max(0, Math.Min(length, value));
}
private void MoveHorizontal(int count, InputModifiers modifiers)
{
var text = Text ?? string.Empty;
var caretIndex = CaretIndex;
if ((modifiers & InputModifiers.Control) != 0)
{
if (count > 0)
{
count = StringUtils.NextWord(text, caretIndex, false) - caretIndex;
}
else
{
count = StringUtils.PreviousWord(text, caretIndex, false) - caretIndex;
}
}
CaretIndex = caretIndex += count;
}
private void MoveVertical(int count, InputModifiers modifiers)
{
var formattedText = _presenter.FormattedText;
var lines = formattedText.GetLines().ToList();
var caretIndex = CaretIndex;
var lineIndex = GetLine(caretIndex, lines) + count;
if (lineIndex >= 0 && lineIndex < lines.Count)
{
var line = lines[lineIndex];
var rect = formattedText.HitTestTextPosition(caretIndex);
var y = count < 0 ? rect.Y : rect.Bottom;
var point = new Point(rect.X, y + (count * (line.Height / 2)));
var hit = formattedText.HitTestPoint(point);
CaretIndex = hit.TextPosition + (hit.IsTrailing ? 1 : 0);
}
}
private void MoveHome(InputModifiers modifiers)
{
var text = Text ?? string.Empty;
var caretIndex = CaretIndex;
if ((modifiers & InputModifiers.Control) != 0)
{
caretIndex = 0;
}
else
{
var lines = _presenter.FormattedText.GetLines();
var pos = 0;
foreach (var line in lines)
{
if (pos + line.Length > caretIndex || pos + line.Length == text.Length)
{
break;
}
pos += line.Length;
}
caretIndex = pos;
}
CaretIndex = caretIndex;
}
private void MoveEnd(InputModifiers modifiers)
{
var text = Text ?? string.Empty;
var caretIndex = CaretIndex;
if ((modifiers & InputModifiers.Control) != 0)
{
caretIndex = text.Length;
}
else
{
var lines = _presenter.FormattedText.GetLines();
var pos = 0;
foreach (var line in lines)
{
pos += line.Length;
if (pos > caretIndex)
{
if (pos < text.Length)
{
--pos;
}
break;
}
}
caretIndex = pos;
}
CaretIndex = caretIndex;
}
private void SelectAll()
{
SelectionStart = 0;
SelectionEnd = Text.Length;
}
private bool DeleteSelection()
{
if (!IsReadOnly)
{
var selectionStart = SelectionStart;
var selectionEnd = SelectionEnd;
if (selectionStart != selectionEnd)
{
var start = Math.Min(selectionStart, selectionEnd);
var end = Math.Max(selectionStart, selectionEnd);
var text = Text;
Text = text.Substring(0, start) + text.Substring(end);
SelectionStart = SelectionEnd = CaretIndex = start;
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
private string GetSelection()
{
var selectionStart = SelectionStart;
var selectionEnd = SelectionEnd;
var start = Math.Min(selectionStart, selectionEnd);
var end = Math.Max(selectionStart, selectionEnd);
if (start == end || (Text?.Length ?? 0) < end)
{
return "";
}
return Text.Substring(start, end - start);
}
private int GetLine(int caretIndex, IList<FormattedTextLine> lines)
{
int pos = 0;
int i;
for (i = 0; i < lines.Count; ++i)
{
var line = lines[i];
pos += line.Length;
if (pos > caretIndex)
{
break;
}
}
return i;
}
UndoRedoState UndoRedoHelper<UndoRedoState>.IUndoRedoHost.UndoRedoState
{
get { return new UndoRedoState(Text, CaretIndex); }
set
{
Text = value.Text;
SelectionStart = SelectionEnd = CaretIndex = value.CaretPosition;
}
}
}
}
| |
using Patterns.Logging;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
namespace SocketHttpListener.Net
{
sealed class EndPointListener
{
IPEndPoint endpoint;
Socket sock;
Hashtable prefixes; // Dictionary <ListenerPrefix, HttpListener>
ArrayList unhandled; // List<ListenerPrefix> unhandled; host = '*'
ArrayList all; // List<ListenerPrefix> all; host = '+'
X509Certificate2 cert;
bool secure;
Dictionary<HttpConnection, HttpConnection> unregistered;
private readonly ILogger _logger;
private bool _closed;
public EndPointListener(ILogger logger, IPAddress addr, int port, bool secure, string certificateLocation)
{
_logger = logger;
if (secure)
{
this.secure = secure;
LoadCertificateAndKey(addr, port, certificateLocation);
}
endpoint = new IPEndPoint(addr, port);
prefixes = new Hashtable();
unregistered = new Dictionary<HttpConnection, HttpConnection>();
CreateSocket();
}
private void CreateSocket()
{
sock = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sock.Bind(endpoint);
// This is the number TcpListener uses.
sock.Listen(2147483647);
StartAccept(null);
_closed = false;
}
void LoadCertificateAndKey(IPAddress addr, int port, string certificateLocation)
{
// Actually load the certificate
try
{
_logger.Info("attempting to load pfx: {0}", certificateLocation);
if (!File.Exists(certificateLocation))
{
_logger.Error("Secure requested, but no certificate found at: {0}", certificateLocation);
return;
}
X509Certificate2 localCert = new X509Certificate2(certificateLocation);
if (localCert.PrivateKey == null)
{
_logger.Error("Secure requested, no private key included in: {0}", certificateLocation);
return;
}
this.cert = localCert;
}
catch (Exception e)
{
_logger.ErrorException("Exception loading certificate: {0}", e, certificateLocation ?? "<NULL>");
// ignore errors
}
}
public void StartAccept(SocketAsyncEventArgs acceptEventArg)
{
if (acceptEventArg == null)
{
acceptEventArg = new SocketAsyncEventArgs();
acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(AcceptEventArg_Completed);
}
else
{
// socket must be cleared since the context object is being reused
acceptEventArg.AcceptSocket = null;
}
bool willRaiseEvent = sock.AcceptAsync(acceptEventArg);
if (!willRaiseEvent)
{
ProcessAccept(acceptEventArg);
}
}
// This method is the callback method associated with Socket.AcceptAsync
// operations and is invoked when an accept operation is complete
//
void AcceptEventArg_Completed(object sender, SocketAsyncEventArgs e)
{
ProcessAccept(e);
}
private void ProcessAccept(SocketAsyncEventArgs e)
{
if (_closed)
{
return;
}
// http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.acceptasync%28v=vs.110%29.aspx
// Under certain conditions ConnectionReset can occur
// Need to attept to re-accept
if (e.SocketError == SocketError.ConnectionReset)
{
_logger.Error("SocketError.ConnectionReset reported. Attempting to re-accept.");
StartAccept(e);
return;
}
var acceptSocket = e.AcceptSocket;
if (acceptSocket != null)
{
ProcessAccept(acceptSocket);
}
if (sock != null)
{
// Accept the next connection request
StartAccept(e);
}
}
private void ProcessAccept(Socket accepted)
{
try
{
var listener = this;
if (listener.secure && listener.cert == null)
{
accepted.Close();
return;
}
var connectionId = Guid.NewGuid().ToString("N");
HttpConnection conn = new HttpConnection(_logger, accepted, listener, listener.secure, connectionId, cert);
//_logger.Debug("Adding unregistered connection to {0}. Id: {1}", accepted.RemoteEndPoint, connectionId);
lock (listener.unregistered)
{
listener.unregistered[conn] = conn;
}
conn.BeginReadRequest();
}
catch (Exception ex)
{
_logger.ErrorException("Error in ProcessAccept", ex);
}
}
internal void RemoveConnection(HttpConnection conn)
{
lock (unregistered)
{
unregistered.Remove(conn);
}
}
public bool BindContext(HttpListenerContext context)
{
HttpListenerRequest req = context.Request;
ListenerPrefix prefix;
HttpListener listener = SearchListener(req.Url, out prefix);
if (listener == null)
return false;
context.Listener = listener;
context.Connection.Prefix = prefix;
return true;
}
public void UnbindContext(HttpListenerContext context)
{
if (context == null || context.Request == null)
return;
context.Listener.UnregisterContext(context);
}
HttpListener SearchListener(Uri uri, out ListenerPrefix prefix)
{
prefix = null;
if (uri == null)
return null;
string host = uri.Host;
int port = uri.Port;
string path = WebUtility.UrlDecode(uri.AbsolutePath);
string path_slash = path[path.Length - 1] == '/' ? path : path + "/";
HttpListener best_match = null;
int best_length = -1;
if (host != null && host != "")
{
Hashtable p_ro = prefixes;
foreach (ListenerPrefix p in p_ro.Keys)
{
string ppath = p.Path;
if (ppath.Length < best_length)
continue;
if (p.Host != host || p.Port != port)
continue;
if (path.StartsWith(ppath) || path_slash.StartsWith(ppath))
{
best_length = ppath.Length;
best_match = (HttpListener)p_ro[p];
prefix = p;
}
}
if (best_length != -1)
return best_match;
}
ArrayList list = unhandled;
best_match = MatchFromList(host, path, list, out prefix);
if (path != path_slash && best_match == null)
best_match = MatchFromList(host, path_slash, list, out prefix);
if (best_match != null)
return best_match;
list = all;
best_match = MatchFromList(host, path, list, out prefix);
if (path != path_slash && best_match == null)
best_match = MatchFromList(host, path_slash, list, out prefix);
if (best_match != null)
return best_match;
return null;
}
HttpListener MatchFromList(string host, string path, ArrayList list, out ListenerPrefix prefix)
{
prefix = null;
if (list == null)
return null;
HttpListener best_match = null;
int best_length = -1;
foreach (ListenerPrefix p in list)
{
string ppath = p.Path;
if (ppath.Length < best_length)
continue;
if (path.StartsWith(ppath))
{
best_length = ppath.Length;
best_match = p.Listener;
prefix = p;
}
}
return best_match;
}
void AddSpecial(ArrayList coll, ListenerPrefix prefix)
{
if (coll == null)
return;
foreach (ListenerPrefix p in coll)
{
if (p.Path == prefix.Path) //TODO: code
throw new System.Net.HttpListenerException(400, "Prefix already in use.");
}
coll.Add(prefix);
}
bool RemoveSpecial(ArrayList coll, ListenerPrefix prefix)
{
if (coll == null)
return false;
int c = coll.Count;
for (int i = 0; i < c; i++)
{
ListenerPrefix p = (ListenerPrefix)coll[i];
if (p.Path == prefix.Path)
{
coll.RemoveAt(i);
return true;
}
}
return false;
}
void CheckIfRemove()
{
if (prefixes.Count > 0)
return;
ArrayList list = unhandled;
if (list != null && list.Count > 0)
return;
list = all;
if (list != null && list.Count > 0)
return;
EndPointManager.RemoveEndPoint(this, endpoint);
}
public void Close()
{
_closed = true;
sock.Close();
lock (unregistered)
{
//
// Clone the list because RemoveConnection can be called from Close
//
var connections = new List<HttpConnection>(unregistered.Keys);
foreach (HttpConnection c in connections)
c.Close(true);
unregistered.Clear();
}
}
public void AddPrefix(ListenerPrefix prefix, HttpListener listener)
{
ArrayList current;
ArrayList future;
if (prefix.Host == "*")
{
do
{
current = unhandled;
future = (current != null) ? (ArrayList)current.Clone() : new ArrayList();
prefix.Listener = listener;
AddSpecial(future, prefix);
} while (Interlocked.CompareExchange(ref unhandled, future, current) != current);
return;
}
if (prefix.Host == "+")
{
do
{
current = all;
future = (current != null) ? (ArrayList)current.Clone() : new ArrayList();
prefix.Listener = listener;
AddSpecial(future, prefix);
} while (Interlocked.CompareExchange(ref all, future, current) != current);
return;
}
Hashtable prefs, p2;
do
{
prefs = prefixes;
if (prefs.ContainsKey(prefix))
{
HttpListener other = (HttpListener)prefs[prefix];
if (other != listener) // TODO: code.
throw new System.Net.HttpListenerException(400, "There's another listener for " + prefix);
return;
}
p2 = (Hashtable)prefs.Clone();
p2[prefix] = listener;
} while (Interlocked.CompareExchange(ref prefixes, p2, prefs) != prefs);
}
public void RemovePrefix(ListenerPrefix prefix, HttpListener listener)
{
ArrayList current;
ArrayList future;
if (prefix.Host == "*")
{
do
{
current = unhandled;
future = (current != null) ? (ArrayList)current.Clone() : new ArrayList();
if (!RemoveSpecial(future, prefix))
break; // Prefix not found
} while (Interlocked.CompareExchange(ref unhandled, future, current) != current);
CheckIfRemove();
return;
}
if (prefix.Host == "+")
{
do
{
current = all;
future = (current != null) ? (ArrayList)current.Clone() : new ArrayList();
if (!RemoveSpecial(future, prefix))
break; // Prefix not found
} while (Interlocked.CompareExchange(ref all, future, current) != current);
CheckIfRemove();
return;
}
Hashtable prefs, p2;
do
{
prefs = prefixes;
if (!prefs.ContainsKey(prefix))
break;
p2 = (Hashtable)prefs.Clone();
p2.Remove(prefix);
} while (Interlocked.CompareExchange(ref prefixes, p2, prefs) != prefs);
CheckIfRemove();
}
}
}
| |
/*
* Copyright 2021 Google LLC All Rights Reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/api/label.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Api {
/// <summary>Holder for reflection information generated from google/api/label.proto</summary>
public static partial class LabelReflection {
#region Descriptor
/// <summary>File descriptor for google/api/label.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static LabelReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChZnb29nbGUvYXBpL2xhYmVsLnByb3RvEgpnb29nbGUuYXBpIpwBCg9MYWJl",
"bERlc2NyaXB0b3ISCwoDa2V5GAEgASgJEjkKCnZhbHVlX3R5cGUYAiABKA4y",
"JS5nb29nbGUuYXBpLkxhYmVsRGVzY3JpcHRvci5WYWx1ZVR5cGUSEwoLZGVz",
"Y3JpcHRpb24YAyABKAkiLAoJVmFsdWVUeXBlEgoKBlNUUklORxAAEggKBEJP",
"T0wQARIJCgVJTlQ2NBACQl8KDmNvbS5nb29nbGUuYXBpQgpMYWJlbFByb3Rv",
"UAFaNWdvb2dsZS5nb2xhbmcub3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvYXBp",
"L2xhYmVsO2xhYmVs+AEBogIER0FQSWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.LabelDescriptor), global::Google.Api.LabelDescriptor.Parser, new[]{ "Key", "ValueType", "Description" }, null, new[]{ typeof(global::Google.Api.LabelDescriptor.Types.ValueType) }, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// A description of a label.
/// </summary>
public sealed partial class LabelDescriptor : pb::IMessage<LabelDescriptor>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<LabelDescriptor> _parser = new pb::MessageParser<LabelDescriptor>(() => new LabelDescriptor());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<LabelDescriptor> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.LabelReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public LabelDescriptor() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public LabelDescriptor(LabelDescriptor other) : this() {
key_ = other.key_;
valueType_ = other.valueType_;
description_ = other.description_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public LabelDescriptor Clone() {
return new LabelDescriptor(this);
}
/// <summary>Field number for the "key" field.</summary>
public const int KeyFieldNumber = 1;
private string key_ = "";
/// <summary>
/// The label key.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Key {
get { return key_; }
set {
key_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "value_type" field.</summary>
public const int ValueTypeFieldNumber = 2;
private global::Google.Api.LabelDescriptor.Types.ValueType valueType_ = global::Google.Api.LabelDescriptor.Types.ValueType.String;
/// <summary>
/// The type of data that can be assigned to the label.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Api.LabelDescriptor.Types.ValueType ValueType {
get { return valueType_; }
set {
valueType_ = value;
}
}
/// <summary>Field number for the "description" field.</summary>
public const int DescriptionFieldNumber = 3;
private string description_ = "";
/// <summary>
/// A human-readable description for the label.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Description {
get { return description_; }
set {
description_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as LabelDescriptor);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(LabelDescriptor other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Key != other.Key) return false;
if (ValueType != other.ValueType) return false;
if (Description != other.Description) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Key.Length != 0) hash ^= Key.GetHashCode();
if (ValueType != global::Google.Api.LabelDescriptor.Types.ValueType.String) hash ^= ValueType.GetHashCode();
if (Description.Length != 0) hash ^= Description.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Key.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Key);
}
if (ValueType != global::Google.Api.LabelDescriptor.Types.ValueType.String) {
output.WriteRawTag(16);
output.WriteEnum((int) ValueType);
}
if (Description.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Description);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Key.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Key);
}
if (ValueType != global::Google.Api.LabelDescriptor.Types.ValueType.String) {
output.WriteRawTag(16);
output.WriteEnum((int) ValueType);
}
if (Description.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Description);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Key.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Key);
}
if (ValueType != global::Google.Api.LabelDescriptor.Types.ValueType.String) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ValueType);
}
if (Description.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Description);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(LabelDescriptor other) {
if (other == null) {
return;
}
if (other.Key.Length != 0) {
Key = other.Key;
}
if (other.ValueType != global::Google.Api.LabelDescriptor.Types.ValueType.String) {
ValueType = other.ValueType;
}
if (other.Description.Length != 0) {
Description = other.Description;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Key = input.ReadString();
break;
}
case 16: {
ValueType = (global::Google.Api.LabelDescriptor.Types.ValueType) input.ReadEnum();
break;
}
case 26: {
Description = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Key = input.ReadString();
break;
}
case 16: {
ValueType = (global::Google.Api.LabelDescriptor.Types.ValueType) input.ReadEnum();
break;
}
case 26: {
Description = input.ReadString();
break;
}
}
}
}
#endif
#region Nested types
/// <summary>Container for nested types declared in the LabelDescriptor message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static partial class Types {
/// <summary>
/// Value types that can be used as label values.
/// </summary>
public enum ValueType {
/// <summary>
/// A variable-length string. This is the default.
/// </summary>
[pbr::OriginalName("STRING")] String = 0,
/// <summary>
/// Boolean; true or false.
/// </summary>
[pbr::OriginalName("BOOL")] Bool = 1,
/// <summary>
/// A 64-bit signed integer.
/// </summary>
[pbr::OriginalName("INT64")] Int64 = 2,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// ReportNames is used to control the names of objects in the report
/// </summary>
internal class ReportNames
{
XmlDocument _doc;
List<XmlNode> _ReportNodes; // array of report nodes; used for tabbing around the nodes
Dictionary<string, XmlNode> _ReportItems; // name/xmlnode pairs of report items
Dictionary<string, XmlNode> _Groupings; // name/xmlnode pairs of grouping names
internal ReportNames(XmlDocument rDoc)
{
_doc = rDoc;
BuildNames(); // build the name hash tables
}
private void BuildNames()
{
_ReportItems = new Dictionary<string, XmlNode>(StringComparer.InvariantCultureIgnoreCase);
_Groupings = new Dictionary<string, XmlNode>(StringComparer.InvariantCultureIgnoreCase);
_ReportNodes = new List<XmlNode>();
BuildNamesLoop(_doc.LastChild);
}
private void BuildNamesLoop(XmlNode xNode)
{
if (xNode == null)
return;
foreach (XmlNode cNode in xNode)
{
// this is not a complete list of object names. It doesn't
// need to be complete but can be optimized so subobjects aren't
// pursued unnecessarily. However, all reportitems and
// grouping must be traversed to get at all the names.
// List should be built in paint order so
// that list of nodes is in correct tab order.
switch (cNode.Name)
{
case "Report":
BuildNamesLoop(DesignXmlDraw.FindNextInHierarchy(cNode, "PageHeader", "ReportItems"));
BuildNamesLoop(DesignXmlDraw.FindNextInHierarchy(cNode, "Body", "ReportItems"));
BuildNamesLoop(DesignXmlDraw.FindNextInHierarchy(cNode, "PageFooter", "ReportItems"));
break;
// have a name but no subobjects
case "Textbox":
case "Image":
case "Line":
case "Subreport":
case "CustomReportItem":
this.AddNode(cNode);
break;
case "Chart":
this.AddNode(cNode);
BuildNamesLoop(DesignXmlDraw.FindNextInHierarchy(cNode, "SeriesGroupings"));
BuildNamesLoop(DesignXmlDraw.FindNextInHierarchy(cNode, "CategoryGroupings"));
break;
// named object having subobjects
case "Table":
this.AddNode(cNode);
BuildNamesLoop(DesignXmlDraw.FindNextInHierarchy(cNode, "Header", "TableRows"));
BuildNamesLoop(DesignXmlDraw.FindNextInHierarchy(cNode, "TableGroups"));
BuildNamesLoop(DesignXmlDraw.FindNextInHierarchy(cNode, "Details"));
BuildNamesLoop(DesignXmlDraw.FindNextInHierarchy(cNode, "Footer", "TableRows"));
break;
case "fyi:Grid":
case "Grid":
this.AddNode(cNode);
BuildNamesLoop(DesignXmlDraw.FindNextInHierarchy(cNode, "Header", "TableRows"));
BuildNamesLoop(DesignXmlDraw.FindNextInHierarchy(cNode, "Details"));
BuildNamesLoop(DesignXmlDraw.FindNextInHierarchy(cNode, "Footer", "TableRows"));
break;
case "List":
this.AddNode(cNode);
BuildNamesLoop(DesignXmlDraw.FindNextInHierarchy(cNode, "Grouping"));
BuildNamesLoop(DesignXmlDraw.FindNextInHierarchy(cNode, "ReportItems"));
break;
case "Rectangle":
this.AddNode(cNode);
BuildNamesLoop(DesignXmlDraw.FindNextInHierarchy(cNode, "ReportItems"));
break;
case "Matrix":
this.AddNode(cNode);
BuildNamesLoop(cNode);
break;
// don't have a name and don't have named subobjects with names
case "Style":
case "Filters":
break;
case "Grouping":
XmlAttribute xAttr = cNode.Attributes["Name"];
if (xAttr == null || _Groupings.ContainsKey(xAttr.Value))
this.GenerateGroupingName(cNode);
else
_Groupings.Add(xAttr.Value, cNode);
break;
// don't have a name but could have subobjects with names
default:
BuildNamesLoop(cNode); // recursively go thru entire report
break;
}
}
return;
}
internal bool ChangeName(XmlNode xNode, string newName)
{
XmlNode fNode;
_ReportItems.TryGetValue(newName, out fNode);
if (fNode != null)
{
if (fNode != xNode)
return false; // this would cause a duplicate
return true; // newName and oldName are the same
}
XmlAttribute xAttr = xNode.Attributes["Name"];
// Remove the old name (if one exists)
if (xAttr != null)
{
string oldName = xAttr.Value;
this._ReportItems.Remove(oldName);
}
// Set the new name
SetElementAttribute(xNode, "Name", newName);
_ReportItems.Add(newName, xNode);
return true;
}
internal bool ChangeGroupName(XmlNode xNode, string newName)
{
XmlNode fNode;
_Groupings.TryGetValue(newName, out fNode);
if (fNode != null)
{
if (fNode != xNode)
return false; // this would cause a duplicate
return true; // newName and oldName are the same
}
XmlAttribute xAttr = xNode.Attributes["Name"];
// Remove the old name (if one exists)
if (xAttr != null)
{
string oldName = xAttr.Value;
this._Groupings.Remove(oldName);
}
// Set the new name
SetElementAttribute(xNode, "Name", newName);
_Groupings.Add(newName, xNode);
return true;
}
internal XmlNode GetRINodeFromName(string ri_name)
{
try
{
return _ReportItems[ri_name];
}
catch
{
return null;
}
}
internal XmlNode FindNext(XmlNode xNode)
{
if (_ReportNodes.Count <= 0)
return null;
if (xNode == null)
return _ReportNodes[0];
bool bNext = false;
foreach (XmlNode nNode in _ReportNodes)
{
if (bNext)
return nNode;
if (nNode == xNode)
bNext = true;
}
return _ReportNodes[0];
}
internal XmlNode FindPrior(XmlNode xNode)
{
if (_ReportItems.Count <= 0)
return null;
if (xNode == null)
return _ReportNodes[0];
XmlNode previous=null;
foreach (XmlNode nNode in _ReportNodes)
{
if (nNode == xNode)
{
if (previous == null)
return _ReportNodes[_ReportNodes.Count-1];
else
return previous;
}
previous = nNode;
}
return _ReportNodes[_ReportNodes.Count-1];
}
internal ICollection ReportItemNames
{
get
{
return _ReportItems.Keys;
}
}
internal ICollection ReportItems
{
get
{
return _ReportItems.Values;
}
}
internal void AddNode(XmlNode xNode)
{
XmlAttribute xAttr = xNode.Attributes["Name"];
if (xAttr == null)
GenerateName(xNode); // when no name; we generate one
else if (_ReportItems.ContainsKey(xAttr.Value))
GenerateName(xNode); // when duplicate name; we generate another; this can be a problem but...
else
{
this._ReportItems.Add(xAttr.Value, xNode);
this._ReportNodes.Add(xNode);
}
}
/// <summary>
/// Generates a new name based on the object type. Replaces the old name in the node but
/// does not delete it from the hash. Use when you're copying nodes and need another name.
/// </summary>
/// <param name="xNode"></param>
/// <returns></returns>
internal string GenerateName(XmlNode xNode)
{
string basename = xNode.Name;
if (basename.StartsWith("fyi:"))
basename = basename.Substring(4);
string name;
int index=1;
while (true)
{
name = basename + index.ToString();
if (!_ReportItems.ContainsKey(name))
{
SetElementAttribute(xNode, "Name", name);
break;
}
index++;
}
_ReportItems.Add(name, xNode); // add generated name
this._ReportNodes.Add(xNode);
return name;
}
internal string GenerateGroupingName(XmlNode xNode)
{
string basename=xNode.ParentNode.Name + "Group";
string name;
int index=1;
List<string> dsets = new List<string>(this.DataSetNames);
while (true)
{
name = basename + index.ToString();
if (_Groupings.ContainsKey(name) == false &&
dsets.IndexOf(name) < 0 &&
_ReportItems.ContainsKey(name) == false)
{
SetElementAttribute(xNode, "Name", name);
break;
}
index++;
}
_Groupings.Add(name, xNode);
return name;
}
internal string NameError(XmlNode xNode, string name)
{
if (name == null || name.Trim().Length <= 0)
return "Name must be provided.";
if (!IsNameValid(name))
return "Invalid characters in name.";
XmlNode fNode;
_ReportItems.TryGetValue(name, out fNode);
if (fNode == xNode)
return null;
if (fNode != null)
return "Duplicate name.";
// Grouping; also restrict to not being same name as any group or dataset
if (xNode.Name == "Grouping")
{
_Groupings.TryGetValue(name, out fNode);
if (fNode != null)
return "Duplicate name.";
List<string> dsets = new List<string>(this.DataSetNames);
if (dsets.IndexOf(name) >= 0)
return "Duplicate name.";
}
return null;
}
internal string GroupingNameCheck(XmlNode xNode, string name)
{
if (name == null || name.Trim().Length <= 0)
return "Name must be provided.";
if (!IsNameValid(name))
return "Invalid characters in name.";
// Grouping; also restrict to not being same name as any group or dataset
XmlNode fNode;
_Groupings.TryGetValue(name, out fNode);
if (fNode != null && fNode != xNode)
return "Duplicate name.";
List<string> dsets = new List<string>(this.DataSetNames);
if (dsets.IndexOf(name) >= 0)
return "Duplicate name.";
return null;
}
static internal bool IsNameValid(string name)
{
if (name == null || name.Length == 0)
return false;
// TODO use algorithm in http://www.unicode.org/unicode/reports/tr15/tr15-18.html#Programming%20Language%20Identifiers
// below regular expression isn't completely correct but matches most ascii language users
// expectations
Match m = Regex.Match(name, @"\A[a-zA-Z_]+[a-zA-Z_0-9]*\Z");
return m.Success;
}
internal void RemoveName(XmlNode xNode)
{
if (xNode == null)
return;
XmlAttribute xAttr = xNode.Attributes["Name"];
if (xAttr == null)
return;
_ReportItems.Remove(xAttr.Value);
_ReportNodes.Remove(xNode);
RemoveChildren(xNode);
}
private void RemoveChildren(XmlNode xNode)
{
XmlAttribute xAttr;
foreach (XmlNode cNode in xNode.ChildNodes)
{
switch (cNode.Name)
{
// have a name but no subobjects
case "Textbox":
case "Image":
case "Line":
case "Subreport":
case "Chart":
xAttr = cNode.Attributes["Name"];
if (xAttr != null)
{
_ReportItems.Remove(xAttr.Value);
_ReportNodes.Remove(cNode);
}
break;
// named object having subobjects
case "Table":
case "List":
case "Rectangle":
case "Matrix":
RemoveChildren(cNode);
xAttr = cNode.Attributes["Name"];
if (xAttr != null)
{
_ReportItems.Remove(xAttr.Value);
_ReportNodes.Remove(cNode);
}
break;
// don't have a name and don't have named subobjects with names
case "Style":
case "Filters":
break;
// don't have a name but could have subobjects with names
default:
RemoveChildren(cNode); // recursively go down the hierarchy
break;
}
}
}
private void SetElementAttribute(XmlNode parent, string name, string val)
{
XmlAttribute attr = parent.Attributes[name];
if (attr != null)
{
attr.Value = val;
}
else
{
attr = _doc.CreateAttribute(name);
attr.Value = val;
parent.Attributes.Append(attr);
}
return;
}
/// <summary>
/// Returns a collection of the GroupingNames
/// </summary>
internal string[] GroupingNames
{
get
{
if (_Groupings == null ||
_Groupings.Count == 0)
return null;
string[] gn = new string[_Groupings.Count];
int i=0;
foreach (string o in _Groupings.Keys)
gn[i++] = o;
return gn;
}
}
/// <summary>
/// Returns a collection of the DataSetNames
/// </summary>
internal string[] DataSetNames
{
get
{
List<string> ds = new List<string>();
XmlNode rNode = _doc.LastChild;
XmlNode node = DesignXmlDraw.FindNextInHierarchy(rNode, "DataSets");
if (node == null)
return ds.ToArray();
foreach (XmlNode cNode in node.ChildNodes)
{
if (cNode.NodeType != XmlNodeType.Element ||
cNode.Name != "DataSet")
continue;
XmlAttribute xAttr = cNode.Attributes["Name"];
if (xAttr != null)
ds.Add(xAttr.Value);
}
return ds.ToArray();
}
}
internal XmlNode DataSourceName(string dsn)
{
XmlNode rNode = _doc.LastChild;
XmlNode node = DesignXmlDraw.FindNextInHierarchy(rNode, "DataSources");
if (node == null)
return null;
foreach (XmlNode cNode in node.ChildNodes)
{
if (cNode.Name != "DataSource")
continue;
XmlAttribute xAttr = cNode.Attributes["Name"];
if (xAttr != null && xAttr.Value == dsn)
return cNode;
}
return null;
}
/// <summary>
/// Returns a collection of the DataSourceNames
/// </summary>
internal string[] DataSourceNames
{
get
{
List<string> ds = new List<string>();
XmlNode rNode = _doc.LastChild;
XmlNode node = DesignXmlDraw.FindNextInHierarchy(rNode, "DataSources");
if (node == null)
return ds.ToArray();
foreach (XmlNode cNode in node.ChildNodes)
{
if (cNode.NodeType != XmlNodeType.Element ||
cNode.Name != "DataSource")
continue;
XmlAttribute xAttr = cNode.Attributes["Name"];
if (xAttr != null)
ds.Add(xAttr.Value);
}
return ds.ToArray();
}
}
/// <summary>
/// Returns a collection of the EmbeddedImage names
/// </summary>
internal string[] EmbeddedImageNames
{
get
{
List<string> ds = new List<string>();
XmlNode rNode = _doc.LastChild;
XmlNode node = DesignXmlDraw.FindNextInHierarchy(rNode, "EmbeddedImages");
if (node == null)
return ds.ToArray();
foreach (XmlNode cNode in node.ChildNodes)
{
if (cNode.NodeType != XmlNodeType.Element ||
cNode.Name != "EmbeddedImage")
continue;
XmlAttribute xAttr = cNode.Attributes["Name"];
if (xAttr != null)
ds.Add(xAttr.Value);
}
return ds.ToArray();
}
}
/// <summary>
/// Gets the fields within the requested dataset. If dataset is null then the first
/// dataset is used.
/// </summary>
/// <param name="dataSetName"></param>
/// <param name="asExpression">When true names are returned as expressions.</param>
/// <returns></returns>
internal string[] GetFields(string dataSetName, bool asExpression)
{
XmlNode nodes = DesignXmlDraw.FindNextInHierarchy(_doc.LastChild, "DataSets");
if (nodes == null || !nodes.HasChildNodes)
return null;
// Find the right dataset
XmlNode dataSet=null;
foreach (XmlNode ds in nodes.ChildNodes)
{
if (ds.Name != "DataSet")
continue;
XmlAttribute xAttr = ds.Attributes["Name"];
if (xAttr == null)
continue;
if (xAttr.Value == dataSetName ||
dataSetName == null || dataSetName == "")
{
dataSet = ds;
break;
}
}
if (dataSet == null)
return null;
// Find the fields
XmlNode fields = DesignXmlDraw.FindNextInHierarchy(dataSet, "Fields");
if (fields == null || !fields.HasChildNodes)
return null;
StringCollection st = new StringCollection();
foreach (XmlNode f in fields.ChildNodes)
{
XmlAttribute xAttr = f.Attributes["Name"];
if (xAttr == null)
continue;
if (asExpression)
st.Add(string.Format("=Fields!{0}.Value", xAttr.Value));
else
st.Add(xAttr.Value);
}
if (st.Count <= 0)
return null;
string[] result = new string[st.Count];
st.CopyTo(result, 0);
return result;
}
internal string[] GetReportParameters(bool asExpression)
{
XmlNode rNode = _doc.LastChild;
XmlNode rpsNode = DesignXmlDraw.FindNextInHierarchy(rNode, "ReportParameters");
if (rpsNode == null)
return null;
StringCollection st = new StringCollection();
foreach (XmlNode repNode in rpsNode)
{
if (repNode.Name != "ReportParameter")
continue;
XmlAttribute nAttr = repNode.Attributes["Name"];
if (nAttr == null) // shouldn't really happen
continue;
if (asExpression)
st.Add(string.Format("=Parameters!{0}.Value", nAttr.Value));
else
st.Add(nAttr.Value);
}
if (st.Count <= 0)
return null;
string[] result = new string[st.Count];
st.CopyTo(result, 0);
return result;
}
/// <summary>
/// EBN 30/03/2014
/// Get the modules defined in the report if any
/// </summary>
/// <param name="asExpression">When true names are returned as expressions.</param>
/// <returns></returns>
internal string[] GetReportModules(bool asExpression)
{
XmlNode rNode = _doc.LastChild;
XmlNode rpsNode = DesignXmlDraw.FindNextInHierarchy(rNode, "CodeModules");
if (rpsNode == null)
return null;
StringCollection st = new StringCollection();
foreach (XmlNode repNode in rpsNode)
{
if (repNode.Name != "CodeModule")
continue;
if (repNode.InnerText == "") // shouldn't really happen
continue;
if (asExpression)
st.Add(string.Format("=Module!{0}", repNode.InnerText));
else
st.Add(repNode.InnerText);
}
if (st.Count <= 0)
return null;
string[] result = new string[st.Count];
st.CopyTo(result, 0);
return result;
}
/// <summary>
/// EBN 30/03/2014
/// Get the modules defined in the report if any
/// </summary>
/// <param name="asExpression">When true names are returned as expressions.</param>
/// <returns></returns>
internal string[] GetReportClasses(bool asExpression)
{
XmlNode rNode = _doc.LastChild;
XmlNode rpsNode = DesignXmlDraw.FindNextInHierarchy(rNode, "Classes");
if (rpsNode == null)
return null;
StringCollection st = new StringCollection();
foreach (XmlNode repNode in rpsNode)
{
string ClassName = "";
string InstanceName = "";
if (repNode.Name != "Class")
continue;
if (repNode.InnerText == "") // shouldn't really happen
continue;
foreach (XmlNode claNode in repNode)
{
if (claNode.Name == "ClassName")
ClassName = claNode.InnerText;
if (claNode.Name == "InstanceName")
InstanceName = claNode.InnerText;
}
if (ClassName != "")
{
if (asExpression)
st.Add(string.Format("=({0}){1}",ClassName,InstanceName));
else
st.Add(string.Format("{0}", ClassName));
}
}
if (st.Count <= 0)
return null;
string[] result = new string[st.Count];
st.CopyTo(result, 0);
return result;
}
}
}
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Hard coded images referenced from C++ code
//------------------------------------------------------------------------------
// editor/SelectHandle.png
// editor/DefaultHandle.png
// editor/LockedHandle.png
//------------------------------------------------------------------------------
// Functions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Mission Editor
//------------------------------------------------------------------------------
function Editor::create()
{
// Not much to do here, build it and they will come...
// Only one thing... the editor is a gui control which
// expect the Canvas to exist, so it must be constructed
// before the editor.
new EditManager(Editor)
{
profile = "GuiContentProfile";
horizSizing = "right";
vertSizing = "top";
position = "0 0";
extent = "640 480";
minExtent = "8 8";
visible = "1";
setFirstResponder = "0";
modal = "1";
helpTag = "0";
open = false;
};
}
function Editor::getUndoManager(%this)
{
if ( !isObject( %this.undoManager ) )
{
/// This is the global undo manager used by all
/// of the mission editor sub-editors.
%this.undoManager = new UndoManager( EUndoManager )
{
numLevels = 200;
};
}
return %this.undoManager;
}
function Editor::setUndoManager(%this, %undoMgr)
{
%this.undoManager = %undoMgr;
}
function Editor::onAdd(%this)
{
// Ignore Replicated fxStatic Instances.
EWorldEditor.ignoreObjClass("fxShapeReplicatedStatic");
}
function Editor::checkActiveLoadDone()
{
if(isObject(EditorGui) && EditorGui.loadingMission)
{
Canvas.setContent(EditorGui);
EditorGui.loadingMission = false;
return true;
}
return false;
}
//------------------------------------------------------------------------------
function toggleEditor(%make)
{
if (Canvas.isFullscreen())
{
MessageBoxOK("Windowed Mode Required", "Please switch to windowed mode to access the Mission Editor.");
return;
}
if (%make)
{
%timerId = startPrecisionTimer();
if( $InGuiEditor )
GuiEdit();
if( !$missionRunning )
{
// Flag saying, when level is chosen, launch it with the editor open.
ChooseLevelDlg.launchInEditor = true;
Canvas.pushDialog( ChooseLevelDlg );
}
else
{
pushInstantGroup();
if ( !isObject( Editor ) )
{
Editor::create();
MissionCleanup.add( Editor );
MissionCleanup.add( Editor.getUndoManager() );
}
if( EditorIsActive() )
{
if (theLevelInfo.type $= "DemoScene")
{
commandToServer('dropPlayerAtCamera');
Editor.close("SceneGui");
}
else
{
Editor.close("PlayGui");
}
}
else
{
if ( !$GuiEditorBtnPressed )
{
canvas.pushDialog( EditorLoadingGui );
canvas.repaint();
}
else
{
$GuiEditorBtnPressed = false;
}
Editor.open();
// Cancel the scheduled event to prevent
// the level from cycling after it's duration
// has elapsed.
cancel($Game::Schedule);
if (theLevelInfo.type $= "DemoScene")
commandToServer('dropCameraAtPlayer', true);
canvas.popDialog(EditorLoadingGui);
}
popInstantGroup();
}
%elapsed = stopPrecisionTimer( %timerId );
warn( "Time spent in toggleEditor() : " @ %elapsed / 1000.0 @ " s" );
}
}
//------------------------------------------------------------------------------
// The editor action maps are defined in editor.bind.cs
GlobalActionMap.bind(keyboard, "f11", toggleEditor);
// The scenario:
// The editor is open and the user closes the level by any way other than
// the file menu ( exit level ), eg. typing disconnect() in the console.
//
// The problem:
// Editor::close() is not called in this scenario which means onEditorDisable
// is not called on objects which hook into it and also gEditingMission will no
// longer be valid.
//
// The solution:
// Override the stock disconnect() function which is in game scripts from here
// in tools so we avoid putting our code in there.
//
// Disclaimer:
// If you think of a better way to do this feel free. The thing which could
// be dangerous about this is that no one will ever realize this code overriding
// a fairly standard and core game script from a somewhat random location.
// If it 'did' have unforscene sideeffects who would ever find it?
package EditorDisconnectOverride
{
function disconnect()
{
if ( isObject( Editor ) && Editor.isEditorEnabled() )
{
if ( $UseUnifiedShell )
{
if (isObject( UnifiedMainMenuGui ))
Editor.close("UnifiedMainMenuGui");
else if (isObject( MainMenuGui ))
Editor.close("MainMenuGui");
}
else if (isObject( MainMenuGui ))
Editor.close("MainMenuGui");
}
Parent::disconnect();
}
};
activatePackage( EditorDisconnectOverride );
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace derpirc.Data.Models.Settings
{
public partial class Network : IBaseModel, INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _Id;
private string _DisplayName;
private string _Name;
private string _HostName;
private string _Ports;
private string _Password;
private List<Favorite> _Favorites;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnCreated();
partial void OnIdChanging(int value);
partial void OnIdChanged();
partial void OnDisplayNameChanging(string value);
partial void OnDisplayNameChanged();
partial void OnNameChanging(string value);
partial void OnNameChanged();
partial void OnHostNameChanging(string value);
partial void OnHostNameChanged();
partial void OnPortsChanging(string value);
partial void OnPortsChanged();
partial void OnPasswordChanging(string value);
partial void OnPasswordChanged();
#endregion
public Network()
{
this._Favorites = new List<Favorite>();
OnCreated();
}
public int Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
/// <summary>
/// Friendly network name
/// </summary>
public string DisplayName
{
get
{
return this._DisplayName;
}
set
{
if (string.Compare(this._DisplayName, value, StringComparison.OrdinalIgnoreCase) != 0)
{
var newValue = (value ?? string.Empty).ToLowerInvariant();
this.OnDisplayNameChanging(newValue);
this.SendPropertyChanging();
this._DisplayName = newValue;
this.SendPropertyChanged("DisplayName");
this.OnDisplayNameChanged();
}
}
}
/// <summary>
/// Name returned by network servers
/// </summary>
public string Name
{
get
{
return this._Name;
}
set
{
if (string.Compare(this._Name, value, StringComparison.OrdinalIgnoreCase) != 0)
{
var newValue = (value ?? string.Empty).ToLowerInvariant();
this.OnNameChanging(newValue);
this.SendPropertyChanging();
this._Name = newValue;
this.SendPropertyChanged("Name");
this.OnNameChanged();
}
}
}
/// <summary>
/// Hostname of server to join
/// </summary>
public string HostName
{
get
{
return this._HostName;
}
set
{
if (string.Compare(this._HostName, value, StringComparison.OrdinalIgnoreCase) != 0)
{
var newValue = (value ?? string.Empty).ToLowerInvariant();
this.OnHostNameChanging(newValue);
this.SendPropertyChanging();
this._HostName = newValue;
this.SendPropertyChanged("HostName");
this.OnHostNameChanged();
}
}
}
/// <summary>
/// Ports to connect to
/// </summary>
public string Ports
{
get
{
return this._Ports;
}
set
{
if ((this._Ports != value))
{
this.OnPortsChanging(value);
this.SendPropertyChanging();
this._Ports = value;
this.SendPropertyChanged("Ports");
this.OnPortsChanged();
}
}
}
/// <summary>
/// Network server password
/// </summary>
public string Password
{
get
{
return this._Password;
}
set
{
if ((this._Password != value))
{
this.OnPasswordChanging(value);
this.SendPropertyChanging();
this._Password = value;
this.SendPropertyChanged("Password");
this.OnPasswordChanged();
}
}
}
/// <summary>
/// Favorite channels
/// </summary>
public List<Favorite> Favorites
{
get
{
return _Favorites;
}
set
{
if (!ReferenceEquals(_Favorites, value))
{
this.SendPropertyChanging();
this._Favorites = value;
this.SendPropertyChanged("Favorites");
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| |
using UnityEngine;
using System.Collections;
public class ThirdPersonCamera : MonoBehaviour
{
public Transform cameraTransform;
private Transform _target;
// The distance in the x-z plane to the target
public float distance = 7.0f;
// the height we want the camera to be above the target
public float height = 3.0f;
public float angularSmoothLag = 0.3f;
public float angularMaxSpeed = 15.0f;
public float heightSmoothLag = 0.3f;
public float snapSmoothLag = 0.2f;
public float snapMaxSpeed = 720.0f;
public float clampHeadPositionScreenSpace = 0.75f;
public float lockCameraTimeout = 0.2f;
private Vector3 headOffset = Vector3.zero;
private Vector3 centerOffset = Vector3.zero;
private float heightVelocity = 0.0f;
private float angleVelocity = 0.0f;
private bool snap = false;
private ThirdPersonController controller;
private float targetHeight = 100000.0f;
private Camera m_CameraTransformCamera;
void OnEnable()
{
if( !cameraTransform && Camera.main )
cameraTransform = Camera.main.transform;
if( !cameraTransform )
{
Debug.Log( "Please assign a camera to the ThirdPersonCamera script." );
enabled = false;
}
m_CameraTransformCamera = cameraTransform.GetComponent<Camera>();
_target = transform;
if( _target )
{
controller = _target.GetComponent<ThirdPersonController>();
}
if( controller )
{
CharacterController characterController = (CharacterController)_target.GetComponent<Collider>();
centerOffset = characterController.bounds.center - _target.position;
headOffset = centerOffset;
headOffset.y = characterController.bounds.max.y - _target.position.y;
}
else
Debug.Log( "Please assign a target to the camera that has a ThirdPersonController script attached." );
Cut( _target, centerOffset );
}
void DebugDrawStuff()
{
Debug.DrawLine( _target.position, _target.position + headOffset );
}
float AngleDistance( float a, float b )
{
a = Mathf.Repeat( a, 360 );
b = Mathf.Repeat( b, 360 );
return Mathf.Abs( b - a );
}
void Apply( Transform dummyTarget, Vector3 dummyCenter )
{
// Early out if we don't have a target
if( !controller )
return;
Vector3 targetCenter = _target.position + centerOffset;
Vector3 targetHead = _target.position + headOffset;
// DebugDrawStuff();
// Calculate the current & target rotation angles
float originalTargetAngle = _target.eulerAngles.y;
float currentAngle = cameraTransform.eulerAngles.y;
// Adjust real target angle when camera is locked
float targetAngle = originalTargetAngle;
// When pressing Fire2 (alt) the camera will snap to the target direction real quick.
// It will stop snapping when it reaches the target
if( Input.GetButton( "Fire2" ) )
snap = true;
if( snap )
{
// We are close to the target, so we can stop snapping now!
if( AngleDistance( currentAngle, originalTargetAngle ) < 3.0f )
snap = false;
currentAngle = Mathf.SmoothDampAngle( currentAngle, targetAngle, ref angleVelocity, snapSmoothLag, snapMaxSpeed );
}
// Normal camera motion
else
{
if( controller.GetLockCameraTimer() < lockCameraTimeout )
{
targetAngle = currentAngle;
}
// Lock the camera when moving backwards!
// * It is really confusing to do 180 degree spins when turning around.
if( AngleDistance( currentAngle, targetAngle ) > 160 && controller.IsMovingBackwards() )
targetAngle += 180;
currentAngle = Mathf.SmoothDampAngle( currentAngle, targetAngle, ref angleVelocity, angularSmoothLag, angularMaxSpeed );
}
// When jumping don't move camera upwards but only down!
if( controller.IsJumping() )
{
// We'd be moving the camera upwards, do that only if it's really high
float newTargetHeight = targetCenter.y + height;
if( newTargetHeight < targetHeight || newTargetHeight - targetHeight > 5 )
targetHeight = targetCenter.y + height;
}
// When walking always update the target height
else
{
targetHeight = targetCenter.y + height;
}
// Damp the height
float currentHeight = cameraTransform.position.y;
currentHeight = Mathf.SmoothDamp( currentHeight, targetHeight, ref heightVelocity, heightSmoothLag );
// Convert the angle into a rotation, by which we then reposition the camera
Quaternion currentRotation = Quaternion.Euler( 0, currentAngle, 0 );
// Set the position of the camera on the x-z plane to:
// distance meters behind the target
cameraTransform.position = targetCenter;
cameraTransform.position += currentRotation * Vector3.back * distance;
// Set the height of the camera
cameraTransform.position = new Vector3( cameraTransform.position.x, currentHeight, cameraTransform.position.z );
// Always look at the target
SetUpRotation( targetCenter, targetHead );
}
void LateUpdate()
{
Apply( transform, Vector3.zero );
}
void Cut( Transform dummyTarget, Vector3 dummyCenter )
{
float oldHeightSmooth = heightSmoothLag;
float oldSnapMaxSpeed = snapMaxSpeed;
float oldSnapSmooth = snapSmoothLag;
snapMaxSpeed = 10000;
snapSmoothLag = 0.001f;
heightSmoothLag = 0.001f;
snap = true;
Apply( transform, Vector3.zero );
heightSmoothLag = oldHeightSmooth;
snapMaxSpeed = oldSnapMaxSpeed;
snapSmoothLag = oldSnapSmooth;
}
void SetUpRotation( Vector3 centerPos, Vector3 headPos )
{
// Now it's getting hairy. The devil is in the details here, the big issue is jumping of course.
// * When jumping up and down we don't want to center the guy in screen space.
// This is important to give a feel for how high you jump and avoiding large camera movements.
//
// * At the same time we dont want him to ever go out of screen and we want all rotations to be totally smooth.
//
// So here is what we will do:
//
// 1. We first find the rotation around the y axis. Thus he is always centered on the y-axis
// 2. When grounded we make him be centered
// 3. When jumping we keep the camera rotation but rotate the camera to get him back into view if his head is above some threshold
// 4. When landing we smoothly interpolate towards centering him on screen
Vector3 cameraPos = cameraTransform.position;
Vector3 offsetToCenter = centerPos - cameraPos;
// Generate base rotation only around y-axis
Quaternion yRotation = Quaternion.LookRotation( new Vector3( offsetToCenter.x, 0, offsetToCenter.z ) );
Vector3 relativeOffset = Vector3.forward * distance + Vector3.down * height;
cameraTransform.rotation = yRotation * Quaternion.LookRotation( relativeOffset );
// Calculate the projected center position and top position in world space
Ray centerRay = m_CameraTransformCamera.ViewportPointToRay( new Vector3( 0.5f, 0.5f, 1 ) );
Ray topRay = m_CameraTransformCamera.ViewportPointToRay( new Vector3( 0.5f, clampHeadPositionScreenSpace, 1 ) );
Vector3 centerRayPos = centerRay.GetPoint( distance );
Vector3 topRayPos = topRay.GetPoint( distance );
float centerToTopAngle = Vector3.Angle( centerRay.direction, topRay.direction );
float heightToAngle = centerToTopAngle / ( centerRayPos.y - topRayPos.y );
float extraLookAngle = heightToAngle * ( centerRayPos.y - centerPos.y );
if( extraLookAngle < centerToTopAngle )
{
extraLookAngle = 0;
}
else
{
extraLookAngle = extraLookAngle - centerToTopAngle;
cameraTransform.rotation *= Quaternion.Euler( -extraLookAngle, 0, 0 );
}
}
Vector3 GetCenterOffset()
{
return centerOffset;
}
}
| |
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace Google.ComputeEngine.Common
{
public sealed class MetadataUpdateEventArgs : EventArgs
{
public MetadataJson Metadata { get; private set; }
public MetadataUpdateEventArgs(MetadataJson metadata)
{
this.Metadata = metadata;
}
}
public sealed class MetadataWatcher
{
private const string MetadataServer = "http://metadata.google.internal/computeMetadata/v1";
private const string MetadataHang = "/?recursive=true&alt=json&wait_for_change=true&timeout_sec=60&last_etag=";
private const string DefaultEtag = "NONE";
// 70 seconds in case of an abandoned request.
private const int RequestTimeout = 70 * 1000;
// Make the MetadataWatcher a singleton object.
private static readonly MetadataWatcher WatcherInstance = new MetadataWatcher();
private MetadataWatcher() { }
public static MetadataWatcher Watcher { get { return WatcherInstance; } }
// Store the Etag used for subsequent retrievals of metadata.
private static string Etag { get; set; }
// Flag indicating if we should print a WebException.
// Web exceptions should only be printed once, and then a success
// message should follow.
private static bool PrintWebException { get; set; }
// Use the CancellationToken as an exit condition.
private static CancellationTokenSource Token { get; set; }
public delegate void EventHandler(object sender, MetadataUpdateEventArgs e);
public static event EventHandler MetadataUpdateEvent;
private static void ActivateMetadataUpdate(MetadataJson metadata)
{
MetadataUpdateEventArgs eventArgs = new MetadataUpdateEventArgs(metadata);
if (MetadataUpdateEvent != null)
{
MetadataUpdateEvent(null, eventArgs);
}
}
/// <summary>
/// Creates a WebRequest to the metadata server given a URL.
/// </summary>
private static WebRequest CreateRequest(string metadataRequest)
{
HttpWebRequest request = WebRequest.CreateHttp(metadataRequest);
request.Headers.Add("Metadata-Flavor", "Google");
request.Timeout = RequestTimeout;
return request;
}
/// <summary>
/// The etag determines whether the content of the metadata server
/// has changed. We reset the etag at initialization. Resetting the
/// etag will result in an immediate response from anything that waits
/// for a change in the metadata server contents.
/// </summary>
private static void ResetEtag()
{
Etag = DefaultEtag;
}
private static void UpdateEtag(WebResponse response)
{
Etag = response.Headers.Get("etag");
if (Etag == null)
{
ResetEtag();
}
}
/// <summary>
/// Makes a hanging get request against the metadata server.
/// Marked async so the cancellation token from the main loop can
/// terminate this wait.
/// </summary>
private static async Task<string> WaitForUpdate()
{
WebRequest request = CreateRequest(MetadataServer + MetadataHang + Etag);
try
{
using (WebResponse response = await request.GetResponseAsync())
{
UpdateEtag(response);
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
return await sr.ReadToEndAsync();
}
}
}
catch (WebException e)
{
if (PrintWebException)
{
Logger.Warning("WebException waiting for metadata change: {0}", e.Message);
PrintWebException = false;
}
ResetEtag();
throw;
}
catch (Exception e)
{
Logger.Error("Exception waiting for metadata change: {0}", e.Message);
throw;
}
}
/// <summary>
/// Wait for metadata changes until cancellation is requested.
/// Deserialize the response from the metadata server into a JSON
/// object. Emit an event with this object indicating the metadata
/// server content has updated.
/// </summary>
private static async Task<string> GetMetadataUpdate()
{
try
{
string metadata = await WaitForUpdate();
// There are no network issues if we reach this point.
if (!PrintWebException)
{
PrintWebException = true;
Logger.Warning("Network access restored.");
}
return metadata;
}
catch (WebException e)
{
if (PrintWebException)
{
Logger.Warning("WebException responding to metadata server update: {0}", e.Message);
PrintWebException = false;
}
// Sleep for five seconds before trying again.
Thread.Sleep(5000);
}
catch (Exception e)
{
// Log Exception and try again.
Logger.Error("Exception responding to metadata server update: {0}\n{1}", e.Message, e.StackTrace);
}
return null;
}
/// <summary>
/// Wait for metadata changes until cancellation is requested.
/// </summary>
private static async void WatchMetadata()
{
while (!Token.IsCancellationRequested)
{
string metadata = await GetMetadataUpdate();
// Check if the response from deserialize is null.
if (!string.IsNullOrEmpty(metadata))
{
MetadataJson metadataJson = MetadataDeserializer.DeserializeMetadata<MetadataJson>(metadata);
ActivateMetadataUpdate(metadataJson);
}
}
}
/// <summary>
/// Updates the CancellationToken and starts the Metadata Watcher.
/// The CancellationToken represents the exit condition for
/// watching the metadata server contents.
/// </summary>
public static void UpdateToken(CancellationTokenSource tokenSource)
{
Token = tokenSource;
ResetEtag();
PrintWebException = true;
WatchMetadata();
}
/// <summary>
/// Synchronously waits and retrieves metadata server contents.
/// </summary>
/// <returns>The deserialized contents of the metadata server.</returns>
public static MetadataJson GetMetadata()
{
ResetEtag();
PrintWebException = true;
string metadata;
do
{
metadata = GetMetadataUpdate().Result;
}
while (string.IsNullOrEmpty(metadata));
return MetadataDeserializer.DeserializeMetadata<MetadataJson>(metadata);
}
}
}
| |
//! \file ArcMBL.cs
//! \date Fri Mar 27 23:11:19 2015
//! \brief Marble Engine archive implementation.
//
// Copyright (C) 2015 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using GameRes.Formats.Properties;
using GameRes.Formats.Strings;
using GameRes.Utility;
namespace GameRes.Formats.Marble
{
public class MblOptions : ResourceOptions
{
public string PassPhrase;
}
public class MblArchive : ArcFile
{
public readonly byte[] Key;
public MblArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, string password)
: base (arc, impl, dir)
{
Key = Encodings.cp932.GetBytes (password);
}
}
[Serializable]
public class MblScheme : ResourceScheme
{
public Dictionary<string, string> KnownKeys;
}
[Export(typeof(ArchiveFormat))]
public class MblOpener : ArchiveFormat
{
public override string Tag { get { return "MBL"; } }
public override string Description { get { return "Marble engine resource archive"; } }
public override uint Signature { get { return 0; } }
public override bool IsHierarchic { get { return false; } }
public override bool CanCreate { get { return false; } }
public override ArcFile TryOpen (ArcView file)
{
int count = file.View.ReadInt32 (0);
if (count <= 0 || count > 0xfffff)
return null;
ArcFile arc = null;
uint filename_len = file.View.ReadUInt32 (4);
if (filename_len > 0 && filename_len <= 0xff)
arc = ReadIndex (file, count, filename_len, 8);
if (null == arc)
arc = ReadIndex (file, count, 0x10, 4);
if (null == arc)
arc = ReadIndex (file, count, 0x38, 4);
return arc;
}
static readonly Lazy<ImageFormat> PrsFormat = new Lazy<ImageFormat> (() => ImageFormat.FindByTag ("PRS"));
private ArcFile ReadIndex (ArcView file, int count, uint filename_len, uint index_offset)
{
uint index_size = (8u + filename_len) * (uint)count;
if (index_size > file.View.Reserve (index_offset, index_size))
return null;
try
{
bool contains_scripts = false;
var dir = new List<Entry> (count);
for (int i = 0; i < count; ++i)
{
string name = file.View.ReadString (index_offset, filename_len);
if (0 == name.Length)
return null;
if (filename_len-name.Length > 1)
{
string ext = file.View.ReadString (index_offset+name.Length+1, filename_len-(uint)name.Length-1);
if (0 != ext.Length)
name = Path.ChangeExtension (name, ext);
}
name = name.ToLowerInvariant();
index_offset += (uint)filename_len;
uint offset = file.View.ReadUInt32 (index_offset);
string type = null;
if (name.EndsWith (".s"))
{
type = "script";
contains_scripts = true;
}
else if (4 == Path.GetExtension (name).Length)
{
type = FormatCatalog.Instance.GetTypeFromName (name);
}
Entry entry;
if (string.IsNullOrEmpty (type))
{
entry = new AutoEntry (name, () => {
uint signature = file.View.ReadUInt32 (offset);
if (0x4259 == (0xffff & signature))
return PrsFormat.Value;
else if (0 != signature)
return FormatCatalog.Instance.LookupSignature (signature).FirstOrDefault();
else
return null;
});
}
else
{
entry = new Entry { Name = name, Type = type };
}
entry.Offset = offset;
entry.Size = file.View.ReadUInt32 (index_offset+4);
if (offset < index_size || !entry.CheckPlacement (file.MaxOffset))
return null;
dir.Add (entry);
index_offset += 8;
}
if (0 == dir.Count)
return null;
if (contains_scripts)
{
var options = Query<MblOptions> (arcStrings.MBLNotice);
if (options.PassPhrase.Length > 0)
return new MblArchive (file, this, dir, options.PassPhrase);
}
return new ArcFile (file, this, dir);
}
catch
{
return null;
}
}
public static Dictionary<string, string> KnownKeys = new Dictionary<string, string>();
public override ResourceScheme Scheme
{
get { return new MblScheme { KnownKeys = KnownKeys }; }
set { KnownKeys = ((MblScheme)value).KnownKeys; }
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
if (entry.Type != "script" || !entry.Name.EndsWith (".s"))
return arc.File.CreateStream (entry.Offset, entry.Size);
var marc = arc as MblArchive;
var data = new byte[entry.Size];
arc.File.View.Read (entry.Offset, data, 0, entry.Size);
if (null == marc || null == marc.Key)
{
for (int i = 0; i < data.Length; ++i)
{
data[i] = (byte)-data[i];
}
}
else
{
for (int i = 0; i < data.Length; ++i)
{
data[i] ^= marc.Key[i % marc.Key.Length];
}
}
return new MemoryStream (data);
}
public override ResourceOptions GetDefaultOptions ()
{
return new MblOptions { PassPhrase = Settings.Default.MBLPassPhrase };
}
public override object GetAccessWidget ()
{
return new GUI.WidgetMBL();
}
}
}
| |
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# port by: Lars Brubaker
// larsbrubaker@gmail.com
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using MatterHackers.Agg.Platform;
using MatterHackers.RenderOpenGl;
#if USE_GLES
using OpenTK.Graphics.ES11;
#else
using OpenTK.Graphics.OpenGL;
#endif
namespace MatterHackers.Agg.UI
{
public class OpenGLSystemWindow : WinformsSystemWindow
{
private AggGLControl glControl;
public OpenGLSystemWindow()
{
// Set GraphicsMode via user overridable settings
var config = AggContext.Config.GraphicsMode;
var graphicsMode = new OpenTK.Graphics.GraphicsMode(config.Color, config.Depth, config.Stencil, config.FSAASamples);
glControl = new AggGLControl(graphicsMode)
{
Dock = DockStyle.Fill,
Location = new Point(0, 0),
TabIndex = 0,
VSync = false
};
RenderOpenGl.OpenGl.GL.Instance = new OpenTkGl();
this.Controls.Add(glControl);
}
private bool doneLoading = false;
protected override void OnClosed(EventArgs e)
{
if (!this.IsDisposed
|| !glControl.IsDisposed)
{
glControl.MakeCurrent();
glControl.releaseAllGlData.Release();
}
base.OnClosed(e);
}
protected override void OnLoad(EventArgs e)
{
id = count++;
base.OnLoad(e);
doneLoading = true;
this.EventSink = new WinformsEventSink(glControl, AggSystemWindow);
// Init();
if (!AggSystemWindow.Resizable)
{
this.FormBorderStyle = FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
}
// Change the WindowsForms window to match the target SystemWindow bounds
this.ClientSize = new Size((int)AggSystemWindow.Width, (int)AggSystemWindow.Height);
// Restore to the last maximized or normal window state
this.WindowState = AggSystemWindow.Maximized ? FormWindowState.Maximized : FormWindowState.Normal;
this.IsInitialized = true;
initHasBeenCalled = true;
}
private void SetupViewport()
{
// If this throws an assert, you are calling MakeCurrent() before the glControl is done being constructed.
// Call this function you have called Show().
glControl.MakeCurrent();
int w = glControl.Width;
int h = glControl.Height;
#if USE_GLES
GL.MatrixMode(All.Projection);
#else
GL.MatrixMode(MatrixMode.Projection);
#endif
GL.LoadIdentity();
GL.Ortho(0, w, 0, h, -1, 1); // Bottom-left corner pixel has coordinate (0, 0)
GL.Viewport(0, 0, w, h); // Use all of the glControl painting area
}
protected override void OnPaint(PaintEventArgs paintEventArgs)
{
if (Focused)
{
glControl.Focus();
}
// We have to make current the gl for the window we are.
// If this throws an assert, you are calling MakeCurrent() before the glControl is done being constructed.
// Call this function after you have called Show().
glControl.MakeCurrent();
if (CheckGlControl())
{
base.OnPaint(paintEventArgs);
}
CheckGlControl();
}
protected override void OnResize(EventArgs e)
{
Rectangle bounds = new Rectangle(0, 0, ClientSize.Width, ClientSize.Height);
// Suppress resize events on the Windows platform when the form is being minimized and/or when a Resize event has fired
// but the control dimensions remain the same. This prevents a bounds resize from the current dimensions to 0,0 and a
// subsequent resize on Restore to the origin dimensions. In addition, this guard prevents the loss of control state
// due to cascading control regeneration and avoids the associated performance hit and visible rendering lag during Restore
if (doneLoading && this.WindowState != FormWindowState.Minimized && glControl.Bounds != bounds)
{
// If this throws an assert, you are calling MakeCurrent() before the glControl is done being constructed.
// Call this function you have called Show().
glControl.MakeCurrent();
Invalidate();
// glSurface.Location = new Point(0, 0);
glControl.Bounds = bounds;
if (initHasBeenCalled)
{
CheckGlControl();
SetAndClearViewPort();
base.OnResize(e);
CheckGlControl();
}
else
{
base.OnResize(e);
}
SetupViewport();
}
}
public override void CopyBackBufferToScreen(Graphics displayGraphics)
{
// If this throws an assert, you are calling MakeCurrent() before the glControl is done being constructed.
// Call this function you have called Show().
glControl.SwapBuffers();
}
private static int count;
private int id;
public override string ToString()
{
return id.ToString();
}
private bool viewPortHasBeenSet = false;
private void SetAndClearViewPort()
{
GL.Viewport(0, 0, this.ClientSize.Width, this.ClientSize.Height); // Reset The Current Viewport
viewPortHasBeenSet = true;
// The following lines set the screen up for a perspective view. Meaning things in the distance get smaller.
// This creates a realistic looking scene.
// The perspective is calculated with a 45 degree viewing angle based on the windows width and height.
// The 0.1f, 100.0f is the starting point and ending point for how deep we can draw into the screen.
GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
GL.MatrixMode(MatrixMode.Modelview);
GL.LoadIdentity();
GL.Scissor(0, 0, this.ClientSize.Width, this.ClientSize.Height);
NewGraphics2D().Clear(new ColorF(1, 1, 1, 1));
}
private bool CheckGlControl()
{
if (firstGlControlSeen == null)
{
firstGlControlSeen = AggGLControl.currentControl;
}
// if (firstGlControlSeen != MyGLControl.currentControl)
if (AggGLControl.currentControl.Id != this.id)
{
Debug.WriteLine("Is {0} Should be {1}".FormatWith(firstGlControlSeen.Id, AggGLControl.currentControl.Id));
// throw new Exception("We have the wrong gl control realized.");
return false;
}
return true;
}
private AggGLControl firstGlControlSeen = null;
public override Graphics2D NewGraphics2D()
{
if (!viewPortHasBeenSet)
{
SetAndClearViewPort();
}
Graphics2D graphics2D = new Graphics2DOpenGL(this.ClientSize.Width, this.ClientSize.Height, GuiWidget.DeviceScale);
graphics2D.PushTransform();
return graphics2D;
}
private bool initHasBeenCalled = false;
private Keys modifierKeys = Keys.None;
private bool modifiersOverridden = false;
internal void SetModifierKeys(Keys modifiers)
{
modifierKeys = modifiers;
modifiersOverridden = true;
}
public override Keys ModifierKeys
{
get {
if (modifiersOverridden)
{
return modifierKeys;
}
return base.ModifierKeys;
}
}
}
}
| |
//
// Copyright (c) Microsoft. 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;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using Microsoft.Rest.Azure;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Rest;
using Newtonsoft.Json.Linq;
using Xunit;
using Microsoft.Rest.Azure.OData;
namespace ResourceGroups.Tests
{
public class InMemoryResourceGroupTests
{
public ResourceManagementClient GetResourceManagementClient(RecordedDelegatingHandler handler)
{
var subscriptionId = Guid.NewGuid().ToString();
var token = new TokenCredentials(subscriptionId, "abc123");
handler.IsPassThrough = false;
var client = new ResourceManagementClient(token, handler);
client.SubscriptionId = subscriptionId;
return client;
}
[Fact]
public void ResourceGroupCreateOrUpdateValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio',
'name': 'foo',
'location': 'WestEurope',
'tags' : {
'department':'finance',
'tagname':'tagvalue'
},
'properties': {
'provisioningState': 'Succeeded'
}
}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.ResourceGroups.CreateOrUpdate("foo", new ResourceGroup
{
Location = "WestEurope",
Tags = new Dictionary<string, string>() { { "department", "finance" }, { "tagname", "tagvalue" } },
});
JObject json = JObject.Parse(handler.Request);
// Validate headers
Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First());
Assert.Equal(HttpMethod.Put, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
// Validate payload
Assert.Equal("WestEurope", json["location"].Value<string>());
Assert.Equal("finance", json["tags"]["department"].Value<string>());
Assert.Equal("tagvalue", json["tags"]["tagname"].Value<string>());
// Validate response
Assert.Equal("/subscriptions/abc123/resourcegroups/csmrgr5mfggio", result.Id);
Assert.Equal("Succeeded", result.Properties.ProvisioningState);
Assert.Equal("foo", result.Name);
Assert.Equal("finance", result.Tags["department"]);
Assert.Equal("tagvalue", result.Tags["tagname"]);
Assert.Equal("WestEurope", result.Location);
}
[Fact]
public void ResourceGroupCreateOrUpdateThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = GetResourceManagementClient(handler);
Assert.Throws<Microsoft.Rest.ValidationException>(() => client.ResourceGroups.CreateOrUpdate(null, new ResourceGroup()));
Assert.Throws<Microsoft.Rest.ValidationException>(() => client.ResourceGroups.CreateOrUpdate("foo", null));
}
[Fact]
public void ResourceGroupExistsReturnsTrue()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.NoContent };
var client = GetResourceManagementClient(handler);
var result = client.ResourceGroups.CheckExistence("foo");
// Validate payload
Assert.Empty(handler.Request);
// Validate response
Assert.True(result.Value);
}
[Fact]
public void ResourceGroupExistsReturnsFalse()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.NotFound };
var client = GetResourceManagementClient(handler);
var result = client.ResourceGroups.CheckExistence(Guid.NewGuid().ToString());
// Validate payload
Assert.Empty(handler.Request);
// Validate response
Assert.False(result.Value);
}
[Fact()]
public void ResourceGroupExistsThrowsException()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.BadRequest };
var client = GetResourceManagementClient(handler);
Assert.Throws<CloudException>(() => client.ResourceGroups.CheckExistence("foo"));
}
[Fact]
public void ResourceGroupPatchValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'subscriptionId': '123456',
'name': 'foo',
'location': 'WestEurope',
'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio',
'properties': {
'provisioningState': 'Succeeded'
}
}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.ResourceGroups.Patch("foo", new ResourceGroup
{
Location = "WestEurope",
});
JObject json = JObject.Parse(handler.Request);
// Validate headers
Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First());
Assert.Equal("patch", handler.Method.Method.Trim().ToLower());
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
// Validate payload
Assert.Equal("WestEurope", json["location"].Value<string>());
// Validate response
Assert.Equal("/subscriptions/abc123/resourcegroups/csmrgr5mfggio", result.Id);
Assert.Equal("Succeeded", result.Properties.ProvisioningState);
Assert.Equal("foo", result.Name);
Assert.Equal("WestEurope", result.Location);
}
[Fact(Skip = "Parameter validation using pattern match is not supported yet at code-gen, the work is on-going.")]
public void ResourceGroupUpdateStateThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = GetResourceManagementClient(handler);
Assert.Throws<ArgumentNullException>(() => client.ResourceGroups.Patch(null, new ResourceGroup()));
Assert.Throws<ArgumentNullException>(() => client.ResourceGroups.Patch("foo", null));
Assert.Throws<ArgumentOutOfRangeException>(() => client.ResourceGroups.Patch("~`123", new ResourceGroup()));
}
[Fact]
public void ResourceGroupGetValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio',
'name': 'foo',
'location': 'WestEurope',
'properties': {
'provisioningState': 'Succeeded'
}
}")
};
response.Headers.Add("x-ms-request-id", "1");
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.ResourceGroups.Get("foo");
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
// Validate result
Assert.Equal("/subscriptions/abc123/resourcegroups/csmrgr5mfggio", result.Id);
Assert.Equal("WestEurope", result.Location);
Assert.Equal("foo", result.Name);
Assert.Equal("Succeeded", result.Properties.ProvisioningState);
Assert.True(result.Properties.ProvisioningState == "Succeeded");
}
[Fact]
public void ResourceGroupNameAcceptsAllAllowableCharacters()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio',
'name': 'foo',
'location': 'WestEurope',
'properties': {
'provisioningState': 'Succeeded'
}
}")
};
response.Headers.Add("x-ms-request-id", "1");
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
client.ResourceGroups.Get("foo-123_bar");
}
[Fact(Skip = "Parameter validation using pattern match is not supported yet at code-gen, the work is on-going.")]
public void ResourceGroupGetThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = GetResourceManagementClient(handler);
Assert.Throws<ArgumentNullException>(() => client.ResourceGroups.Get(null));
Assert.Throws<ArgumentOutOfRangeException>(() => client.ResourceGroups.Get("~`123"));
}
[Fact]
public void ResourceGroupListAllValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'value': [{
'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio',
'name': 'myresourcegroup1',
'location': 'westus',
'properties': {
'provisioningState': 'Succeeded'
}
},
{
'id': '/subscriptions/abc123/resourcegroups/fdfdsdsf',
'name': 'myresourcegroup2',
'location': 'eastus',
'properties': {
'provisioningState': 'Succeeded'
}
}
],
'nextLink': 'https://wa/subscriptions/subId/resourcegroups?api-version=1.0&$skiptoken=662idk',
}")
};
response.Headers.Add("x-ms-request-id", "1");
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.ResourceGroups.List(null);
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
// Validate result
Assert.Equal(2, result.Count());
Assert.Equal("myresourcegroup1", result.First().Name);
Assert.Equal("Succeeded", result.First().Properties.ProvisioningState);
Assert.Equal("/subscriptions/abc123/resourcegroups/csmrgr5mfggio", result.First().Id);
Assert.Equal("https://wa/subscriptions/subId/resourcegroups?api-version=1.0&$skiptoken=662idk", result.NextPageLink);
}
[Fact]
public void ResourceGroupListAllWorksForEmptyLists()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{'value': []}")
};
response.Headers.Add("x-ms-request-id", "1");
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.ResourceGroups.List(null);
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
// Validate result
Assert.Equal(0, result.Count());
}
[Fact]
public void ResourceGroupListValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'value': [{
'name': 'myresourcegroup1',
'location': 'westus',
'locked': 'true'
},
{
'name': 'myresourcegroup2',
'location': 'eastus',
'locked': 'false'
}
],
'nextLink': 'https://wa/subscriptions/subId/resourcegroups?api-version=1.0&$skiptoken=662idk',
}")
};
response.Headers.Add("x-ms-request-id", "1");
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.ResourceGroups.List(new ODataQuery<ResourceGroupFilter> { Top = 5 });
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
Assert.True(handler.Uri.ToString().Contains("$top=5"));
// Validate result
Assert.Equal(2, result.Count());
Assert.Equal("myresourcegroup1", result.First().Name);
Assert.Equal("https://wa/subscriptions/subId/resourcegroups?api-version=1.0&$skiptoken=662idk", result.NextPageLink);
}
[Fact]
public void ResourceGroupDeleteValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.Accepted);
response.Headers.Add("Location", "http://foo");
var handler = new RecordedDelegatingHandler(response)
{
StatusCodeToReturn = HttpStatusCode.Accepted,
SubsequentStatusCodeToReturn = HttpStatusCode.OK
};
var client = GetResourceManagementClient(handler);
client.LongRunningOperationRetryTimeout = 0;
client.ResourceGroups.Delete("foo");
}
[Fact]
public void ResourceGroupDeleteThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = GetResourceManagementClient(handler);
Assert.Throws<ValidationException>(() => client.ResourceGroups.Delete(null));
Assert.Throws<ValidationException>(() => client.ResourceGroups.Delete("~`123"));
}
}
}
| |
// ------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.PSharp.DataFlowAnalysis
{
/// <summary>
/// A static analysis context.
/// </summary>
public sealed class AnalysisContext
{
/// <summary>
/// The solution of the P# program.
/// </summary>
public readonly Solution Solution;
/// <summary>
/// The project compilation for this analysis context.
/// </summary>
public readonly Compilation Compilation;
/// <summary>
/// Set of registered immutable types.
/// </summary>
private readonly ISet<Type> RegisteredImmutableTypes;
/// <summary>
/// Dictionary containing information about
/// gives-up ownership methods.
/// </summary>
internal IDictionary<string, ISet<int>> GivesUpOwnershipMethods;
/// <summary>
/// Initializes a new instance of the <see cref="AnalysisContext"/> class.
/// </summary>
/// <param name="project">The project to analyze.</param>
private AnalysisContext(Project project)
{
this.Solution = project.Solution;
this.Compilation = project.GetCompilationAsync().Result;
this.RegisteredImmutableTypes = new HashSet<Type>();
this.GivesUpOwnershipMethods = new Dictionary<string, ISet<int>>();
}
/// <summary>
/// Create a new static analysis context.
/// </summary>
public static AnalysisContext Create(Project project)
{
return new AnalysisContext(project);
}
/// <summary>
/// Registers the specified immutable type.
/// </summary>
public void RegisterImmutableType(Type type)
{
this.RegisteredImmutableTypes.Add(type);
}
/// <summary>
/// Registers the gives-up ownership method, and its gives-up parameter indexes.
/// The method name should include the full namespace.
/// </summary>
public void RegisterGivesUpOwnershipMethod(string methodName, ISet<int> givesUpParamIndexes)
{
if (this.GivesUpOwnershipMethods.ContainsKey(methodName))
{
this.GivesUpOwnershipMethods[methodName].Clear();
}
else
{
this.GivesUpOwnershipMethods.Add(methodName, new HashSet<int>());
}
this.GivesUpOwnershipMethods[methodName].UnionWith(givesUpParamIndexes);
}
/// <summary>
/// Returns the full name of the given class.
/// </summary>
public static string GetFullClassName(ClassDeclarationSyntax node)
{
string name = node.Identifier.ValueText;
return GetFullQualifierNameOfSyntaxNode(node) + name;
}
/// <summary>
/// Returns the full name of the given struct.
/// </summary>
public static string GetFullStructName(StructDeclarationSyntax node)
{
string name = node.Identifier.ValueText;
return GetFullQualifierNameOfSyntaxNode(node) + name;
}
/// <summary>
/// Returns the full name of the given method.
/// </summary>
public static string GetFullMethodName(BaseMethodDeclarationSyntax node)
{
string name = null;
if (node is MethodDeclarationSyntax)
{
name = (node as MethodDeclarationSyntax).Identifier.ValueText;
}
else if (node is ConstructorDeclarationSyntax)
{
name = (node as ConstructorDeclarationSyntax).Identifier.ValueText;
}
return GetFullQualifierNameOfSyntaxNode(node) + name;
}
/// <summary>
/// Returns the base type symbols of the given class.
/// </summary>
public IList<INamedTypeSymbol> GetBaseTypes(ClassDeclarationSyntax node)
{
var baseTypes = new List<INamedTypeSymbol>();
var model = this.Compilation.GetSemanticModel(node.SyntaxTree);
INamedTypeSymbol typeSymbol = model.GetDeclaredSymbol(node);
while (typeSymbol.BaseType != null)
{
baseTypes.Add(typeSymbol.BaseType);
typeSymbol = typeSymbol.BaseType;
}
return baseTypes;
}
/// <summary>
/// Returns true if the given type is passed by value or is immutable.
/// </summary>
public bool IsTypePassedByValueOrImmutable(ITypeSymbol type)
{
if (type.TypeKind == TypeKind.Array)
{
return false;
}
else if (type.TypeKind == TypeKind.Enum)
{
return true;
}
var typeName = type.ContainingNamespace.ToString() + "." + type.Name;
if (typeName.Equals(typeof(bool).FullName) ||
typeName.Equals(typeof(byte).FullName) ||
typeName.Equals(typeof(sbyte).FullName) ||
typeName.Equals(typeof(char).FullName) ||
typeName.Equals(typeof(decimal).FullName) ||
typeName.Equals(typeof(double).FullName) ||
typeName.Equals(typeof(float).FullName) ||
typeName.Equals(typeof(int).FullName) ||
typeName.Equals(typeof(uint).FullName) ||
typeName.Equals(typeof(long).FullName) ||
typeName.Equals(typeof(ulong).FullName) ||
typeName.Equals(typeof(short).FullName) ||
typeName.Equals(typeof(ushort).FullName) ||
typeName.Equals(typeof(string).FullName))
{
return true;
}
if (this.RegisteredImmutableTypes.Any(t => t.FullName.Equals(typeName)))
{
return true;
}
return false;
}
/// <summary>
/// Returns the identifier from the expression.
/// </summary>
public static IdentifierNameSyntax GetIdentifier(ExpressionSyntax expr)
{
IdentifierNameSyntax identifier = null;
ExpressionSyntax exprToParse = expr;
while (identifier is null)
{
if (exprToParse is IdentifierNameSyntax)
{
identifier = exprToParse as IdentifierNameSyntax;
}
else if (exprToParse is MemberAccessExpressionSyntax)
{
exprToParse = (exprToParse as MemberAccessExpressionSyntax).Name;
}
else if (exprToParse is ElementAccessExpressionSyntax)
{
exprToParse = (exprToParse as ElementAccessExpressionSyntax).Expression;
}
else if (exprToParse is BinaryExpressionSyntax &&
(exprToParse as BinaryExpressionSyntax).IsKind(SyntaxKind.AsExpression))
{
exprToParse = (exprToParse as BinaryExpressionSyntax).Left;
}
else
{
break;
}
}
return identifier;
}
/// <summary>
/// Returns the root identifier from the expression.
/// </summary>
public static IdentifierNameSyntax GetRootIdentifier(ExpressionSyntax expr)
{
IdentifierNameSyntax identifier = null;
ExpressionSyntax exprToParse = expr;
while (identifier is null)
{
if (exprToParse is IdentifierNameSyntax)
{
identifier = exprToParse as IdentifierNameSyntax;
}
else if (exprToParse is MemberAccessExpressionSyntax)
{
exprToParse = (exprToParse as MemberAccessExpressionSyntax).DescendantNodes().
OfType<IdentifierNameSyntax>().FirstOrDefault();
}
else if (exprToParse is ElementAccessExpressionSyntax)
{
exprToParse = (exprToParse as ElementAccessExpressionSyntax).Expression;
}
else if (exprToParse is BinaryExpressionSyntax &&
(exprToParse as BinaryExpressionSyntax).IsKind(SyntaxKind.AsExpression))
{
exprToParse = (exprToParse as BinaryExpressionSyntax).Left;
}
else
{
break;
}
}
return identifier;
}
/// <summary>
/// Returns all identifiers.
/// </summary>
public static HashSet<IdentifierNameSyntax> GetIdentifiers(ExpressionSyntax expr) =>
new HashSet<IdentifierNameSyntax>(expr.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>());
/// <summary>
/// Returns the callee of the given call expression.
/// </summary>
public static string GetCalleeOfInvocation(InvocationExpressionSyntax invocation)
{
string callee = string.Empty;
if (invocation.Expression is MemberAccessExpressionSyntax)
{
var memberAccessExpr = invocation.Expression as MemberAccessExpressionSyntax;
if (memberAccessExpr.Name is IdentifierNameSyntax)
{
callee = (memberAccessExpr.Name as IdentifierNameSyntax).Identifier.ValueText;
}
else if (memberAccessExpr.Name is GenericNameSyntax)
{
callee = (memberAccessExpr.Name as GenericNameSyntax).Identifier.ValueText;
}
}
else
{
callee = invocation.Expression.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().
First().Identifier.ValueText;
}
return callee;
}
/// <summary>
/// Returns the argument list after resolving the given call expression.
/// </summary>
public static ArgumentListSyntax GetArgumentList(ExpressionSyntax call)
{
ArgumentListSyntax argumentList = null;
if (call is InvocationExpressionSyntax)
{
argumentList = (call as InvocationExpressionSyntax).ArgumentList;
}
else if (call is ObjectCreationExpressionSyntax)
{
argumentList = (call as ObjectCreationExpressionSyntax).ArgumentList;
}
return argumentList;
}
/// <summary>
/// Returns the full qualifier name of the given syntax node.
/// </summary>
private static string GetFullQualifierNameOfSyntaxNode(SyntaxNode syntaxNode)
{
string result = string.Empty;
if (syntaxNode is null)
{
return result;
}
SyntaxNode ancestor = null;
while ((ancestor = syntaxNode.Ancestors().Where(val
=> val is ClassDeclarationSyntax).FirstOrDefault()) != null)
{
result = (ancestor as ClassDeclarationSyntax).Identifier.ValueText + "." + result;
syntaxNode = ancestor;
}
ancestor = null;
while ((ancestor = syntaxNode.Ancestors().Where(val
=> val is NamespaceDeclarationSyntax).FirstOrDefault()) != null)
{
result = (ancestor as NamespaceDeclarationSyntax).Name + "." + result;
syntaxNode = ancestor;
}
return result;
}
}
}
| |
// 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.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.ReferenceHighlighting
{
internal abstract class AbstractDocumentHighlightsService : IDocumentHighlightsService
{
public async Task<IEnumerable<DocumentHighlights>> GetDocumentHighlightsAsync(Document document, int position, IEnumerable<Document> documentsToSearch, CancellationToken cancellationToken)
{
// use speculative semantic model to see whether we are on a symbol we can do HR
var span = new TextSpan(position, 0);
var solution = document.Project.Solution;
var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false);
var symbol = SymbolFinder.FindSymbolAtPosition(semanticModel, position, solution.Workspace, cancellationToken: cancellationToken);
if (symbol == null)
{
return SpecializedCollections.EmptyEnumerable<DocumentHighlights>();
}
symbol = await GetSymbolToSearchAsync(document, position, semanticModel, symbol, cancellationToken).ConfigureAwait(false);
if (symbol == null)
{
return SpecializedCollections.EmptyEnumerable<DocumentHighlights>();
}
// Get unique tags for referenced symbols
return await GetTagsForReferencedSymbolAsync(symbol, ImmutableHashSet.CreateRange(documentsToSearch), solution, cancellationToken).ConfigureAwait(false);
}
private async Task<ISymbol> GetSymbolToSearchAsync(Document document, int position, SemanticModel semanticModel, ISymbol symbol, CancellationToken cancellationToken)
{
// see whether we can use the symbol as it is
var currentSemanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (currentSemanticModel == semanticModel)
{
return symbol;
}
// get symbols from current document again
return SymbolFinder.FindSymbolAtPosition(currentSemanticModel, position, document.Project.Solution.Workspace, cancellationToken: cancellationToken);
}
private async Task<IEnumerable<DocumentHighlights>> GetTagsForReferencedSymbolAsync(
ISymbol symbol,
IImmutableSet<Document> documentsToSearch,
Solution solution,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(symbol);
if (ShouldConsiderSymbol(symbol))
{
var references = await SymbolFinder.FindReferencesAsync(
symbol, solution, progress: null, documents: documentsToSearch, cancellationToken: cancellationToken).ConfigureAwait(false);
return await FilterAndCreateSpansAsync(references, solution, documentsToSearch, symbol, cancellationToken).ConfigureAwait(false);
}
return SpecializedCollections.EmptyEnumerable<DocumentHighlights>();
}
private bool ShouldConsiderSymbol(ISymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.Method:
switch (((IMethodSymbol)symbol).MethodKind)
{
case MethodKind.AnonymousFunction:
case MethodKind.PropertyGet:
case MethodKind.PropertySet:
case MethodKind.EventAdd:
case MethodKind.EventRaise:
case MethodKind.EventRemove:
return false;
default:
return true;
}
default:
return true;
}
}
private async Task<IEnumerable<DocumentHighlights>> FilterAndCreateSpansAsync(
IEnumerable<ReferencedSymbol> references, Solution solution, IImmutableSet<Document> documentsToSearch, ISymbol symbol, CancellationToken cancellationToken)
{
references = references.FilterUnreferencedSyntheticDefinitions();
references = references.FilterNonMatchingMethodNames(solution, symbol);
references = references.FilterToAliasMatches(symbol as IAliasSymbol);
if (symbol.IsConstructor())
{
references = references.Where(r => r.Definition.OriginalDefinition.Equals(symbol.OriginalDefinition));
}
var additionalReferences = new List<Location>();
foreach (var document in documentsToSearch)
{
additionalReferences.AddRange(await GetAdditionalReferencesAsync(document, symbol, cancellationToken).ConfigureAwait(false));
}
return await CreateSpansAsync(solution, symbol, references, additionalReferences, documentsToSearch, cancellationToken).ConfigureAwait(false);
}
private Task<IEnumerable<Location>> GetAdditionalReferencesAsync(
Document document, ISymbol symbol, CancellationToken cancellationToken)
{
var additionalReferenceProvider = document.Project.LanguageServices.GetService<IReferenceHighlightingAdditionalReferenceProvider>();
if (additionalReferenceProvider != null)
{
return additionalReferenceProvider.GetAdditionalReferencesAsync(document, symbol, cancellationToken);
}
return Task.FromResult<IEnumerable<Location>>(SpecializedCollections.EmptyEnumerable<Location>());
}
private async Task<IEnumerable<DocumentHighlights>> CreateSpansAsync(
Solution solution,
ISymbol symbol,
IEnumerable<ReferencedSymbol> references,
IEnumerable<Location> additionalReferences,
IImmutableSet<Document> documentToSearch,
CancellationToken cancellationToken)
{
var spanSet = new HashSet<ValueTuple<Document, TextSpan>>();
var tagMap = new MultiDictionary<Document, HighlightSpan>();
bool addAllDefinitions = true;
// Add definitions
// Filter out definitions that cannot be highlighted. e.g: alias symbols defined via project property pages.
if (symbol.Kind == SymbolKind.Alias &&
symbol.Locations.Length > 0)
{
addAllDefinitions = false;
if (symbol.Locations.First().IsInSource)
{
// For alias symbol we want to get the tag only for the alias definition, not the target symbol's definition.
await AddLocationSpan(symbol.Locations.First(), solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false);
}
}
// Add references and definitions
foreach (var reference in references)
{
if (addAllDefinitions && ShouldIncludeDefinition(reference.Definition))
{
foreach (var location in reference.Definition.Locations)
{
if (location.IsInSource)
{
var document = solution.GetDocument(location.SourceTree);
// GetDocument will return null for locations in #load'ed trees.
// TODO: Remove this check and add logic to fetch the #load'ed tree's
// Document once https://github.com/dotnet/roslyn/issues/5260 is fixed.
if (document == null)
{
Debug.Assert(solution.Workspace.Kind == "Interactive");
continue;
}
if (documentToSearch.Contains(document))
{
await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false);
}
}
}
}
foreach (var referenceLocation in reference.Locations)
{
var referenceKind = referenceLocation.IsWrittenTo ? HighlightSpanKind.WrittenReference : HighlightSpanKind.Reference;
await AddLocationSpan(referenceLocation.Location, solution, spanSet, tagMap, referenceKind, cancellationToken).ConfigureAwait(false);
}
}
// Add additional references
foreach (var location in additionalReferences)
{
await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Reference, cancellationToken).ConfigureAwait(false);
}
var list = new List<DocumentHighlights>(tagMap.Count);
foreach (var kvp in tagMap)
{
var spans = new List<HighlightSpan>(kvp.Value.Count);
foreach (var span in kvp.Value)
{
spans.Add(span);
}
list.Add(new DocumentHighlights(kvp.Key, spans));
}
return list;
}
private static bool ShouldIncludeDefinition(ISymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.Namespace:
return false;
case SymbolKind.NamedType:
return !((INamedTypeSymbol)symbol).IsScriptClass;
case SymbolKind.Parameter:
// If it's an indexer parameter, we will have also cascaded to the accessor
// one that actually receives the references
var containingProperty = symbol.ContainingSymbol as IPropertySymbol;
if (containingProperty != null && containingProperty.IsIndexer)
{
return false;
}
break;
}
return true;
}
private async Task AddLocationSpan(Location location, Solution solution, HashSet<ValueTuple<Document, TextSpan>> spanSet, MultiDictionary<Document, HighlightSpan> tagList, HighlightSpanKind kind, CancellationToken cancellationToken)
{
var span = await GetLocationSpanAsync(solution, location, cancellationToken).ConfigureAwait(false);
if (span != null && !spanSet.Contains(span.Value))
{
spanSet.Add(span.Value);
tagList.Add(span.Value.Item1, new HighlightSpan(span.Value.Item2, kind));
}
}
private async Task<ValueTuple<Document, TextSpan>?> GetLocationSpanAsync(Solution solution, Location location, CancellationToken cancellationToken)
{
var tree = location.SourceTree;
var document = solution.GetDocument(tree);
var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
// Specify findInsideTrivia: true to ensure that we search within XML doc comments.
var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var token = root.FindToken(location.SourceSpan.Start, findInsideTrivia: true);
return syntaxFacts.IsGenericName(token.Parent) || syntaxFacts.IsIndexerMemberCRef(token.Parent)
? ValueTuple.Create(document, token.Span)
: ValueTuple.Create(document, location.SourceSpan);
}
}
}
| |
using System.Collections;
using System.Collections.Concurrent;
using System.Globalization;
using System.Windows.Threading;
namespace Meziantou.Framework.WPF.Collections;
internal sealed class DispatchedObservableCollection<T> : ObservableCollectionBase<T>, IReadOnlyObservableCollection<T>, IList<T>, IList
{
private readonly ConcurrentQueue<PendingEvent<T>> _pendingEvents = new();
private readonly ConcurrentObservableCollection<T> _collection;
private readonly Dispatcher _dispatcher;
private bool _isDispatcherPending;
public DispatchedObservableCollection(ConcurrentObservableCollection<T> collection!!, Dispatcher dispatcher!!)
: base(collection)
{
_collection = collection;
_dispatcher = dispatcher;
}
private void AssertIsOnDispatcherThread()
{
if (!IsOnDispatcherThread())
{
var currentThreadId = Environment.CurrentManagedThreadId;
throw new InvalidOperationException("The collection must be accessed from the dispatcher thread only. Current thread ID: " + currentThreadId.ToString(CultureInfo.InvariantCulture));
}
}
private static void AssertType(object? value, string argumentName)
{
if (value is null || value is T)
return;
throw new ArgumentException($"value must be of type '{typeof(T).FullName}'", argumentName);
}
public int Count
{
get
{
AssertIsOnDispatcherThread();
return Items.Count;
}
}
bool ICollection<T>.IsReadOnly
{
get
{
AssertIsOnDispatcherThread();
return ((ICollection<T>)_collection).IsReadOnly;
}
}
int ICollection.Count
{
get
{
AssertIsOnDispatcherThread();
return Count;
}
}
object ICollection.SyncRoot
{
get
{
AssertIsOnDispatcherThread();
return ((ICollection)Items).SyncRoot;
}
}
bool ICollection.IsSynchronized
{
get
{
AssertIsOnDispatcherThread();
return ((ICollection)Items).IsSynchronized;
}
}
bool IList.IsReadOnly
{
get
{
AssertIsOnDispatcherThread();
return ((IList)Items).IsReadOnly;
}
}
bool IList.IsFixedSize
{
get
{
AssertIsOnDispatcherThread();
return ((IList)Items).IsFixedSize;
}
}
object? IList.this[int index]
{
get
{
AssertIsOnDispatcherThread();
return this[index];
}
set
{
// it will immediatly modify both collections as we are on the dispatcher thread
AssertType(value, nameof(value));
AssertIsOnDispatcherThread();
_collection[index] = (T)value!;
}
}
T IList<T>.this[int index]
{
get
{
AssertIsOnDispatcherThread();
return this[index];
}
set
{
// it will immediatly modify both collections as we are on the dispatcher thread
AssertIsOnDispatcherThread();
_collection[index] = value;
}
}
public IEnumerator<T> GetEnumerator()
{
AssertIsOnDispatcherThread();
return Items.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public void CopyTo(T[] array, int arrayIndex)
{
AssertIsOnDispatcherThread();
Items.CopyTo(array, arrayIndex);
}
public int IndexOf(T item)
{
AssertIsOnDispatcherThread();
return Items.IndexOf(item);
}
public bool Contains(T item)
{
AssertIsOnDispatcherThread();
return Items.Contains(item);
}
public T this[int index]
{
get
{
AssertIsOnDispatcherThread();
return Items[index];
}
}
internal void EnqueueReplace(int index, T value)
{
EnqueueEvent(PendingEvent.Replace(index, value));
}
internal void EnqueueReset(System.Collections.Immutable.ImmutableList<T> items)
{
EnqueueEvent(PendingEvent.Reset(items));
}
internal void EnqueueAdd(T item)
{
EnqueueEvent(PendingEvent.Add(item));
}
internal void EnqueueAddRange(System.Collections.Immutable.ImmutableList<T> items)
{
EnqueueEvent(PendingEvent.AddRange(items));
}
internal bool EnqueueRemove(T item)
{
EnqueueEvent(PendingEvent.Remove(item));
return true;
}
internal void EnqueueRemoveAt(int index)
{
EnqueueEvent(PendingEvent.RemoveAt<T>(index));
}
internal void EnqueueClear()
{
EnqueueEvent(PendingEvent.Clear<T>());
}
internal void EnqueueInsert(int index, T item)
{
EnqueueEvent(PendingEvent.Insert(index, item));
}
internal void EnqueueInsertRange(int index, System.Collections.Immutable.ImmutableList<T> items)
{
EnqueueEvent(PendingEvent.InsertRange(index, items));
}
private void EnqueueEvent(PendingEvent<T> @event)
{
_pendingEvents.Enqueue(@event);
ProcessPendingEventsOrDispatch();
}
private void ProcessPendingEventsOrDispatch()
{
if (!IsOnDispatcherThread())
{
if (!_isDispatcherPending)
{
_isDispatcherPending = true;
_dispatcher.BeginInvoke(ProcessPendingEvents);
}
return;
}
ProcessPendingEvents();
}
private void ProcessPendingEvents()
{
_isDispatcherPending = false;
while (_pendingEvents.TryDequeue(out var pendingEvent))
{
switch (pendingEvent.Type)
{
case PendingEventType.Add:
AddItem(pendingEvent.Item);
break;
case PendingEventType.AddRange:
AddItems(pendingEvent.Items);
break;
case PendingEventType.Remove:
RemoveItem(pendingEvent.Item);
break;
case PendingEventType.Clear:
ClearItems();
break;
case PendingEventType.Insert:
InsertItem(pendingEvent.Index, pendingEvent.Item);
break;
case PendingEventType.InsertRange:
InsertItems(pendingEvent.Index, pendingEvent.Items);
break;
case PendingEventType.RemoveAt:
RemoveItemAt(pendingEvent.Index);
break;
case PendingEventType.Replace:
ReplaceItem(pendingEvent.Index, pendingEvent.Item);
break;
case PendingEventType.Reset:
Reset(pendingEvent.Items);
break;
}
}
}
private bool IsOnDispatcherThread()
{
return _dispatcher.Thread == Thread.CurrentThread;
}
void IList<T>.Insert(int index, T item)
{
// it will immediatly modify both collections as we are on the dispatcher thread
AssertIsOnDispatcherThread();
_collection.Insert(index, item);
}
void IList<T>.RemoveAt(int index)
{
// it will immediatly modify both collections as we are on the dispatcher thread
AssertIsOnDispatcherThread();
_collection.RemoveAt(index);
}
void ICollection<T>.Add(T item)
{
// it will immediatly modify both collections as we are on the dispatcher thread
AssertIsOnDispatcherThread();
_collection.Add(item);
}
void ICollection<T>.Clear()
{
// it will immediatly modify both collections as we are on the dispatcher thread
AssertIsOnDispatcherThread();
_collection.Clear();
}
bool ICollection<T>.Remove(T item)
{
// it will immediatly modify both collections as we are on the dispatcher thread
AssertIsOnDispatcherThread();
return _collection.Remove(item);
}
void ICollection.CopyTo(Array array, int index)
{
((ICollection)Items).CopyTo(array, index);
}
int IList.Add(object? value)
{
// it will immediatly modify both collections as we are on the dispatcher thread
AssertType(value, nameof(value));
AssertIsOnDispatcherThread();
return ((IList)_collection).Add(value);
}
bool IList.Contains(object? value)
{
// it will immediatly modify both collections as we are on the dispatcher thread
AssertType(value, nameof(value));
AssertIsOnDispatcherThread();
return ((IList)_collection).Contains(value);
}
void IList.Clear()
{
// it will immediatly modify both collections as we are on the dispatcher thread
AssertIsOnDispatcherThread();
((IList)_collection).Clear();
}
int IList.IndexOf(object? value)
{
// it will immediatly modify both collections as we are on the dispatcher thread
AssertType(value, nameof(value));
AssertIsOnDispatcherThread();
return Items.IndexOf((T)value!);
}
void IList.Insert(int index, object? value)
{
// it will immediatly modify both collections as we are on the dispatcher thread
AssertType(value, nameof(value));
AssertIsOnDispatcherThread();
((IList)_collection).Insert(index, value);
}
void IList.Remove(object? value)
{
// it will immediatly modify both collections as we are on the dispatcher thread
AssertType(value, nameof(value));
AssertIsOnDispatcherThread();
((IList)_collection).Remove(value);
}
void IList.RemoveAt(int index)
{
// it will immediatly modify both collections as we are on the dispatcher thread
AssertIsOnDispatcherThread();
((IList)_collection).RemoveAt(index);
}
}
| |
#region License
// <copyright file="HelpText.cs" company="Giacomo Stelluti Scala">
// Copyright 2015-2013 Giacomo Stelluti Scala
// </copyright>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
#region Using Directives
using System;
using System.Collections.Generic;
using System.Text;
using CommandLine.Extensions;
using CommandLine.Infrastructure;
#endregion
namespace CommandLine.Text
{
/// <summary>
/// Provides means to format an help screen.
/// You can assign it in place of a <see cref="System.String"/> instance.
/// </summary>
public class HelpText
{
private const int BuilderCapacity = 128;
private const int DefaultMaximumLength = 80; // default console width
private const string DefaultRequiredWord = "Required.";
private readonly StringBuilder _preOptionsHelp;
private readonly StringBuilder _postOptionsHelp;
private readonly BaseSentenceBuilder _sentenceBuilder;
private int? _maximumDisplayWidth;
private string _heading;
private string _copyright;
private bool _additionalNewLineAfterOption;
private StringBuilder _optionsHelp;
private bool _addDashesToOption;
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class.
/// </summary>
public HelpText()
{
_preOptionsHelp = new StringBuilder(BuilderCapacity);
_postOptionsHelp = new StringBuilder(BuilderCapacity);
_sentenceBuilder = BaseSentenceBuilder.CreateBuiltIn();
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class
/// specifying the sentence builder.
/// </summary>
/// <param name="sentenceBuilder">
/// A <see cref="BaseSentenceBuilder"/> instance.
/// </param>
public HelpText(BaseSentenceBuilder sentenceBuilder)
: this()
{
Assumes.NotNull(sentenceBuilder, "sentenceBuilder");
_sentenceBuilder = sentenceBuilder;
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class
/// specifying heading string.
/// </summary>
/// <param name="heading">An heading string or an instance of <see cref="CommandLine.Text.HeadingInfo"/>.</param>
/// <exception cref="System.ArgumentException">Thrown when parameter <paramref name="heading"/> is null or empty string.</exception>
public HelpText(string heading)
: this()
{
Assumes.NotNullOrEmpty(heading, "heading");
_heading = heading;
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class
/// specifying the sentence builder and heading string.
/// </summary>
/// <param name="sentenceBuilder">A <see cref="BaseSentenceBuilder"/> instance.</param>
/// <param name="heading">A string with heading or an instance of <see cref="CommandLine.Text.HeadingInfo"/>.</param>
public HelpText(BaseSentenceBuilder sentenceBuilder, string heading)
: this(heading)
{
Assumes.NotNull(sentenceBuilder, "sentenceBuilder");
_sentenceBuilder = sentenceBuilder;
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class
/// specifying heading and copyright strings.
/// </summary>
/// <param name="heading">A string with heading or an instance of <see cref="CommandLine.Text.HeadingInfo"/>.</param>
/// <param name="copyright">A string with copyright or an instance of <see cref="CommandLine.Text.CopyrightInfo"/>.</param>
/// <exception cref="System.ArgumentException">Thrown when one or more parameters <paramref name="heading"/> are null or empty strings.</exception>
public HelpText(string heading, string copyright)
: this()
{
Assumes.NotNullOrEmpty(heading, "heading");
Assumes.NotNullOrEmpty(copyright, "copyright");
_heading = heading;
_copyright = copyright;
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class
/// specifying heading and copyright strings.
/// </summary>
/// <param name="sentenceBuilder">A <see cref="BaseSentenceBuilder"/> instance.</param>
/// <param name="heading">A string with heading or an instance of <see cref="CommandLine.Text.HeadingInfo"/>.</param>
/// <param name="copyright">A string with copyright or an instance of <see cref="CommandLine.Text.CopyrightInfo"/>.</param>
/// <exception cref="System.ArgumentException">Thrown when one or more parameters <paramref name="heading"/> are null or empty strings.</exception>
public HelpText(BaseSentenceBuilder sentenceBuilder, string heading, string copyright)
: this(heading, copyright)
{
Assumes.NotNull(sentenceBuilder, "sentenceBuilder");
_sentenceBuilder = sentenceBuilder;
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class
/// specifying heading and copyright strings.
/// </summary>
/// <param name="heading">A string with heading or an instance of <see cref="CommandLine.Text.HeadingInfo"/>.</param>
/// <param name="copyright">A string with copyright or an instance of <see cref="CommandLine.Text.CopyrightInfo"/>.</param>
/// <param name="options">The instance that collected command line arguments parsed with <see cref="Parser"/> class.</param>
/// <exception cref="System.ArgumentException">Thrown when one or more parameters <paramref name="heading"/> are null or empty strings.</exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "When DoAddOptions is called with fireEvent=false virtual member is not called")]
public HelpText(string heading, string copyright, object options)
: this()
{
Assumes.NotNullOrEmpty(heading, "heading");
Assumes.NotNullOrEmpty(copyright, "copyright");
Assumes.NotNull(options, "options");
_heading = heading;
_copyright = copyright;
DoAddOptions(options, DefaultRequiredWord, MaximumDisplayWidth, fireEvent: false);
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class
/// specifying heading and copyright strings.
/// </summary>
/// <param name="sentenceBuilder">A <see cref="BaseSentenceBuilder"/> instance.</param>
/// <param name="heading">A string with heading or an instance of <see cref="CommandLine.Text.HeadingInfo"/>.</param>
/// <param name="copyright">A string with copyright or an instance of <see cref="CommandLine.Text.CopyrightInfo"/>.</param>
/// <param name="options">The instance that collected command line arguments parsed with <see cref="Parser"/> class.</param>
/// <exception cref="System.ArgumentException">Thrown when one or more parameters <paramref name="heading"/> are null or empty strings.</exception>
public HelpText(BaseSentenceBuilder sentenceBuilder, string heading, string copyright, object options)
: this(heading, copyright, options)
{
Assumes.NotNull(sentenceBuilder, "sentenceBuilder");
_sentenceBuilder = sentenceBuilder;
}
/// <summary>
/// Occurs when an option help text is formatted.
/// </summary>
public event EventHandler<FormatOptionHelpTextEventArgs> FormatOptionHelpText;
/// <summary>
/// Gets or sets the heading string.
/// You can directly assign a <see cref="CommandLine.Text.HeadingInfo"/> instance.
/// </summary>
public string Heading
{
get
{
return _heading;
}
set
{
Assumes.NotNullOrEmpty(value, "value");
_heading = value;
}
}
/// <summary>
/// Gets or sets the copyright string.
/// You can directly assign a <see cref="CommandLine.Text.CopyrightInfo"/> instance.
/// </summary>
public string Copyright
{
get
{
return _heading;
}
set
{
Assumes.NotNullOrEmpty(value, "value");
_copyright = value;
}
}
/// <summary>
/// Gets or sets the maximum width of the display. This determines word wrap when displaying the text.
/// </summary>
/// <value>The maximum width of the display.</value>
public int MaximumDisplayWidth
{
get { return _maximumDisplayWidth.HasValue ? _maximumDisplayWidth.Value : DefaultMaximumLength; }
set { _maximumDisplayWidth = value; }
}
/// <summary>
/// Gets or sets a value indicating whether the format of options should contain dashes.
/// It modifies behavior of <see cref="AddOptions(System.Object)"/> method.
/// </summary>
public bool AddDashesToOption
{
get { return this._addDashesToOption; }
set { this._addDashesToOption = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to add an additional line after the description of the option.
/// </summary>
public bool AdditionalNewLineAfterOption
{
get { return _additionalNewLineAfterOption; }
set { _additionalNewLineAfterOption = value; }
}
/// <summary>
/// Gets the <see cref="BaseSentenceBuilder"/> instance specified in constructor.
/// </summary>
public BaseSentenceBuilder SentenceBuilder
{
get { return _sentenceBuilder; }
}
/// <summary>
/// Creates a new instance of the <see cref="CommandLine.Text.HelpText"/> class using common defaults.
/// </summary>
/// <returns>
/// An instance of <see cref="CommandLine.Text.HelpText"/> class.
/// </returns>
/// <param name='options'>The instance that collected command line arguments parsed with <see cref="Parser"/> class.</param>
public static HelpText AutoBuild(object options)
{
return AutoBuild(options, (Action<HelpText>)null);
}
/// <summary>
/// Creates a new instance of the <see cref="CommandLine.Text.HelpText"/> class using common defaults.
/// </summary>
/// <returns>
/// An instance of <see cref="CommandLine.Text.HelpText"/> class.
/// </returns>
/// <param name='options'>The instance that collected command line arguments parsed with <see cref="Parser"/> class.</param>
/// <param name='onError'>A delegate used to customize the text block for reporting parsing errors.</param>
/// <param name="verbsIndex">If true the output style is consistent with verb commands (no dashes), otherwise it outputs options.</param>
public static HelpText AutoBuild(object options, Action<HelpText> onError, bool verbsIndex = false)
{
var auto = new HelpText
{
Heading = HeadingInfo.Default,
Copyright = CopyrightInfo.Default,
AdditionalNewLineAfterOption = true,
AddDashesToOption = !verbsIndex
};
if (onError != null)
{
var list = ReflectionHelper.RetrievePropertyList<ParserStateAttribute>(options);
if (list != null)
{
onError(auto);
}
}
var license = ReflectionHelper.GetAttribute<AssemblyLicenseAttribute>();
if (license != null)
{
license.AddToHelpText(auto, true);
}
var usage = ReflectionHelper.GetAttribute<AssemblyUsageAttribute>();
if (usage != null)
{
usage.AddToHelpText(auto, true);
}
auto.AddOptions(options);
return auto;
}
/// <summary>
/// Creates a new instance of the <see cref="CommandLine.Text.HelpText"/> class using common defaults,
/// for verb commands scenario.
/// </summary>
/// <returns>
/// An instance of <see cref="CommandLine.Text.HelpText"/> class.
/// </returns>
/// <param name='options'>The instance that collected command line arguments parsed with <see cref="Parser"/> class.</param>
/// <param name="verb">The verb command invoked.</param>
public static HelpText AutoBuild(object options, string verb)
{
bool found;
var instance = Parser.InternalGetVerbOptionsInstanceByName(verb, options, out found);
var verbsIndex = verb == null || !found;
var target = verbsIndex ? options : instance;
return HelpText.AutoBuild(target, current => HelpText.DefaultParsingErrorsHandler(target, current), verbsIndex);
}
/// <summary>
/// Supplies a default parsing error handler implementation.
/// </summary>
/// <param name="options">The instance that collects parsed arguments parsed and associates <see cref="CommandLine.ParserStateAttribute"/>
/// to a property of type <see cref="IParserState"/>.</param>
/// <param name="current">The <see cref="CommandLine.Text.HelpText"/> instance.</param>
public static void DefaultParsingErrorsHandler(object options, HelpText current)
{
var list = ReflectionHelper.RetrievePropertyList<ParserStateAttribute>(options);
if (list.Count == 0)
{
return;
}
var parserState = (IParserState)list[0].Left.GetValue(options, null);
if (parserState == null || parserState.Errors.Count == 0)
{
return;
}
var errors = current.RenderParsingErrorsText(options, 2); // indent with two spaces
if (!string.IsNullOrEmpty(errors))
{
current.AddPreOptionsLine(string.Concat(Environment.NewLine, current.SentenceBuilder.ErrorsHeadingText));
var lines = errors.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
foreach (var line in lines)
{
current.AddPreOptionsLine(line);
}
}
}
/// <summary>
/// Converts the help instance to a <see cref="System.String"/>.
/// </summary>
/// <param name="info">This <see cref="CommandLine.Text.HelpText"/> instance.</param>
/// <returns>The <see cref="System.String"/> that contains the help screen.</returns>
public static implicit operator string(HelpText info)
{
return info.ToString();
}
/// <summary>
/// Adds a text line after copyright and before options usage strings.
/// </summary>
/// <param name="value">A <see cref="System.String"/> instance.</param>
/// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="value"/> is null or empty string.</exception>
public void AddPreOptionsLine(string value)
{
AddPreOptionsLine(value, MaximumDisplayWidth);
}
/// <summary>
/// Adds a text line at the bottom, after options usage string.
/// </summary>
/// <param name="value">A <see cref="System.String"/> instance.</param>
/// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="value"/> is null or empty string.</exception>
public void AddPostOptionsLine(string value)
{
AddLine(_postOptionsHelp, value);
}
/// <summary>
/// Adds a text block with options usage string.
/// </summary>
/// <param name="options">The instance that collected command line arguments parsed with <see cref="Parser"/> class.</param>
/// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="options"/> is null.</exception>
public void AddOptions(object options)
{
AddOptions(options, DefaultRequiredWord);
}
/// <summary>
/// Adds a text block with options usage string.
/// </summary>
/// <param name="options">The instance that collected command line arguments parsed with the <see cref="Parser"/> class.</param>
/// <param name="requiredWord">The word to use when the option is required.</param>
/// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="options"/> is null.</exception>
/// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="requiredWord"/> is null or empty string.</exception>
public void AddOptions(object options, string requiredWord)
{
Assumes.NotNull(options, "options");
Assumes.NotNullOrEmpty(requiredWord, "requiredWord");
AddOptions(options, requiredWord, MaximumDisplayWidth);
}
/// <summary>
/// Adds a text block with options usage string.
/// </summary>
/// <param name="options">The instance that collected command line arguments parsed with the <see cref="Parser"/> class.</param>
/// <param name="requiredWord">The word to use when the option is required.</param>
/// <param name="maximumLength">The maximum length of the help documentation.</param>
/// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="options"/> is null.</exception>
/// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="requiredWord"/> is null or empty string.</exception>
public void AddOptions(object options, string requiredWord, int maximumLength)
{
Assumes.NotNull(options, "options");
Assumes.NotNullOrEmpty(requiredWord, "requiredWord");
DoAddOptions(options, requiredWord, maximumLength);
}
/// <summary>
/// Builds a string that contains a parsing error message.
/// </summary>
/// <param name="options">An options target instance that collects parsed arguments parsed with the <see cref="CommandLine.ParserStateAttribute"/>
/// associated to a property of type <see cref="IParserState"/>.</param>
/// <param name="indent">Number of spaces used to indent text.</param>
/// <returns>The <see cref="System.String"/> that contains the parsing error message.</returns>
public string RenderParsingErrorsText(object options, int indent)
{
var list = ReflectionHelper.RetrievePropertyList<ParserStateAttribute>(options);
if (list.Count == 0)
{
return string.Empty; // Or exception?
}
var parserState = (IParserState)list[0].Left.GetValue(options, null);
if (parserState == null || parserState.Errors.Count == 0)
{
return string.Empty;
}
var text = new StringBuilder();
foreach (var e in parserState.Errors)
{
var line = new StringBuilder();
line.Append(indent.Spaces());
if (e.BadOption.ShortName != null)
{
line.Append('-');
line.Append(e.BadOption.ShortName);
if (!string.IsNullOrEmpty(e.BadOption.LongName))
{
line.Append('/');
}
}
if (!string.IsNullOrEmpty(e.BadOption.LongName))
{
line.Append("--");
line.Append(e.BadOption.LongName);
}
line.Append(" ");
line.Append(e.ViolatesRequired ?
_sentenceBuilder.RequiredOptionMissingText :
_sentenceBuilder.OptionWord);
if (e.ViolatesFormat)
{
line.Append(" ");
line.Append(_sentenceBuilder.ViolatesFormatText);
}
if (e.ViolatesMutualExclusiveness)
{
if (e.ViolatesFormat || e.ViolatesRequired)
{
line.Append(" ");
line.Append(_sentenceBuilder.AndWord);
}
line.Append(" ");
line.Append(_sentenceBuilder.ViolatesMutualExclusivenessText);
}
line.Append('.');
text.AppendLine(line.ToString());
}
return text.ToString();
}
/// <summary>
/// Returns the help screen as a <see cref="System.String"/>.
/// </summary>
/// <returns>The <see cref="System.String"/> that contains the help screen.</returns>
public override string ToString()
{
const int ExtraLength = 10;
var builder = new StringBuilder(GetLength(_heading) + GetLength(_copyright) +
GetLength(_preOptionsHelp) + GetLength(this._optionsHelp) + ExtraLength);
builder.Append(_heading);
if (!string.IsNullOrEmpty(_copyright))
{
builder.Append(Environment.NewLine);
builder.Append(_copyright);
}
if (_preOptionsHelp.Length > 0)
{
builder.Append(Environment.NewLine);
builder.Append(_preOptionsHelp);
}
if (this._optionsHelp != null && this._optionsHelp.Length > 0)
{
builder.Append(Environment.NewLine);
builder.Append(Environment.NewLine);
builder.Append(this._optionsHelp);
}
if (_postOptionsHelp.Length > 0)
{
builder.Append(Environment.NewLine);
builder.Append(_postOptionsHelp);
}
return builder.ToString();
}
/// <summary>
/// The OnFormatOptionHelpText method also allows derived classes to handle the event without attaching a delegate.
/// This is the preferred technique for handling the event in a derived class.
/// </summary>
/// <param name="e">Data for the <see cref="FormatOptionHelpText"/> event.</param>
protected virtual void OnFormatOptionHelpText(FormatOptionHelpTextEventArgs e)
{
EventHandler<FormatOptionHelpTextEventArgs> handler = FormatOptionHelpText;
if (handler != null)
{
handler(this, e);
}
}
private static int GetLength(string value)
{
if (value == null)
{
return 0;
}
return value.Length;
}
private static int GetLength(StringBuilder value)
{
if (value == null)
{
return 0;
}
return value.Length;
}
private static void AddLine(StringBuilder builder, string value, int maximumLength)
{
Assumes.NotNull(value, "value");
if (builder.Length > 0)
{
builder.Append(Environment.NewLine);
}
do
{
int wordBuffer = 0;
string[] words = value.Split(new[] { ' ' });
for (int i = 0; i < words.Length; i++)
{
if (words[i].Length < (maximumLength - wordBuffer))
{
builder.Append(words[i]);
wordBuffer += words[i].Length;
if ((maximumLength - wordBuffer) > 1 && i != words.Length - 1)
{
builder.Append(" ");
wordBuffer++;
}
}
else if (words[i].Length >= maximumLength && wordBuffer == 0)
{
builder.Append(words[i].Substring(0, maximumLength));
wordBuffer = maximumLength;
break;
}
else
{
break;
}
}
value = value.Substring(Math.Min(wordBuffer, value.Length));
if (value.Length > 0)
{
builder.Append(Environment.NewLine);
}
}
while (value.Length > maximumLength);
builder.Append(value);
}
private void DoAddOptions(object options, string requiredWord, int maximumLength, bool fireEvent = true)
{
var optionList = ReflectionHelper.RetrievePropertyAttributeList<BaseOptionAttribute>(options);
var optionHelp = ReflectionHelper.RetrieveMethodAttributeOnly<HelpOptionAttribute>(options);
if (optionHelp != null)
{
optionList.Add(optionHelp);
}
if (optionList.Count == 0)
{
return;
}
int maxLength = GetMaxLength(optionList);
this._optionsHelp = new StringBuilder(BuilderCapacity);
int remainingSpace = maximumLength - (maxLength + 6);
foreach (BaseOptionAttribute option in optionList)
{
AddOption(requiredWord, maxLength, option, remainingSpace, fireEvent);
}
}
private void AddPreOptionsLine(string value, int maximumLength)
{
AddLine(_preOptionsHelp, value, maximumLength);
}
private void AddOption(string requiredWord, int maxLength, BaseOptionAttribute option, int widthOfHelpText, bool fireEvent = true)
{
this._optionsHelp.Append(" ");
var optionName = new StringBuilder(maxLength);
if (option.HasShortName)
{
if (this._addDashesToOption)
{
optionName.Append('-');
}
optionName.AppendFormat("{0}", option.ShortName);
if (option.HasMetaValue)
{
optionName.AppendFormat(" {0}", option.MetaValue);
}
if (option.HasLongName)
{
optionName.Append(", ");
}
}
if (option.HasLongName)
{
if (this._addDashesToOption)
{
optionName.Append("--");
}
optionName.AppendFormat("{0}", option.LongName);
if (option.HasMetaValue)
{
optionName.AppendFormat("={0}", option.MetaValue);
}
}
this._optionsHelp.Append(optionName.Length < maxLength ?
optionName.ToString().PadRight(maxLength) :
optionName.ToString());
this._optionsHelp.Append(" ");
if (option.HasDefaultValue)
{
option.HelpText = "(Default: {0}) ".FormatLocal(option.DefaultValue) + option.HelpText;
}
if (option.Required)
{
option.HelpText = "{0} ".FormatInvariant(requiredWord) + option.HelpText;
}
if (fireEvent)
{
var e = new FormatOptionHelpTextEventArgs(option);
OnFormatOptionHelpText(e);
option.HelpText = e.Option.HelpText;
}
if (!string.IsNullOrEmpty(option.HelpText))
{
do
{
int wordBuffer = 0;
var words = option.HelpText.Split(new[] { ' ' });
for (int i = 0; i < words.Length; i++)
{
if (words[i].Length < (widthOfHelpText - wordBuffer))
{
this._optionsHelp.Append(words[i]);
wordBuffer += words[i].Length;
if ((widthOfHelpText - wordBuffer) > 1 && i != words.Length - 1)
{
this._optionsHelp.Append(" ");
wordBuffer++;
}
}
else if (words[i].Length >= widthOfHelpText && wordBuffer == 0)
{
this._optionsHelp.Append(words[i].Substring(0, widthOfHelpText));
wordBuffer = widthOfHelpText;
break;
}
else
{
break;
}
}
option.HelpText = option.HelpText.Substring(
Math.Min(wordBuffer, option.HelpText.Length)).Trim();
if (option.HelpText.Length > 0)
{
this._optionsHelp.Append(Environment.NewLine);
this._optionsHelp.Append(new string(' ', maxLength + 6));
}
}
while (option.HelpText.Length > widthOfHelpText);
}
this._optionsHelp.Append(option.HelpText);
this._optionsHelp.Append(Environment.NewLine);
if (_additionalNewLineAfterOption)
{
this._optionsHelp.Append(Environment.NewLine);
}
}
private void AddLine(StringBuilder builder, string value)
{
Assumes.NotNull(value, "value");
AddLine(builder, value, MaximumDisplayWidth);
}
private int GetMaxLength(IEnumerable<BaseOptionAttribute> optionList)
{
int length = 0;
foreach (BaseOptionAttribute option in optionList)
{
int optionLength = 0;
bool hasShort = option.HasShortName;
bool hasLong = option.HasLongName;
int metaLength = 0;
if (option.HasMetaValue)
{
metaLength = option.MetaValue.Length + 1;
}
if (hasShort)
{
++optionLength;
if (AddDashesToOption)
{
++optionLength;
}
optionLength += metaLength;
}
if (hasLong)
{
optionLength += option.LongName.Length;
if (AddDashesToOption)
{
optionLength += 2;
}
optionLength += metaLength;
}
if (hasShort && hasLong)
{
optionLength += 2; // ", "
}
length = Math.Max(length, optionLength);
}
return length;
}
}
}
| |
/*
* 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.Threading;
using log4net;
using OpenSim.Framework;
using OpenSim.Framework.RegionLoader.Filesystem;
using OpenSim.Framework.RegionLoader.Web;
using OpenSim.Region.CoreModules.Agent.AssetTransaction;
using OpenSim.Region.CoreModules.Avatar.InstantMessage;
using OpenSim.Region.CoreModules.Scripting.DynamicTexture;
using OpenSim.Region.CoreModules.Scripting.LoadImageURL;
using OpenSim.Region.CoreModules.Scripting.XMLRPC;
namespace OpenSim.ApplicationPlugins.LoadRegions
{
public class LoadRegionsPlugin : IApplicationPlugin, IRegionCreator
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public event NewRegionCreated OnNewRegionCreated;
private NewRegionCreated m_newRegionCreatedHandler;
#region IApplicationPlugin Members
// TODO: required by IPlugin, but likely not at all right
private string m_name = "LoadRegionsPlugin";
private string m_version = "0.0";
public string Version
{
get { return m_version; }
}
public string Name
{
get { return m_name; }
}
protected OpenSimBase m_openSim;
public void Initialise()
{
m_log.Error("[LOADREGIONS]: " + Name + " cannot be default-initialized!");
throw new PluginNotInitialisedException(Name);
}
public void Initialise(OpenSimBase openSim)
{
m_openSim = openSim;
m_openSim.ApplicationRegistry.RegisterInterface<IRegionCreator>(this);
}
public void PostInitialise()
{
//m_log.Info("[LOADREGIONS]: Load Regions addin being initialised");
IRegionLoader regionLoader;
if (m_openSim.ConfigSource.Source.Configs["Startup"].GetString("region_info_source", "filesystem") == "filesystem")
{
m_log.Info("[LOADREGIONS]: Loading region configurations from filesystem");
regionLoader = new RegionLoaderFileSystem();
}
else
{
m_log.Info("[LOADREGIONSPLUGIN]: Loading region configurations from web");
regionLoader = new RegionLoaderWebServer();
}
m_log.Info("[LOADREGIONSPLUGIN]: Loading region configurations...");
regionLoader.SetIniConfigSource(m_openSim.ConfigSource.Source);
RegionInfo[] regionsToLoad = regionLoader.LoadRegions();
m_log.Info("[LOADREGIONSPLUGIN]: Loading specific shared modules...");
m_log.Info("[LOADREGIONSPLUGIN]: DynamicTextureModule...");
m_openSim.ModuleLoader.LoadDefaultSharedModule(new DynamicTextureModule());
m_log.Info("[LOADREGIONSPLUGIN]: InstantMessageModule...");
m_openSim.ModuleLoader.LoadDefaultSharedModule(new InstantMessageModule());
m_log.Info("[LOADREGIONSPLUGIN]: LoadImageURLModule...");
m_openSim.ModuleLoader.LoadDefaultSharedModule(new LoadImageURLModule());
m_log.Info("[LOADREGIONSPLUGIN]: XMLRPCModule...");
m_openSim.ModuleLoader.LoadDefaultSharedModule(new XMLRPCModule());
m_log.Info("[LOADREGIONSPLUGIN]: AssetTransactionModule...");
m_openSim.ModuleLoader.LoadDefaultSharedModule(new AssetTransactionModule());
m_log.Info("[LOADREGIONSPLUGIN]: Done.");
if (!CheckRegionsForSanity(regionsToLoad))
{
m_log.Error("[LOADREGIONS]: Halting startup due to conflicts in region configurations");
Environment.Exit(1);
}
for (int i = 0; i < regionsToLoad.Length; i++)
{
IScene scene;
m_log.Debug("[LOADREGIONS]: Creating Region: " + regionsToLoad[i].RegionName + " (ThreadID: " +
Thread.CurrentThread.ManagedThreadId.ToString() +
")");
m_openSim.CreateRegion(regionsToLoad[i], true, out scene);
if (scene != null)
{
m_newRegionCreatedHandler = OnNewRegionCreated;
if (m_newRegionCreatedHandler != null)
{
m_newRegionCreatedHandler(scene);
}
}
}
m_openSim.ModuleLoader.PostInitialise();
m_openSim.ModuleLoader.ClearCache();
}
public void Dispose()
{
}
#endregion
/// <summary>
/// Check that region configuration information makes sense.
/// </summary>
/// <param name="regions"></param>
/// <returns>True if we're sane, false if we're insane</returns>
private bool CheckRegionsForSanity(RegionInfo[] regions)
{
if (regions.Length <= 1)
return true;
for (int i = 0; i < regions.Length - 1; i++)
{
for (int j = i + 1; j < regions.Length; j++)
{
if (regions[i].RegionID == regions[j].RegionID)
{
m_log.ErrorFormat(
"[LOADREGIONS]: Regions {0} and {1} have the same UUID {2}",
regions[i].RegionName, regions[j].RegionName, regions[i].RegionID);
return false;
}
else if (
regions[i].RegionLocX == regions[j].RegionLocX && regions[i].RegionLocY == regions[j].RegionLocY)
{
m_log.ErrorFormat(
"[LOADREGIONS]: Regions {0} and {1} have the same grid location ({2}, {3})",
regions[i].RegionName, regions[j].RegionName, regions[i].RegionLocX, regions[i].RegionLocY);
return false;
}
else if (regions[i].InternalEndPoint.Port == regions[j].InternalEndPoint.Port)
{
m_log.ErrorFormat(
"[LOADREGIONS]: Regions {0} and {1} have the same internal IP port {2}",
regions[i].RegionName, regions[j].RegionName, regions[i].InternalEndPoint.Port);
return false;
}
}
}
return true;
}
public void LoadRegionFromConfig(OpenSimBase openSim, ulong regionhandle)
{
m_log.Info("[LOADREGIONS]: Load Regions addin being initialised");
IRegionLoader regionLoader;
if (openSim.ConfigSource.Source.Configs["Startup"].GetString("region_info_source", "filesystem") == "filesystem")
{
m_log.Info("[LOADREGIONS]: Loading Region Info from filesystem");
regionLoader = new RegionLoaderFileSystem();
}
else
{
m_log.Info("[LOADREGIONS]: Loading Region Info from web");
regionLoader = new RegionLoaderWebServer();
}
regionLoader.SetIniConfigSource(openSim.ConfigSource.Source);
RegionInfo[] regionsToLoad = regionLoader.LoadRegions();
for (int i = 0; i < regionsToLoad.Length; i++)
{
if (regionhandle == regionsToLoad[i].RegionHandle)
{
IScene scene;
m_log.Debug("[LOADREGIONS]: Creating Region: " + regionsToLoad[i].RegionName + " (ThreadID: " +
Thread.CurrentThread.ManagedThreadId.ToString() + ")");
openSim.CreateRegion(regionsToLoad[i], true, out scene);
}
}
}
}
}
| |
// 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 CompareNotEqualScalarSingle()
{
var test = new SimpleBinaryOpTest__CompareNotEqualScalarSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareNotEqualScalarSingle
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Single);
private static Single[] _data1 = new Single[ElementCount];
private static Single[] _data2 = new Single[ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private SimpleBinaryOpTest__DataTable<Single> _dataTable;
static SimpleBinaryOpTest__CompareNotEqualScalarSingle()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__CompareNotEqualScalarSingle()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Single>(_data1, _data2, new Single[ElementCount], VectorSize);
}
public bool IsSupported => Sse.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse.CompareNotEqualScalar(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse.CompareNotEqualScalar(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse.CompareNotEqualScalar(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareNotEqualScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareNotEqualScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareNotEqualScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse.CompareNotEqualScalar(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse.CompareNotEqualScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareNotEqualScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareNotEqualScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__CompareNotEqualScalarSingle();
var result = Sse.CompareNotEqualScalar(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse.CompareNotEqualScalar(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[ElementCount];
Single[] inArray2 = new Single[ElementCount];
Single[] outArray = new Single[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[ElementCount];
Single[] inArray2 = new Single[ElementCount];
Single[] outArray = new Single[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
if (BitConverter.SingleToInt32Bits(result[0]) != ((left[0] != right[0]) ? -1 : 0))
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if (BitConverter.SingleToInt32Bits(left[i]) != BitConverter.SingleToInt32Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.CompareNotEqualScalar)}<Single>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableSortedDictionaryTest : ImmutableDictionaryTestBase
{
private enum Operation
{
Add,
Set,
Remove,
Last,
}
[Fact]
public void RandomOperationsTest()
{
int operationCount = this.RandomOperationsCount;
var expected = new SortedDictionary<int, bool>();
var actual = ImmutableSortedDictionary<int, bool>.Empty;
int seed = unchecked((int)DateTime.Now.Ticks);
Debug.WriteLine("Using random seed {0}", seed);
var random = new Random(seed);
for (int iOp = 0; iOp < operationCount; iOp++)
{
switch ((Operation)random.Next((int)Operation.Last))
{
case Operation.Add:
int key;
do
{
key = random.Next();
}
while (expected.ContainsKey(key));
bool value = random.Next() % 2 == 0;
Debug.WriteLine("Adding \"{0}\"={1} to the set.", key, value);
expected.Add(key, value);
actual = actual.Add(key, value);
break;
case Operation.Set:
bool overwrite = expected.Count > 0 && random.Next() % 2 == 0;
if (overwrite)
{
int position = random.Next(expected.Count);
key = expected.Skip(position).First().Key;
}
else
{
do
{
key = random.Next();
}
while (expected.ContainsKey(key));
}
value = random.Next() % 2 == 0;
Debug.WriteLine("Setting \"{0}\"={1} to the set (overwrite={2}).", key, value, overwrite);
expected[key] = value;
actual = actual.SetItem(key, value);
break;
case Operation.Remove:
if (expected.Count > 0)
{
int position = random.Next(expected.Count);
key = expected.Skip(position).First().Key;
Debug.WriteLine("Removing element \"{0}\" from the set.", key);
Assert.True(expected.Remove(key));
actual = actual.Remove(key);
}
break;
}
Assert.Equal<KeyValuePair<int, bool>>(expected.ToList(), actual.ToList());
}
}
[Fact]
public void AddExistingKeySameValueTest()
{
AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "Microsoft");
AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.OrdinalIgnoreCase), "Company", "Microsoft", "MICROSOFT");
}
[Fact]
public void AddExistingKeyDifferentValueTest()
{
AddExistingKeyDifferentValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "MICROSOFT");
}
[Fact]
public void ToUnorderedTest()
{
var sortedMap = Empty<int, GenericParameterHelper>().AddRange(Enumerable.Range(1, 100).Select(n => new KeyValuePair<int, GenericParameterHelper>(n, new GenericParameterHelper(n))));
var unsortedMap = sortedMap.ToImmutableDictionary();
Assert.IsAssignableFrom(typeof(ImmutableDictionary<int, GenericParameterHelper>), unsortedMap);
Assert.Equal(sortedMap.Count, unsortedMap.Count);
Assert.Equal<KeyValuePair<int, GenericParameterHelper>>(sortedMap.ToList(), unsortedMap.ToList());
}
[Fact]
public void SortChangeTest()
{
var map = Empty<string, string>(StringComparer.Ordinal)
.Add("Johnny", "Appleseed")
.Add("JOHNNY", "Appleseed");
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("Johnny"));
Assert.False(map.ContainsKey("johnny"));
var newMap = map.ToImmutableSortedDictionary(StringComparer.OrdinalIgnoreCase);
Assert.Equal(1, newMap.Count);
Assert.True(newMap.ContainsKey("Johnny"));
Assert.True(newMap.ContainsKey("johnny")); // because it's case insensitive
}
[Fact]
public void InitialBulkAddUniqueTest()
{
var uniqueEntries = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string,string>("a", "b"),
new KeyValuePair<string,string>("c", "d"),
};
var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal);
var actual = map.AddRange(uniqueEntries);
Assert.Equal(2, actual.Count);
}
[Fact]
public void InitialBulkAddWithExactDuplicatesTest()
{
var uniqueEntries = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string,string>("a", "b"),
new KeyValuePair<string,string>("a", "b"),
};
var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal);
var actual = map.AddRange(uniqueEntries);
Assert.Equal(1, actual.Count);
}
[Fact]
public void ContainsValueTest()
{
this.ContainsValueTestHelper(ImmutableSortedDictionary<int, GenericParameterHelper>.Empty, 1, new GenericParameterHelper());
}
[Fact]
public void InitialBulkAddWithKeyCollisionTest()
{
var uniqueEntries = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string,string>("a", "b"),
new KeyValuePair<string,string>("a", "d"),
};
var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal);
Assert.Throws<ArgumentException>(null, () => map.AddRange(uniqueEntries));
}
[Fact]
public void Create()
{
IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "b" } };
var keyComparer = StringComparer.OrdinalIgnoreCase;
var valueComparer = StringComparer.CurrentCulture;
var dictionary = ImmutableSortedDictionary.Create<string, string>();
Assert.Equal(0, dictionary.Count);
Assert.Same(Comparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.Create<string, string>(keyComparer);
Assert.Equal(0, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.Create(keyComparer, valueComparer);
Assert.Equal(0, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.CreateRange(pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(Comparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.CreateRange(keyComparer, pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.CreateRange(keyComparer, valueComparer, pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
}
[Fact]
public void ToImmutableSortedDictionary()
{
IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "B" } };
var keyComparer = StringComparer.OrdinalIgnoreCase;
var valueComparer = StringComparer.CurrentCulture;
ImmutableSortedDictionary<string, string> dictionary = pairs.ToImmutableSortedDictionary();
Assert.Equal(1, dictionary.Count);
Assert.Same(Comparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(keyComparer);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(keyComparer, valueComparer);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant());
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(Comparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer);
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer, valueComparer);
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
}
[Fact]
public void WithComparers()
{
var map = ImmutableSortedDictionary.Create<string, string>().Add("a", "1").Add("B", "1");
Assert.Same(Comparer<string>.Default, map.KeyComparer);
Assert.True(map.ContainsKey("a"));
Assert.False(map.ContainsKey("A"));
map = map.WithComparers(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.True(map.ContainsKey("A"));
Assert.True(map.ContainsKey("b"));
var cultureComparer = StringComparer.CurrentCulture;
map = map.WithComparers(StringComparer.OrdinalIgnoreCase, cultureComparer);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Same(cultureComparer, map.ValueComparer);
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.True(map.ContainsKey("A"));
Assert.True(map.ContainsKey("b"));
}
[Fact]
public void WithComparersCollisions()
{
// First check where collisions have matching values.
var map = ImmutableSortedDictionary.Create<string, string>()
.Add("a", "1").Add("A", "1");
map = map.WithComparers(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Equal(1, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.Equal("1", map["a"]);
// Now check where collisions have conflicting values.
map = ImmutableSortedDictionary.Create<string, string>()
.Add("a", "1").Add("A", "2").Add("b", "3");
Assert.Throws<ArgumentException>(null, () => map.WithComparers(StringComparer.OrdinalIgnoreCase));
// Force all values to be considered equal.
map = map.WithComparers(StringComparer.OrdinalIgnoreCase, EverythingEqual<string>.Default);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Same(EverythingEqual<string>.Default, map.ValueComparer);
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.True(map.ContainsKey("b"));
}
[Fact]
public void CollisionExceptionMessageContainsKey()
{
var map = ImmutableSortedDictionary.Create<string, string>()
.Add("firstKey", "1").Add("secondKey", "2");
var exception = Assert.Throws<ArgumentException>(null, () => map.Add("firstKey", "3"));
if (!PlatformDetection.IsNetNative) //.Net Native toolchain removes exception messages.
{
Assert.Contains("firstKey", exception.Message);
}
}
[Fact]
public void WithComparersEmptyCollection()
{
var map = ImmutableSortedDictionary.Create<string, string>();
Assert.Same(Comparer<string>.Default, map.KeyComparer);
map = map.WithComparers(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var collection = ImmutableSortedDictionary.Create<int, int>().Add(3, 5);
var enumerator = collection.GetEnumerator();
var enumeratorCopy = enumerator;
Assert.True(enumerator.MoveNext());
Assert.False(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = collection.GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Dispose();
}
[Fact]
public void Remove_KeyExists_RemovesKeyValuePair()
{
ImmutableSortedDictionary<int, string> dictionary = new Dictionary<int, string>
{
{ 1, "a" }
}.ToImmutableSortedDictionary();
Assert.Equal(0, dictionary.Remove(1).Count);
}
[Fact]
public void Remove_FirstKey_RemovesKeyValuePair()
{
ImmutableSortedDictionary<int, string> dictionary = new Dictionary<int, string>
{
{ 1, "a" },
{ 2, "b" }
}.ToImmutableSortedDictionary();
Assert.Equal(1, dictionary.Remove(1).Count);
}
[Fact]
public void Remove_SecondKey_RemovesKeyValuePair()
{
ImmutableSortedDictionary<int, string> dictionary = new Dictionary<int, string>
{
{ 1, "a" },
{ 2, "b" }
}.ToImmutableSortedDictionary();
Assert.Equal(1, dictionary.Remove(2).Count);
}
[Fact]
public void Remove_KeyDoesntExist_DoesNothing()
{
ImmutableSortedDictionary<int, string> dictionary = new Dictionary<int, string>
{
{ 1, "a" }
}.ToImmutableSortedDictionary();
Assert.Equal(1, dictionary.Remove(2).Count);
Assert.Equal(1, dictionary.Remove(-1).Count);
}
[Fact]
public void Remove_EmptyDictionary_DoesNothing()
{
ImmutableSortedDictionary<int, string> dictionary = ImmutableSortedDictionary<int, string>.Empty;
Assert.Equal(0, dictionary.Remove(2).Count);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableSortedDictionary.Create<string, int>());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableSortedDictionary.Create<int, int>());
object rootNode = DebuggerAttributes.GetFieldValue(ImmutableSortedDictionary.Create<string, string>(), "_root");
DebuggerAttributes.ValidateDebuggerDisplayReferences(rootNode);
}
////[Fact] // not really a functional test -- but very useful to enable when collecting perf traces.
public void EnumerationPerformance()
{
var dictionary = Enumerable.Range(1, 1000).ToImmutableSortedDictionary(k => k, k => k);
var timing = new TimeSpan[3];
var sw = new Stopwatch();
for (int j = 0; j < timing.Length; j++)
{
sw.Start();
for (int i = 0; i < 10000; i++)
{
foreach (var entry in dictionary)
{
}
}
timing[j] = sw.Elapsed;
sw.Reset();
}
string timingText = string.Join(Environment.NewLine, timing);
Debug.WriteLine("Timing:{0}{1}", Environment.NewLine, timingText);
}
////[Fact] // not really a functional test -- but very useful to enable when collecting perf traces.
public void EnumerationPerformance_Empty()
{
var dictionary = ImmutableSortedDictionary<int, int>.Empty;
var timing = new TimeSpan[3];
var sw = new Stopwatch();
for (int j = 0; j < timing.Length; j++)
{
sw.Start();
for (int i = 0; i < 10000; i++)
{
foreach (var entry in dictionary)
{
}
}
timing[j] = sw.Elapsed;
sw.Reset();
}
string timingText = string.Join(Environment.NewLine, timing);
Debug.WriteLine("Timing_Empty:{0}{1}", Environment.NewLine, timingText);
}
protected override IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>()
{
return ImmutableSortedDictionaryTest.Empty<TKey, TValue>();
}
protected override IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer)
{
return ImmutableSortedDictionary.Create<string, TValue>(comparer);
}
protected override IEqualityComparer<TValue> GetValueComparer<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary)
{
return ((ImmutableSortedDictionary<TKey, TValue>)dictionary).ValueComparer;
}
internal override IBinaryTree GetRootNode<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary)
{
return ((ImmutableSortedDictionary<TKey, TValue>)dictionary).Root;
}
protected void ContainsValueTestHelper<TKey, TValue>(ImmutableSortedDictionary<TKey, TValue> map, TKey key, TValue value)
{
Assert.False(map.ContainsValue(value));
Assert.True(map.Add(key, value).ContainsValue(value));
}
private static IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>(IComparer<TKey> keyComparer = null, IEqualityComparer<TValue> valueComparer = null)
{
return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer);
}
}
}
| |
using System;
using System.Diagnostics;
using Android.Graphics;
using XamarinApp.ViewModels;
using Pdi.Android;
using Pdi.Barlib;
using Java.Nio;
using Exception = System.Exception;
using Object = Java.Lang.Object;
using XamarinApp.Common;
using System.Text;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Newtonsoft.Json;
using XamarinApp.Common.Scan;
using XamarinApp.HoursOfService.Repository.Tables;
namespace XamarinApp.Droid.Scanning
{
public class PageScanFour : Object, IDocumentScanner, Pdiscan.ICallback
{
private bool verbose = true;
/// <summary>
///We pass this activity to the PageScanFour because the driver requires
///certain events & commands to be sent on the same activity that
///did the initialize, even though other things such as hearing
///PageEnd events can take place on their own object-thread.
/// </summary>
private MainActivity mainActivity;
private string _workingSaveDirectory;
#region Constructor(s)
public PageScanFour(MainActivity ma)
{
mainActivity = ma;
imagingHelper = new ImagingHelper();
RaiseLogThis("Initialize");
Pdiscan.Initialize(mainActivity);
if (verbose) RaiseLogThis("Subscribe");
Pdiscan.SetCallback(this);
try
{
Pdiscan.Connect();
if (Pdiscan.IsConnected) ConfigureDevice();
RaiseConnectivityChanged(IsConnected);
}
catch (Exception ex)
{
Debug.WriteLine($"GET Error {ex.Message}");
}
}
#endregion Constructor(s)
#region Events
#region LogThis event
public event EventHandler<string> LogThis;
protected void RaiseLogThis(string e)
{
EventHandler<string> handler = LogThis;
handler?.Invoke(this, e);
}
#endregion LogThis
#region NewImage event
/// <summary>Argument is the path to the saved bitmap
///
/// </summary>
public event EventHandler<ScanInfo> NewImage;
protected void RaiseNewImage(ScanInfo e)
{
EventHandler<ScanInfo> handler = NewImage;
handler?.Invoke(this, e);
}
#endregion NewImage
#region ConnectivityChanged event
/// <summary>Bool event arg indicates if is now connected. You can also check the IsConnected property to confirm.
///
/// </summary>
public event EventHandler<bool> ConnectivityChanged;
protected void RaiseConnectivityChanged(bool e)
{
EventHandler<bool> handler = ConnectivityChanged;
handler?.Invoke(this, e);
}
#endregion ConnectivityChanged
#region RaisePaperJam
/// <summary>Bool event arg indicates if is now jammed.
///
/// </summary>
public event EventHandler<bool> PaperJam;
protected void RaisePaperJam(bool e)
{
EventHandler<bool> handler = PaperJam;
handler?.Invoke(this, e);
}
#endregion RaisePaperJam
#region DeviceFirstTimeConnect
public event EventHandler DeviceFirstTimeConnect;
protected void RaiseDeviceFirstTimeConnect()
{
EventHandler handler = DeviceFirstTimeConnect;
handler?.Invoke(this, null);
}
#endregion DeviceFirstTimeConnect
#endregion Events
#region Properties
#region ImagingHelper
public XamarinApp.Common.ImagingHelper imagingHelper { get; set; }
#endregion ImagingHelper
#region IsConnected
public bool IsConnected
{
get { return Pdiscan.IsConnected; }
}
#endregion IsConnected
#region IsPaperJam
private bool _IsPaperJam;
public bool IsPaperJam
{
[DebuggerStepThrough]
get
{
return _IsPaperJam;
}
[DebuggerStepThrough]
set
{
if (_IsPaperJam == value) return;
if (value == true)
{
Xamarin.Forms.Device.StartTimer(new TimeSpan(0, 0, 1), StillJammed);
}
_IsPaperJam = value;
}
}
#endregion IsPaperJam
#region WorkingSaveDirectory
private string _WorkingSaveDirectory;
public string WorkingSaveDirectory
{
[DebuggerStepThrough]
get
{
return _WorkingSaveDirectory;
}
[DebuggerStepThrough]
set
{
if (_WorkingSaveDirectory == value) return;
//OnPropertyChanging(() => WorkingSaveDirectory);
_WorkingSaveDirectory = value;
//NotifyPropertyChanged("WorkingSaveDirectory");
//OnPropertyChanged(() => WorkingSaveDirectory);
System.IO.Directory.CreateDirectory(value);
}
}
public object BarcodeEngine { get; set; }
#endregion WorkingSaveDirectory
#region Brightness
private object _Brightness = "20"; // default
/// <summary>Expecting an int, but will convert a string or object
///
/// </summary>
public object Brightness
{
[DebuggerStepThrough]
get
{
//return _Brightness;
return Pdiscan.BitonalThreshold.ToString();
}
//[DebuggerStepThrough]
set
{
if (_Brightness == value) return;
_Brightness = value;
var brightness = 0;
if (value is string)
{
if (!string.IsNullOrEmpty(value.ToString()))
{
int.TryParse(value.ToString(), out brightness);
}
}
else brightness = (int)value;
brightness = brightness < 15 ? 15 : brightness;
brightness = brightness > 85 ? 85 : brightness;
if (IsConnected)
{
var a = Pdiscan.CapBitonialThreshold();
DisableFeeder();
Pdiscan.BitonalThreshold = (int)brightness;
}
EnableFeeder();
}
}
#endregion Brightness
#endregion Properties
#region App state change handlers
public bool OnResume()
{
try
{
if (!Pdiscan.IsConnected) Pdiscan.ReConnect();
RaiseLogThis(string.Format("{0} by {1} is {2}",
Pdiscan.Product,
Pdiscan.Manufacturer,
Pdiscan.IsConnected ? "ready" : "DISconnected"));
RaiseConnectivityChanged(IsConnected);
return true;
}
catch (Exception ex)
{
RaiseLogThis(string.Format("Error: {0}", ex.Message));
return false;
}
}
#endregion App state change handlers
private bool isFirstScan = true;
#region PDIScan ICallback members
public bool StillJammed()
{
Pdiscan.EjectPage(Pdiscan.E_ejectDirection.Front, true);
Eject();
EnableFeeder();
IsPaperJam = false;
return false;
}
/// <summary>Pdiscan callback handler. Do not rename. Receives the new scan.
///
/// </summary>
/// <param name="bmpFront"></param>
/// <param name="bmpBack"></param>
public void PageEnd(Bitmap bmpFront, Bitmap bmpBack)
{
try
{
RaiseLogThis("hit PageEnd");
if (bmpFront == null)
{
RaiseLogThis("bmpFront is null");
return;
}
//PS4 doesn't do double-sided so this is CYA
bmpBack?.Recycle();
RaiseLogThis("bmpBack recycled");
DisableFeeder();
RaiseLogThis("feeder disabled");
RaiseLogThis(string.Format("New Scan {0}, {1}",
bmpFront.GetBitmapInfo().Width,
bmpFront.GetBitmapInfo().Height));
var fileName = DateTime.Now.ToString("HHmmssfff");
var savedPath = imagingHelper.ExportAsPNG(bmpFront, WorkingSaveDirectory, fileName);
var barcodes = ReadBarcode(savedPath);
ScanInfo info = new ScanInfo(savedPath, barcodes)
{
ScannerVersion = $"{Pdiscan.Version} ({Pdiscan.FirmwareVersion})"
};
RaiseNewImage(info);
return;/*
//Important: Saves blocks until the entire file is written before we raise the
//notification. We can't just react to a new file notice because in that case the
//the file is STARTED but not necessarily FINISHED.
if (!string.IsNullOrWhiteSpace(savedPath) &&
System.IO.File.Exists(savedPath))
{
var imageinfo = barcodes == null ? savedPath : savedPath + barcodes;
RaiseLogThis(string.Format("Image info: {0}", imageinfo));
RaiseNewImage(imageinfo);
}
//if (!Pdiscan.IsFeederEnabled)
//{
// EnableFeeder();
// Let the VM decide when to re-enable the feeder, after its done processing
//}
bmpFront?.Recycle();
bmpFront?.Dispose();
RaiseConnectivityChanged(true);
if (isFirstScan)
{
isFirstScan = false;
Eject();
}
//Pdiscan.EjectPage(Pdiscan.E_ejectDirection.Rear, false);
*/
}
catch (Exception ex)
{
RaiseLogThis(string.Format("PageEnd Ex> {0}", ex.Message));
RaiseLogThis(ex.InnerException?.Message);
}
}
public void ScanningError(int errorNumber, string errorMessage)
{
try
{
switch (errorNumber)
{
case Pdiscan.ErrorCodes.PageStart:
//The start of a scan isn't really an error as far as we are concerned
// so if we paper jam we don't set to front scanning
//Pdiscan.EjectPage(Pdiscan.E_ejectDirection.AutoRear, false);
break;
case Pdiscan.ErrorCodes.PageEnd:
//mainActivity.RunOnUiThread(() =>
//{
if (isFirstScan)
{
isFirstScan = false;
//DisableFeeder();
//bool wasEnabled = Pdiscan.IsFeederEnabled;
mainActivity.RunOnUiThread(() =>
{
DisableFeeder();
Pdiscan.EjectPage(Pdiscan.E_ejectDirection.Rear, true);
});
//Eject();
//if (!wasEnabled) DisableFeeder();
}
//});
break;
case Pdiscan.ErrorCodes.ScannerAvailable://No scanner attached at app launch. Now there is a scanner available for the first time.
////TODO: Raise event for first connection instructions
//RaiseDeviceFirstTimeConnect();
//break;
case Pdiscan.ErrorCodes.ScannerAttached://Scanner that was already attached has re-attached to be more precise
ConfigureDevice();//Just in case it isn't the SAME scanner, or it went through a power cycle.
RaiseConnectivityChanged(true);
RaiseLogThis("Scanner Attached");
break;
case Pdiscan.ErrorCodes.ScannerDetached:
RaiseConnectivityChanged(false);
RaiseLogThis("Scanner detached");
break;
case Pdiscan.ErrorCodes.ScannerCoverOpen:
case Pdiscan.ErrorCodes.PaperJam://TODO: RaiseEvent for VM to handle
RaiseLogThis("Paper jammed");
IsPaperJam = true;
RaisePaperJam(true);
break;
default:
RaiseLogThis(string.Format("PS4Error> {0}, '{1}'",
errorNumber,
errorMessage));
break;
}
}
catch (Exception ex)
{
RaiseLogThis(string.Format("PS4Error ex> {0}", ex.ToString()));
if (ex.Message != null) RaiseLogThis(string.Format("PS4Error ex> {0}", ex.Message));
}
}
// Keycode is our dev license with pdi, do not change!
static int keyCode = 24196;
//public pdibarcode BarcodeEngine;
#endregion PDIScan ICallback members
/// <summary>Return string list of barcodes, or null if none</string>
/// <para><example></example></para>
/// </summary>
/// <param name="bmpPath"></param>
/// <returns>Return string list of barcodes, or null if none</returns>
public List<string> ReadBarcode(string bmpPath)
{
if (string.IsNullOrWhiteSpace(bmpPath)) return null;
pdibarcode BarcodeEngine = this.BarcodeEngine as pdibarcode;
//Let's try to open the file with Write permissions. If that fails the file may still be getting written.
DateTime giveUp = DateTime.Now.AddSeconds(10);
while (DateTime.Now < giveUp)
{
try
{
var dummyStream = File.OpenWrite(bmpPath);
dummyStream.Dispose();
dummyStream = null;
break;//We have success
}
catch (Exception)
{
RaiseLogThis("Unable to open file to read barcodes");
}
//unable to open the file with adequate permissions to prove its done
return null;
}
if (!BarcodeEngine.IsInitialized)
{
RaiseLogThis("Barcode engine refuses to initialize");
return null;
}
try
{
// set an upper bounds for storage on byte array so we don't go out of memory.
var byteArrayForBitmap = new byte[16 * 1024];
var options = new BitmapFactory.Options();
options.InTempStorage = byteArrayForBitmap;// set the bounds for the storage so we don't run out of memory while loading the scanned image
Bitmap bitmap = BitmapFactory.DecodeFile(bmpPath, options);// go get the bitmap and load it.
// scale the bitmap so we don't run out of memory when reading barcodes
//Bitmap TmpBM = Bitmap.CreateScaledBitmap(bitmap, (int)(bitmap.GetBitmapInfo().Width / 2), (int)(bitmap.GetBitmapInfo().Height / 2), true);
BarcodeEngine.SetBitmap(bitmap, 0);// 0 = default == 8000 pixels per meter == 203.2 DPI
BarcodeEngine.SetSearchOption(pdibarcode.E_option.Scanmode, pdibarcode.SearchMode.ScHorzvert);
BarcodeEngine.SetSearchOption(pdibarcode.E_option.BarcodeType, pdibarcode.BarcodeType.BcCodeall);
/*
* Each bar code must have a white(or quiet) zone in front and back of the bar code.
* The specifications of the various bar codes require a minimum of 0.25 inch.
* However in some cases this is not respected and this option can be used to change the quiet zone.
* Value is expressed in 1 / 100 of an inch.
* Default is 0.25 or 25.
* Please make sure the value is bigger than the widest white bar in the bar code.
* If not the white bars will be confused with the quiet zone and therefore the bar code will not read properly.
*/
// Images are scaled down by a factor of 2 so quietzone must be as well.
BarcodeEngine.SetSearchOption(pdibarcode.E_option.Quietzone, (25));
// If this value is zero then the bar code reader will
// stop reading bar-codes once it has found one bar code.
// In case this value is set to none zero, the reader will
// continue to look for more bar codes until it has exhausted
// all possibilities.
// In other words 0 or non-zero as a binary. 0-Multiplebarcodes=false. !0-Multiplebarcodes=true
BarcodeEngine.SetSearchOption(pdibarcode.E_option.Multiplebarcodes, 1);
int result = BarcodeEngine.DecodeBarcodes();
var results = new List<string>();
if (result != 0)
{
for (int i = 1; i <= result; i++)
{
var r = BarcodeEngine.GetBarcodeValue(i);
results.Add(r);
}
}
if (!results.Any()) return null;
return results;/*
bitmap?.Recycle();
bitmap?.Dispose();
if (results.Count >= 1)
{
var barcodes = new StringBuilder();
foreach (var r in results)
{
barcodes.Append("," + r);
}
RaiseLogThis(string.Format("Barcodes found: {0}", barcodes.ToString()));
return barcodes.ToString();
}*/
}
catch (Exception ex)
{
RaiseLogThis(string.Format("PageScanFour > ReadBarcode > ex: {0}",
ex.Message));
return null;
}
return null;
}
void DisableFeeder()
{
if (!Pdiscan.IsConnected) return;
try
{
// ReSharper disable once UseNullPropagation
if (mainActivity != null)
{
mainActivity.RunOnUiThread(() =>
{
if (verbose) RaiseLogThis("PageEnd> Feed DISable-ING");
Pdiscan.DisableFeeder();
if (verbose) RaiseLogThis("PageEnd> Feeder DISable-ED");
});
}
}
catch (Exception ex)
{
RaiseLogThis(string.Format("PS4Error ex> {0}", ex.Message));
}
}
public void EnableFeeder()
{
if (!Pdiscan.IsConnected) return;
try
{
if (mainActivity != null)
{
mainActivity.RunOnUiThread(() =>
{
//if (isFirstScan)
//{
// isFirstScan = false;
// Eject();
//}
Pdiscan.EjectPage(Pdiscan.E_ejectDirection.AutoRear, false);
//if (verbose) RaiseLogThis("PageEnd> Feed Enable-ING");
Pdiscan.EnableFeeder();
//if (verbose) RaiseLogThis("PageEnd> Feeder Enabl-ED");
RaiseConnectivityChanged(true);
});
}
}
catch (Exception ex)
{
if (verbose) RaiseLogThis(string.Format("PS4Error ex> {0}", ex.Message));
}
}
public void Eject()
{
if (!Pdiscan.IsConnected) return;
DisableFeeder();
//Pdiscan.EjectPage(Pdiscan.E_ejectDirection.Rear, false);
Pdiscan.EjectPage(Pdiscan.E_ejectDirection.AutoRear, false);
}
public async void ConfigureDevice()
{
try
{
if (verbose) RaiseLogThis("Connect");
//if (Pdiscan.IsConnected)
//{
// Pdiscan.Disconnect();
// await Task.Delay(250);//I'm suspecting the PDI driver doesn't do well with races
//}
if (!Pdiscan.IsConnected)
{
Pdiscan.Connect();
//await Task.Delay(250);//Returns out of method from here
}
if (Pdiscan.IsConnected)
{
if (verbose) RaiseLogThis("Configure");
Pdiscan.Color = Pdiscan.E_colorDepth.Bw;
Pdiscan.TransportSpeed = Pdiscan.E_transportSpeed.Half;
Pdiscan.Resolution = Pdiscan.E_resolution.Dpi200;
Pdiscan.SinglePageMode = true;
// Set the maximum length of the document that will be scanned.
// This value will be used to set the jam detection on the scanner.
// This value is also used internally to limit the size of the memory buffers one needs while scanning.
// Setting the value to the lowest value needed in an application
// will help in the Jam detection and with the memory management.
// Default - 1400
//Pdiscan.MaxDocumentLength = 1400;
//await Task.Delay(250);//Returns out of method from here
Pdiscan.EjectPage(Pdiscan.E_ejectDirection.AutoRear, false);
EnableFeeder();
Pdiscan.EjectPage(Pdiscan.E_ejectDirection.Rear, false);//Alert the user its good
RaiseLogThis(string.Format("{0} by {1} is {2}",
Pdiscan.Product,
Pdiscan.Manufacturer,
Pdiscan.IsConnected ? "ready" : "DISconnected"));
RaiseConnectivityChanged(IsConnected);
}
}
catch (Exception ex)
{
RaiseLogThis(string.Format("Error subscribing to scanner {0}",
ex.Message));
//Pdiscan.Terminate();
}
}
public string GetStatus()
{
var alpha = Pdiscan.Resolution;
var bravo = Pdiscan.Color;
var charlie = Pdiscan.IsConnected;
var delta = Pdiscan.TransportSpeed;
var status = string.Format("Res:{0}, Color:{1}, Trans:{2}, Con:{3}",
alpha, bravo, delta, charlie);
return status;
}
}
[Flags]
public enum pdiscan_errors
{
Rear_Left_Sensor_Covered = 0x01,
Rear_Right_Sensor_Covered = 0x02,
Brander_Position_Sensor_Covered = 0x04,
Hi_Speed_Mode = 0x08,
Download_Needed = 0x10,
Future_Use_Not_Defined = 0x20,
Scanner_Enabled = 0x40,
Always_Set_to_1_0x80 = 0x80,
Front1_Left_Sensor_Covered = 0x0100,
Front2_M1_Sensor_Covered = 0x0200,
Front3_M2_Sensor_Covered = 0x0400,
Front4_M3_Sensor_Covered = 0x0800,
Front5_M4_Sensor_Covered = 0x1000,
Front6_M5_Sensor_Covered = 0x2000,
Front_7_Right_Sensor_Covered = 0x4000,
Always_Set_to_1_0x8000 = 0x8000,
Scanner_Ready = 0x010000,
XMT_Aborted_Com_Error = 0x020000,
Document_Jam = 0x040000,
Scan_Array_Pixel_Error = 0x080000,
In_Diagnostic_Mode = 0x100000,
Doc_in_Scanner = 0x200000,
Calibration_of_unit_needed = 0x400000,
Always_Set_to_1_0x800000 = 0x800000,
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// E05_CountryColl (editable child list).<br/>
/// This is a generated base class of <see cref="E05_CountryColl"/> business object.
/// </summary>
/// <remarks>
/// This class is child of <see cref="E04_SubContinent"/> editable child object.<br/>
/// The items of the collection are <see cref="E06_Country"/> objects.
/// </remarks>
[Serializable]
public partial class E05_CountryColl : BusinessListBase<E05_CountryColl, E06_Country>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="E06_Country"/> item from the collection.
/// </summary>
/// <param name="country_ID">The Country_ID of the item to be removed.</param>
public void Remove(int country_ID)
{
foreach (var e06_Country in this)
{
if (e06_Country.Country_ID == country_ID)
{
Remove(e06_Country);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="E06_Country"/> item is in the collection.
/// </summary>
/// <param name="country_ID">The Country_ID of the item to search for.</param>
/// <returns><c>true</c> if the E06_Country is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int country_ID)
{
foreach (var e06_Country in this)
{
if (e06_Country.Country_ID == country_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="E06_Country"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="country_ID">The Country_ID of the item to search for.</param>
/// <returns><c>true</c> if the E06_Country is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int country_ID)
{
foreach (var e06_Country in DeletedList)
{
if (e06_Country.Country_ID == country_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="E06_Country"/> item of the <see cref="E05_CountryColl"/> collection, based on item key properties.
/// </summary>
/// <param name="country_ID">The Country_ID.</param>
/// <returns>A <see cref="E06_Country"/> object.</returns>
public E06_Country FindE06_CountryByParentProperties(int country_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].Country_ID.Equals(country_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="E05_CountryColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="E05_CountryColl"/> collection.</returns>
internal static E05_CountryColl NewE05_CountryColl()
{
return DataPortal.CreateChild<E05_CountryColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="E05_CountryColl"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="E05_CountryColl"/> object.</returns>
internal static E05_CountryColl GetE05_CountryColl(SafeDataReader dr)
{
E05_CountryColl obj = new E05_CountryColl();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="E05_CountryColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public E05_CountryColl()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads all <see cref="E05_CountryColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
var args = new DataPortalHookArgs(dr);
OnFetchPre(args);
while (dr.Read())
{
Add(E06_Country.GetE06_Country(dr));
}
OnFetchPost(args);
RaiseListChangedEvents = rlce;
}
/// <summary>
/// Loads <see cref="E06_Country"/> items on the E05_CountryObjects collection.
/// </summary>
/// <param name="collection">The grand parent <see cref="E03_SubContinentColl"/> collection.</param>
internal void LoadItems(E03_SubContinentColl collection)
{
foreach (var item in this)
{
var obj = collection.FindE04_SubContinentByParentProperties(item.parent_SubContinent_ID);
var rlce = obj.E05_CountryObjects.RaiseListChangedEvents;
obj.E05_CountryObjects.RaiseListChangedEvents = false;
obj.E05_CountryObjects.Add(item);
obj.E05_CountryObjects.RaiseListChangedEvents = rlce;
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
using UnityEngine;
using UnityEngine.Rendering;
using System.Collections.Generic;
[ExecuteInEditMode]
public class TubeLight : MonoBehaviour
{
public float m_Intensity = 0.8f;
public Color m_Color = Color.white;
public float m_Range = 10.0f;
public float m_Radius = 0.3f;
public float m_Length = 0.0f;
[HideInInspector]
public Mesh m_Sphere;
[HideInInspector]
public Mesh m_Capsule;
[HideInInspector]
public Shader m_ProxyShader;
Material m_ProxyMaterial;
public bool m_RenderSource = false;
Renderer m_SourceRenderer;
Transform m_SourceTransform;
Mesh m_SourceMesh;
float m_LastLength = -1;
public const int maxPlanes = 2;
[HideInInspector]
public TubeLightShadowPlane[] m_ShadowPlanes = new TubeLightShadowPlane[maxPlanes];
bool m_Initialized = false;
MaterialPropertyBlock m_props;
const float kMinRadius = 0.001f;
bool renderSource {get{return m_RenderSource && m_Radius >= kMinRadius;}}
Dictionary<Camera, CommandBuffer> m_Cameras = new Dictionary<Camera, CommandBuffer>();
static CameraEvent kCameraEvent = CameraEvent.AfterLighting;
void Start()
{
if(!Init())
return;
UpdateMeshesAndBounds();
}
bool Init()
{
if (m_Initialized)
return true;
// Sometimes on editor startup (especially after project upgrade?), Init() gets called
// while m_ProxyShader, m_Sphere or m_Capsule is still null/hasn't loaded.
if (m_ProxyShader == null || m_Sphere == null || m_Capsule == null)
return false;
// Proxy
m_ProxyMaterial = new Material(m_ProxyShader);
m_ProxyMaterial.hideFlags = HideFlags.HideAndDontSave;
// Source
m_SourceMesh = Instantiate<Mesh>(m_Capsule);
m_SourceMesh.hideFlags = HideFlags.HideAndDontSave;
// Can't create the MeshFilter here, since for some reason the DontSave flag has
// no effect on it. Has to be added to the prefab instead.
//m_SourceMeshFilter = gameObject.AddComponent<MeshFilter>();
MeshFilter mfs = gameObject.GetComponent<MeshFilter>();
// Hmm, causes trouble
// mfs.hideFlags = HideFlags.HideInInspector;
mfs.sharedMesh = m_SourceMesh;
// A similar problem here.
// m_SourceRenderer = gameObject.AddComponent<MeshRenderer>();
m_SourceRenderer = gameObject.GetComponent<MeshRenderer>();
m_SourceRenderer.enabled = true;
// We want it to be pickable in the scene view, so no HideAndDontSave
// Hmm, causes trouble
// m_SourceRenderer.hideFlags = HideFlags.DontSave | HideFlags.HideInInspector;
m_SourceTransform = transform;
m_Initialized = true;
return true;
}
void OnEnable()
{
if(m_props == null)
m_props = new MaterialPropertyBlock();
if(!Init())
return;
UpdateMeshesAndBounds();
}
void OnDisable()
{
if(!Application.isPlaying)
Cleanup();
else
for(var e = m_Cameras.GetEnumerator(); e.MoveNext();)
if(e.Current.Value != null)
e.Current.Value.Clear();
}
void OnDestroy()
{
if (m_ProxyMaterial != null)
DestroyImmediate(m_ProxyMaterial);
if (m_SourceMesh != null)
DestroyImmediate(m_SourceMesh);
Cleanup();
}
void Cleanup()
{
for(var e = m_Cameras.GetEnumerator(); e.MoveNext();)
{
var cam = e.Current;
if(cam.Key != null && cam.Value != null)
cam.Key.RemoveCommandBuffer (kCameraEvent, cam.Value);
}
m_Cameras.Clear();
}
void UpdateMeshesAndBounds()
{
// Sanitize
m_Range = Mathf.Max(m_Range, 0);
m_Radius = Mathf.Max(m_Radius, 0);
m_Length = Mathf.Max(m_Length, 0);
m_Intensity = Mathf.Max(m_Intensity, 0);
Vector3 sourceSize = renderSource ? Vector3.one * m_Radius * 2.0f : Vector3.one;
if (m_SourceTransform.localScale != sourceSize || m_Length != m_LastLength)
{
m_LastLength = m_Length;
Vector3[] vertices = m_Capsule.vertices;
for (int i = 0; i < vertices.Length; i++)
{
if (renderSource)
vertices[i].y += Mathf.Sign(vertices[i].y) * (- 0.5f + 0.25f * m_Length / m_Radius);
else
vertices[i] = Vector3.one * 0.0001f;
}
m_SourceMesh.vertices = vertices;
}
m_SourceTransform.localScale = sourceSize;
float range = m_Range + m_Radius;
// TODO: lazy for now, should draw a tight capsule
range += 0.5f * m_Length;
range *= 1.02f;
range /= m_Radius;
m_SourceMesh.bounds = new Bounds(Vector3.zero, Vector3.one * range);
}
void Update()
{
if(!Init())
return;
UpdateMeshesAndBounds();
if(Application.isPlaying)
for(var e = m_Cameras.GetEnumerator(); e.MoveNext();)
if(e.Current.Value != null)
e.Current.Value.Clear();
}
Color GetColor()
{
if (QualitySettings.activeColorSpace == ColorSpace.Gamma)
return m_Color * m_Intensity;
return new Color(
Mathf.GammaToLinearSpace(m_Color.r * m_Intensity),
Mathf.GammaToLinearSpace(m_Color.g * m_Intensity),
Mathf.GammaToLinearSpace(m_Color.b * m_Intensity),
1.0f
);
}
void OnWillRenderObject()
{
if(InsideShadowmapCameraRender())
return;
if(!Init())
return;
// TODO: This is just a very rough guess. Need to properly calculate the surface emission
// intensity based on light's intensity.
m_props.SetVector("_EmissionColor", m_Color * Mathf.Sqrt(m_Intensity) * 2.0f);
m_SourceRenderer.SetPropertyBlock(m_props);
SetUpCommandBuffer();
}
void SetUpCommandBuffer()
{
Camera cam = Camera.current;
CommandBuffer buf = null;
if (!m_Cameras.ContainsKey(cam))
{
buf = new CommandBuffer();
buf.name = gameObject.name;
m_Cameras[cam] = buf;
cam.AddCommandBuffer(kCameraEvent, buf);
cam.depthTextureMode |= DepthTextureMode.Depth;
}
else
{
buf = m_Cameras[cam];
buf.Clear();
}
Transform t = transform;
Vector3 lightAxis = t.up;
Vector3 lightPos = t.position - 0.5f * lightAxis * m_Length;
buf.SetGlobalVector("_LightPos", new Vector4(lightPos.x, lightPos.y, lightPos.z, 1.0f/(m_Range*m_Range)));
buf.SetGlobalVector("_LightAxis", new Vector4(lightAxis.x, lightAxis.y, lightAxis.z, 0.0f));
buf.SetGlobalFloat("_LightAsQuad", 0);
buf.SetGlobalFloat("_LightRadius", m_Radius);
buf.SetGlobalFloat("_LightLength", m_Length);
buf.SetGlobalVector("_LightColor", GetColor());
SetShadowPlaneVectors(buf);
float range = m_Range + m_Radius;
// TODO: lazy for now, should draw a tight capsule
range += 0.5f * m_Length;
range *= 1.02f;
range /= m_Radius;
Matrix4x4 m = Matrix4x4.Scale(Vector3.one * range);
buf.DrawMesh(m_Sphere, t.localToWorldMatrix * m, m_ProxyMaterial, 0, 0);
}
public TubeLightShadowPlane.Params[] GetShadowPlaneParams(ref TubeLightShadowPlane.Params[] p)
{
if (p == null || p.Length != maxPlanes)
p = new TubeLightShadowPlane.Params[maxPlanes];
for(int i = 0; i < maxPlanes; i++)
{
TubeLightShadowPlane sp = m_ShadowPlanes[i];
p[i].plane = sp == null ? new Vector4(0, 0, 0, 1) : sp.GetShadowPlaneVector();
p[i].feather = sp == null ? 1 : sp.feather;
}
return p;
}
TubeLightShadowPlane.Params[] sppArr = new TubeLightShadowPlane.Params[maxPlanes];
void SetShadowPlaneVectors(CommandBuffer buf)
{
var p = GetShadowPlaneParams(ref sppArr);
for (int i = 0, n = p.Length; i < n; ++i)
{
var spp = p[i];
if(i == 0) {
buf.SetGlobalVector("_ShadowPlane0", spp.plane);
buf.SetGlobalFloat("_ShadowPlaneFeather0", spp.feather);
} else if(i == 1) {
buf.SetGlobalVector("_ShadowPlane1", spp.plane);
buf.SetGlobalFloat("_ShadowPlaneFeather1", spp.feather);
} else {
buf.SetGlobalVector("_ShadowPlane" + i, spp.plane);
buf.SetGlobalFloat("_ShadowPlaneFeather" + i, spp.feather);
}
}
}
void OnDrawGizmosSelected()
{
if (m_SourceTransform == null)
return;
Gizmos.color = Color.white;
// Skip the scale
Matrix4x4 m = new Matrix4x4();
m.SetTRS(m_SourceTransform.position, m_SourceTransform.rotation, Vector3.one);
Gizmos.matrix = m;
Gizmos.DrawWireSphere(Vector3.zero, m_Radius + m_Range + 0.5f * m_Length);
Vector3 start = 0.5f * Vector3.up * m_Length;
Gizmos.DrawWireSphere(start, m_Radius);
if (m_Length == 0.0f)
return;
Vector3 end = - 0.5f * Vector3.up * m_Length;
Gizmos.DrawWireSphere(end, m_Radius);
Vector3 r = Vector3.forward * m_Radius;
Gizmos.DrawLine(start + r, end + r);
Gizmos.DrawLine(start - r, end - r);
r = Vector3.right * m_Radius;
Gizmos.DrawLine(start + r, end + r);
Gizmos.DrawLine(start - r, end - r);
}
void OnDrawGizmos()
{
// TODO: Looks like this changed the name. Find a more robust way to use the icon.
// Gizmos.DrawIcon(transform.position, "PointLight Gizmo_MIP0.png", true);
}
bool InsideShadowmapCameraRender()
{
RenderTexture target = Camera.current.targetTexture;
return target != null && target.format == RenderTextureFormat.Shadowmap;
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// File: TypographyProperties.cs
//
// Description: Typography properties.
//
// History:
// 06/13/2003 : sergeym - created.
//
//---------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.TextFormatting;
namespace MS.Internal.Text
{
/// <summary>
/// Typography properties provider.
/// </summary>
internal sealed class TypographyProperties : TextRunTypographyProperties
{
/// <summary>
/// Used as indexes to bitscale for boolean properties
/// </summary>
private enum PropertyId
{
/// <summary> StandardLigatures property </summary>
StandardLigatures = 0,
/// <summary> ContextualLigatures property </summary>
ContextualLigatures = 1,
/// <summary> DiscretionaryLigatures property </summary>
DiscretionaryLigatures = 2,
/// <summary> HistoricalLigatures property </summary>
HistoricalLigatures = 3,
/// <summary> CaseSensitiveForms property </summary>
CaseSensitiveForms = 4,
/// <summary> ContextualAlternates property </summary>
ContextualAlternates = 5,
/// <summary> HistoricalForms property </summary>
HistoricalForms = 6,
/// <summary> Kerning property </summary>
Kerning = 7,
/// <summary> CapitalSpacing property </summary>
CapitalSpacing = 8,
/// <summary> StylisticSet1 property </summary>
StylisticSet1 = 9,
/// <summary> StylisticSet2 property </summary>
StylisticSet2 = 10,
/// <summary> StylisticSet3 property </summary>
StylisticSet3 = 11,
/// <summary> StylisticSet4 property </summary>
StylisticSet4 = 12,
/// <summary> StylisticSet5 property </summary>
StylisticSet5 = 13,
/// <summary> StylisticSet6 property </summary>
StylisticSet6 = 14,
/// <summary> StylisticSet7 property </summary>
StylisticSet7 = 15,
/// <summary> StylisticSet8 property </summary>
StylisticSet8 = 16,
/// <summary> StylisticSet9 property </summary>
StylisticSet9 = 17,
/// <summary> StylisticSet10 property </summary>
StylisticSet10 = 18,
/// <summary> StylisticSet11 property </summary>
StylisticSet11 = 19,
/// <summary> StylisticSet12 property </summary>
StylisticSet12 = 20,
/// <summary> StylisticSet13 property </summary>
StylisticSet13 = 21,
/// <summary> StylisticSet14 property </summary>
StylisticSet14 = 22,
/// <summary> StylisticSet15 property </summary>
StylisticSet15 = 23,
/// <summary> StylisticSet16 property </summary>
StylisticSet16 = 24,
/// <summary> StylisticSet17 property </summary>
StylisticSet17 = 25,
/// <summary> StylisticSet18 property </summary>
StylisticSet18 = 26,
/// <summary> StylisticSet19 property </summary>
StylisticSet19 = 27,
/// <summary> StylisticSet20 property </summary>
StylisticSet20 = 28,
/// <summary> SlashedZero property </summary>
SlashedZero = 29,
/// <summary> MathematicalGreek property </summary>
MathematicalGreek = 30,
/// <summary> EastAsianExpertForms property </summary>
EastAsianExpertForms = 31,
/// <summary>
/// Total number of properties. Should not be >32.
/// Otherwise bitmask field _idPropertySetFlags should be changed to ulong
/// </summary>
PropertyCount = 32
}
/// <summary>
/// Create new typographyProperties with deefault values
/// </summary>
public TypographyProperties()
{
// Flags are stored in uint (32 bits).
// Any way to check it at compile time?
Debug.Assert((uint)PropertyId.PropertyCount <= 32);
ResetProperties();
}
#region Public typography properties
/// <summary>
///
/// </summary>
public override bool StandardLigatures
{
get { return IsBooleanPropertySet(PropertyId.StandardLigatures); }
}
public void SetStandardLigatures(bool value)
{
SetBooleanProperty(PropertyId.StandardLigatures, value);
}
/// <summary>
///
/// </summary>
public override bool ContextualLigatures
{
get { return IsBooleanPropertySet(PropertyId.ContextualLigatures); }
}
public void SetContextualLigatures(bool value)
{
SetBooleanProperty(PropertyId.ContextualLigatures, value);
}
/// <summary>
///
/// </summary>
public override bool DiscretionaryLigatures
{
get { return IsBooleanPropertySet(PropertyId.DiscretionaryLigatures); }
}
public void SetDiscretionaryLigatures(bool value)
{
SetBooleanProperty(PropertyId.DiscretionaryLigatures, value);
}
/// <summary>
///
/// </summary>
public override bool HistoricalLigatures
{
get { return IsBooleanPropertySet(PropertyId.HistoricalLigatures); }
}
public void SetHistoricalLigatures(bool value)
{
SetBooleanProperty(PropertyId.HistoricalLigatures, value);
}
/// <summary>
///
/// </summary>
public override bool CaseSensitiveForms
{
get { return IsBooleanPropertySet(PropertyId.CaseSensitiveForms); }
}
public void SetCaseSensitiveForms(bool value)
{
SetBooleanProperty(PropertyId.CaseSensitiveForms, value);
}
/// <summary>
///
/// </summary>
public override bool ContextualAlternates
{
get { return IsBooleanPropertySet(PropertyId.ContextualAlternates); }
}
public void SetContextualAlternates(bool value)
{
SetBooleanProperty(PropertyId.ContextualAlternates, value);
}
/// <summary>
///
/// </summary>
public override bool HistoricalForms
{
get { return IsBooleanPropertySet(PropertyId.HistoricalForms); }
}
public void SetHistoricalForms(bool value)
{
SetBooleanProperty(PropertyId.HistoricalForms, value);
}
/// <summary>
///
/// </summary>
public override bool Kerning
{
get { return IsBooleanPropertySet(PropertyId.Kerning); }
}
public void SetKerning(bool value)
{
SetBooleanProperty(PropertyId.Kerning, value);
}
/// <summary>
///
/// </summary>
public override bool CapitalSpacing
{
get { return IsBooleanPropertySet(PropertyId.CapitalSpacing); }
}
public void SetCapitalSpacing(bool value)
{
SetBooleanProperty(PropertyId.CapitalSpacing, value);
}
/// <summary>
///
/// </summary>
public override bool StylisticSet1
{
get { return IsBooleanPropertySet(PropertyId.StylisticSet1); }
}
public void SetStylisticSet1(bool value)
{
SetBooleanProperty(PropertyId.StylisticSet1, value);
}
/// <summary>
///
/// </summary>
public override bool StylisticSet2
{
get { return IsBooleanPropertySet(PropertyId.StylisticSet2); }
}
public void SetStylisticSet2(bool value)
{
SetBooleanProperty(PropertyId.StylisticSet2, value);
}
/// <summary>
///
/// </summary>
public override bool StylisticSet3
{
get { return IsBooleanPropertySet(PropertyId.StylisticSet3); }
}
public void SetStylisticSet3(bool value)
{
SetBooleanProperty(PropertyId.StylisticSet3, value);
}
/// <summary>
///
/// </summary>
public override bool StylisticSet4
{
get { return IsBooleanPropertySet(PropertyId.StylisticSet4); }
}
public void SetStylisticSet4(bool value)
{
SetBooleanProperty(PropertyId.StylisticSet4, value);
}
/// <summary>
///
/// </summary>
public override bool StylisticSet5
{
get { return IsBooleanPropertySet(PropertyId.StylisticSet5); }
}
public void SetStylisticSet5(bool value)
{
SetBooleanProperty(PropertyId.StylisticSet5, value);
}
/// <summary>
///
/// </summary>
public override bool StylisticSet6
{
get { return IsBooleanPropertySet(PropertyId.StylisticSet6); }
}
public void SetStylisticSet6(bool value)
{
SetBooleanProperty(PropertyId.StylisticSet6, value);
}
/// <summary>
///
/// </summary>
public override bool StylisticSet7
{
get { return IsBooleanPropertySet(PropertyId.StylisticSet7); }
}
public void SetStylisticSet7(bool value)
{
SetBooleanProperty(PropertyId.StylisticSet7, value);
}
/// <summary>
///
/// </summary>
public override bool StylisticSet8
{
get { return IsBooleanPropertySet(PropertyId.StylisticSet8); }
}
public void SetStylisticSet8(bool value)
{
SetBooleanProperty(PropertyId.StylisticSet8, value);
}
/// <summary>
///
/// </summary>
public override bool StylisticSet9
{
get { return IsBooleanPropertySet(PropertyId.StylisticSet9); }
}
public void SetStylisticSet9(bool value)
{
SetBooleanProperty(PropertyId.StylisticSet9, value);
}
/// <summary>
///
/// </summary>
public override bool StylisticSet10
{
get { return IsBooleanPropertySet(PropertyId.StylisticSet10); }
}
public void SetStylisticSet10(bool value)
{
SetBooleanProperty(PropertyId.StylisticSet10, value);
}
/// <summary>
///
/// </summary>
public override bool StylisticSet11
{
get { return IsBooleanPropertySet(PropertyId.StylisticSet11); }
}
public void SetStylisticSet11(bool value)
{
SetBooleanProperty(PropertyId.StylisticSet11, value);
}
/// <summary>
///
/// </summary>
public override bool StylisticSet12
{
get { return IsBooleanPropertySet(PropertyId.StylisticSet12); }
}
public void SetStylisticSet12(bool value)
{
SetBooleanProperty(PropertyId.StylisticSet12, value);
}
/// <summary>
///
/// </summary>
public override bool StylisticSet13
{
get { return IsBooleanPropertySet(PropertyId.StylisticSet13); }
}
public void SetStylisticSet13(bool value)
{
SetBooleanProperty(PropertyId.StylisticSet13, value);
}
/// <summary>
///
/// </summary>
public override bool StylisticSet14
{
get { return IsBooleanPropertySet(PropertyId.StylisticSet14); }
}
public void SetStylisticSet14(bool value)
{
SetBooleanProperty(PropertyId.StylisticSet14, value);
}
/// <summary>
///
/// </summary>
public override bool StylisticSet15
{
get { return IsBooleanPropertySet(PropertyId.StylisticSet15); }
}
public void SetStylisticSet15(bool value)
{
SetBooleanProperty(PropertyId.StylisticSet15, value);
}
/// <summary>
///
/// </summary>
public override bool StylisticSet16
{
get { return IsBooleanPropertySet(PropertyId.StylisticSet16); }
}
public void SetStylisticSet16(bool value)
{
SetBooleanProperty(PropertyId.StylisticSet16, value);
}
/// <summary>
///
/// </summary>
public override bool StylisticSet17
{
get { return IsBooleanPropertySet(PropertyId.StylisticSet17); }
}
public void SetStylisticSet17(bool value)
{
SetBooleanProperty(PropertyId.StylisticSet17, value);
}
/// <summary>
///
/// </summary>
public override bool StylisticSet18
{
get { return IsBooleanPropertySet(PropertyId.StylisticSet18); }
}
public void SetStylisticSet18(bool value)
{
SetBooleanProperty(PropertyId.StylisticSet18, value);
}
/// <summary>
///
/// </summary>
public override bool StylisticSet19
{
get { return IsBooleanPropertySet(PropertyId.StylisticSet19); }
}
public void SetStylisticSet19(bool value)
{
SetBooleanProperty(PropertyId.StylisticSet19, value);
}
/// <summary>
///
/// </summary>
public override bool StylisticSet20
{
get { return IsBooleanPropertySet(PropertyId.StylisticSet20); }
}
public void SetStylisticSet20(bool value)
{
SetBooleanProperty(PropertyId.StylisticSet20, value);
}
/// <summary>
///
/// </summary>
public override FontFraction Fraction
{
get { return _fraction; }
}
public void SetFraction(FontFraction value)
{
_fraction = value;
OnPropertiesChanged();
}
/// <summary>
///
/// </summary>
public override bool SlashedZero
{
get { return IsBooleanPropertySet(PropertyId.SlashedZero); }
}
public void SetSlashedZero(bool value)
{
SetBooleanProperty(PropertyId.SlashedZero, value);
}
/// <summary>
///
/// </summary>
public override bool MathematicalGreek
{
get { return IsBooleanPropertySet(PropertyId.MathematicalGreek); }
}
public void SetMathematicalGreek(bool value)
{
SetBooleanProperty(PropertyId.MathematicalGreek, value);
}
/// <summary>
///
/// </summary>
public override bool EastAsianExpertForms
{
get { return IsBooleanPropertySet(PropertyId.EastAsianExpertForms); }
}
public void SetEastAsianExpertForms(bool value)
{
SetBooleanProperty(PropertyId.EastAsianExpertForms, value);
}
/// <summary>
///
/// </summary>
public override FontVariants Variants
{
get { return _variant; }
}
public void SetVariants(FontVariants value)
{
_variant = value;
OnPropertiesChanged();
}
/// <summary>
///
/// </summary>
public override FontCapitals Capitals
{
get { return _capitals; }
}
public void SetCapitals(FontCapitals value)
{
_capitals = value;
OnPropertiesChanged();
}
/// <summary>
///
/// </summary>
public override FontNumeralStyle NumeralStyle
{
get { return _numeralStyle; }
}
public void SetNumeralStyle(FontNumeralStyle value)
{
_numeralStyle = value;
OnPropertiesChanged();
}
/// <summary>
///
/// </summary>
public override FontNumeralAlignment NumeralAlignment
{
get { return _numeralAlignment; }
}
public void SetNumeralAlignment(FontNumeralAlignment value)
{
_numeralAlignment = value;
OnPropertiesChanged();
}
/// <summary>
///
/// </summary>
public override FontEastAsianWidths EastAsianWidths
{
get { return _eastAsianWidths; }
}
public void SetEastAsianWidths(FontEastAsianWidths value)
{
_eastAsianWidths = value;
OnPropertiesChanged();
}
/// <summary>
///
/// </summary>
public override FontEastAsianLanguage EastAsianLanguage
{
get { return _eastAsianLanguage; }
}
public void SetEastAsianLanguage(FontEastAsianLanguage value)
{
_eastAsianLanguage = value;
OnPropertiesChanged();
}
/// <summary>
///
/// </summary>
public override int StandardSwashes
{
get { return _standardSwashes; }
}
public void SetStandardSwashes(int value)
{
_standardSwashes = value;
OnPropertiesChanged();
}
/// <summary>
///
/// </summary>
public override int ContextualSwashes
{
get { return _contextualSwashes; }
}
public void SetContextualSwashes(int value)
{
_contextualSwashes = value;
OnPropertiesChanged();
}
/// <summary>
///
/// </summary>
public override int StylisticAlternates
{
get { return _stylisticAlternates; }
}
public void SetStylisticAlternates(int value)
{
_stylisticAlternates = value;
OnPropertiesChanged();
}
/// <summary>
///
/// </summary>
public override int AnnotationAlternates
{
get { return _annotationAlternates; }
}
public void SetAnnotationAlternates(int value)
{
_annotationAlternates = value;
OnPropertiesChanged();
}
#endregion Public typography properties
/// <summary>
/// Check whether two Property sets are equal
/// </summary>
/// <param name="other">property to compare</param>
/// <returns></returns>
public override bool Equals(object other)
{
if (other == null)
{
return false;
}
if (this.GetType() != other.GetType())
{
return false;
}
TypographyProperties genericOther = (TypographyProperties)other;
return //This will cover all boolean properties
_idPropertySetFlags == genericOther._idPropertySetFlags &&
//And this will cover the rest
_variant == genericOther._variant &&
_capitals == genericOther._capitals &&
_fraction == genericOther._fraction &&
_numeralStyle == genericOther._numeralStyle &&
_numeralAlignment == genericOther._numeralAlignment &&
_eastAsianWidths == genericOther._eastAsianWidths &&
_eastAsianLanguage == genericOther._eastAsianLanguage &&
_standardSwashes == genericOther._standardSwashes &&
_contextualSwashes == genericOther._contextualSwashes &&
_stylisticAlternates == genericOther._stylisticAlternates &&
_annotationAlternates == genericOther._annotationAlternates;
}
public override int GetHashCode()
{
return (int)(_idPropertySetFlags >> 32) ^
(int)(_idPropertySetFlags & 0xFFFFFFFF) ^
(int)_variant << 28 ^
(int)_capitals << 24 ^
(int)_numeralStyle << 20 ^
(int)_numeralAlignment << 18 ^
(int)_eastAsianWidths << 14 ^
(int)_eastAsianLanguage << 10 ^
(int)_standardSwashes << 6 ^
(int)_contextualSwashes << 2 ^
(int)_stylisticAlternates ^
(int)_fraction << 16 ^
(int)_annotationAlternates << 12;
}
public static bool operator ==(TypographyProperties first, TypographyProperties second)
{
//Need to cast to object to do null comparision.
if (((object)first) == null) return (((object)second) == null);
return first.Equals(second);
}
public static bool operator !=(TypographyProperties first, TypographyProperties second)
{
return !(first == second);
}
#region Private methods
/// <summary>
/// Set all properties to default value
/// </summary>
private void ResetProperties()
{
//clean flags
_idPropertySetFlags = 0;
//assign non-trivial(not bolean) values
_standardSwashes = 0;
_contextualSwashes = 0;
_stylisticAlternates = 0;
_annotationAlternates = 0;
_variant = FontVariants.Normal;
_capitals = FontCapitals.Normal;
_numeralStyle = FontNumeralStyle.Normal;
_numeralAlignment = FontNumeralAlignment.Normal;
_eastAsianWidths = FontEastAsianWidths.Normal;
_eastAsianLanguage = FontEastAsianLanguage.Normal;
_fraction = FontFraction.Normal;
OnPropertiesChanged();
}
/// <summary>
/// Check whether boolean property is set to non-default value
/// </summary>
/// <param name="propertyId">PropertyId</param>
/// <returns></returns>
private bool IsBooleanPropertySet(PropertyId propertyId)
{
Debug.Assert((uint)propertyId < (uint)PropertyId.PropertyCount, "Invalid typography property id");
uint flagMask = (uint)(((uint)1) << ((int)propertyId));
return (_idPropertySetFlags & flagMask) != 0;
}
/// <summary>
/// Set/clean flag that property value is non-default
/// Used only internally to support quick checks while forming FeatureSet
///
/// </summary>
/// <param name="propertyId">Property id</param>
/// <param name="flagValue">Value of the flag</param>
private void SetBooleanProperty(PropertyId propertyId, bool flagValue)
{
Debug.Assert((uint)propertyId < (uint)PropertyId.PropertyCount, "Invalid typography property id");
uint flagMask = (uint)(((uint)1) << ((int)propertyId));
if (flagValue)
_idPropertySetFlags |= flagMask;
else
_idPropertySetFlags &= ~flagMask;
OnPropertiesChanged();
}
private uint _idPropertySetFlags;
private int _standardSwashes;
private int _contextualSwashes;
private int _stylisticAlternates;
private int _annotationAlternates;
private FontVariants _variant;
private FontCapitals _capitals;
private FontFraction _fraction;
private FontNumeralStyle _numeralStyle;
private FontNumeralAlignment _numeralAlignment;
private FontEastAsianWidths _eastAsianWidths;
private FontEastAsianLanguage _eastAsianLanguage;
#endregion Private members
}
}
| |
// 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.CompilerServices;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
namespace System
{
/// <summary>
/// Span represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed
/// or native memory, or to memory allocated on the stack. It is type- and memory-safe.
/// </summary>
[DebuggerTypeProxy(typeof(SpanDebugView<>))]
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public readonly ref struct Span<T>
{
/// <summary>
/// Creates a new span over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span(T[] array)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException_ArrayTypeMustBeExactMatch(typeof(T));
_length = array.Length;
_pinnable = Unsafe.As<Pinnable<T>>(array);
_byteOffset = SpanHelpers.PerTypeValues<T>.ArrayAdjustment;
}
/// <summary>
/// Creates a new span over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the span.</param>
/// <param name="length">The number of items in the span.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span(T[] array, int start, int length)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException_ArrayTypeMustBeExactMatch(typeof(T));
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_length = length;
_pinnable = Unsafe.As<Pinnable<T>>(array);
_byteOffset = SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start);
}
/// <summary>
/// Creates a new span over the target unmanaged buffer. Clearly this
/// is quite dangerous, because we are creating arbitrarily typed T's
/// out of a void*-typed block of memory. And the length is not checked.
/// But if this creation is correct, then all subsequent uses are correct.
/// </summary>
/// <param name="pointer">An unmanaged pointer to memory.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="length"/> is negative.
/// </exception>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe Span(void* pointer, int length)
{
if (SpanHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T));
if (length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_length = length;
_pinnable = null;
_byteOffset = new IntPtr(pointer);
}
/// <summary>
/// Create a new span over a portion of a regular managed object. This can be useful
/// if part of a managed object represents a "fixed array." This is dangerous because neither the
/// <paramref name="length"/> is checked, nor <paramref name="obj"/> being null, nor the fact that
/// "rawPointer" actually lies within <paramref name="obj"/>.
/// </summary>
/// <param name="obj">The managed object that contains the data to span over.</param>
/// <param name="objectData">A reference to data within that object.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[EditorBrowsable(EditorBrowsableState.Never)]
public static Span<T> DangerousCreate(object obj, ref T objectData, int length)
{
Pinnable<T> pinnable = Unsafe.As<Pinnable<T>>(obj);
IntPtr byteOffset = Unsafe.ByteOffset<T>(ref pinnable.Data, ref objectData);
return new Span<T>(pinnable, byteOffset, length);
}
// Constructor for internal use only.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Span(Pinnable<T> pinnable, IntPtr byteOffset, int length)
{
Debug.Assert(length >= 0);
_length = length;
_pinnable = pinnable;
_byteOffset = byteOffset;
}
//Debugger Display = {T[length]}
private string DebuggerDisplay => string.Format("{{{0}[{1}]}}", typeof(T).Name, _length);
/// <summary>
/// The number of items in the span.
/// </summary>
public int Length => _length;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
/// Returns a reference to specified element of the Span.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
/// <exception cref="System.IndexOutOfRangeException">
/// Thrown when index less than 0 or index greater than or equal to Length
/// </exception>
public ref T this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if ((uint)index >= ((uint)_length))
ThrowHelper.ThrowIndexOutOfRangeException();
if (_pinnable == null)
unsafe { return ref Unsafe.Add<T>(ref Unsafe.AsRef<T>(_byteOffset.ToPointer()), index); }
else
return ref Unsafe.Add<T>(ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset), index);
}
}
/// <summary>
/// Clears the contents of this span.
/// </summary>
public unsafe void Clear()
{
int length = _length;
if (length == 0)
return;
var byteLength = (UIntPtr)((uint)length * Unsafe.SizeOf<T>());
if ((Unsafe.SizeOf<T>() & (sizeof(IntPtr) - 1)) != 0)
{
if (_pinnable == null)
{
var ptr = (byte*)_byteOffset.ToPointer();
SpanHelpers.ClearLessThanPointerSized(ptr, byteLength);
}
else
{
ref byte b = ref Unsafe.As<T, byte>(ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset));
SpanHelpers.ClearLessThanPointerSized(ref b, byteLength);
}
}
else
{
if (SpanHelpers.IsReferenceOrContainsReferences<T>())
{
UIntPtr pointerSizedLength = (UIntPtr)((length * Unsafe.SizeOf<T>()) / sizeof(IntPtr));
ref IntPtr ip = ref Unsafe.As<T, IntPtr>(ref DangerousGetPinnableReference());
SpanHelpers.ClearPointerSizedWithReferences(ref ip, pointerSizedLength);
}
else
{
ref byte b = ref Unsafe.As<T, byte>(ref DangerousGetPinnableReference());
SpanHelpers.ClearPointerSizedWithoutReferences(ref b, byteLength);
}
}
}
/// <summary>
/// Fills the contents of this span with the given value.
/// </summary>
public unsafe void Fill(T value)
{
int length = _length;
if (length == 0)
return;
if (Unsafe.SizeOf<T>() == 1)
{
byte fill = Unsafe.As<T, byte>(ref value);
if (_pinnable == null)
{
Unsafe.InitBlockUnaligned(_byteOffset.ToPointer(), fill, (uint)length);
}
else
{
ref byte r = ref Unsafe.As<T, byte>(ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset));
Unsafe.InitBlockUnaligned(ref r, fill, (uint)length);
}
}
else
{
ref T r = ref DangerousGetPinnableReference();
// TODO: Create block fill for value types of power of two sizes e.g. 2,4,8,16
// Simple loop unrolling
int i = 0;
for (; i < (length & ~7); i += 8)
{
Unsafe.Add<T>(ref r, i + 0) = value;
Unsafe.Add<T>(ref r, i + 1) = value;
Unsafe.Add<T>(ref r, i + 2) = value;
Unsafe.Add<T>(ref r, i + 3) = value;
Unsafe.Add<T>(ref r, i + 4) = value;
Unsafe.Add<T>(ref r, i + 5) = value;
Unsafe.Add<T>(ref r, i + 6) = value;
Unsafe.Add<T>(ref r, i + 7) = value;
}
if (i < (length & ~3))
{
Unsafe.Add<T>(ref r, i + 0) = value;
Unsafe.Add<T>(ref r, i + 1) = value;
Unsafe.Add<T>(ref r, i + 2) = value;
Unsafe.Add<T>(ref r, i + 3) = value;
i += 4;
}
for (; i < length; i++)
{
Unsafe.Add<T>(ref r, i) = value;
}
}
}
/// <summary>
/// Copies the contents of this span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
///
/// <param name="destination">The span to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination Span is shorter than the source Span.
/// </exception>
/// </summary>
public void CopyTo(Span<T> destination)
{
if (!TryCopyTo(destination))
ThrowHelper.ThrowArgumentException_DestinationTooShort();
}
/// <summary>
/// Copies the contents of this span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
///
/// <returns>If the destination span is shorter than the source span, this method
/// return false and no data is written to the destination.</returns>
/// </summary>
/// <param name="destination">The span to copy items into.</param>
public bool TryCopyTo(Span<T> destination)
{
int length = _length;
int destLength = destination._length;
if ((uint)length == 0)
return true;
if ((uint)length > (uint)destLength)
return false;
ref T src = ref DangerousGetPinnableReference();
ref T dst = ref destination.DangerousGetPinnableReference();
SpanHelpers.CopyTo<T>(ref dst, destLength, ref src, length);
return true;
}
/// <summary>
/// Returns true if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator ==(Span<T> left, Span<T> right)
{
return left._length == right._length && Unsafe.AreSame<T>(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference());
}
/// <summary>
/// Returns false if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator !=(Span<T> left, Span<T> right) => !(left == right);
/// <summary>
/// This method is not supported as spans cannot be boxed. To compare two spans, use operator==.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("Equals() on Span will always throw an exception. Use == instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
throw new NotSupportedException(SR.CannotCallEqualsOnSpan);
}
/// <summary>
/// This method is not supported as spans cannot be boxed.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("GetHashCode() on Span will always throw an exception.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
throw new NotSupportedException(SR.CannotCallGetHashCodeOnSpan);
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="Span{T}"/>
/// </summary>
public static implicit operator Span<T>(T[] array) => array != null ? new Span<T>(array) : default;
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Span{T}"/>
/// </summary>
public static implicit operator Span<T>(ArraySegment<T> arraySegment)
=> arraySegment.Array != null ? new Span<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count) : default;
/// <summary>
/// Defines an implicit conversion of a <see cref="Span{T}"/> to a <see cref="ReadOnlySpan{T}"/>
/// </summary>
public static implicit operator ReadOnlySpan<T>(Span<T> span) => new ReadOnlySpan<T>(span._pinnable, span._byteOffset, span._length);
/// <summary>
/// Forms a slice out of the given span, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<T> Slice(int start)
{
if ((uint)start > (uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
IntPtr newOffset = _byteOffset.Add<T>(start);
int length = _length - start;
return new Span<T>(_pinnable, newOffset, length);
}
/// <summary>
/// Forms a slice out of the given span, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<T> Slice(int start, int length)
{
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
IntPtr newOffset = _byteOffset.Add<T>(start);
return new Span<T>(_pinnable, newOffset, length);
}
/// <summary>
/// Copies the contents of this span into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] ToArray()
{
if (_length == 0)
return SpanHelpers.PerTypeValues<T>.EmptyArray;
T[] result = new T[_length];
CopyTo(result);
return result;
}
/// <summary>
/// Returns a 0-length span whose base is the null pointer.
/// </summary>
public static Span<T> Empty => default(Span<T>);
/// <summary>
/// This method is obsolete, use System.Runtime.InteropServices.MemoryMarshal.GetReference instead.
/// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element
/// would have been stored. Such a reference can be used for pinning but must never be dereferenced.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[EditorBrowsable(EditorBrowsableState.Never)]
internal ref T DangerousGetPinnableReference()
{
if (_pinnable == null)
unsafe { return ref Unsafe.AsRef<T>(_byteOffset.ToPointer()); }
else
return ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset);
}
/// <summary>Gets an enumerator for this span.</summary>
public Enumerator GetEnumerator() => new Enumerator(this);
/// <summary>Enumerates the elements of a <see cref="Span{T}"/>.</summary>
public ref struct Enumerator
{
/// <summary>The span being enumerated.</summary>
private readonly Span<T> _span;
/// <summary>The next index to yield.</summary>
private int _index;
/// <summary>Initialize the enumerator.</summary>
/// <param name="span">The span to enumerate.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Enumerator(Span<T> span)
{
_span = span;
_index = -1;
}
/// <summary>Advances the enumerator to the next element of the span.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
int index = _index + 1;
if (index < _span.Length)
{
_index = index;
return true;
}
return false;
}
/// <summary>Gets the element at the current position of the enumerator.</summary>
public ref T Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref _span[_index];
}
}
// These expose the internal representation for Span-related apis use only.
internal Pinnable<T> Pinnable => _pinnable;
internal IntPtr ByteOffset => _byteOffset;
//
// If the Span was constructed from an object,
//
// _pinnable = that object (unsafe-casted to a Pinnable<T>)
// _byteOffset = offset in bytes from "ref _pinnable.Data" to "ref span[0]"
//
// If the Span was constructed from a native pointer,
//
// _pinnable = null
// _byteOffset = the pointer
//
private readonly Pinnable<T> _pinnable;
private readonly IntPtr _byteOffset;
private readonly int _length;
}
}
| |
// Copyright 2008 Adrian Akison
// Distributed under license terms of CPOL http://www.codeproject.com/info/cpol10.aspx
using System;
using System.Collections;
using System.Collections.Generic;
namespace Utilities.Combinatorics
{
/// <summary>
/// Permutations defines a meta-collection, typically a list of lists, of all
/// possible orderings of a set of values. This list is enumerable and allows
/// the scanning of all possible permutations using a simple foreach() loop.
/// The MetaCollectionType parameter of the constructor allows for the creation of
/// two types of sets, those with and without repetition in the output set when
/// presented with repetition in the input set.
/// </summary>
/// <remarks>
/// When given a input collect {A A B}, the following sets are generated:
/// MetaCollectionType.WithRepetition =>
/// {A A B}, {A B A}, {A A B}, {A B A}, {B A A}, {B A A}
/// MetaCollectionType.WithoutRepetition =>
/// {A A B}, {A B A}, {B A A}
///
/// When generating non-repetition sets, ordering is based on the lexicographic
/// ordering of the lists based on the provided Comparer.
/// If no comparer is provided, then T must be IComparable on T.
///
/// When generating repetition sets, no comparisions are performed and therefore
/// no comparer is required and T does not need to be IComparable.
/// </remarks>
/// <typeparam name="T">The type of the values within the list.</typeparam>
public class Permutations<T> : IMetaCollection<T> {
#region Constructors
/// <summary>
/// No default constructor, must at least provided a list of values.
/// </summary>
protected Permutations() {
;
}
/// <summary>
/// Create a permutation set from the provided list of values.
/// The values (T) must implement IComparable.
/// If T does not implement IComparable use a constructor with an explict IComparer.
/// The repetition type defaults to MetaCollectionType.WithholdRepetitionSets
/// </summary>
/// <param name="values">List of values to permute.</param>
public Permutations(IList<T> values) {
Initialize(values, GenerateOption.WithoutRepetition, null);
}
/// <summary>
/// Create a permutation set from the provided list of values.
/// If type is MetaCollectionType.WithholdRepetitionSets, then values (T) must implement IComparable.
/// If T does not implement IComparable use a constructor with an explict IComparer.
/// </summary>
/// <param name="values">List of values to permute.</param>
/// <param name="type">The type of permutation set to calculate.</param>
public Permutations(IList<T> values, GenerateOption type) {
Initialize(values, type, null);
}
/// <summary>
/// Create a permutation set from the provided list of values.
/// The values will be compared using the supplied IComparer.
/// The repetition type defaults to MetaCollectionType.WithholdRepetitionSets
/// </summary>
/// <param name="values">List of values to permute.</param>
/// <param name="comparer">Comparer used for defining the lexigraphic order.</param>
public Permutations(IList<T> values, IComparer<T> comparer) {
Initialize(values, GenerateOption.WithoutRepetition, comparer);
}
#endregion
#region IEnumerable Interface
/// <summary>
/// Gets an enumerator for collecting the list of permutations.
/// </summary>
/// <returns>The enumerator.</returns>
public virtual IEnumerator GetEnumerator() {
return new Enumerator(this);
}
/// <summary>
/// Gets an enumerator for collecting the list of permutations.
/// </summary>
/// <returns>The enumerator.</returns>
IEnumerator<IList<T>> IEnumerable<IList<T>>.GetEnumerator() {
return new Enumerator(this);
}
#endregion
#region Enumerator Inner-Class
/// <summary>
/// The enumerator that enumerates each meta-collection of the enclosing Permutations class.
/// </summary>
public class Enumerator : IEnumerator<IList<T>> {
#region Constructors
/// <summary>
/// Construct a enumerator with the parent object.
/// </summary>
/// <param name="source">The source Permutations object.</param>
public Enumerator(Permutations<T> source) {
myParent = source;
myLexicographicalOrders = new int[source.myLexicographicOrders.Length];
source.myLexicographicOrders.CopyTo(myLexicographicalOrders, 0);
Reset();
}
#endregion
#region IEnumerator Interface
/// <summary>
/// Resets the permutations enumerator to the first permutation.
/// This will be the first lexicographically order permutation.
/// </summary>
public void Reset() {
myPosition = Position.BeforeFirst;
}
/// <summary>
/// Advances to the next permutation.
/// </summary>
/// <returns>True if successfully moved to next permutation, False if no more permutations exist.</returns>
/// <remarks>
/// Continuation was tried (i.e. yield return) by was not nearly as efficient.
/// Performance is further increased by using value types and removing generics, that is, the LexicographicOrder parellel array.
/// This is a issue with the .NET CLR not optimizing as well as it could in this infrequently used scenario.
/// </remarks>
public bool MoveNext() {
if(myPosition == Position.BeforeFirst) {
myValues = new List<T>(myParent.myValues.Count);
myValues.AddRange(myParent.myValues);
Array.Sort(myLexicographicalOrders);
myPosition = Position.InSet;
} else if(myPosition == Position.InSet) {
if(myValues.Count < 2) {
myPosition = Position.AfterLast;
}
else if(NextPermutation() == false) {
myPosition = Position.AfterLast;
}
}
return myPosition != Position.AfterLast;
}
/// <summary>
/// The current permutation.
/// </summary>
public object Current {
get {
if(myPosition == Position.InSet) {
return new List<T>(myValues);
}
else {
throw new InvalidOperationException();
}
}
}
/// <summary>
/// The current permutation.
/// </summary>
IList<T> IEnumerator<IList<T>>.Current {
get {
if(myPosition == Position.InSet) {
return new List<T>(myValues);
}
else {
throw new InvalidOperationException();
}
}
}
/// <summary>
/// Cleans up non-managed resources, of which there are none used here.
/// </summary>
public virtual void Dispose() {
;
}
#endregion
#region Heavy Lifting Methods
/// <summary>
/// Calculates the next lexicographical permutation of the set.
/// This is a permutation with repetition where values that compare as equal will not
/// swap positions to create a new permutation.
/// http://www.cut-the-knot.org/do_you_know/AllPerm.shtml
/// E. W. Dijkstra, A Discipline of Programming, Prentice-Hall, 1997
/// </summary>
/// <returns>True if a new permutation has been returned, false if not.</returns>
/// <remarks>
/// This uses the integers of the lexicographical order of the values so that any
/// comparison of values are only performed during initialization.
/// </remarks>
private bool NextPermutation() {
int i = myLexicographicalOrders.Length - 1;
while(myLexicographicalOrders[i - 1] >= myLexicographicalOrders[i]) {
--i;
if(i == 0) {
return false;
}
}
int j = myLexicographicalOrders.Length;
while(myLexicographicalOrders[j - 1] <= myLexicographicalOrders[i - 1]) {
--j;
}
Swap(i - 1, j - 1);
++i;
j = myLexicographicalOrders.Length;
while(i < j) {
Swap(i - 1, j - 1);
++i;
--j;
}
return true;
}
/// <summary>
/// Helper function for swapping two elements within the internal collection.
/// This swaps both the lexicographical order and the values, maintaining the parallel array.
/// </summary>
private void Swap(int i, int j) {
myTemp = myValues[i];
myValues[i] = myValues[j];
myValues[j] = myTemp;
myKviTemp = myLexicographicalOrders[i];
myLexicographicalOrders[i] = myLexicographicalOrders[j];
myLexicographicalOrders[j] = myKviTemp;
}
#endregion
#region Data and Internal Members
/// <summary>
/// Single instance of swap variable for T, small performance improvement over declaring in Swap function scope.
/// </summary>
private T myTemp;
/// <summary>
/// Single instance of swap variable for int, small performance improvement over declaring in Swap function scope.
/// </summary>
private int myKviTemp;
/// <summary>
/// Flag indicating the position of the enumerator.
/// </summary>
private Position myPosition = Position.BeforeFirst;
/// <summary>
/// Parrellel array of integers that represent the location of items in the myValues array.
/// This is generated at Initialization and is used as a performance speed up rather that
/// comparing T each time, much faster to let the CLR optimize around integers.
/// </summary>
private int[] myLexicographicalOrders;
/// <summary>
/// The list of values that are current to the enumerator.
/// </summary>
private List<T> myValues;
/// <summary>
/// The set of permuations that this enumerator enumerates.
/// </summary>
private Permutations<T> myParent;
/// <summary>
/// Internal position type for tracking enumertor position.
/// </summary>
private enum Position {
BeforeFirst,
InSet,
AfterLast
}
#endregion
}
#endregion
#region IMetaList Interface
/// <summary>
/// The count of all permutations that will be returned.
/// If type is MetaCollectionType.WithholdGeneratedSets, then this does not double count permutations with multiple identical values.
/// I.e. count of permutations of "AAB" will be 3 instead of 6.
/// If type is MetaCollectionType.WithRepetition, then this is all combinations and is therefore N!, where N is the number of values.
/// </summary>
public long Count {
get {
return myCount;
}
}
/// <summary>
/// The type of Permutations set that is generated.
/// </summary>
public GenerateOption Type {
get {
return myMetaCollectionType;
}
}
/// <summary>
/// The upper index of the meta-collection, equal to the number of items in the initial set.
/// </summary>
public int UpperIndex {
get {
return myValues.Count;
}
}
/// <summary>
/// The lower index of the meta-collection, equal to the number of items returned each iteration.
/// For Permutation, this is always equal to the UpperIndex.
/// </summary>
public int LowerIndex {
get {
return myValues.Count;
}
}
#endregion
#region Heavy Lifting Members
/// <summary>
/// Common intializer used by the multiple flavors of constructors.
/// </summary>
/// <remarks>
/// Copies information provided and then creates a parellel int array of lexicographic
/// orders that will be used for the actual permutation algorithm.
/// The input array is first sorted as required for WithoutRepetition and always just for consistency.
/// This array is constructed one of two way depending on the type of the collection.
///
/// When type is MetaCollectionType.WithRepetition, then all N! permutations are returned
/// and the lexicographic orders are simply generated as 1, 2, ... N.
/// E.g.
/// Input array: {A A B C D E E}
/// Lexicograhpic Orders: {1 2 3 4 5 6 7}
///
/// When type is MetaCollectionType.WithoutRepetition, then fewer are generated, with each
/// identical element in the input array not repeated. The lexicographic sort algorithm
/// handles this natively as long as the repetition is repeated.
/// E.g.
/// Input array: {A A B C D E E}
/// Lexicograhpic Orders: {1 1 2 3 4 5 5}
/// </remarks>
private void Initialize(IList<T> values, GenerateOption type, IComparer<T> comparer) {
myMetaCollectionType = type;
myValues = new List<T>(values.Count);
myValues.AddRange(values);
myLexicographicOrders = new int[values.Count];
if(type == GenerateOption.WithRepetition) {
for(int i = 0; i < myLexicographicOrders.Length; ++i) {
myLexicographicOrders[i] = i;
}
}
else {
if(comparer == null) {
comparer = new SelfComparer<T>();
}
myValues.Sort(comparer);
int j = 1;
if(myLexicographicOrders.Length > 0) {
myLexicographicOrders[0] = j;
}
for(int i = 1; i < myLexicographicOrders.Length; ++i) {
if(comparer.Compare(myValues[i - 1], myValues[i]) != 0) {
++j;
}
myLexicographicOrders[i] = j;
}
}
myCount = GetCount();
}
/// <summary>
/// Calculates the total number of permutations that will be returned.
/// As this can grow very large, extra effort is taken to avoid overflowing the accumulator.
/// While the algorithm looks complex, it really is just collecting numerator and denominator terms
/// and cancelling out all of the denominator terms before taking the product of the numerator terms.
/// </summary>
/// <returns>The number of permutations.</returns>
private long GetCount() {
int runCount = 1;
List<int> divisors = new List<int>();
List<int> numerators = new List<int>();
for(int i = 1; i < myLexicographicOrders.Length; ++i) {
numerators.AddRange(SmallPrimeUtility.Factor(i + 1));
if(myLexicographicOrders[i] == myLexicographicOrders[i - 1]) {
++runCount;
}
else {
for(int f = 2; f <= runCount; ++f) {
divisors.AddRange(SmallPrimeUtility.Factor(f));
}
runCount = 1;
}
}
for(int f = 2; f <= runCount; ++f) {
divisors.AddRange(SmallPrimeUtility.Factor(f));
}
return SmallPrimeUtility.EvaluatePrimeFactors(SmallPrimeUtility.DividePrimeFactors(numerators, divisors));
}
#endregion
#region Data and Internal Members
/// <summary>
/// A list of T that represents the order of elements as originally provided, used for Reset.
/// </summary>
private List<T> myValues;
/// <summary>
/// Parrellel array of integers that represent the location of items in the myValues array.
/// This is generated at Initialization and is used as a performance speed up rather that
/// comparing T each time, much faster to let the CLR optimize around integers.
/// </summary>
private int[] myLexicographicOrders;
/// <summary>
/// Inner class that wraps an IComparer around a type T when it is IComparable
/// </summary>
private class SelfComparer<U> : IComparer<U> {
public int Compare(U x, U y) {
return ((IComparable<U>)x).CompareTo(y);
}
}
/// <summary>
/// The count of all permutations. Calculated at Initialization and returned by Count property.
/// </summary>
private long myCount;
/// <summary>
/// The type of Permutations that this was intialized from.
/// </summary>
private GenerateOption myMetaCollectionType;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.Runtime.Scheduler;
namespace Orleans.Runtime.GrainDirectory
{
/// <summary>
/// Most methods of this class are synchronized since they might be called both
/// from LocalGrainDirectory on CacheValidator.SchedulingContext and from RemoteGrainDirectory.
/// </summary>
internal class GrainDirectoryHandoffManager
{
private const int HANDOFF_CHUNK_SIZE = 500;
private static readonly TimeSpan RetryDelay = TimeSpan.FromMilliseconds(250);
private const int MAX_OPERATION_DEQUEUE = 2;
private readonly LocalGrainDirectory localDirectory;
private readonly ISiloStatusOracle siloStatusOracle;
private readonly IInternalGrainFactory grainFactory;
private readonly Dictionary<SiloAddress, GrainDirectoryPartition> directoryPartitionsMap;
private readonly List<SiloAddress> silosHoldingMyPartition;
private readonly Dictionary<SiloAddress, Task> lastPromise;
private readonly ILogger logger;
private readonly Factory<GrainDirectoryPartition> createPartion;
private readonly Queue<(string name, Func<Task> action)> pendingOperations = new Queue<(string name, Func<Task> action)>();
private readonly AsyncLock executorLock = new AsyncLock();
internal GrainDirectoryHandoffManager(
LocalGrainDirectory localDirectory,
ISiloStatusOracle siloStatusOracle,
IInternalGrainFactory grainFactory,
Factory<GrainDirectoryPartition> createPartion,
ILoggerFactory loggerFactory)
{
logger = loggerFactory.CreateLogger<GrainDirectoryHandoffManager>();
this.localDirectory = localDirectory;
this.siloStatusOracle = siloStatusOracle;
this.grainFactory = grainFactory;
this.createPartion = createPartion;
directoryPartitionsMap = new Dictionary<SiloAddress, GrainDirectoryPartition>();
silosHoldingMyPartition = new List<SiloAddress>();
lastPromise = new Dictionary<SiloAddress, Task>();
}
internal List<ActivationAddress> GetHandedOffInfo(GrainId grain)
{
lock (this)
{
foreach (var partition in directoryPartitionsMap.Values)
{
var result = partition.LookUpActivations(grain);
if (result.Addresses != null)
return result.Addresses;
}
}
return null;
}
private async Task HandoffMyPartitionUponStop(Dictionary<GrainId, IGrainInfo> batchUpdate, List<SiloAddress> silosHoldingMyPartitionCopy, bool isFullCopy)
{
if (batchUpdate.Count == 0 || silosHoldingMyPartitionCopy.Count == 0)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug((isFullCopy ? "FULL" : "DELTA") + " handoff finished with empty delta (nothing to send)");
return;
}
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Sending {0} items to my {1}: (ring status is {2})",
batchUpdate.Count, silosHoldingMyPartitionCopy.ToStrings(), localDirectory.RingStatusToString());
var tasks = new List<Task>();
var n = 0;
var chunk = new Dictionary<GrainId, IGrainInfo>();
// Note that batchUpdate will not change while this method is executing
foreach (var pair in batchUpdate)
{
chunk[pair.Key] = pair.Value;
n++;
if ((n % HANDOFF_CHUNK_SIZE != 0) && (n != batchUpdate.Count))
{
// If we haven't filled in a chunk yet, keep looping.
continue;
}
foreach (SiloAddress silo in silosHoldingMyPartitionCopy)
{
SiloAddress captureSilo = silo;
Dictionary<GrainId, IGrainInfo> captureChunk = chunk;
bool captureIsFullCopy = isFullCopy;
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Sending handed off partition to " + captureSilo);
Task pendingRequest;
if (lastPromise.TryGetValue(captureSilo, out pendingRequest))
{
try
{
await pendingRequest;
}
catch (Exception)
{
}
}
Task task = localDirectory.Scheduler.RunOrQueueTask(
() => localDirectory.GetDirectoryReference(captureSilo).AcceptHandoffPartition(
localDirectory.MyAddress,
captureChunk,
captureIsFullCopy),
localDirectory.RemoteGrainDirectory.SchedulingContext);
lastPromise[captureSilo] = task;
tasks.Add(task);
}
// We need to use a new Dictionary because the call to AcceptHandoffPartition, which reads the current Dictionary,
// happens asynchronously (and typically after some delay).
chunk = new Dictionary<GrainId, IGrainInfo>();
// This is a quick temporary solution. We send a full copy by sending one chunk as a full copy and follow-on chunks as deltas.
// Obviously, this will really mess up if there's a failure after the first chunk but before the others are sent, since on a
// full copy receive the follower dumps all old data and replaces it with the new full copy.
// On the other hand, over time things should correct themselves, and of course, losing directory data isn't necessarily catastrophic.
isFullCopy = false;
}
await Task.WhenAll(tasks);
}
internal void ProcessSiloRemoveEvent(SiloAddress removedSilo)
{
lock (this)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Processing silo remove event for " + removedSilo);
// Reset our follower list to take the changes into account
ResetFollowers();
// check if this is one of our successors (i.e., if I hold this silo's copy)
// (if yes, adjust local and/or handoffed directory partitions)
if (!directoryPartitionsMap.ContainsKey(removedSilo)) return;
// at least one predcessor should exist, which is me
SiloAddress predecessor = localDirectory.FindPredecessors(removedSilo, 1)[0];
Dictionary<SiloAddress, List<ActivationAddress>> duplicates;
if (localDirectory.MyAddress.Equals(predecessor))
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Merging my partition with the copy of silo " + removedSilo);
// now I am responsible for this directory part
duplicates = localDirectory.DirectoryPartition.Merge(directoryPartitionsMap[removedSilo]);
// no need to send our new partition to all others, as they
// will realize the change and combine their copies without any additional communication (see below)
}
else
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Merging partition of " + predecessor + " with the copy of silo " + removedSilo);
// adjust copy for the predecessor of the failed silo
duplicates = directoryPartitionsMap[predecessor].Merge(directoryPartitionsMap[removedSilo]);
}
localDirectory.GsiActivationMaintainer.TrackDoubtfulGrains(directoryPartitionsMap[removedSilo].GetItems());
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Removed copied partition of silo " + removedSilo);
directoryPartitionsMap.Remove(removedSilo);
DestroyDuplicateActivations(duplicates);
}
}
internal Task ProcessSiloStoppingEvent()
{
return ProcessSiloStoppingEvent_Impl();
}
private async Task ProcessSiloStoppingEvent_Impl()
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Processing silo stopping event");
// As we're about to enter an async context further down, this is the latest opportunity to lock, modify and copy
// silosHoldingMyPartition for use inside of HandoffMyPartitionUponStop
List<SiloAddress> silosHoldingMyPartitionCopy;
lock (this)
{
// Select our nearest predecessor to receive our hand-off, since that's the silo that will wind up owning our partition (assuming
// that it doesn't also fail and that no other silo joins during the transition period).
if (silosHoldingMyPartition.Count == 0)
{
silosHoldingMyPartition.AddRange(localDirectory.FindPredecessors(localDirectory.MyAddress, 1));
}
silosHoldingMyPartitionCopy = silosHoldingMyPartition.ToList();
}
// take a copy of the current directory partition
Dictionary<GrainId, IGrainInfo> batchUpdate = localDirectory.DirectoryPartition.GetItems();
await HandoffMyPartitionUponStop(batchUpdate, silosHoldingMyPartitionCopy, true);
}
internal void ProcessSiloAddEvent(SiloAddress addedSilo)
{
lock (this)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Processing silo add event for " + addedSilo);
// Reset our follower list to take the changes into account
ResetFollowers();
// check if this is one of our successors (i.e., if I should hold this silo's copy)
// (if yes, adjust local and/or copied directory partitions by splitting them between old successors and the new one)
// NOTE: We need to move part of our local directory to the new silo if it is an immediate successor.
List<SiloAddress> successors = localDirectory.FindSuccessors(localDirectory.MyAddress, 1);
if (!successors.Contains(addedSilo))
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug($"{addedSilo} is not one of my successors.");
return;
}
// check if this is an immediate successor
if (successors[0].Equals(addedSilo))
{
// split my local directory and send to my new immediate successor his share
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Splitting my partition between me and " + addedSilo);
GrainDirectoryPartition splitPart = localDirectory.DirectoryPartition.Split(
grain =>
{
var s = localDirectory.CalculateGrainDirectoryPartition(grain);
return (s != null) && !localDirectory.MyAddress.Equals(s);
}, false);
List<ActivationAddress> splitPartListSingle = splitPart.ToListOfActivations(true);
List<ActivationAddress> splitPartListMulti = splitPart.ToListOfActivations(false);
EnqueueOperation(
$"{nameof(ProcessSiloAddEvent)}({addedSilo})",
() => ProcessAddedSiloAsync(addedSilo, splitPartListSingle, splitPartListMulti));
}
else
{
// adjust partitions by splitting them accordingly between new and old silos
SiloAddress predecessorOfNewSilo = localDirectory.FindPredecessors(addedSilo, 1)[0];
if (!directoryPartitionsMap.ContainsKey(predecessorOfNewSilo))
{
// we should have the partition of the predcessor of our new successor
logger.Warn(ErrorCode.DirectoryPartitionPredecessorExpected, "This silo is expected to hold directory partition of " + predecessorOfNewSilo);
}
else
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Splitting partition of " + predecessorOfNewSilo + " and creating a copy for " + addedSilo);
GrainDirectoryPartition splitPart = directoryPartitionsMap[predecessorOfNewSilo].Split(
grain =>
{
// Need to review the 2nd line condition.
var s = localDirectory.CalculateGrainDirectoryPartition(grain);
return (s != null) && !predecessorOfNewSilo.Equals(s);
}, true);
directoryPartitionsMap[addedSilo] = splitPart;
}
}
// remove partition of one of the old successors that we do not need to now
SiloAddress oldSuccessor = directoryPartitionsMap.FirstOrDefault(pair => !successors.Contains(pair.Key)).Key;
if (oldSuccessor == null) return;
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Removing copy of the directory partition of silo " + oldSuccessor + " (holding copy of " + addedSilo + " instead)");
directoryPartitionsMap.Remove(oldSuccessor);
}
}
private async Task ProcessAddedSiloAsync(SiloAddress addedSilo, List<ActivationAddress> splitPartListSingle, List<ActivationAddress> splitPartListMulti)
{
if (!this.localDirectory.Running) return;
if (this.siloStatusOracle.GetApproximateSiloStatus(addedSilo) == SiloStatus.Active)
{
if (splitPartListSingle.Count > 0)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Sending " + splitPartListSingle.Count + " single activation entries to " + addedSilo);
}
if (splitPartListMulti.Count > 0)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Sending " + splitPartListMulti.Count + " entries to " + addedSilo);
}
await localDirectory.GetDirectoryReference(addedSilo).AcceptSplitPartition(splitPartListSingle, splitPartListMulti);
}
else
{
if (logger.IsEnabled(LogLevel.Warning)) logger.LogWarning("Silo " + addedSilo + " is no longer active and therefore cannot receive this partition split");
return;
}
if (splitPartListSingle.Count > 0)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Removing " + splitPartListSingle.Count + " single activation after partition split");
splitPartListSingle.ForEach(
activationAddress =>
localDirectory.DirectoryPartition.RemoveGrain(activationAddress.Grain));
}
if (splitPartListMulti.Count > 0)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Removing " + splitPartListMulti.Count + " multiple activation after partition split");
splitPartListMulti.ForEach(
activationAddress =>
localDirectory.DirectoryPartition.RemoveGrain(activationAddress.Grain));
}
}
internal void AcceptExistingRegistrations(List<ActivationAddress> singleActivations, List<ActivationAddress> multiActivations)
{
this.EnqueueOperation(
nameof(AcceptExistingRegistrations),
() => AcceptExistingRegistrationsAsync(singleActivations, multiActivations));
}
private async Task AcceptExistingRegistrationsAsync(List<ActivationAddress> singleActivations, List<ActivationAddress> multiActivations)
{
if (!this.localDirectory.Running) return;
if (this.logger.IsEnabled(LogLevel.Debug))
{
this.logger.LogDebug(
$"{nameof(AcceptExistingRegistrations)}: accepting {singleActivations?.Count ?? 0} single-activation registrations and {multiActivations?.Count ?? 0} multi-activation registrations.");
}
if (singleActivations != null && singleActivations.Count > 0)
{
var tasks = singleActivations.Select(addr => this.localDirectory.RegisterAsync(addr, true, 1)).ToArray();
try
{
await Task.WhenAll(tasks);
}
catch (Exception exception)
{
if (this.logger.IsEnabled(LogLevel.Warning))
this.logger.LogWarning($"Exception registering activations in {nameof(AcceptExistingRegistrations)}: {LogFormatter.PrintException(exception)}");
throw;
}
finally
{
Dictionary<SiloAddress, List<ActivationAddress>> duplicates = new Dictionary<SiloAddress, List<ActivationAddress>>();
for (var i = tasks.Length - 1; i >= 0; i--)
{
// Retry failed tasks next time.
if (tasks[i].Status != TaskStatus.RanToCompletion) continue;
// Record the applications which lost the registration race (duplicate activations).
var winner = await tasks[i];
if (!winner.Address.Equals(singleActivations[i]))
{
var duplicate = singleActivations[i];
if (!duplicates.TryGetValue(duplicate.Silo, out var activations))
{
activations = duplicates[duplicate.Silo] = new List<ActivationAddress>(1);
}
activations.Add(duplicate);
}
// Remove tasks which completed.
singleActivations.RemoveAt(i);
}
// Destroy any duplicate activations.
DestroyDuplicateActivations(duplicates);
}
}
// Multi-activation grains are much simpler because there is no need for duplicate activation logic.
if (multiActivations != null && multiActivations.Count > 0)
{
var tasks = multiActivations.Select(addr => this.localDirectory.RegisterAsync(addr, false, 1)).ToArray();
try
{
await Task.WhenAll(tasks);
}
catch (Exception exception)
{
if (this.logger.IsEnabled(LogLevel.Warning))
this.logger.LogWarning($"Exception registering activations in {nameof(AcceptExistingRegistrations)}: {LogFormatter.PrintException(exception)}");
throw;
}
finally
{
for (var i = tasks.Length - 1; i >= 0; i--)
{
// Retry failed tasks next time.
if (tasks[i].Status != TaskStatus.RanToCompletion) continue;
// Remove tasks which completed.
multiActivations.RemoveAt(i);
}
}
}
}
internal void AcceptHandoffPartition(SiloAddress source, Dictionary<GrainId, IGrainInfo> partition, bool isFullCopy)
{
lock (this)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Got request to register " + (isFullCopy ? "FULL" : "DELTA") + " directory partition with " + partition.Count + " elements from " + source);
if (!directoryPartitionsMap.ContainsKey(source))
{
if (!isFullCopy)
{
logger.Warn(ErrorCode.DirectoryUnexpectedDelta,
String.Format("Got delta of the directory partition from silo {0} (Membership status {1}) while not holding a full copy. Membership active cluster size is {2}",
source, this.siloStatusOracle.GetApproximateSiloStatus(source),
this.siloStatusOracle.GetApproximateSiloStatuses(true).Count));
}
directoryPartitionsMap[source] = this.createPartion();
}
if (isFullCopy)
{
directoryPartitionsMap[source].Set(partition);
}
else
{
directoryPartitionsMap[source].Update(partition);
}
localDirectory.GsiActivationMaintainer.TrackDoubtfulGrains(partition);
}
}
internal void RemoveHandoffPartition(SiloAddress source)
{
lock (this)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Got request to unregister directory partition copy from " + source);
directoryPartitionsMap.Remove(source);
}
}
private void ResetFollowers()
{
var copyList = silosHoldingMyPartition.ToList();
foreach (var follower in copyList)
{
RemoveOldFollower(follower);
}
}
private void RemoveOldFollower(SiloAddress silo)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Removing my copy from silo " + silo);
// release this old copy, as we have got a new one
silosHoldingMyPartition.Remove(silo);
localDirectory.Scheduler.QueueTask(() =>
localDirectory.GetDirectoryReference(silo).RemoveHandoffPartition(localDirectory.MyAddress),
localDirectory.RemoteGrainDirectory.SchedulingContext).Ignore();
}
private void DestroyDuplicateActivations(Dictionary<SiloAddress, List<ActivationAddress>> duplicates)
{
if (duplicates == null || duplicates.Count == 0) return;
this.EnqueueOperation(
nameof(DestroyDuplicateActivations),
() => DestroyDuplicateActivationsAsync(duplicates));
}
private async Task DestroyDuplicateActivationsAsync(Dictionary<SiloAddress, List<ActivationAddress>> duplicates)
{
while (duplicates.Count > 0)
{
var pair = duplicates.FirstOrDefault();
if (this.siloStatusOracle.GetApproximateSiloStatus(pair.Key) == SiloStatus.Active)
{
if (this.logger.IsEnabled(LogLevel.Debug))
{
this.logger.LogDebug(
$"{nameof(DestroyDuplicateActivations)} will destroy {duplicates.Count} duplicate activations on silo {pair.Key}: {string.Join("\n * ", pair.Value.Select(_ => _))}");
}
var remoteCatalog = this.grainFactory.GetSystemTarget<ICatalog>(Constants.CatalogId, pair.Key);
await remoteCatalog.DeleteActivations(pair.Value);
}
duplicates.Remove(pair.Key);
}
}
private void EnqueueOperation(string name, Func<Task> action)
{
lock (this)
{
this.pendingOperations.Enqueue((name, action));
if (this.pendingOperations.Count <= 2)
{
this.localDirectory.Scheduler.QueueTask(this.ExecutePendingOperations, this.localDirectory.RemoteGrainDirectory.SchedulingContext);
}
}
}
private async Task ExecutePendingOperations()
{
using (await executorLock.LockAsync())
{
var dequeueCount = 0;
while (true)
{
// Get the next operation, or exit if there are none.
(string Name, Func<Task> Action) op;
lock (this)
{
if (this.pendingOperations.Count == 0) break;
op = this.pendingOperations.Peek();
}
dequeueCount++;
try
{
await op.Action();
// Success, reset the dequeue count
dequeueCount = 0;
}
catch (Exception exception)
{
if (dequeueCount < MAX_OPERATION_DEQUEUE)
{
if (this.logger.IsEnabled(LogLevel.Warning))
this.logger.LogWarning($"{op.Name} failed, will be retried: {LogFormatter.PrintException(exception)}.");
await Task.Delay(RetryDelay);
}
else
{
if (this.logger.IsEnabled(LogLevel.Warning))
this.logger.LogWarning($"{op.Name} failed, will NOT be retried: {LogFormatter.PrintException(exception)}");
}
}
if (dequeueCount == 0 || dequeueCount >= MAX_OPERATION_DEQUEUE)
{
lock (this)
{
// Remove the operation from the queue if it was a success
// or if we tried too many times
this.pendingOperations.Dequeue();
}
}
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.InteropServices;
using System;
internal class NullableTest1
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((char?)o) == null;
}
public static void Run()
{
char? s = null;
Console.WriteLine("char");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest2
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((bool?)o) == null;
}
public static void Run()
{
bool? s = null;
Console.WriteLine("bool");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest3
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((byte?)o) == null;
}
public static void Run()
{
byte? s = null;
Console.WriteLine("byte");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest4
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((sbyte?)o) == null;
}
public static void Run()
{
sbyte? s = null;
Console.WriteLine("sbyte");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest5
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((short?)o) == null;
}
public static void Run()
{
short? s = null;
Console.WriteLine("short");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest6
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((ushort?)o) == null;
}
public static void Run()
{
ushort? s = null;
Console.WriteLine("ushort");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest7
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((int?)o) == null;
}
public static void Run()
{
int? s = null;
Console.WriteLine("int");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest8
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((uint?)o) == null;
}
public static void Run()
{
uint? s = null;
Console.WriteLine("uint");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest9
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((long?)o) == null;
}
public static void Run()
{
long? s = null;
Console.WriteLine("long");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest10
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((ulong?)o) == null;
}
public static void Run()
{
ulong? s = null;
Console.WriteLine("ulong");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest11
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((float?)o) == null;
}
public static void Run()
{
float? s = null;
Console.WriteLine("float");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest12
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((double?)o) == null;
}
public static void Run()
{
double? s = null;
Console.WriteLine("double");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest13
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((decimal?)o) == null;
}
public static void Run()
{
decimal? s = null;
Console.WriteLine("decimal");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest14
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((IntPtr?)o) == null;
}
public static void Run()
{
IntPtr? s = null;
Console.WriteLine("IntPtr");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest15
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((UIntPtr?)o) == null;
}
public static void Run()
{
UIntPtr? s = null;
Console.WriteLine("UIntPtr");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest16
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((Guid?)o) == null;
}
public static void Run()
{
Guid? s = null;
Console.WriteLine("Guid");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest17
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((GCHandle?)o) == null;
}
public static void Run()
{
GCHandle? s = null;
Console.WriteLine("GCHandle");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest18
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((ByteE?)o) == null;
}
public static void Run()
{
ByteE? s = null;
Console.WriteLine("ByteE");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest19
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((IntE?)o) == null;
}
public static void Run()
{
IntE? s = null;
Console.WriteLine("IntE");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest20
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((LongE?)o) == null;
}
public static void Run()
{
LongE? s = null;
Console.WriteLine("LongE");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest21
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((EmptyStruct?)o) == null;
}
public static void Run()
{
EmptyStruct? s = null;
Console.WriteLine("EmptyStruct");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest22
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NotEmptyStruct?)o) == null;
}
public static void Run()
{
NotEmptyStruct? s = null;
Console.WriteLine("NotEmptyStruct");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest23
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NotEmptyStructQ?)o) == null;
}
public static void Run()
{
NotEmptyStructQ? s = null;
Console.WriteLine("NotEmptyStructQ");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest24
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NotEmptyStructA?)o) == null;
}
public static void Run()
{
NotEmptyStructA? s = null;
Console.WriteLine("NotEmptyStructA");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest25
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NotEmptyStructQA?)o) == null;
}
public static void Run()
{
NotEmptyStructQA? s = null;
Console.WriteLine("NotEmptyStructQA");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest26
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((EmptyStructGen<int>?)o) == null;
}
public static void Run()
{
EmptyStructGen<int>? s = null;
Console.WriteLine("EmptyStructGen<int>");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest27
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NotEmptyStructGen<int>?)o) == null;
}
public static void Run()
{
NotEmptyStructGen<int>? s = null;
Console.WriteLine("NotEmptyStructGen<int>");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest28
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NotEmptyStructConstrainedGen<int>?)o) == null;
}
public static void Run()
{
NotEmptyStructConstrainedGen<int>? s = null;
Console.WriteLine("NotEmptyStructConstrainedGen<int>");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest29
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NotEmptyStructConstrainedGenA<int>?)o) == null;
}
public static void Run()
{
NotEmptyStructConstrainedGenA<int>? s = null;
Console.WriteLine("NotEmptyStructConstrainedGenA<int>");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest30
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NotEmptyStructConstrainedGenQ<int>?)o) == null;
}
public static void Run()
{
NotEmptyStructConstrainedGenQ<int>? s = null;
Console.WriteLine("NotEmptyStructConstrainedGenQ<int>");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest31
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NotEmptyStructConstrainedGenQA<int>?)o) == null;
}
public static void Run()
{
NotEmptyStructConstrainedGenQA<int>? s = null;
Console.WriteLine("NotEmptyStructConstrainedGenQA<int>");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest32
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NestedStruct?)o) == null;
}
public static void Run()
{
NestedStruct? s = null;
Console.WriteLine("NestedStruct");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest33
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NestedStructGen<int>?)o) == null;
}
public static void Run()
{
NestedStructGen<int>? s = null;
Console.WriteLine("NestedStructGen<int>");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest34
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((ExplicitFieldOffsetStruct?)o) == null;
}
public static void Run()
{
ExplicitFieldOffsetStruct? s = null;
Console.WriteLine("ExplicitFieldOffsetStruct");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest37
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((MarshalAsStruct?)o) == null;
}
public static void Run()
{
MarshalAsStruct? s = null;
Console.WriteLine("MarshalAsStruct");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest38
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((ImplementOneInterface?)o) == null;
}
public static void Run()
{
ImplementOneInterface? s = null;
Console.WriteLine("ImplementOneInterface");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest39
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((ImplementTwoInterface?)o) == null;
}
public static void Run()
{
ImplementTwoInterface? s = null;
Console.WriteLine("ImplementTwoInterface");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest40
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((ImplementOneInterfaceGen<int>?)o) == null;
}
public static void Run()
{
ImplementOneInterfaceGen<int>? s = null;
Console.WriteLine("ImplementOneInterfaceGen<int>");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest41
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((ImplementTwoInterfaceGen<int>?)o) == null;
}
public static void Run()
{
ImplementTwoInterfaceGen<int>? s = null;
Console.WriteLine("ImplementTwoInterfaceGen<int>");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest42
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((ImplementAllInterface<int>?)o) == null;
}
public static void Run()
{
ImplementAllInterface<int>? s = null;
Console.WriteLine("ImplementAllInterface<int>");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest43
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((WithMultipleGCHandleStruct?)o) == null;
}
public static void Run()
{
WithMultipleGCHandleStruct? s = null;
Console.WriteLine("WithMultipleGCHandleStruct");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest44
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((WithOnlyFXTypeStruct?)o) == null;
}
public static void Run()
{
WithOnlyFXTypeStruct? s = null;
Console.WriteLine("WithOnlyFXTypeStruct");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest45
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((MixedAllStruct?)o) == null;
}
public static void Run()
{
MixedAllStruct? s = null;
Console.WriteLine("MixedAllStruct");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class Test
{
private static int Main()
{
try
{
NullableTest1.Run();
NullableTest2.Run();
NullableTest3.Run();
NullableTest4.Run();
NullableTest5.Run();
NullableTest6.Run();
NullableTest7.Run();
NullableTest8.Run();
NullableTest9.Run();
NullableTest10.Run();
NullableTest11.Run();
NullableTest12.Run();
NullableTest13.Run();
NullableTest14.Run();
NullableTest15.Run();
NullableTest16.Run();
NullableTest17.Run();
NullableTest18.Run();
NullableTest19.Run();
NullableTest20.Run();
NullableTest21.Run();
NullableTest22.Run();
NullableTest23.Run();
NullableTest24.Run();
NullableTest25.Run();
NullableTest26.Run();
NullableTest27.Run();
NullableTest28.Run();
NullableTest29.Run();
NullableTest30.Run();
NullableTest31.Run();
NullableTest32.Run();
NullableTest33.Run();
NullableTest34.Run();
NullableTest37.Run();
NullableTest38.Run();
NullableTest39.Run();
NullableTest40.Run();
NullableTest41.Run();
NullableTest42.Run();
NullableTest43.Run();
NullableTest44.Run();
NullableTest45.Run();
}
catch (Exception ex)
{
Console.WriteLine("Test FAILED");
Console.WriteLine(ex);
return 666;
}
Console.WriteLine("Test SUCCESS");
return 100;
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using IdSharp.Common.Utils;
using IdSharp.Tagging.ID3v2.Extensions;
namespace IdSharp.Tagging.ID3v2.Frames
{
internal sealed class Comments : Frame, IComments
{
private EncodingType _textEncoding;
private string _languageCode;
private string _description;
private string _value;
public EncodingType TextEncoding
{
get { return _textEncoding; }
set
{
_textEncoding = value;
RaisePropertyChanged("TextEncoding");
}
}
public string LanguageCode
{
get { return _languageCode; }
set
{
if (string.IsNullOrEmpty(value))
{
_languageCode = "eng";
}
else
{
_languageCode = value.ToLower().Trim();
// Language code must be 3 characters
if (_languageCode.Length != 3)
{
string msg = string.Format("Invalid language code '{0}' in COMM frame", value);
Trace.WriteLine(msg);
// TODO: Should this fire a warning?
if (_languageCode.Length > 3)
_languageCode = _languageCode.Substring(0, 3);
else
_languageCode = _languageCode.PadRight(3, ' ');
}
}
RaisePropertyChanged("LanguageCode");
}
}
public string Description
{
get { return _description; }
set
{
_description = value;
RaisePropertyChanged("Description");
}
}
public string Value
{
get { return _value; }
set
{
_value = value;
RaisePropertyChanged("Value");
}
}
public override string GetFrameID(ID3v2TagVersion tagVersion)
{
switch (tagVersion)
{
case ID3v2TagVersion.ID3v24:
case ID3v2TagVersion.ID3v23:
return "COMM";
case ID3v2TagVersion.ID3v22:
return "COM";
default:
throw new ArgumentException("Unknown tag version");
}
}
public override void Read(TagReadingInfo tagReadingInfo, Stream stream)
{
_frameHeader.Read(tagReadingInfo, ref stream);
// Sometimes a frame size of "0" comes through (which is explicitly forbidden in spec)
if (_frameHeader.FrameSizeExcludingAdditions >= 1)
{
TextEncoding = (EncodingType)stream.Read1();
// TODO: A common mis-implementation is to exclude the language code and description
// Haven't decided how to handle this yet. Maybe if a lookup to the language table fails,
// the rest of the frame should be treated as suspicious.
if (_frameHeader.FrameSizeExcludingAdditions >= 4)
{
string languageCode = ID3v2Utils.ReadString(EncodingType.ISO88591, stream, 3);
int bytesLeft = _frameHeader.FrameSizeExcludingAdditions - 1 - 3;
string description = ID3v2Utils.ReadString(TextEncoding, stream, ref bytesLeft);
bool invalidFrame = false;
if (LanguageHelper.Languages.ContainsKey(languageCode.ToLower()) == false && languageCode.ToLower() != "xxx")
{
// most likely, it's en\0, or some other funk
if (languageCode.StartsWith("en"))
{
languageCode = "";
}
invalidFrame = true;
if (bytesLeft == 0)
{
Description = "";
}
else
{
Description = languageCode + description;
}
LanguageCode = "eng";
}
else
{
LanguageCode = languageCode;
Description = description;
}
if (bytesLeft > 0)
{
Value = ID3v2Utils.ReadString(TextEncoding, stream, bytesLeft);
}
else
{
if (invalidFrame)
{
if (languageCode.Contains("\0"))
{
// forget it, too messed up.
Value = "";
}
else
{
Value = languageCode + description;
}
}
else
{
Value = "";
}
}
}
else
{
string msg = string.Format("Under-sized ({0} bytes) COMM frame at position {1}", _frameHeader.FrameSizeExcludingAdditions, stream.Position);
Trace.WriteLine(msg);
LanguageCode = "eng";
Value = "";
}
}
else
{
string msg = string.Format("Under-sized ({0} bytes) COMM frame at position {1}", _frameHeader.FrameSizeExcludingAdditions, stream.Position);
Trace.WriteLine(msg);
LanguageCode = "eng";
Value = "";
}
}
public override byte[] GetBytes(ID3v2TagVersion tagVersion)
{
if (string.IsNullOrEmpty(Value))
return new byte[0];
if (LanguageCode == null || LanguageCode.Length != 3)
LanguageCode = "eng";
byte[] descriptionData;
byte[] valueData;
do
{
descriptionData = ID3v2Utils.GetStringBytes(tagVersion, TextEncoding, Description, true);
valueData = ID3v2Utils.GetStringBytes(tagVersion, TextEncoding, Value, false);
} while (
this.RequiresFix(tagVersion, Description, descriptionData) ||
this.RequiresFix(tagVersion, Value, valueData)
);
using (MemoryStream frameData = new MemoryStream())
{
frameData.WriteByte((byte)TextEncoding);
frameData.Write(ByteUtils.ISO88591GetBytes(LanguageCode));
frameData.Write(descriptionData);
frameData.Write(valueData);
return _frameHeader.GetBytes(frameData, tagVersion, GetFrameID(tagVersion));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using System.Reflection.Runtime.General;
using Internal.NativeFormat;
using Internal.TypeSystem;
using Internal.Runtime;
using Internal.Runtime.Augments;
using Internal.Runtime.TypeLoader;
using Internal.Metadata.NativeFormat;
using Debug = System.Diagnostics.Debug;
namespace Internal.TypeSystem.NoMetadata
{
/// <summary>
/// Type that once had metadata, but that metadata is not available
/// for the lifetime of the TypeSystemContext. Directly correlates
/// to a RuntimeTypeHandle useable in the current environment.
/// This type replaces the placeholder NoMetadataType that comes
/// with the common type system codebase
/// </summary>
internal class NoMetadataType : DefType
{
private TypeSystemContext _context;
private int _hashcode;
private RuntimeTypeHandle _genericTypeDefinition;
private DefType _genericTypeDefinitionAsDefType;
private Instantiation _instantiation;
// "_baseType == this" means "base type was not initialized yet"
private DefType _baseType;
public NoMetadataType(TypeSystemContext context, RuntimeTypeHandle genericTypeDefinition, DefType genericTypeDefinitionAsDefType, Instantiation instantiation, int hashcode)
{
_hashcode = hashcode;
_context = context;
_genericTypeDefinition = genericTypeDefinition;
_genericTypeDefinitionAsDefType = genericTypeDefinitionAsDefType;
if (_genericTypeDefinitionAsDefType == null)
_genericTypeDefinitionAsDefType = this;
_instantiation = instantiation;
// Instantiation must either be:
// Something valid (if the type is generic, or a generic type definition)
// or Empty (if the type isn't a generic of any form)
unsafe
{
Debug.Assert(((_instantiation.Length > 0) && _genericTypeDefinition.ToEETypePtr()->IsGenericTypeDefinition) ||
((_instantiation.Length == 0) && !_genericTypeDefinition.ToEETypePtr()->IsGenericTypeDefinition));
}
// Base type is not initialized
_baseType = this;
}
public override int GetHashCode()
{
return _hashcode;
}
public override TypeSystemContext Context
{
get
{
return _context;
}
}
public override DefType BaseType
{
get
{
// _baseType == this means we didn't initialize it yet
if (_baseType != this)
return _baseType;
if (RetrieveRuntimeTypeHandleIfPossible())
{
RuntimeTypeHandle baseTypeHandle;
if (!RuntimeAugments.TryGetBaseType(RuntimeTypeHandle, out baseTypeHandle))
{
Debug.Assert(false);
}
DefType baseType = !baseTypeHandle.IsNull() ? (DefType)Context.ResolveRuntimeTypeHandle(baseTypeHandle) : null;
SetBaseType(baseType);
return baseType;
}
else
{
// Parsing of the base type has not yet happened. Perform that part of native layout parsing
// just-in-time
TypeBuilderState state = GetOrCreateTypeBuilderState();
ComputeTemplate();
NativeParser typeInfoParser = state.GetParserForNativeLayoutInfo();
NativeParser baseTypeParser = typeInfoParser.GetParserForBagElementKind(BagElementKind.BaseType);
ParseBaseType(state.NativeLayoutInfo.LoadContext, baseTypeParser);
Debug.Assert(_baseType != this);
return _baseType;
}
}
}
internal override void ParseBaseType(NativeLayoutInfoLoadContext nativeLayoutInfoLoadContext, NativeParser baseTypeParser)
{
if (!baseTypeParser.IsNull)
{
// If the base type is available from the native layout info use it if the type we have is a NoMetadataType
SetBaseType((DefType)nativeLayoutInfoLoadContext.GetType(ref baseTypeParser));
}
else
{
// Set the base type for no metadata types, if we reach this point, and there isn't a parser, then we simply use the value from the template
SetBaseType(ComputeTemplate().BaseType);
}
}
/// <summary>
/// This is used to set base type for generic types without metadata
/// </summary>
public void SetBaseType(DefType baseType)
{
Debug.Assert(_baseType == this || _baseType == baseType);
_baseType = baseType;
}
protected override TypeFlags ComputeTypeFlags(TypeFlags mask)
{
TypeFlags flags = 0;
if ((mask & TypeFlags.CategoryMask) != 0)
{
unsafe
{
EEType* eetype = _genericTypeDefinition.ToEETypePtr();
if (eetype->IsValueType)
{
if (eetype->CorElementType == 0)
{
flags |= TypeFlags.ValueType;
}
else
{
if (eetype->BaseType == typeof(System.Enum).TypeHandle.ToEETypePtr())
{
flags |= TypeFlags.Enum;
}
else
{
// Primitive type.
if (eetype->CorElementType <= CorElementType.ELEMENT_TYPE_U8)
{
flags |= (TypeFlags)eetype->CorElementType;
}
else
{
switch (eetype->CorElementType)
{
case CorElementType.ELEMENT_TYPE_I:
flags |= TypeFlags.IntPtr;
break;
case CorElementType.ELEMENT_TYPE_U:
flags |= TypeFlags.UIntPtr;
break;
case CorElementType.ELEMENT_TYPE_R4:
flags |= TypeFlags.Single;
break;
case CorElementType.ELEMENT_TYPE_R8:
flags |= TypeFlags.Double;
break;
default:
throw new BadImageFormatException();
}
}
}
}
}
else if (eetype->IsInterface)
{
flags |= TypeFlags.Interface;
}
else
{
flags |= TypeFlags.Class;
}
}
}
if ((mask & TypeFlags.AttributeCacheComputed) != 0)
{
flags |= TypeFlags.AttributeCacheComputed;
unsafe
{
EEType* eetype = _genericTypeDefinition.ToEETypePtr();
if (eetype->IsByRefLike)
{
flags |= TypeFlags.IsByRefLike;
}
}
}
return flags;
}
// Canonicalization handling
public override bool IsCanonicalSubtype(CanonicalFormKind policy)
{
foreach (TypeDesc t in Instantiation)
{
if (t.IsCanonicalSubtype(policy))
{
return true;
}
}
return false;
}
protected override TypeDesc ConvertToCanonFormImpl(CanonicalFormKind kind)
{
bool needsChange;
Instantiation canonInstantiation = Context.ConvertInstantiationToCanonForm(Instantiation, kind, out needsChange);
if (needsChange)
{
TypeDesc openType = GetTypeDefinition();
return openType.InstantiateSignature(canonInstantiation, new Instantiation());
}
return this;
}
public override TypeDesc GetTypeDefinition()
{
if (_genericTypeDefinitionAsDefType != null)
return _genericTypeDefinitionAsDefType;
else
return this;
}
public override TypeDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation)
{
TypeDesc[] clone = null;
for (int i = 0; i < _instantiation.Length; i++)
{
TypeDesc uninst = _instantiation[i];
TypeDesc inst = uninst.InstantiateSignature(typeInstantiation, methodInstantiation);
if (inst != uninst)
{
if (clone == null)
{
clone = new TypeDesc[_instantiation.Length];
for (int j = 0; j < clone.Length; j++)
{
clone[j] = _instantiation[j];
}
}
clone[i] = inst;
}
}
return (clone == null) ? this : _genericTypeDefinitionAsDefType.Context.ResolveGenericInstantiation(_genericTypeDefinitionAsDefType, new Instantiation(clone));
}
public override Instantiation Instantiation
{
get
{
return _instantiation;
}
}
public override TypeDesc UnderlyingType
{
get
{
if (!this.IsEnum)
return this;
unsafe
{
CorElementType corElementType = RuntimeTypeHandle.ToEETypePtr()->CorElementType;
return Context.GetTypeFromCorElementType(corElementType);
}
}
}
private void GetTypeNameHelper(out string name, out string nsName, out string assemblyName)
{
TypeReferenceHandle typeRefHandle;
QTypeDefinition qTypeDefinition;
MetadataReader reader;
RuntimeTypeHandle genericDefinitionHandle = GetTypeDefinition().GetRuntimeTypeHandle();
Debug.Assert(!genericDefinitionHandle.IsNull());
string enclosingDummy;
// Try to get the name from metadata
if (TypeLoaderEnvironment.Instance.TryGetMetadataForNamedType(genericDefinitionHandle, out qTypeDefinition))
{
TypeDefinitionHandle typeDefHandle = qTypeDefinition.NativeFormatHandle;
typeDefHandle.GetFullName(qTypeDefinition.NativeFormatReader, out name, out enclosingDummy, out nsName);
assemblyName = typeDefHandle.GetContainingModuleName(qTypeDefinition.NativeFormatReader);
}
// Try to get the name from diagnostic metadata
else if (TypeLoaderEnvironment.TryGetTypeReferenceForNamedType(genericDefinitionHandle, out reader, out typeRefHandle))
{
typeRefHandle.GetFullName(reader, out name, out enclosingDummy, out nsName);
assemblyName = typeRefHandle.GetContainingModuleName(reader);
}
else
{
name = genericDefinitionHandle.LowLevelToStringRawEETypeAddress();
nsName = "";
assemblyName = "?";
}
}
public string DiagnosticNamespace
{
get
{
string name, nsName, assemblyName;
GetTypeNameHelper(out name, out nsName, out assemblyName);
return nsName;
}
}
public string DiagnosticName
{
get
{
string name, nsName, assemblyName;
GetTypeNameHelper(out name, out nsName, out assemblyName);
return name;
}
}
public string DiagnosticModuleName
{
get
{
string name, nsName, assemblyName;
GetTypeNameHelper(out name, out nsName, out assemblyName);
return assemblyName;
}
}
#if DEBUG
private string _cachedToString = null;
public override string ToString()
{
if (_cachedToString != null)
return _cachedToString;
StringBuilder sb = new StringBuilder();
if (!_genericTypeDefinition.IsNull())
sb.Append(_genericTypeDefinition.LowLevelToString());
else if (!RuntimeTypeHandle.IsNull())
sb.Append(RuntimeTypeHandle.LowLevelToString());
if (!Instantiation.IsNull)
{
for (int i = 0; i < Instantiation.Length; i++)
{
sb.Append(i == 0 ? "[" : ", ");
sb.Append(Instantiation[i].ToString());
}
if (Instantiation.Length > 0) sb.Append("]");
}
_cachedToString = sb.ToString();
return _cachedToString;
}
#endif
}
}
| |
//
// Theme.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2007-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Gtk;
using Gdk;
using Cairo;
using Hyena.Gui;
namespace Hyena.Gui.Theming
{
public abstract class Theme
{
private static Cairo.Color black = new Cairo.Color (0, 0, 0);
private Stack<ThemeContext> contexts = new Stack<ThemeContext> ();
private GtkColors colors;
private Cairo.Color selection_fill;
private Cairo.Color selection_stroke;
private Cairo.Color view_fill;
private Cairo.Color view_fill_transparent;
private Cairo.Color text_mid;
public GtkColors Colors {
get { return colors; }
}
public Widget Widget { get; private set; }
public Theme (Widget widget) : this (widget, new GtkColors ())
{
}
public Theme (Widget widget, GtkColors colors)
{
this.Widget = widget;
this.colors = colors;
this.colors.Refreshed += delegate { OnColorsRefreshed (); };
this.colors.Widget = widget;
PushContext ();
}
protected virtual void OnColorsRefreshed ()
{
selection_fill = colors.GetWidgetColor (GtkColorClass.Dark, StateType.Active);
selection_stroke = colors.GetWidgetColor (GtkColorClass.Background, StateType.Selected);
view_fill = colors.GetWidgetColor (GtkColorClass.Base, StateType.Normal);
view_fill_transparent = view_fill;
view_fill_transparent.A = 0;
text_mid = CairoExtensions.AlphaBlend (
colors.GetWidgetColor (GtkColorClass.Base, StateType.Normal),
colors.GetWidgetColor (GtkColorClass.Text, StateType.Normal),
0.5);
}
#region Drawing
public abstract void DrawPie (double fraction);
public abstract void DrawArrow (Cairo.Context cr, Gdk.Rectangle alloc, Hyena.Data.SortType type);
public void DrawFrame (Cairo.Context cr, Gdk.Rectangle alloc, bool baseColor)
{
DrawFrameBackground (cr, alloc, baseColor);
DrawFrameBorder (cr, alloc);
}
public void DrawFrame (Cairo.Context cr, Gdk.Rectangle alloc, Cairo.Color color)
{
DrawFrameBackground (cr, alloc, color);
DrawFrameBorder (cr, alloc);
}
public void DrawFrameBackground (Cairo.Context cr, Gdk.Rectangle alloc, bool baseColor)
{
DrawFrameBackground (cr, alloc, baseColor
? colors.GetWidgetColor (GtkColorClass.Base, StateType.Normal)
: colors.GetWidgetColor (GtkColorClass.Background, StateType.Normal));
}
public void DrawFrameBackground (Cairo.Context cr, Gdk.Rectangle alloc, Cairo.Color color)
{
DrawFrameBackground (cr, alloc, color, null);
}
public void DrawFrameBackground (Cairo.Context cr, Gdk.Rectangle alloc, Cairo.Pattern pattern)
{
DrawFrameBackground (cr, alloc, black , pattern);
}
public abstract void DrawFrameBackground (Cairo.Context cr, Gdk.Rectangle alloc, Cairo.Color color, Cairo.Pattern pattern);
public abstract void DrawFrameBorder (Cairo.Context cr, Gdk.Rectangle alloc);
public abstract void DrawHeaderBackground (Cairo.Context cr, Gdk.Rectangle alloc);
public abstract void DrawColumnHeaderFocus (Cairo.Context cr, Gdk.Rectangle alloc);
public abstract void DrawHeaderSeparator (Cairo.Context cr, Gdk.Rectangle alloc, int x);
public void DrawListBackground (Cairo.Context cr, Gdk.Rectangle alloc, bool baseColor)
{
DrawListBackground (cr, alloc, baseColor
? colors.GetWidgetColor (GtkColorClass.Base, StateType.Normal)
: colors.GetWidgetColor (GtkColorClass.Background, StateType.Normal));
}
public abstract void DrawListBackground (Cairo.Context cr, Gdk.Rectangle alloc, Cairo.Color color);
public void DrawColumnHighlight (Cairo.Context cr, double cellWidth, double cellHeight)
{
Gdk.Rectangle alloc = new Gdk.Rectangle ();
alloc.Width = (int)cellWidth;
alloc.Height = (int)cellHeight;
DrawColumnHighlight (cr, alloc);
}
public void DrawColumnHighlight (Cairo.Context cr, Gdk.Rectangle alloc)
{
DrawColumnHighlight (cr, alloc, colors.GetWidgetColor (GtkColorClass.Background, StateType.Selected));
}
public abstract void DrawColumnHighlight (Cairo.Context cr, Gdk.Rectangle alloc, Cairo.Color color);
public void DrawRowSelection (Cairo.Context cr, int x, int y, int width, int height)
{
DrawRowSelection (cr, x, y, width, height, true);
}
public void DrawRowSelection (Cairo.Context cr, int x, int y, int width, int height, bool filled)
{
DrawRowSelection (cr, x, y, width, height, filled, true,
colors.GetWidgetColor (GtkColorClass.Background, StateType.Selected), CairoCorners.All);
}
public void DrawRowSelection (Cairo.Context cr, int x, int y, int width, int height,
bool filled, bool stroked, Cairo.Color color)
{
DrawRowSelection (cr, x, y, width, height, filled, stroked, color, CairoCorners.All);
}
public void DrawRowCursor (Cairo.Context cr, int x, int y, int width, int height)
{
DrawRowCursor (cr, x, y, width, height, colors.GetWidgetColor (GtkColorClass.Background, StateType.Selected));
}
public void DrawRowCursor (Cairo.Context cr, int x, int y, int width, int height, Cairo.Color color)
{
DrawRowCursor (cr, x, y, width, height, color, CairoCorners.All);
}
public abstract void DrawRowCursor (Cairo.Context cr, int x, int y, int width, int height, Cairo.Color color, CairoCorners corners);
public abstract void DrawRowSelection (Cairo.Context cr, int x, int y, int width, int height,
bool filled, bool stroked, Cairo.Color color, CairoCorners corners);
public abstract void DrawRowRule (Cairo.Context cr, int x, int y, int width, int height);
public Cairo.Color ViewFill {
get { return view_fill; }
}
public Cairo.Color ViewFillTransparent {
get { return view_fill_transparent; }
}
public Cairo.Color SelectionFill {
get { return selection_fill; }
}
public Cairo.Color SelectionStroke {
get { return selection_stroke; }
}
public Cairo.Color TextMidColor {
get { return text_mid; }
protected set { text_mid = value; }
}
public virtual int BorderWidth {
get { return 1; }
}
public virtual int InnerBorderWidth {
get { return 4; }
}
public int TotalBorderWidth {
get { return BorderWidth + InnerBorderWidth; }
}
#endregion
#region Contexts
public virtual void PushContext ()
{
PushContext (new ThemeContext ());
}
public virtual void PushContext (ThemeContext context)
{
lock (this) {
contexts.Push (context);
}
}
public virtual ThemeContext PopContext ()
{
lock (this) {
return contexts.Pop ();
}
}
public virtual ThemeContext Context {
get { lock (this) { return contexts.Peek (); } }
}
#endregion
#region Static Utilities
public static double Clamp (double min, double max, double value)
{
return Math.Max (min, Math.Min (max, value));
}
#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.
/*=============================================================================
**
**
**
** Purpose: Domains represent an application within the runtime. Objects can
** not be shared between domains and each domain can be configured
** independently.
**
**
=============================================================================*/
namespace System
{
using System;
using System.Reflection;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using System.Security.Util;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Reflection.Emit;
using CultureInfo = System.Globalization.CultureInfo;
using System.IO;
using AssemblyHashAlgorithm = System.Configuration.Assemblies.AssemblyHashAlgorithm;
using System.Text;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.ExceptionServices;
[ComVisible(true)]
public class ResolveEventArgs : EventArgs
{
private String _Name;
private Assembly _RequestingAssembly;
public String Name {
get {
return _Name;
}
}
public Assembly RequestingAssembly
{
get
{
return _RequestingAssembly;
}
}
public ResolveEventArgs(String name)
{
_Name = name;
}
public ResolveEventArgs(String name, Assembly requestingAssembly)
{
_Name = name;
_RequestingAssembly = requestingAssembly;
}
}
[ComVisible(true)]
public class AssemblyLoadEventArgs : EventArgs
{
private Assembly _LoadedAssembly;
public Assembly LoadedAssembly {
get {
return _LoadedAssembly;
}
}
public AssemblyLoadEventArgs(Assembly loadedAssembly)
{
_LoadedAssembly = loadedAssembly;
}
}
[Serializable]
[ComVisible(true)]
public delegate Assembly ResolveEventHandler(Object sender, ResolveEventArgs args);
[Serializable]
[ComVisible(true)]
public delegate void AssemblyLoadEventHandler(Object sender, AssemblyLoadEventArgs args);
[Serializable]
[ComVisible(true)]
public delegate void AppDomainInitializer(string[] args);
internal class AppDomainInitializerInfo
{
internal class ItemInfo
{
public string TargetTypeAssembly;
public string TargetTypeName;
public string MethodName;
}
internal ItemInfo[] Info;
internal AppDomainInitializerInfo(AppDomainInitializer init)
{
Info=null;
if (init==null)
return;
List<ItemInfo> itemInfo = new List<ItemInfo>();
List<AppDomainInitializer> nestedDelegates = new List<AppDomainInitializer>();
nestedDelegates.Add(init);
int idx=0;
while (nestedDelegates.Count>idx)
{
AppDomainInitializer curr = nestedDelegates[idx++];
Delegate[] list= curr.GetInvocationList();
for (int i=0;i<list.Length;i++)
{
if (!list[i].Method.IsStatic)
{
if(list[i].Target==null)
continue;
AppDomainInitializer nested = list[i].Target as AppDomainInitializer;
if (nested!=null)
nestedDelegates.Add(nested);
else
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeStatic"),
list[i].Method.ReflectedType.FullName+"::"+list[i].Method.Name);
}
else
{
ItemInfo info=new ItemInfo();
info.TargetTypeAssembly=list[i].Method.ReflectedType.Module.Assembly.FullName;
info.TargetTypeName=list[i].Method.ReflectedType.FullName;
info.MethodName=list[i].Method.Name;
itemInfo.Add(info);
}
}
}
Info = itemInfo.ToArray();
}
internal AppDomainInitializer Unwrap()
{
if (Info==null)
return null;
AppDomainInitializer retVal=null;
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert();
for (int i=0;i<Info.Length;i++)
{
Assembly assembly=Assembly.Load(Info[i].TargetTypeAssembly);
AppDomainInitializer newVal=(AppDomainInitializer)Delegate.CreateDelegate(typeof(AppDomainInitializer),
assembly.GetType(Info[i].TargetTypeName),
Info[i].MethodName);
if(retVal==null)
retVal=newVal;
else
retVal+=newVal;
}
return retVal;
}
}
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(System._AppDomain))]
[ComVisible(true)]
public sealed class AppDomain :
_AppDomain, IEvidenceFactory
{
// Domain security information
// These fields initialized from the other side only. (NOTE: order
// of these fields cannot be changed without changing the layout in
// the EE- AppDomainBaseObject in this case)
private AppDomainManager _domainManager;
private Dictionary<String, Object[]> _LocalStore;
private AppDomainSetup _FusionStore;
private Evidence _SecurityIdentity;
#pragma warning disable 169
private Object[] _Policies; // Called from the VM.
#pragma warning restore 169
[method: System.Security.SecurityCritical]
public event AssemblyLoadEventHandler AssemblyLoad;
private ResolveEventHandler _TypeResolve;
public event ResolveEventHandler TypeResolve
{
add
{
lock (this)
{
_TypeResolve += value;
}
}
remove
{
lock (this)
{
_TypeResolve -= value;
}
}
}
private ResolveEventHandler _ResourceResolve;
public event ResolveEventHandler ResourceResolve
{
add
{
lock (this)
{
_ResourceResolve += value;
}
}
remove
{
lock (this)
{
_ResourceResolve -= value;
}
}
}
private ResolveEventHandler _AssemblyResolve;
public event ResolveEventHandler AssemblyResolve
{
add
{
lock (this)
{
_AssemblyResolve += value;
}
}
remove
{
lock (this)
{
_AssemblyResolve -= value;
}
}
}
#if FEATURE_REFLECTION_ONLY_LOAD
[method: System.Security.SecurityCritical]
public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
#endif // FEATURE_REFLECTION_ONLY
private ApplicationTrust _applicationTrust;
private EventHandler _processExit;
private EventHandler _domainUnload;
private UnhandledExceptionEventHandler _unhandledException;
// The compat flags are set at domain creation time to indicate that the given breaking
// changes (named in the strings) should not be used in this domain. We only use the
// keys, the vhe values are ignored.
private Dictionary<String, object> _compatFlags;
// Delegate that will hold references to FirstChance exception notifications
private EventHandler<FirstChanceExceptionEventArgs> _firstChanceException;
private IntPtr _pDomain; // this is an unmanaged pointer (AppDomain * m_pDomain)` used from the VM.
private bool _HasSetPolicy;
private bool _IsFastFullTrustDomain; // quick check to see if the AppDomain is fully trusted and homogenous
private bool _compatFlagsInitialized;
internal const String TargetFrameworkNameAppCompatSetting = "TargetFrameworkName";
#if FEATURE_APPX
private static APPX_FLAGS s_flags;
//
// Keep in async with vm\appdomainnative.cpp
//
[Flags]
private enum APPX_FLAGS
{
APPX_FLAGS_INITIALIZED = 0x01,
APPX_FLAGS_APPX_MODEL = 0x02,
APPX_FLAGS_APPX_DESIGN_MODE = 0x04,
APPX_FLAGS_APPX_NGEN = 0x08,
APPX_FLAGS_APPX_MASK = APPX_FLAGS_APPX_MODEL |
APPX_FLAGS_APPX_DESIGN_MODE |
APPX_FLAGS_APPX_NGEN,
APPX_FLAGS_API_CHECK = 0x10,
}
private static APPX_FLAGS Flags
{
get
{
if (s_flags == 0)
s_flags = nGetAppXFlags();
Debug.Assert(s_flags != 0);
return s_flags;
}
}
internal static bool ProfileAPICheck
{
get
{
return (Flags & APPX_FLAGS.APPX_FLAGS_API_CHECK) != 0;
}
}
internal static bool IsAppXNGen
{
get
{
return (Flags & APPX_FLAGS.APPX_FLAGS_APPX_NGEN) != 0;
}
}
#endif // FEATURE_APPX
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool DisableFusionUpdatesFromADManager(AppDomainHandle domain);
#if FEATURE_APPX
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I4)]
private static extern APPX_FLAGS nGetAppXFlags();
#endif
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetAppDomainManagerType(AppDomainHandle domain,
StringHandleOnStack retAssembly,
StringHandleOnStack retType);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void SetAppDomainManagerType(AppDomainHandle domain,
string assembly,
string type);
[SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void SetSecurityHomogeneousFlag(AppDomainHandle domain,
[MarshalAs(UnmanagedType.Bool)] bool runtimeSuppliedHomogenousGrantSet);
/// <summary>
/// Get a handle used to make a call into the VM pointing to this domain
/// </summary>
internal AppDomainHandle GetNativeHandle()
{
// This should never happen under normal circumstances. However, there ar ways to create an
// uninitialized object through remoting, etc.
if (_pDomain.IsNull())
{
throw new InvalidOperationException(Environment.GetResourceString("Argument_InvalidHandle"));
}
return new AppDomainHandle(_pDomain);
}
/// <summary>
/// If this AppDomain is configured to have an AppDomain manager then create the instance of it.
/// This method is also called from the VM to create the domain manager in the default domain.
/// </summary>
private void CreateAppDomainManager()
{
Debug.Assert(_domainManager == null, "_domainManager == null");
AppDomainSetup adSetup = FusionStore;
String trustedPlatformAssemblies = (String)(GetData("TRUSTED_PLATFORM_ASSEMBLIES"));
if (trustedPlatformAssemblies != null)
{
String platformResourceRoots = (String)(GetData("PLATFORM_RESOURCE_ROOTS"));
if (platformResourceRoots == null)
{
platformResourceRoots = String.Empty;
}
String appPaths = (String)(GetData("APP_PATHS"));
if (appPaths == null)
{
appPaths = String.Empty;
}
String appNiPaths = (String)(GetData("APP_NI_PATHS"));
if (appNiPaths == null)
{
appNiPaths = String.Empty;
}
String appLocalWinMD = (String)(GetData("APP_LOCAL_WINMETADATA"));
if (appLocalWinMD == null)
{
appLocalWinMD = String.Empty;
}
SetupBindingPaths(trustedPlatformAssemblies, platformResourceRoots, appPaths, appNiPaths, appLocalWinMD);
}
string domainManagerAssembly;
string domainManagerType;
GetAppDomainManagerType(out domainManagerAssembly, out domainManagerType);
if (domainManagerAssembly != null && domainManagerType != null)
{
try
{
new PermissionSet(PermissionState.Unrestricted).Assert();
_domainManager = CreateInstanceAndUnwrap(domainManagerAssembly, domainManagerType) as AppDomainManager;
CodeAccessPermission.RevertAssert();
}
catch (FileNotFoundException e)
{
throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"), e);
}
catch (SecurityException e)
{
throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"), e);
}
catch (TypeLoadException e)
{
throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"), e);
}
if (_domainManager == null)
{
throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"));
}
// If this domain was not created by a managed call to CreateDomain, then the AppDomainSetup
// will not have the correct values for the AppDomainManager set.
FusionStore.AppDomainManagerAssembly = domainManagerAssembly;
FusionStore.AppDomainManagerType = domainManagerType;
bool notifyFusion = _domainManager.GetType() != typeof(System.AppDomainManager) && !DisableFusionUpdatesFromADManager();
AppDomainSetup FusionStoreOld = null;
if (notifyFusion)
FusionStoreOld = new AppDomainSetup(FusionStore, true);
// Initialize the AppDomainMAnager and register the instance with the native host if requested
_domainManager.InitializeNewDomain(FusionStore);
if (notifyFusion)
SetupFusionStore(_FusionStore, FusionStoreOld); // Notify Fusion about the changes the user implementation of InitializeNewDomain may have made to the FusionStore object.
}
InitializeCompatibilityFlags();
}
/// <summary>
/// Initialize the compatibility flags to non-NULL values.
/// This method is also called from the VM when the default domain dosen't have a domain manager.
/// </summary>
private void InitializeCompatibilityFlags()
{
AppDomainSetup adSetup = FusionStore;
// set up shim flags regardless of whether we create a DomainManager in this method.
if (adSetup.GetCompatibilityFlags() != null)
{
_compatFlags = new Dictionary<String, object>(adSetup.GetCompatibilityFlags(), StringComparer.OrdinalIgnoreCase);
}
// for perf, we don't intialize the _compatFlags dictionary when we don't need to. However, we do need to make a
// note that we've run this method, because IsCompatibilityFlagsSet needs to return different values for the
// case where the compat flags have been setup.
Debug.Assert(!_compatFlagsInitialized);
_compatFlagsInitialized = true;
CompatibilitySwitches.InitializeSwitches();
}
/// <summary>
/// Returns the setting of the corresponding compatibility config switch (see CreateAppDomainManager for the impact).
/// </summary>
internal bool DisableFusionUpdatesFromADManager()
{
return DisableFusionUpdatesFromADManager(GetNativeHandle());
}
/// <summary>
/// Returns whether the current AppDomain follows the AppX rules.
/// </summary>
[Pure]
internal static bool IsAppXModel()
{
#if FEATURE_APPX
return (Flags & APPX_FLAGS.APPX_FLAGS_APPX_MODEL) != 0;
#else
return false;
#endif
}
/// <summary>
/// Returns the setting of the AppXDevMode config switch.
/// </summary>
[Pure]
internal static bool IsAppXDesignMode()
{
#if FEATURE_APPX
return (Flags & APPX_FLAGS.APPX_FLAGS_APPX_MASK) == (APPX_FLAGS.APPX_FLAGS_APPX_MODEL | APPX_FLAGS.APPX_FLAGS_APPX_DESIGN_MODE);
#else
return false;
#endif
}
/// <summary>
/// Checks (and throws on failure) if the domain supports Assembly.LoadFrom.
/// </summary>
[Pure]
internal static void CheckLoadFromSupported()
{
#if FEATURE_APPX
if (IsAppXModel())
throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.LoadFrom"));
#endif
}
/// <summary>
/// Checks (and throws on failure) if the domain supports Assembly.LoadFile.
/// </summary>
[Pure]
internal static void CheckLoadFileSupported()
{
#if FEATURE_APPX
if (IsAppXModel())
throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.LoadFile"));
#endif
}
/// <summary>
/// Checks (and throws on failure) if the domain supports Assembly.ReflectionOnlyLoad.
/// </summary>
[Pure]
internal static void CheckReflectionOnlyLoadSupported()
{
#if FEATURE_APPX
if (IsAppXModel())
throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.ReflectionOnlyLoad"));
#endif
}
/// <summary>
/// Checks (and throws on failure) if the domain supports Assembly.Load(byte[] ...).
/// </summary>
[Pure]
internal static void CheckLoadByteArraySupported()
{
#if FEATURE_APPX
if (IsAppXModel())
throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.Load(byte[], ...)"));
#endif
}
/// <summary>
/// Get the name of the assembly and type that act as the AppDomainManager for this domain
/// </summary>
internal void GetAppDomainManagerType(out string assembly, out string type)
{
// We can't just use our parameters because we need to ensure that the strings used for hte QCall
// are on the stack.
string localAssembly = null;
string localType = null;
GetAppDomainManagerType(GetNativeHandle(),
JitHelpers.GetStringHandleOnStack(ref localAssembly),
JitHelpers.GetStringHandleOnStack(ref localType));
assembly = localAssembly;
type = localType;
}
/// <summary>
/// Set the assembly and type which act as the AppDomainManager for this domain
/// </summary>
private void SetAppDomainManagerType(string assembly, string type)
{
Debug.Assert(assembly != null, "assembly != null");
Debug.Assert(type != null, "type != null");
SetAppDomainManagerType(GetNativeHandle(), assembly, type);
}
/// <summary>
/// Called for every AppDomain (including the default domain) to initialize the security of the AppDomain)
/// </summary>
private void InitializeDomainSecurity(Evidence providedSecurityInfo,
Evidence creatorsSecurityInfo,
bool generateDefaultEvidence,
IntPtr parentSecurityDescriptor,
bool publishAppDomain)
{
AppDomainSetup adSetup = FusionStore;
bool runtimeSuppliedHomogenousGrant = false;
ApplicationTrust appTrust = adSetup.ApplicationTrust;
if (appTrust != null) {
SetupDomainSecurityForHomogeneousDomain(appTrust, runtimeSuppliedHomogenousGrant);
}
else if (_IsFastFullTrustDomain) {
SetSecurityHomogeneousFlag(GetNativeHandle(), runtimeSuppliedHomogenousGrant);
}
// Get the evidence supplied for the domain. If no evidence was supplied, it means that we want
// to use the default evidence creation strategy for this domain
Evidence newAppDomainEvidence = (providedSecurityInfo != null ? providedSecurityInfo : creatorsSecurityInfo);
if (newAppDomainEvidence == null && generateDefaultEvidence) {
newAppDomainEvidence = new Evidence();
}
// Set the evidence on the managed side
_SecurityIdentity = newAppDomainEvidence;
// Set the evidence of the AppDomain in the VM.
// Also, now that the initialization is complete, signal that to the security system.
// Finish the AppDomain initialization and resolve the policy for the AppDomain evidence.
SetupDomainSecurity(newAppDomainEvidence,
parentSecurityDescriptor,
publishAppDomain);
}
private void SetupDomainSecurityForHomogeneousDomain(ApplicationTrust appTrust,
bool runtimeSuppliedHomogenousGrantSet)
{
// If the CLR has supplied the homogenous grant set (that is, this domain would have been
// heterogenous in v2.0), then we need to strip the ApplicationTrust from the AppDomainSetup of
// the current domain. This prevents code which does:
// AppDomain.CreateDomain(..., AppDomain.CurrentDomain.SetupInformation);
//
// From looking like it is trying to create a homogenous domain intentionally, and therefore
// having its evidence check bypassed.
if (runtimeSuppliedHomogenousGrantSet)
{
BCLDebug.Assert(_FusionStore.ApplicationTrust != null, "Expected to find runtime supplied ApplicationTrust");
}
_applicationTrust = appTrust;
// Set the homogeneous bit in the VM's ApplicationSecurityDescriptor.
SetSecurityHomogeneousFlag(GetNativeHandle(),
runtimeSuppliedHomogenousGrantSet);
}
public AppDomainManager DomainManager {
get {
return _domainManager;
}
}
#if FEATURE_REFLECTION_ONLY_LOAD
private Assembly ResolveAssemblyForIntrospection(Object sender, ResolveEventArgs args)
{
Contract.Requires(args != null);
return Assembly.ReflectionOnlyLoad(ApplyPolicy(args.Name));
}
// Helper class for method code:EnableResolveAssembliesForIntrospection
private class NamespaceResolverForIntrospection
{
private IEnumerable<string> _packageGraphFilePaths;
public NamespaceResolverForIntrospection(IEnumerable<string> packageGraphFilePaths)
{
_packageGraphFilePaths = packageGraphFilePaths;
}
public void ResolveNamespace(
object sender,
System.Runtime.InteropServices.WindowsRuntime.NamespaceResolveEventArgs args)
{
Contract.Requires(args != null);
IEnumerable<string> fileNames = System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata.ResolveNamespace(
args.NamespaceName,
null, // windowsSdkFilePath ... Use OS installed .winmd files
_packageGraphFilePaths);
foreach (string fileName in fileNames)
{
args.ResolvedAssemblies.Add(Assembly.ReflectionOnlyLoadFrom(fileName));
}
}
}
// Called only by native function code:ValidateWorker
private void EnableResolveAssembliesForIntrospection(string verifiedFileDirectory)
{
CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(ResolveAssemblyForIntrospection);
string[] packageGraphFilePaths = null;
if (verifiedFileDirectory != null)
packageGraphFilePaths = new string[] { verifiedFileDirectory };
NamespaceResolverForIntrospection namespaceResolver = new NamespaceResolverForIntrospection(packageGraphFilePaths);
System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata.ReflectionOnlyNamespaceResolve +=
new EventHandler<System.Runtime.InteropServices.WindowsRuntime.NamespaceResolveEventArgs>(namespaceResolver.ResolveNamespace);
}
#endif // FEATURE_REFLECTION_ONLY_LOAD
public ObjectHandle CreateInstance(String assemblyName,
String typeName)
{
// jit does not check for that, so we should do it ...
if (this == null)
throw new NullReferenceException();
if (assemblyName == null)
throw new ArgumentNullException(nameof(assemblyName));
Contract.EndContractBlock();
return Activator.CreateInstance(assemblyName,
typeName);
}
internal ObjectHandle InternalCreateInstanceWithNoSecurity (string assemblyName, string typeName) {
PermissionSet.s_fullTrust.Assert();
return CreateInstance(assemblyName, typeName);
}
public ObjectHandle CreateInstanceFrom(String assemblyFile,
String typeName)
{
// jit does not check for that, so we should do it ...
if (this == null)
throw new NullReferenceException();
Contract.EndContractBlock();
return Activator.CreateInstanceFrom(assemblyFile,
typeName);
}
internal ObjectHandle InternalCreateInstanceFromWithNoSecurity (string assemblyName, string typeName) {
PermissionSet.s_fullTrust.Assert();
return CreateInstanceFrom(assemblyName, typeName);
}
[Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstance which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public ObjectHandle CreateInstance(String assemblyName,
String typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
Object[] activationAttributes,
Evidence securityAttributes)
{
// jit does not check for that, so we should do it ...
if (this == null)
throw new NullReferenceException();
if (assemblyName == null)
throw new ArgumentNullException(nameof(assemblyName));
Contract.EndContractBlock();
#pragma warning disable 618
return Activator.CreateInstance(assemblyName,
typeName,
ignoreCase,
bindingAttr,
binder,
args,
culture,
activationAttributes,
securityAttributes);
#pragma warning restore 618
}
internal ObjectHandle InternalCreateInstanceWithNoSecurity (string assemblyName,
string typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
Object[] activationAttributes,
Evidence securityAttributes)
{
PermissionSet.s_fullTrust.Assert();
#pragma warning disable 618
return CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
#pragma warning restore 618
}
[Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstanceFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public ObjectHandle CreateInstanceFrom(String assemblyFile,
String typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
Object[] activationAttributes,
Evidence securityAttributes)
{
// jit does not check for that, so we should do it ...
if (this == null)
throw new NullReferenceException();
Contract.EndContractBlock();
return Activator.CreateInstanceFrom(assemblyFile,
typeName,
ignoreCase,
bindingAttr,
binder,
args,
culture,
activationAttributes,
securityAttributes);
}
internal ObjectHandle InternalCreateInstanceFromWithNoSecurity (string assemblyName,
string typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
Object[] activationAttributes,
Evidence securityAttributes)
{
PermissionSet.s_fullTrust.Assert();
#pragma warning disable 618
return CreateInstanceFrom(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
#pragma warning restore 618
}
public static AppDomain CurrentDomain
{
get {
Contract.Ensures(Contract.Result<AppDomain>() != null);
return Thread.GetDomain();
}
}
public String BaseDirectory
{
get {
return FusionStore.ApplicationBase;
}
}
public override String ToString()
{
StringBuilder sb = StringBuilderCache.Acquire();
String fn = nGetFriendlyName();
if (fn != null) {
sb.Append(Environment.GetResourceString("Loader_Name") + fn);
sb.Append(Environment.NewLine);
}
if(_Policies == null || _Policies.Length == 0)
sb.Append(Environment.GetResourceString("Loader_NoContextPolicies")
+ Environment.NewLine);
else {
sb.Append(Environment.GetResourceString("Loader_ContextPolicies")
+ Environment.NewLine);
for(int i = 0;i < _Policies.Length; i++) {
sb.Append(_Policies[i]);
sb.Append(Environment.NewLine);
}
}
return StringBuilderCache.GetStringAndRelease(sb);
}
// this is true when we've removed the handles etc so really can't do anything
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern bool IsUnloadingForcedFinalize();
// this is true when we've just started going through the finalizers and are forcing objects to finalize
// so must be aware that certain infrastructure may have gone away
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern bool IsFinalizingForUnload();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void PublishAnonymouslyHostedDynamicMethodsAssembly(RuntimeAssembly assemblyHandle);
public void SetData (string name, object data) {
SetDataHelper(name, data, null);
}
private void SetDataHelper (string name, object data, IPermission permission)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
// SetData should only be used to set values that don't already exist.
object[] currentVal;
lock (((ICollection)LocalStore).SyncRoot) {
LocalStore.TryGetValue(name, out currentVal);
}
if (currentVal != null && currentVal[0] != null)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData_OnlyOnce"));
}
lock (((ICollection)LocalStore).SyncRoot) {
LocalStore[name] = new object[] {data, permission};
}
}
[Pure]
public Object GetData(string name)
{
if(name == null)
throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
int key = AppDomainSetup.Locate(name);
if(key == -1)
{
if(name.Equals(AppDomainSetup.LoaderOptimizationKey))
return FusionStore.LoaderOptimization;
else
{
object[] data;
lock (((ICollection)LocalStore).SyncRoot) {
LocalStore.TryGetValue(name, out data);
}
if (data == null)
return null;
if (data[1] != null) {
IPermission permission = (IPermission) data[1];
permission.Demand();
}
return data[0];
}
}
else {
// Be sure to call these properties, not Value, so
// that the appropriate permission demand will be done
switch(key) {
case (int) AppDomainSetup.LoaderInformation.ApplicationBaseValue:
return FusionStore.ApplicationBase;
case (int) AppDomainSetup.LoaderInformation.ApplicationNameValue:
return FusionStore.ApplicationName;
default:
Debug.Assert(false, "Need to handle new LoaderInformation value in AppDomain.GetData()");
return null;
}
}
}
[Obsolete("AppDomain.GetCurrentThreadId has been deprecated because it does not provide a stable Id when managed threads are running on fibers (aka lightweight threads). To get a stable identifier for a managed thread, use the ManagedThreadId property on Thread. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[DllImport(Microsoft.Win32.Win32Native.KERNEL32)]
public static extern int GetCurrentThreadId();
private AppDomain() {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_Constructor));
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void nCreateContext();
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void nSetupBindingPaths(String trustedPlatformAssemblies, String platformResourceRoots, String appPath, String appNiPaths, String appLocalWinMD);
internal void SetupBindingPaths(String trustedPlatformAssemblies, String platformResourceRoots, String appPath, String appNiPaths, String appLocalWinMD)
{
nSetupBindingPaths(trustedPlatformAssemblies, platformResourceRoots, appPath, appNiPaths, appLocalWinMD);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern String nGetFriendlyName();
// support reliability for certain event handlers, if the target
// methods also participate in this discipline. If caller passes
// an existing MulticastDelegate, then we could use a MDA to indicate
// that reliability is not guaranteed. But if it is a single cast
// scenario, we can make it work.
public event EventHandler ProcessExit
{
add
{
if (value != null)
{
RuntimeHelpers.PrepareContractedDelegate(value);
lock(this)
_processExit += value;
}
}
remove
{
lock(this)
_processExit -= value;
}
}
public event EventHandler DomainUnload
{
add
{
if (value != null)
{
RuntimeHelpers.PrepareContractedDelegate(value);
lock(this)
_domainUnload += value;
}
}
remove
{
lock(this)
_domainUnload -= value;
}
}
public event UnhandledExceptionEventHandler UnhandledException
{
add
{
if (value != null)
{
RuntimeHelpers.PrepareContractedDelegate(value);
lock(this)
_unhandledException += value;
}
}
remove
{
lock(this)
_unhandledException -= value;
}
}
// This is the event managed code can wireup against to be notified
// about first chance exceptions.
//
// To register/unregister the callback, the code must be SecurityCritical.
public event EventHandler<FirstChanceExceptionEventArgs> FirstChanceException
{
add
{
if (value != null)
{
RuntimeHelpers.PrepareContractedDelegate(value);
lock(this)
_firstChanceException += value;
}
}
remove
{
lock(this)
_firstChanceException -= value;
}
}
private void OnAssemblyLoadEvent(RuntimeAssembly LoadedAssembly)
{
AssemblyLoadEventHandler eventHandler = AssemblyLoad;
if (eventHandler != null) {
AssemblyLoadEventArgs ea = new AssemblyLoadEventArgs(LoadedAssembly);
eventHandler(this, ea);
}
}
// This method is called by the VM.
private RuntimeAssembly OnResourceResolveEvent(RuntimeAssembly assembly, String resourceName)
{
ResolveEventHandler eventHandler = _ResourceResolve;
if ( eventHandler == null)
return null;
Delegate[] ds = eventHandler.GetInvocationList();
int len = ds.Length;
for (int i = 0; i < len; i++) {
Assembly asm = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(resourceName, assembly));
RuntimeAssembly ret = GetRuntimeAssembly(asm);
if (ret != null)
return ret;
}
return null;
}
// This method is called by the VM
private RuntimeAssembly OnTypeResolveEvent(RuntimeAssembly assembly, String typeName)
{
ResolveEventHandler eventHandler = _TypeResolve;
if (eventHandler == null)
return null;
Delegate[] ds = eventHandler.GetInvocationList();
int len = ds.Length;
for (int i = 0; i < len; i++) {
Assembly asm = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(typeName, assembly));
RuntimeAssembly ret = GetRuntimeAssembly(asm);
if (ret != null)
return ret;
}
return null;
}
// This method is called by the VM.
private RuntimeAssembly OnAssemblyResolveEvent(RuntimeAssembly assembly, String assemblyFullName)
{
ResolveEventHandler eventHandler = _AssemblyResolve;
if (eventHandler == null)
{
return null;
}
Delegate[] ds = eventHandler.GetInvocationList();
int len = ds.Length;
for (int i = 0; i < len; i++) {
Assembly asm = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(assemblyFullName, assembly));
RuntimeAssembly ret = GetRuntimeAssembly(asm);
if (ret != null)
return ret;
}
return null;
}
#if FEATURE_COMINTEROP
// Called by VM - code:CLRPrivTypeCacheWinRT::RaiseDesignerNamespaceResolveEvent
private string[] OnDesignerNamespaceResolveEvent(string namespaceName)
{
return System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata.OnDesignerNamespaceResolveEvent(this, namespaceName);
}
#endif // FEATURE_COMINTEROP
internal AppDomainSetup FusionStore
{
get {
Debug.Assert(_FusionStore != null,
"Fusion store has not been correctly setup in this domain");
return _FusionStore;
}
}
internal static RuntimeAssembly GetRuntimeAssembly(Assembly asm)
{
if (asm == null)
return null;
RuntimeAssembly rtAssembly = asm as RuntimeAssembly;
if (rtAssembly != null)
return rtAssembly;
AssemblyBuilder ab = asm as AssemblyBuilder;
if (ab != null)
return ab.InternalAssembly;
return null;
}
private Dictionary<String, Object[]> LocalStore
{
get {
if (_LocalStore != null)
return _LocalStore;
else {
_LocalStore = new Dictionary<String, Object[]>();
return _LocalStore;
}
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void nSetNativeDllSearchDirectories(string paths);
private void SetupFusionStore(AppDomainSetup info, AppDomainSetup oldInfo)
{
Contract.Requires(info != null);
if (info.ApplicationBase == null)
{
info.SetupDefaults(RuntimeEnvironment.GetModuleFileName(), imageLocationAlreadyNormalized : true);
}
nCreateContext();
if (info.LoaderOptimization != LoaderOptimization.NotSpecified || (oldInfo != null && info.LoaderOptimization != oldInfo.LoaderOptimization))
UpdateLoaderOptimization(info.LoaderOptimization);
// This must be the last action taken
_FusionStore = info;
}
private static void RunInitializer(AppDomainSetup setup)
{
if (setup.AppDomainInitializer!=null)
{
string[] args=null;
if (setup.AppDomainInitializerArguments!=null)
args=(string[])setup.AppDomainInitializerArguments.Clone();
setup.AppDomainInitializer(args);
}
}
// Used to switch into other AppDomain and call SetupRemoteDomain.
// We cannot simply call through the proxy, because if there
// are any remoting sinks registered, they can add non-mscorlib
// objects to the message (causing an assembly load exception when
// we try to deserialize it on the other side)
private static object PrepareDataForSetup(String friendlyName,
AppDomainSetup setup,
Evidence providedSecurityInfo,
Evidence creatorsSecurityInfo,
IntPtr parentSecurityDescriptor,
string sandboxName,
string[] propertyNames,
string[] propertyValues)
{
byte[] serializedEvidence = null;
bool generateDefaultEvidence = false;
AppDomainInitializerInfo initializerInfo = null;
if (setup!=null && setup.AppDomainInitializer!=null)
initializerInfo=new AppDomainInitializerInfo(setup.AppDomainInitializer);
// will travel x-Ad, drop non-agile data
AppDomainSetup newSetup = new AppDomainSetup(setup, false);
// Remove the special AppDomainCompatSwitch entries from the set of name value pairs
// And add them to the AppDomainSetup
//
// This is only supported on CoreCLR through ICLRRuntimeHost2.CreateAppDomainWithManager
// Desktop code should use System.AppDomain.CreateDomain() or
// System.AppDomainManager.CreateDomain() and add the flags to the AppDomainSetup
List<String> compatList = new List<String>();
if(propertyNames!=null && propertyValues != null)
{
for (int i=0; i<propertyNames.Length; i++)
{
if(String.Compare(propertyNames[i], "AppDomainCompatSwitch", StringComparison.OrdinalIgnoreCase) == 0)
{
compatList.Add(propertyValues[i]);
propertyNames[i] = null;
propertyValues[i] = null;
}
}
if (compatList.Count > 0)
{
newSetup.SetCompatibilitySwitches(compatList);
}
}
return new Object[]
{
friendlyName,
newSetup,
parentSecurityDescriptor,
generateDefaultEvidence,
serializedEvidence,
initializerInfo,
sandboxName,
propertyNames,
propertyValues
};
} // PrepareDataForSetup
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static Object Setup(Object arg)
{
Contract.Requires(arg != null && arg is Object[]);
Contract.Requires(((Object[])arg).Length >= 8);
Object[] args=(Object[])arg;
String friendlyName = (String)args[0];
AppDomainSetup setup = (AppDomainSetup)args[1];
IntPtr parentSecurityDescriptor = (IntPtr)args[2];
bool generateDefaultEvidence = (bool)args[3];
byte[] serializedEvidence = (byte[])args[4];
AppDomainInitializerInfo initializerInfo = (AppDomainInitializerInfo)args[5];
string sandboxName = (string)args[6];
string[] propertyNames = (string[])args[7]; // can contain null elements
string[] propertyValues = (string[])args[8]; // can contain null elements
// extract evidence
Evidence providedSecurityInfo = null;
Evidence creatorsSecurityInfo = null;
AppDomain ad = AppDomain.CurrentDomain;
AppDomainSetup newSetup=new AppDomainSetup(setup,false);
if(propertyNames!=null && propertyValues != null)
{
for (int i = 0; i < propertyNames.Length; i++)
{
// We want to set native dll probing directories before any P/Invokes have a
// chance to fire. The Path class, for one, has P/Invokes.
if (propertyNames[i] == "NATIVE_DLL_SEARCH_DIRECTORIES")
{
if (propertyValues[i] == null)
throw new ArgumentNullException("NATIVE_DLL_SEARCH_DIRECTORIES");
string paths = propertyValues[i];
if (paths.Length == 0)
break;
nSetNativeDllSearchDirectories(paths);
}
}
for (int i=0; i<propertyNames.Length; i++)
{
if(propertyNames[i]=="APPBASE") // make sure in sync with Fusion
{
if(propertyValues[i]==null)
throw new ArgumentNullException("APPBASE");
if (PathInternal.IsPartiallyQualified(propertyValues[i]))
throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
newSetup.ApplicationBase = NormalizePath(propertyValues[i], fullCheck: true);
}
else if(propertyNames[i]=="LOADER_OPTIMIZATION")
{
if(propertyValues[i]==null)
throw new ArgumentNullException("LOADER_OPTIMIZATION");
switch(propertyValues[i])
{
case "SingleDomain": newSetup.LoaderOptimization=LoaderOptimization.SingleDomain;break;
case "MultiDomain": newSetup.LoaderOptimization=LoaderOptimization.MultiDomain;break;
case "MultiDomainHost": newSetup.LoaderOptimization=LoaderOptimization.MultiDomainHost;break;
case "NotSpecified": newSetup.LoaderOptimization=LoaderOptimization.NotSpecified;break;
default: throw new ArgumentException(Environment.GetResourceString("Argument_UnrecognizedLoaderOptimization"), "LOADER_OPTIMIZATION");
}
}
else if(propertyNames[i]=="TRUSTED_PLATFORM_ASSEMBLIES" ||
propertyNames[i]=="PLATFORM_RESOURCE_ROOTS" ||
propertyNames[i]=="APP_PATHS" ||
propertyNames[i]=="APP_NI_PATHS")
{
string values = propertyValues[i];
if(values == null)
throw new ArgumentNullException(propertyNames[i]);
ad.SetDataHelper(propertyNames[i], NormalizeAppPaths(values), null);
}
else if(propertyNames[i]!= null)
{
ad.SetDataHelper(propertyNames[i],propertyValues[i],null); // just propagate
}
}
}
ad.SetupFusionStore(newSetup, null); // makes FusionStore a ref to newSetup
// technically, we don't need this, newSetup refers to the same object as FusionStore
// but it's confusing since it isn't immediately obvious whether we have a ref or a copy
AppDomainSetup adSetup = ad.FusionStore;
adSetup.InternalSetApplicationTrust(sandboxName);
// set up the friendly name
ad.nSetupFriendlyName(friendlyName);
#if FEATURE_COMINTEROP
if (setup != null && setup.SandboxInterop)
{
ad.nSetDisableInterfaceCache();
}
#endif // FEATURE_COMINTEROP
// set up the AppDomainManager for this domain and initialize security.
if (adSetup.AppDomainManagerAssembly != null && adSetup.AppDomainManagerType != null)
{
ad.SetAppDomainManagerType(adSetup.AppDomainManagerAssembly, adSetup.AppDomainManagerType);
}
ad.CreateAppDomainManager(); // could modify FusionStore's object
ad.InitializeDomainSecurity(providedSecurityInfo,
creatorsSecurityInfo,
generateDefaultEvidence,
parentSecurityDescriptor,
true);
// can load user code now
if(initializerInfo!=null)
adSetup.AppDomainInitializer=initializerInfo.Unwrap();
RunInitializer(adSetup);
return null;
}
private static string NormalizeAppPaths(string values)
{
int estimatedLength = values.Length + 1; // +1 for extra separator temporarily added at end
StringBuilder sb = StringBuilderCache.Acquire(estimatedLength);
for (int pos = 0; pos < values.Length; pos++)
{
string path;
int nextPos = values.IndexOf(Path.PathSeparator, pos);
if (nextPos == -1)
{
path = values.Substring(pos);
pos = values.Length - 1;
}
else
{
path = values.Substring(pos, nextPos - pos);
pos = nextPos;
}
// Skip empty directories
if (path.Length == 0)
continue;
if (PathInternal.IsPartiallyQualified(path))
throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"));
string appPath = NormalizePath(path, fullCheck: true);
sb.Append(appPath);
sb.Append(Path.PathSeparator);
}
// Strip the last separator
if (sb.Length > 0)
{
sb.Remove(sb.Length - 1, 1);
}
return StringBuilderCache.GetStringAndRelease(sb);
}
internal static string NormalizePath(string path, bool fullCheck)
{
return Path.GetFullPath(path);
}
// This routine is called from unmanaged code to
// set the default fusion context.
private void SetupDomain(bool allowRedirects, String path, String configFile, String[] propertyNames, String[] propertyValues)
{
// It is possible that we could have multiple threads initializing
// the default domain. We will just take the winner of these two.
// (eg. one thread doing a com call and another doing attach for IJW)
lock (this)
{
if(_FusionStore == null)
{
AppDomainSetup setup = new AppDomainSetup();
// always use internet permission set
setup.InternalSetApplicationTrust("Internet");
SetupFusionStore(setup, null);
}
}
}
private void SetupDomainSecurity(Evidence appDomainEvidence,
IntPtr creatorsSecurityDescriptor,
bool publishAppDomain)
{
Evidence stackEvidence = appDomainEvidence;
SetupDomainSecurity(GetNativeHandle(),
JitHelpers.GetObjectHandleOnStack(ref stackEvidence),
creatorsSecurityDescriptor,
publishAppDomain);
}
[SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void SetupDomainSecurity(AppDomainHandle appDomain,
ObjectHandleOnStack appDomainEvidence,
IntPtr creatorsSecurityDescriptor,
[MarshalAs(UnmanagedType.Bool)] bool publishAppDomain);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void nSetupFriendlyName(string friendlyName);
#if FEATURE_COMINTEROP
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void nSetDisableInterfaceCache();
#endif // FEATURE_COMINTEROP
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void UpdateLoaderOptimization(LoaderOptimization optimization);
public AppDomainSetup SetupInformation
{
get {
return new AppDomainSetup(FusionStore,true);
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern String IsStringInterned(String str);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern String GetOrInternString(String str);
[SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetGrantSet(AppDomainHandle domain, ObjectHandleOnStack retGrantSet);
public bool IsFullyTrusted
{
get
{
PermissionSet grantSet = null;
GetGrantSet(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref grantSet));
return grantSet == null || grantSet.IsUnrestricted();
}
}
public Object CreateInstanceAndUnwrap(String assemblyName,
String typeName)
{
ObjectHandle oh = CreateInstance(assemblyName, typeName);
if (oh == null)
return null;
return oh.Unwrap();
} // CreateInstanceAndUnwrap
public Int32 Id
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get {
return GetId();
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal extern Int32 GetId();
}
/// <summary>
/// Handle used to marshal an AppDomain to the VM (eg QCall). When marshaled via a QCall, the target
/// method in the VM will recieve a QCall::AppDomainHandle parameter.
/// </summary>
internal struct AppDomainHandle
{
private IntPtr m_appDomainHandle;
// Note: generall an AppDomainHandle should not be directly constructed, instead the
// code:System.AppDomain.GetNativeHandle method should be called to get the handle for a specific
// AppDomain.
internal AppDomainHandle(IntPtr domainHandle)
{
m_appDomainHandle = domainHandle;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Confingo.Services.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// 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 Internal.Cryptography;
using ErrorCode = Interop.NCrypt.ErrorCode;
using KeyBlobMagicNumber = Interop.BCrypt.KeyBlobMagicNumber;
using BCRYPT_RSAKEY_BLOB = Interop.BCrypt.BCRYPT_RSAKEY_BLOB;
namespace System.Security.Cryptography
{
#if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS
internal static partial class RSAImplementation
{
#endif
public sealed partial class RSACng : RSA
{
/// <summary>
/// <para>
/// ImportParameters will replace the existing key that RSACng is working with by creating a
/// new CngKey for the parameters structure. If the parameters structure contains only an
/// exponent and modulus, then only a public key will be imported. If the parameters also
/// contain P and Q values, then a full key pair will be imported.
/// </para>
/// </summary>
/// <exception cref="ArgumentException">
/// if <paramref name="parameters" /> contains neither an exponent nor a modulus.
/// </exception>
/// <exception cref="CryptographicException">
/// if <paramref name="parameters" /> is not a valid RSA key or if <paramref name="parameters"
/// /> is a full key pair and the default KSP is used.
/// </exception>
public override void ImportParameters(RSAParameters parameters)
{
unsafe
{
if (parameters.Exponent == null || parameters.Modulus == null)
throw new CryptographicException(SR.Cryptography_InvalidRsaParameters);
bool includePrivate;
if (parameters.D == null)
{
includePrivate = false;
if (parameters.P != null || parameters.DP != null || parameters.Q != null || parameters.DQ != null || parameters.InverseQ != null)
throw new CryptographicException(SR.Cryptography_InvalidRsaParameters);
}
else
{
includePrivate = true;
if (parameters.P == null || parameters.DP == null || parameters.Q == null || parameters.DQ == null || parameters.InverseQ == null)
throw new CryptographicException(SR.Cryptography_InvalidRsaParameters);
}
//
// We need to build a key blob structured as follows:
//
// BCRYPT_RSAKEY_BLOB header
// byte[cbPublicExp] publicExponent - Exponent
// byte[cbModulus] modulus - Modulus
// -- Only if "includePrivate" is true --
// byte[cbPrime1] prime1 - P
// byte[cbPrime2] prime2 - Q
// ------------------
//
int blobSize = sizeof(BCRYPT_RSAKEY_BLOB) +
parameters.Exponent.Length +
parameters.Modulus.Length;
if (includePrivate)
{
blobSize += parameters.P.Length +
parameters.Q.Length;
}
byte[] rsaBlob = new byte[blobSize];
fixed (byte* pRsaBlob = &rsaBlob[0])
{
// Build the header
BCRYPT_RSAKEY_BLOB* pBcryptBlob = (BCRYPT_RSAKEY_BLOB*)pRsaBlob;
pBcryptBlob->Magic = includePrivate ? KeyBlobMagicNumber.BCRYPT_RSAPRIVATE_MAGIC : KeyBlobMagicNumber.BCRYPT_RSAPUBLIC_MAGIC;
pBcryptBlob->BitLength = parameters.Modulus.Length * 8;
pBcryptBlob->cbPublicExp = parameters.Exponent.Length;
pBcryptBlob->cbModulus = parameters.Modulus.Length;
if (includePrivate)
{
pBcryptBlob->cbPrime1 = parameters.P.Length;
pBcryptBlob->cbPrime2 = parameters.Q.Length;
}
int offset = sizeof(BCRYPT_RSAKEY_BLOB);
Interop.BCrypt.Emit(rsaBlob, ref offset, parameters.Exponent);
Interop.BCrypt.Emit(rsaBlob, ref offset, parameters.Modulus);
if (includePrivate)
{
Interop.BCrypt.Emit(rsaBlob, ref offset, parameters.P);
Interop.BCrypt.Emit(rsaBlob, ref offset, parameters.Q);
}
// We better have computed the right allocation size above!
Debug.Assert(offset == blobSize, "offset == blobSize");
}
ImportKeyBlob(rsaBlob, includePrivate);
}
}
/// <summary>
/// Exports the key used by the RSA object into an RSAParameters object.
/// </summary>
public override RSAParameters ExportParameters(bool includePrivateParameters)
{
byte[] rsaBlob = ExportKeyBlob(includePrivateParameters);
RSAParameters rsaParams = new RSAParameters();
ExportParameters(ref rsaParams, rsaBlob, includePrivateParameters);
return rsaParams;
}
private static void ExportParameters(ref RSAParameters rsaParams, byte[] rsaBlob, bool includePrivateParameters)
{
//
// We now have a buffer laid out as follows:
// BCRYPT_RSAKEY_BLOB header
// byte[cbPublicExp] publicExponent - Exponent
// byte[cbModulus] modulus - Modulus
// -- Private only --
// byte[cbPrime1] prime1 - P
// byte[cbPrime2] prime2 - Q
// byte[cbPrime1] exponent1 - DP
// byte[cbPrime2] exponent2 - DQ
// byte[cbPrime1] coefficient - InverseQ
// byte[cbModulus] privateExponent - D
//
KeyBlobMagicNumber magic = (KeyBlobMagicNumber)BitConverter.ToInt32(rsaBlob, 0);
// Check the magic value in the key blob header. If the blob does not have the required magic,
// then throw a CryptographicException.
CheckMagicValueOfKey(magic, includePrivateParameters);
unsafe
{
// Fail-fast if a rogue provider gave us a blob that isn't even the size of the blob header.
if (rsaBlob.Length < sizeof(BCRYPT_RSAKEY_BLOB))
throw ErrorCode.E_FAIL.ToCryptographicException();
fixed (byte* pRsaBlob = &rsaBlob[0])
{
BCRYPT_RSAKEY_BLOB* pBcryptBlob = (BCRYPT_RSAKEY_BLOB*)pRsaBlob;
int offset = sizeof(BCRYPT_RSAKEY_BLOB);
// Read out the exponent
rsaParams.Exponent = Interop.BCrypt.Consume(rsaBlob, ref offset, pBcryptBlob->cbPublicExp);
rsaParams.Modulus = Interop.BCrypt.Consume(rsaBlob, ref offset, pBcryptBlob->cbModulus);
if (includePrivateParameters)
{
rsaParams.P = Interop.BCrypt.Consume(rsaBlob, ref offset, pBcryptBlob->cbPrime1);
rsaParams.Q = Interop.BCrypt.Consume(rsaBlob, ref offset, pBcryptBlob->cbPrime2);
rsaParams.DP = Interop.BCrypt.Consume(rsaBlob, ref offset, pBcryptBlob->cbPrime1);
rsaParams.DQ = Interop.BCrypt.Consume(rsaBlob, ref offset, pBcryptBlob->cbPrime2);
rsaParams.InverseQ = Interop.BCrypt.Consume(rsaBlob, ref offset, pBcryptBlob->cbPrime1);
rsaParams.D = Interop.BCrypt.Consume(rsaBlob, ref offset, pBcryptBlob->cbModulus);
}
}
}
}
/// <summary>
/// This function checks the magic value in the key blob header
/// </summary>
/// <param name="includePrivateParameters">Private blob if true else public key blob</param>
private static void CheckMagicValueOfKey(KeyBlobMagicNumber magic, bool includePrivateParameters)
{
if (includePrivateParameters)
{
if (magic != KeyBlobMagicNumber.BCRYPT_RSAPRIVATE_MAGIC && magic != KeyBlobMagicNumber.BCRYPT_RSAFULLPRIVATE_MAGIC)
{
throw new CryptographicException(SR.Cryptography_NotValidPrivateKey);
}
}
else
{
if (magic != KeyBlobMagicNumber.BCRYPT_RSAPUBLIC_MAGIC)
{
// Private key magic is permissible too since the public key can be derived from the private key blob.
if (magic != KeyBlobMagicNumber.BCRYPT_RSAPRIVATE_MAGIC && magic != KeyBlobMagicNumber.BCRYPT_RSAFULLPRIVATE_MAGIC)
{
throw new CryptographicException(SR.Cryptography_NotValidPublicOrPrivateKey);
}
}
}
}
}
#if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS
}
#endif
}
| |
using System;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Threading;
using ConfigINI;
namespace GNARLI
{
public class UptimeMonitorUi
{
private Config<ConfigSection, ConfigSetting> _config;
private UptimeMonitor _monitor;
public int SleepTime = 500;
public bool Updating = false;
private string loggingStatus = "ENABLED";
public UptimeMonitorUi(Config<ConfigSection, ConfigSetting> config, UptimeMonitor monitor)
{
_config = config;
_monitor = monitor;
}
public void Update()
{
Updating = true;
do
{
while (!Console.KeyAvailable)
{
MainScreen();
Thread.Sleep(SleepTime);
}
if (Console.ReadKey().Key == ConsoleKey.Enter) Updating = false;
} while (Updating);
Options();
}
public void MainScreen()
{
Console.Clear();
Title();
Status();
PingStats();
PingStatus();
Fails();
Settings();
//var log = new UpTimeLog();
//log.PopulateTest();
//DrawGraph(log);
//Console.ReadLine();
Pause();
}
public void Options()
{
Console.Clear();
Title();
Status();
Settings();
Console.WriteLine(new string('-', 80));
Console.WriteLine("# Main Menu");
Console.WriteLine(new string('-', 80));
Console.WriteLine("V Resume Viewing");
Console.WriteLine("S Start/Stop Monitoring");
Console.WriteLine("L Start/Stop Logging");
//Console.WriteLine("C Clear Log");
//Console.WriteLine("O Set Log Location");
Console.WriteLine("A Add New Address");
Console.WriteLine("R Remove Address");
Console.WriteLine("T Set Timeout");
Console.WriteLine("F Set Frequency");
Console.WriteLine("E Set Sleep Period");
Console.WriteLine("Q Quit");
var key = Console.ReadKey();
switch (key.Key)
{
case (ConsoleKey.V):
{
Update();
break;
}
case (ConsoleKey.S):
{
if (_monitor.IsRunning()) _monitor.StopMonitor();
else new Thread(_monitor.Monitor).Start();
Options();
break;
}
case (ConsoleKey.L):
{
ToggleLogging();
Options();
break;
}
case (ConsoleKey.A):
{
AddNewAddress();
break;
}
case (ConsoleKey.R):
{
RemoveAddress();
break;
}
case (ConsoleKey.T):
{
Console.WriteLine();
Console.WriteLine(new string('-', 80));
Console.WriteLine("Enter New Timeout: ");
var dat = Console.ReadLine();
int val;
if (int.TryParse(dat, out val))
{
_config.SetIntSetting(ConfigSection.Monitor, ConfigSetting.TimeOut, val);
Options();
}
else
{
Console.WriteLine("Must be an Integer");
Console.WriteLine("Press Enter to Continue");
Console.ReadLine();
Options();
}
break;
}
case (ConsoleKey.F):
{
Console.WriteLine();
Console.WriteLine(new string('-', 80));
Console.WriteLine("Enter New Frequency: ");
var dat = Console.ReadLine();
float val;
if (float.TryParse(dat, out val))
{
_config.SetFloatSetting(ConfigSection.Monitor, ConfigSetting.Frequency, val);
Options();
}
else
{
Console.WriteLine("Must be a Float");
Console.WriteLine("Press Enter to Continue");
Console.ReadLine();
Options();
}
break;
}
case (ConsoleKey.E):
{
Console.WriteLine();
Console.WriteLine(new string('-', 80));
Console.WriteLine("Enter New Sleep Period: ");
var dat = Console.ReadLine();
int val;
if (int.TryParse(dat, out val))
{
_config.SetIntSetting(ConfigSection.Monitor, ConfigSetting.SleepPeriod, val);
Options();
}
else
{
Console.WriteLine("Must be an Integer");
Console.WriteLine("Press Enter to Continue");
Console.ReadLine();
Options();
}
break;
}
}
}
private void AddNewAddress()
{
Console.WriteLine();
Console.WriteLine(new string('-', 80));
Console.WriteLine("Leave Blank To Cancel");
Console.WriteLine("Enter Address Name: ");
var name = Console.ReadLine();
if (name.Length == 0)
{
Options();
return;
}
Console.WriteLine(name);
Console.WriteLine("Enter IP Address: ");
var address = Console.ReadLine();
IPAddress addr;
var success = IPAddress.TryParse(address, out addr);
if (success)
{
var ipaddressData = new IpAddressData(name, addr);
_monitor.AddAddresses.Add(ipaddressData);
Update();
return;
}
else
{
Console.WriteLine("\"" + address + "\" is not a valid IP Address");
Console.WriteLine("Press Enter To Continue");
Console.ReadLine();
Options();
return;
}
}
private void RemoveAddress()
{
Console.WriteLine(new string('-', 80));
PingStatus();
Console.WriteLine(new string('-', 80));
Console.WriteLine("Select an Address to Remove (enter 0 to return");
var line = Console.ReadLine();
int val;
if (int.TryParse(line, out val))
{
if (val > _monitor.IpAddresses.Count)
{
Console.WriteLine(val + " is not a valid option.");
Console.WriteLine("Press Enter to Continue");
Console.ReadLine();
Options();
return;
}
else
{
_monitor.RemoveAddresses.Add(_monitor.IpAddresses[val - 1]);
Update();
return;
}
}
else
{
Console.WriteLine(line + " is not a valid option.");
Console.WriteLine("Press Enter to Continue");
Console.ReadLine();
Options();
return;
}
}
private void Title()
{
Console.WriteLine(new string('=', 80));
var header = "Network Uptime Monitor v" + Assembly.GetExecutingAssembly().GetName().Version;
Console.WriteLine(String.Format("{0," + ((80 / 2) + (header.Length / 2)) + "}", header));
Console.WriteLine(new string('=', 80));
}
private void Status()
{
var header = "";
Console.Write(String.Format("{0,25}", "Monitor: "));
if (_monitor.IsRunning())
{
Console.ForegroundColor = ConsoleColor.Green;
header = "RUNNING";
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
header = "STOPPED";
}
Console.Write(header);
Console.ResetColor();
DisplayLoggingStatus();
}
private void DisplayLoggingStatus()
{
Console.Write(String.Format("{0,25}", "Logging: "));
Console.ForegroundColor = ConsoleColor.Red;
if (loggingStatus == "ENABLED")
{
Console.ForegroundColor = ConsoleColor.Green;
}
Console.WriteLine(loggingStatus);
Console.ResetColor();
}
private void Settings()
{
Console.Write(string.Format("{0, 23}", "Timeout: " + _monitor.TimeOut + "ms"));
Console.Write(String.Format("{0,23}", "Frequency: " + _monitor.Interval + "s"));
Console.Write(String.Format("{0,23}", "Sleep: " + _monitor.SleepInterval + "ms"));
Console.WriteLine();
}
private void PingStats()
{
Console.Write(string.Format("{0, 22}", "Success: "));
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(_monitor.SuccessCount);
Console.ResetColor();
Console.Write(string.Format("{0, 22}", "Partial: "));
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write(_monitor.PartialCount);
Console.ResetColor();
Console.Write(string.Format("{0, 22}", "Fails: "));
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(_monitor.FailCount);
Console.WriteLine();
Console.ResetColor();
}
private void PingStatus()
{
Console.WriteLine(new string('-', 80));
Console.Write(string.Format("{0, 18}", "Name"));
Console.Write(string.Format("{0, 18}", "Address"));
Console.Write(string.Format("{0, 9}", "Ping"));
Console.Write(string.Format("{0, 9}", "Avg"));
Console.WriteLine(string.Format("{0, 18}", "Status"));
Console.WriteLine(new string('-', 80));
var count = 1;
foreach (var addr in _monitor.IpAddresses)
{
PingStatus(addr, count);
count++;
}
//Console.WriteLine(new string('-', 80));
}
private void PingStatus(IpAddressData addr, int val)
{
var name = addr.Name;
var ip = addr.Ip.ToString();
var time = addr.Time + "ms";
var avg = ((float) addr.TotalSuccessTime/(float) addr.SuccessCount).ToString("0") + "ms";
var status = addr.Status.ToString();
Console.Write(val + ".");
Console.Write(string.Format("{0, 18}", name));
Console.Write(string.Format("{0, 18}", ip));
Console.Write(string.Format("{0, 9}", time));
Console.Write(string.Format("{0, 9}", avg));
if (addr.Status != IPStatus.Success) Console.ForegroundColor = ConsoleColor.Red;
else Console.ForegroundColor = ConsoleColor.Green;
Console.Write(string.Format("{0, 18}", status));
Console.ResetColor();
Console.Write("\n");
}
private void Fails()
{
Console.WriteLine(new string('-', 80));
var header = "Fails";
Console.WriteLine(String.Format("{0," + ((80 / 2) + (header.Length / 2)) + "}", header));
Console.WriteLine(new string('-', 80));
Console.Write(string.Format("{0, 20}", "Start"));
Console.Write(string.Format("{0, 20}", "End"));
Console.WriteLine(string.Format("{0, 20}", "Duration"));
Console.WriteLine(new string('-', 80));
if (_monitor.ActiveFail != null)
{
Fails(_monitor.ActiveFail, true);
}
foreach (var fail in _monitor.PreviousFails.OrderByDescending(x => x.ReturnTime))
{
Fails(fail);
}
Console.WriteLine(new string('-', 80));
}
private void Fails(FailPeriod period, bool active = false)
{
var startTime = period.FailTime;
var returnTime = DateTime.UtcNow;
if (!active) returnTime = period.ReturnTime;
Console.Write(string.Format("{0, 20}", startTime.ToString("dd/MM/yy HH:mm")));
if (!active) Console.Write(string.Format("{0, 20}", returnTime.ToString("dd/MM/yy HH:mm")));
else Console.Write(string.Format("{0, 20}", "In Progress"));
Console.WriteLine(string.Format("{0, 20}", (returnTime - startTime).TotalSeconds.ToString("0")) + "s");
}
private void Pause()
{
Console.WriteLine(new string('-', 80));
var header = "Press Enter for Options";
Console.WriteLine(String.Format("{0," + ((80 / 2) + (header.Length / 2)) + "}", header));
}
private void ToggleLogging()
{
_config.SetBoolSetting(ConfigSection.Logging, ConfigSetting.LogPingReply, !_config.GetBoolSetting(ConfigSection.Logging, ConfigSetting.LogPingReply));
_config.SetBoolSetting(ConfigSection.Logging, ConfigSetting.LogActiveFail, !_config.GetBoolSetting(ConfigSection.Logging, ConfigSetting.LogActiveFail));
if(_config.GetBoolSetting(ConfigSection.Logging, ConfigSetting.LogPingReply))
{
loggingStatus = "ENABLED";
}
else
{
loggingStatus = "DISABLED";
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.HSSF.UserModel
{
using System;
using System.Collections;
using NPOI.HSSF.Model;
using NPOI.HSSF.Record;
using NPOI.HSSF.Record.Aggregates;
using NPOI.HSSF.UserModel;
using NUnit.Framework;
/**
* Designed to Check wither the records written actually make sense.
*/
public class SanityChecker
{
public class CheckRecord
{
Type record;
char occurance; // 1 = one time, M = 1..many times, * = 0..many, 0 = optional
private bool together;
public CheckRecord(Type record, char occurance)
: this(record, occurance, true)
{
}
/**
* @param record The record type to Check
* @param occurance The occurance 1 = occurs once, M = occurs many times
* @param together
*/
public CheckRecord(Type record, char occurance, bool together)
{
this.record = record;
this.occurance = occurance;
this.together = together;
}
public Type GetRecord()
{
return record;
}
public char GetOccurance()
{
return occurance;
}
public bool IsRequired()
{
return occurance == '1' || occurance == 'M';
}
public bool IsOptional()
{
return occurance == '0' || occurance == '*';
}
public bool Istogether()
{
return together;
}
public bool IsMany()
{
return occurance == '*' || occurance == 'M';
}
public int Match(IList records, int recordIdx)
{
int firstRecord = FindFirstRecord(records, GetRecord(), recordIdx);
if (IsRequired())
{
return MatchRequired(firstRecord, records, recordIdx);
}
else
{
return MatchOptional(firstRecord, records, recordIdx);
}
}
private int MatchOptional(int firstRecord, IList records, int recordIdx)
{
if (firstRecord == -1)
{
return recordIdx;
}
return MatchOneOrMany(records, firstRecord);
}
private int MatchRequired(int firstRecord, IList records, int recordIdx)
{
if (firstRecord == -1)
{
Assert.Fail("Manditory record missing or out of order: " + record);
}
return MatchOneOrMany(records, firstRecord);
}
private int MatchOneOrMany(IList records, int recordIdx)
{
if (IsZeroOrOne())
{
// Check no other records
if (FindFirstRecord(records, GetRecord(), recordIdx + 1) != -1)
Assert.Fail("More than one record Matched for " + GetRecord().Name);
}
else if (IsZeroToMany())
{
if (together)
{
int nextIdx = FindFirstRecord(records, record, recordIdx + 1);
while (nextIdx != -1)
{
if (nextIdx - 1 != recordIdx)
Assert.Fail("Records are not together " + record.Name);
recordIdx = nextIdx;
nextIdx = FindFirstRecord(records, record, recordIdx + 1);
}
}
}
return recordIdx + 1;
}
private bool IsZeroToMany()
{
return occurance == '*' || occurance == 'M';
}
private bool IsZeroOrOne()
{
return occurance == '0' || occurance == '1';
}
}
CheckRecord[] workbookRecords = new CheckRecord[] {
new CheckRecord(typeof(BOFRecord), '1'),
new CheckRecord(typeof(InterfaceHdrRecord), '1'),
new CheckRecord(typeof(MMSRecord), '1'),
new CheckRecord(typeof(InterfaceEndRecord), '1'),
new CheckRecord(typeof(WriteAccessRecord), '1'),
new CheckRecord(typeof(CodepageRecord), '1'),
new CheckRecord(typeof(DSFRecord), '1'),
new CheckRecord(typeof(TabIdRecord), '1'),
new CheckRecord(typeof(FnGroupCountRecord), '1'),
new CheckRecord(typeof(WindowProtectRecord), '1'),
new CheckRecord(typeof(ProtectRecord), '1'),
new CheckRecord(typeof(PasswordRev4Record), '1'),
new CheckRecord(typeof(WindowOneRecord), '1'),
new CheckRecord(typeof(BackupRecord), '1'),
new CheckRecord(typeof(HideObjRecord), '1'),
new CheckRecord(typeof(DateWindow1904Record), '1'),
new CheckRecord(typeof(PrecisionRecord), '1'),
new CheckRecord(typeof(RefreshAllRecord), '1'),
new CheckRecord(typeof(BookBoolRecord), '1'),
new CheckRecord(typeof(FontRecord), 'M'),
new CheckRecord(typeof(FormatRecord), 'M'),
new CheckRecord(typeof(ExtendedFormatRecord), 'M'),
new CheckRecord(typeof(StyleRecord), 'M'),
new CheckRecord(typeof(UseSelFSRecord), '1'),
new CheckRecord(typeof(BoundSheetRecord), 'M'),
new CheckRecord(typeof(CountryRecord), '1'),
new CheckRecord(typeof(SupBookRecord), '0'),
new CheckRecord(typeof(ExternSheetRecord), '0'),
new CheckRecord(typeof(NameRecord), '*'),
new CheckRecord(typeof(SSTRecord), '1'),
new CheckRecord(typeof(ExtSSTRecord), '1'),
new CheckRecord(typeof(EOFRecord), '1'),
};
CheckRecord[] sheetRecords = new CheckRecord[] {
new CheckRecord(typeof(BOFRecord), '1'),
new CheckRecord(typeof(CalcModeRecord), '1'),
new CheckRecord(typeof(RefModeRecord), '1'),
new CheckRecord(typeof(IterationRecord), '1'),
new CheckRecord(typeof(DeltaRecord), '1'),
new CheckRecord(typeof(SaveRecalcRecord), '1'),
new CheckRecord(typeof(PrintHeadersRecord), '1'),
new CheckRecord(typeof(PrintGridlinesRecord), '1'),
new CheckRecord(typeof(GridsetRecord), '1'),
new CheckRecord(typeof(GutsRecord), '1'),
new CheckRecord(typeof(DefaultRowHeightRecord), '1'),
new CheckRecord(typeof(WSBoolRecord), '1'),
new CheckRecord(typeof(PageSettingsBlock), '1'),
new CheckRecord(typeof(DefaultColWidthRecord), '1'),
new CheckRecord(typeof(DimensionsRecord), '1'),
new CheckRecord(typeof(WindowTwoRecord), '1'),
new CheckRecord(typeof(SelectionRecord), '1'),
new CheckRecord(typeof(EOFRecord), '1')
};
private void CheckWorkbookRecords(InternalWorkbook workbook)
{
IList records = workbook.Records;
Assert.IsTrue(records[0] is BOFRecord);
Assert.IsTrue(records[records.Count - 1] is EOFRecord);
CheckRecordOrder(records, workbookRecords);
// CheckRecordstogether(records, workbookRecords);
}
private void CheckSheetRecords(InternalSheet sheet)
{
IList records = sheet.Records;
Assert.IsTrue(records[0] is BOFRecord);
Assert.IsTrue(records[records.Count - 1] is EOFRecord);
CheckRecordOrder(records, sheetRecords);
// CheckRecordstogether(records, sheetRecords);
}
public void CheckHSSFWorkbook(HSSFWorkbook wb)
{
CheckWorkbookRecords(wb.Workbook);
for (int i = 0; i < wb.NumberOfSheets; i++)
CheckSheetRecords(((HSSFSheet)wb.GetSheetAt(i)).Sheet);
}
/*
private void CheckRecordstogether(List records, CheckRecord[] Check)
{
for ( int CheckIdx = 0; CheckIdx < Check.Length; CheckIdx++ )
{
int recordIdx = FindFirstRecord(records, Check[CheckIdx].GetRecord());
bool notFoundAndRecordRequired = (recordIdx == -1 && Check[CheckIdx].isRequired());
if (notFoundAndRecordRequired)
{
Assert.Fail("Expected to Find record of class " + Check.GetClass() + " but did not");
}
else if (recordIdx >= 0)
{
if (Check[CheckIdx].isMany())
{
// Skip records that are together
while (recordIdx < records.Count && Check[CheckIdx].GetRecord().isInstance(records.Get(recordIdx)))
recordIdx++;
}
// Make sure record does not occur in remaining records (after the next)
recordIdx++;
for (int recordIdx2 = recordIdx; recordIdx2 < records.Count; recordIdx2++)
{
if (Check[CheckIdx].GetRecord().isInstance(records.Get(recordIdx2)))
Assert.Fail("Record occurs scattered throughout record chain:\n" + records.Get(recordIdx2));
}
}
}
} */
/* package */
static int FindFirstRecord(IList records, Type record, int startIndex)
{
for (int i = startIndex; i < records.Count; i++)
{
if (record.Name.Equals(records[i].GetType().Name))
return i;
}
return -1;
}
public void CheckRecordOrder(IList records, CheckRecord[] check)
{
int recordIdx = 0;
for (int checkIdx = 0; checkIdx < check.Length; checkIdx++)
{
recordIdx = check[checkIdx].Match(records, recordIdx);
}
}
/*
void CheckRecordOrder(List records, CheckRecord[] Check)
{
int CheckIndex = 0;
for (int recordIndex = 0; recordIndex < records.Count; recordIndex++)
{
Record record = (Record) records.Get(recordIndex);
if (Check[CheckIndex].GetRecord().isInstance(record))
{
if (Check[CheckIndex].GetOccurance() == 'M')
{
// skip over duplicate records if multiples are allowed
while (recordIndex+1 < records.Count && Check[CheckIndex].GetRecord().isInstance(records.Get(recordIndex+1)))
recordIndex++;
// lastGoodMatch = recordIndex;
}
else if (Check[CheckIndex].GetOccurance() == '1')
{
// Check next record to make sure there's not more than one
if (recordIndex != records.Count - 1)
{
if (Check[CheckIndex].GetRecord().isInstance(records.Get(recordIndex+1)))
{
Assert.Fail("More than one occurance of record found:\n" + records.Get(recordIndex).toString());
}
}
// lastGoodMatch = recordIndex;
}
// else if (Check[CheckIndex].GetOccurance() == '0')
// {
//
// }
CheckIndex++;
}
if (CheckIndex >= Check.Length)
return;
}
Assert.Fail("Could not Find required record: " + Check[CheckIndex]);
} */
}
}
| |
// 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.Logic
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// IntegrationAccountsOperations operations.
/// </summary>
public partial interface IIntegrationAccountsOperations
{
/// <summary>
/// Gets a list of integration accounts by subscription.
/// </summary>
/// <param name='top'>
/// The number of items to be included in the result.
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<AzureOperationResponse<IPage<IntegrationAccount>>> ListBySubscriptionWithHttpMessagesAsync(int? top = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a list of integration accounts by resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='top'>
/// The number of items to be included in the result.
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<AzureOperationResponse<IPage<IntegrationAccount>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, int? top = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets an integration account.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<AzureOperationResponse<IntegrationAccount>> GetWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates an integration account.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='integrationAccount'>
/// The integration account.
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<AzureOperationResponse<IntegrationAccount>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, IntegrationAccount integrationAccount, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates an integration account.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='integrationAccount'>
/// The integration account.
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<AzureOperationResponse<IntegrationAccount>> UpdateWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, IntegrationAccount integrationAccount, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes an integration account.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the integration account callback URL.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='notAfter'>
/// The expiry time.
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<AzureOperationResponse<CallbackUrl>> ListCallbackUrlWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, DateTime? notAfter = default(DateTime?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a list of integration accounts by subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<AzureOperationResponse<IPage<IntegrationAccount>>> ListBySubscriptionNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a list of integration accounts by resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<AzureOperationResponse<IPage<IntegrationAccount>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Copyright 2008-2009 Louis DeJardin - http://whereslou.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Spark.Compiler;
using Spark.FileSystem;
using Spark.Tests.Stubs;
namespace Spark.Tests
{
[TestFixture]
public class ImportAndIncludeTester
{
private ISparkView CreateView(IViewFolder viewFolder, string template)
{
var settings = new SparkSettings().SetPageBaseType(typeof(StubSparkView));
var engine = new SparkViewEngine(settings)
{
ViewFolder = viewFolder
};
return engine.CreateInstance(new SparkViewDescriptor().AddTemplate(template));
}
[Test]
public void ImportExplicitFile()
{
var view = CreateView(new InMemoryViewFolder
{
{Path.Combine("importing", "index.spark"), "<p><use import='extra.spark'/>hello ${name}</p>"},
{Path.Combine("importing", "extra.spark"), "this is imported <global name='\"world\"'/>"}
}, Path.Combine("importing", "index.spark"));
var contents = view.RenderView();
Assert.AreEqual("<p>hello world</p>", contents);
Assert.IsFalse(contents.Contains("import"));
}
[Test]
public void ImportExplicitFileFromShared()
{
var view = CreateView(new InMemoryViewFolder
{
{Path.Combine("importing", "index.spark"), "<p><use import='extra.spark'/>hello ${name}</p>"},
{Path.Combine("shared", "extra.spark"), "this is imported <global name='\"world\"'/>"}
}, Path.Combine("importing", "index.spark"));
var contents = view.RenderView();
Assert.AreEqual("<p>hello world</p>", contents);
Assert.IsFalse(contents.Contains("import"));
}
[Test]
public void ImportExplicitWithoutExtension()
{
var view = CreateView(new InMemoryViewFolder
{
{Path.Combine("importing", "index.spark"), "<p>${foo()} ${name}</p><use import='extra'/><use import='another'/>"},
{Path.Combine("importing", "another.spark"), "<macro name='foo'>hello</macro>"},
{Path.Combine("shared", "extra.spark"), "this is imported <global name='\"world\"'/>"}
}, Path.Combine("importing", "index.spark"));
var contents = view.RenderView();
Assert.AreEqual("<p>hello world</p>", contents);
Assert.IsFalse(contents.Contains("import"));
}
[Test]
public void ImportImplicit()
{
var view = CreateView(new InMemoryViewFolder
{
{Path.Combine("importing", "index.spark"), "<p>${foo()} ${name}</p>"},
{Path.Combine("importing", "_global.spark"), "<macro name='foo'>hello</macro>"},
{Path.Combine("shared", "_global.spark"), "this is imported <global name='\"world\"'/>"}
}, Path.Combine("importing", "index.spark"));
var contents = view.RenderView();
Assert.AreEqual("<p>hello world</p>", contents);
Assert.IsFalse(contents.Contains("import"));
}
[Test]
public void IncludeFile()
{
var view = CreateView(new InMemoryViewFolder
{
{Path.Combine("including", "index.spark"), "<p><include href='stuff.spark'/></p>"},
{Path.Combine("including", "stuff.spark"), "hello world"}
}, Path.Combine("including", "index.spark"));
var contents = view.RenderView();
Assert.AreEqual("<p>hello world</p>", contents);
}
[Test]
public void MissingFileThrowsException()
{
Assert.That(() =>
{
var view = CreateView(new InMemoryViewFolder
{
{
Path.Combine("including", "index.spark"),
"<p><include href='stuff.spark'/></p>"
}
}, Path.Combine("including", "index.spark"));
view.RenderView();
},
Throws.TypeOf<CompilerException>());
}
[Test]
public void MissingFileWithEmptyFallbackIsBlank()
{
var view = CreateView(new InMemoryViewFolder
{
{Path.Combine("including", "index.spark"), "<p><include href='stuff.spark'><fallback/></include></p>"}
}, Path.Combine("including", "index.spark"));
var contents = view.RenderView();
Assert.AreEqual("<p></p>", contents);
}
[Test]
public void MissingFileWithFallbackUsesContents()
{
var view = CreateView(new InMemoryViewFolder
{
{Path.Combine("including", "index.spark"), "<p><include href='stuff.spark'><fallback>hello world</fallback></include></p>"}
}, Path.Combine("including", "index.spark"));
var contents = view.RenderView();
Assert.AreEqual("<p>hello world</p>", contents);
}
[Test]
public void ValidIncludeFallbackDisappears()
{
var view = CreateView(new InMemoryViewFolder
{
{Path.Combine("including", "index.spark"), "<p><include href='stuff.spark'><fallback>hello world</fallback></include></p>"},
{Path.Combine("including", "stuff.spark"), "another file"}
}, Path.Combine("including", "index.spark"));
var contents = view.RenderView();
Assert.AreEqual("<p>another file</p>", contents);
}
[Test]
public void FallbackContainsAnotherInclude()
{
var view = CreateView(new InMemoryViewFolder
{
{Path.Combine("including", "index.spark"), "<p><include href='stuff.spark'><fallback><include href='other.spark'/></fallback></include></p>"},
{Path.Combine("including", "other.spark"), "other file"}
}, Path.Combine("including", "index.spark"));
var contents = view.RenderView();
Assert.AreEqual("<p>other file</p>", contents);
}
[Test]
public void IncludeRelativePath()
{
var view = CreateView(new InMemoryViewFolder
{
{Path.Combine("including", "index.spark"), "<p><include href='../lib/other.spark'/></p>"},
{Path.Combine("lib", "other.spark"), "other file"}
}, Path.Combine("including", "index.spark"));
var contents = view.RenderView();
Assert.AreEqual("<p>other file</p>", contents);
}
[Test]
public void IncludeInsideAnInclude()
{
var view = CreateView(new InMemoryViewFolder
{
{Path.Combine("including", "index.spark"), "<p><include href='../lib/other.spark'/></p>"},
{Path.Combine("lib", "other.spark"), "other <include href='third.spark'/> file"},
{Path.Combine("lib", "third.spark"), "third file"}
}, Path.Combine("including", "index.spark"));
var contents = view.RenderView();
Assert.AreEqual("<p>other third file file</p>", contents);
}
[Test]
public void UsingXmlns()
{
var view = CreateView(new InMemoryViewFolder
{
{Path.Combine("including", "index.spark"), "<p xmlns:x='http://www.w3.org/2001/XInclude'><include/><x:include href='../lib/other.spark'/></p>"},
{Path.Combine("lib", "other.spark"), "other file"}
}, Path.Combine("including", "index.spark"));
var contents = view.RenderView();
Assert.AreEqual("<p xmlns:x='http://www.w3.org/2001/XInclude\'><include></include>other file</p>", contents);
}
[Test]
public void IncludingAsText()
{
var view = CreateView(new InMemoryViewFolder
{
{Path.Combine("including", "index.spark"), "<p><include href='item.spark' parse='text'/></p>"},
{Path.Combine("including", "item.spark"), "<li>at&t</li>"}
}, Path.Combine("including", "index.spark"));
var contents = view.RenderView();
Assert.AreEqual("<p><li>at&t</li></p>", contents);
}
[Test]
public void IncludingAsHtmlWithDollar()
{
var view = CreateView(new InMemoryViewFolder
{
{Path.Combine("including", "index.spark"), "<p><include href='jquery.templ.htm' parse='html'/></p>"},
{Path.Combine("including", "jquery.templ.htm"), "<h4>${Title}</h4>"}
}, Path.Combine("including", "index.spark"));
var contents = view.RenderView();
Assert.AreEqual("<p><h4>${Title}</h4></p>", contents);
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal class PropertyGenerator : AbstractCSharpCodeGenerator
{
public static bool CanBeGenerated(IPropertySymbol property)
{
return property.IsIndexer || property.Parameters.Length == 0;
}
private static MemberDeclarationSyntax LastPropertyOrField(
SyntaxList<MemberDeclarationSyntax> members)
{
var lastProperty = members.LastOrDefault(m => m is PropertyDeclarationSyntax);
return lastProperty ?? LastField(members);
}
internal static CompilationUnitSyntax AddPropertyTo(
CompilationUnitSyntax destination,
IPropertySymbol property,
CodeGenerationOptions options,
IList<bool> availableIndices)
{
var declaration = GenerateMemberDeclaration(property, CodeGenerationDestination.CompilationUnit, options);
var members = Insert(destination.Members, declaration, options,
availableIndices, after: LastPropertyOrField, before: FirstMember);
return destination.WithMembers(members);
}
internal static TypeDeclarationSyntax AddPropertyTo(
TypeDeclarationSyntax destination,
IPropertySymbol property,
CodeGenerationOptions options,
IList<bool> availableIndices)
{
var declaration = GenerateMemberDeclaration(property, GetDestination(destination), options);
// Create a clone of the original type with the new method inserted.
var members = Insert(destination.Members, declaration, options,
availableIndices, after: LastPropertyOrField, before: FirstMember);
// Find the best place to put the field. It should go after the last field if we already
// have fields, or at the beginning of the file if we don't.
return AddMembersTo(destination, members);
}
private static MemberDeclarationSyntax GenerateMemberDeclaration(
IPropertySymbol property,
CodeGenerationDestination destination,
CodeGenerationOptions options)
{
var reusableSyntax = GetReuseableSyntaxNodeForSymbol<MemberDeclarationSyntax>(property, options);
if (reusableSyntax != null)
{
return reusableSyntax;
}
var declaration = property.IsIndexer
? GenerateIndexerDeclaration(property, destination, options)
: GeneratePropertyDeclaration(property, destination, options);
return ConditionallyAddDocumentationCommentTo(declaration, property, options);
}
private static MemberDeclarationSyntax GenerateIndexerDeclaration(
IPropertySymbol property,
CodeGenerationDestination destination,
CodeGenerationOptions options)
{
var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(property.ExplicitInterfaceImplementations);
return AddCleanupAnnotationsTo(
AddAnnotationsTo(property, SyntaxFactory.IndexerDeclaration(
attributeLists: AttributeGenerator.GenerateAttributeLists(property.GetAttributes(), options),
modifiers: GenerateModifiers(property, destination, options),
type: property.Type.GenerateTypeSyntax(),
explicitInterfaceSpecifier: explicitInterfaceSpecifier,
parameterList: ParameterGenerator.GenerateBracketedParameterList(property.Parameters, explicitInterfaceSpecifier != null, options),
accessorList: GenerateAccessorList(property, destination, options))));
}
public static MemberDeclarationSyntax GeneratePropertyDeclaration(
IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options)
{
var initializerNode = CodeGenerationPropertyInfo.GetInitializer(property) as ExpressionSyntax;
var initializer = initializerNode != null
? SyntaxFactory.EqualsValueClause(initializerNode)
: default(EqualsValueClauseSyntax);
var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(property.ExplicitInterfaceImplementations);
return AddCleanupAnnotationsTo(
AddAnnotationsTo(property, SyntaxFactory.PropertyDeclaration(
attributeLists: AttributeGenerator.GenerateAttributeLists(property.GetAttributes(), options),
modifiers: GenerateModifiers(property, destination, options),
type: property.Type.GenerateTypeSyntax(),
explicitInterfaceSpecifier: explicitInterfaceSpecifier,
identifier: property.Name.ToIdentifierToken(),
accessorList: GenerateAccessorList(property, destination, options),
initializer: initializer)));
}
private static AccessorListSyntax GenerateAccessorList(
IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options)
{
var accessors = new List<AccessorDeclarationSyntax>
{
GenerateAccessorDeclaration(property, property.GetMethod, SyntaxKind.GetAccessorDeclaration, destination, options),
GenerateAccessorDeclaration(property, property.SetMethod, SyntaxKind.SetAccessorDeclaration, destination, options),
};
return SyntaxFactory.AccessorList(accessors.WhereNotNull().ToSyntaxList());
}
private static AccessorDeclarationSyntax GenerateAccessorDeclaration(
IPropertySymbol property,
IMethodSymbol accessor,
SyntaxKind kind,
CodeGenerationDestination destination,
CodeGenerationOptions options)
{
var hasBody = options.GenerateMethodBodies && HasAccessorBodies(property, destination, accessor);
return accessor == null
? null
: GenerateAccessorDeclaration(property, accessor, kind, hasBody, options);
}
private static AccessorDeclarationSyntax GenerateAccessorDeclaration(
IPropertySymbol property,
IMethodSymbol accessor,
SyntaxKind kind,
bool hasBody,
CodeGenerationOptions options)
{
return AddAnnotationsTo(accessor, SyntaxFactory.AccessorDeclaration(kind)
.WithModifiers(GenerateAccessorModifiers(property, accessor, options))
.WithBody(hasBody ? GenerateBlock(accessor) : null)
.WithSemicolonToken(hasBody ? default(SyntaxToken) : SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
}
private static BlockSyntax GenerateBlock(IMethodSymbol accessor)
{
return SyntaxFactory.Block(
StatementGenerator.GenerateStatements(CodeGenerationMethodInfo.GetStatements(accessor)));
}
private static bool HasAccessorBodies(
IPropertySymbol property,
CodeGenerationDestination destination,
IMethodSymbol accessor)
{
return destination != CodeGenerationDestination.InterfaceType &&
!property.IsAbstract &&
accessor != null &&
!accessor.IsAbstract;
}
private static SyntaxTokenList GenerateAccessorModifiers(
IPropertySymbol property,
IMethodSymbol accessor,
CodeGenerationOptions options)
{
if (accessor.DeclaredAccessibility == Accessibility.NotApplicable ||
accessor.DeclaredAccessibility == property.DeclaredAccessibility)
{
return new SyntaxTokenList();
}
var modifiers = new List<SyntaxToken>();
AddAccessibilityModifiers(accessor.DeclaredAccessibility, modifiers, options, property.DeclaredAccessibility);
return modifiers.ToSyntaxTokenList();
}
private static SyntaxTokenList GenerateModifiers(
IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options)
{
var tokens = new List<SyntaxToken>();
// Most modifiers not allowed if we're an explicit impl.
if (!property.ExplicitInterfaceImplementations.Any())
{
if (destination != CodeGenerationDestination.CompilationUnit &&
destination != CodeGenerationDestination.InterfaceType)
{
AddAccessibilityModifiers(property.DeclaredAccessibility, tokens, options, Accessibility.Private);
if (property.IsStatic)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword));
}
if (property.IsSealed)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword));
}
if (property.IsOverride)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword));
}
if (property.IsVirtual)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.VirtualKeyword));
}
if (property.IsAbstract)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword));
}
}
}
if (CodeGenerationPropertyInfo.GetIsUnsafe(property))
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword));
}
return tokens.ToSyntaxTokenList();
}
}
}
| |
// 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 is where we group together all the runtime export calls.
//
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using Internal.Runtime;
namespace System.Runtime
{
internal static class RuntimeExports
{
//
// internal calls for allocation
//
[RuntimeExport("RhNewObject")]
public unsafe static object RhNewObject(EETypePtr pEEType)
{
EEType* ptrEEType = (EEType*)pEEType.ToPointer();
#if FEATURE_64BIT_ALIGNMENT
if (ptrEEType->RequiresAlign8)
{
if (ptrEEType->IsValueType)
return InternalCalls.RhpNewFastMisalign(ptrEEType);
if (ptrEEType->IsFinalizable)
return InternalCalls.RhpNewFinalizableAlign8(ptrEEType);
return InternalCalls.RhpNewFastAlign8(ptrEEType);
}
else
#endif // FEATURE_64BIT_ALIGNMENT
{
if (ptrEEType->IsFinalizable)
return InternalCalls.RhpNewFinalizable(ptrEEType);
return InternalCalls.RhpNewFast(ptrEEType);
}
}
[RuntimeExport("RhNewArray")]
public unsafe static object RhNewArray(EETypePtr pEEType, int length)
{
EEType* ptrEEType = (EEType*)pEEType.ToPointer();
#if FEATURE_64BIT_ALIGNMENT
if (ptrEEType->RequiresAlign8)
{
return InternalCalls.RhpNewArrayAlign8(ptrEEType, length);
}
else
#endif // FEATURE_64BIT_ALIGNMENT
{
return InternalCalls.RhpNewArray(ptrEEType, length);
}
}
[RuntimeExport("RhBox")]
public unsafe static object RhBox(EETypePtr pEEType, ref byte data)
{
EEType* ptrEEType = (EEType*)pEEType.ToPointer();
int dataOffset = 0;
object result;
// If we're boxing a Nullable<T> then either box the underlying T or return null (if the
// nullable's value is empty).
if (ptrEEType->IsNullable)
{
// The boolean which indicates whether the value is null comes first in the Nullable struct.
if (data == 0)
return null;
// Switch type we're going to box to the Nullable<T> target type and advance the data pointer
// to the value embedded within the nullable.
dataOffset = ptrEEType->NullableValueOffset;
ptrEEType = ptrEEType->NullableType;
}
#if FEATURE_64BIT_ALIGNMENT
if (ptrEEType->RequiresAlign8)
{
result = InternalCalls.RhpNewFastMisalign(ptrEEType);
}
else
#endif // FEATURE_64BIT_ALIGNMENT
{
result = InternalCalls.RhpNewFast(ptrEEType);
}
InternalCalls.RhpBox(result, ref Unsafe.Add(ref data, dataOffset));
return result;
}
[RuntimeExport("RhBoxAny")]
public unsafe static object RhBoxAny(ref byte data, EETypePtr pEEType)
{
EEType* ptrEEType = (EEType*)pEEType.ToPointer();
if (ptrEEType->IsValueType)
{
return RhBox(pEEType, ref data);
}
else
{
return Unsafe.As<byte, Object>(ref data);
}
}
private unsafe static bool UnboxAnyTypeCompare(EEType *pEEType, EEType *ptrUnboxToEEType)
{
bool result = false;
if (pEEType->CorElementType == ptrUnboxToEEType->CorElementType)
{
result = TypeCast.AreTypesEquivalentInternal(pEEType, ptrUnboxToEEType);
if (!result)
{
// Enum's and primitive types should pass the UnboxAny exception cases
// if they have an exactly matching cor element type.
switch (ptrUnboxToEEType->CorElementType)
{
case CorElementType.ELEMENT_TYPE_I1:
case CorElementType.ELEMENT_TYPE_U1:
case CorElementType.ELEMENT_TYPE_I2:
case CorElementType.ELEMENT_TYPE_U2:
case CorElementType.ELEMENT_TYPE_I4:
case CorElementType.ELEMENT_TYPE_U4:
case CorElementType.ELEMENT_TYPE_I8:
case CorElementType.ELEMENT_TYPE_U8:
case CorElementType.ELEMENT_TYPE_I:
case CorElementType.ELEMENT_TYPE_U:
result = true;
break;
}
}
}
return result;
}
[RuntimeExport("RhUnboxAny")]
public unsafe static void RhUnboxAny(object o, ref byte data, EETypePtr pUnboxToEEType)
{
EEType* ptrUnboxToEEType = (EEType*)pUnboxToEEType.ToPointer();
if (ptrUnboxToEEType->IsValueType)
{
bool isValid = false;
if (ptrUnboxToEEType->IsNullable)
{
isValid = (o == null) || TypeCast.AreTypesEquivalentInternal(o.EEType, ptrUnboxToEEType->NullableType);
}
else
{
isValid = (o != null) && UnboxAnyTypeCompare(o.EEType, ptrUnboxToEEType);
}
if (!isValid)
{
// Throw the invalid cast exception defined by the classlib, using the input unbox EEType*
// to find the correct classlib.
ExceptionIDs exID = o == null ? ExceptionIDs.NullReference : ExceptionIDs.InvalidCast;
throw ptrUnboxToEEType->GetClasslibException(exID);
}
InternalCalls.RhUnbox(o, ref data, ptrUnboxToEEType);
}
else
{
if (o != null && (TypeCast.IsInstanceOf(o, ptrUnboxToEEType) == null))
{
throw ptrUnboxToEEType->GetClasslibException(ExceptionIDs.InvalidCast);
}
Unsafe.As<byte, Object>(ref data) = o;
}
}
//
// Unbox helpers with RyuJIT conventions
//
[RuntimeExport("RhUnbox2")]
static public unsafe ref byte RhUnbox2(EETypePtr pUnboxToEEType, Object obj)
{
EEType * ptrUnboxToEEType = (EEType *)pUnboxToEEType.ToPointer();
if (obj.EEType != ptrUnboxToEEType)
{
// We allow enums and their primtive type to be interchangable
if (obj.EEType->CorElementType != ptrUnboxToEEType->CorElementType)
{
throw ptrUnboxToEEType->GetClasslibException(ExceptionIDs.InvalidCast);
}
}
return ref obj.GetRawData();
}
[RuntimeExport("RhUnboxNullable")]
static public unsafe void RhUnboxNullable(ref byte data, EETypePtr pUnboxToEEType, Object obj)
{
EEType* ptrUnboxToEEType = (EEType*)pUnboxToEEType.ToPointer();
if ((obj != null) && (obj.EEType != ptrUnboxToEEType->NullableType))
{
throw ptrUnboxToEEType->GetClasslibException(ExceptionIDs.InvalidCast);
}
InternalCalls.RhUnbox(obj, ref data, ptrUnboxToEEType);
}
[RuntimeExport("RhArrayStoreCheckAny")]
static public unsafe void RhArrayStoreCheckAny(object array, ref byte data)
{
if (array == null)
{
return;
}
Debug.Assert(array.EEType->IsArray, "first argument must be an array");
EEType* arrayElemType = array.EEType->RelatedParameterType;
if (arrayElemType->IsValueType)
{
return;
}
TypeCast.CheckArrayStore(array, Unsafe.As<byte, Object>(ref data));
}
[RuntimeExport("RhBoxAndNullCheck")]
static public unsafe bool RhBoxAndNullCheck(ref byte data, EETypePtr pEEType)
{
EEType* ptrEEType = (EEType*)pEEType.ToPointer();
if (ptrEEType->IsValueType)
return true;
else
return Unsafe.As<byte, Object>(ref data) != null;
}
#pragma warning disable 169 // The field 'System.Runtime.RuntimeExports.Wrapper.o' is never used.
private class Wrapper
{
private Object _o;
}
#pragma warning restore 169
[RuntimeExport("RhAllocLocal")]
public unsafe static object RhAllocLocal(EETypePtr pEEType)
{
EEType* ptrEEType = (EEType*)pEEType.ToPointer();
if (ptrEEType->IsValueType)
{
#if FEATURE_64BIT_ALIGNMENT
if (ptrEEType->RequiresAlign8)
return InternalCalls.RhpNewFastMisalign(ptrEEType);
#endif
return InternalCalls.RhpNewFast(ptrEEType);
}
else
return new Wrapper();
}
[RuntimeExport("RhMemberwiseClone")]
public unsafe static object RhMemberwiseClone(object src)
{
object objClone;
if (src.EEType->IsArray)
objClone = RhNewArray(new EETypePtr((IntPtr)src.EEType), src.GetArrayLength());
else
objClone = RhNewObject(new EETypePtr((IntPtr)src.EEType));
InternalCalls.RhpCopyObjectContents(objClone, src);
return objClone;
}
[RuntimeExport("RhpReversePInvokeBadTransition")]
public static void RhpReversePInvokeBadTransition(IntPtr returnAddress)
{
EH.FailFastViaClasslib(
RhFailFastReason.IllegalNativeCallableEntry,
null,
returnAddress);
}
[RuntimeExport("RhGetCurrentThreadStackTrace")]
[MethodImpl(MethodImplOptions.NoInlining)] // Ensures that the RhGetCurrentThreadStackTrace frame is always present
public static unsafe int RhGetCurrentThreadStackTrace(IntPtr[] outputBuffer)
{
fixed (IntPtr* pOutputBuffer = outputBuffer)
return RhpGetCurrentThreadStackTrace(pOutputBuffer, (uint)((outputBuffer != null) ? outputBuffer.Length : 0));
}
[DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)]
private static unsafe extern int RhpGetCurrentThreadStackTrace(IntPtr* pOutputBuffer, uint outputBufferLength);
// Worker for RhGetCurrentThreadStackTrace. RhGetCurrentThreadStackTrace just allocates a transition
// frame that will be used to seed the stack trace and this method does all the real work.
//
// Input: outputBuffer may be null or non-null
// Return value: positive: number of entries written to outputBuffer
// negative: number of required entries in outputBuffer in case it's too small (or null)
// Output: outputBuffer is filled in with return address IPs, starting with placing the this
// method's return address into index 0
//
// NOTE: We don't want to allocate the array on behalf of the caller because we don't know which class
// library's objects the caller understands (we support multiple class libraries with multiple root
// System.Object types).
[NativeCallable(EntryPoint = "RhpCalculateStackTraceWorker", CallingConvention = CallingConvention.Cdecl)]
private static unsafe int RhpCalculateStackTraceWorker(IntPtr * pOutputBuffer, uint outputBufferLength)
{
uint nFrames = 0;
bool success = true;
StackFrameIterator frameIter = new StackFrameIterator();
bool isValid = frameIter.Init(null);
Debug.Assert(isValid, "Missing RhGetCurrentThreadStackTrace frame");
// Note that the while loop will skip RhGetCurrentThreadStackTrace frame
while (frameIter.Next())
{
if (nFrames < outputBufferLength)
pOutputBuffer[nFrames] = new IntPtr(frameIter.ControlPC);
else
success = false;
nFrames++;
}
return success ? (int)nFrames : -(int)nFrames;
}
// The GC conservative reporting descriptor is a special structure of data that the GC
// parses to determine whether there are specific regions of memory that it should not
// collect or move around.
// During garbage collection, the GC will inspect the data in this structure, and verify that:
// 1) _magic is set to the magic number (also hard coded on the GC side)
// 2) The reported region is valid (checks alignments, size, within bounds of the thread memory, etc...)
// 3) The ConservativelyReportedRegionDesc pointer must be reported by a frame which does not make a pinvoke transition.
// 4) The value of the _hash field is the computed hash of _regionPointerLow with _regionPointerHigh
// 5) The region must be IntPtr aligned, and have a size which is also IntPtr aligned
// If all conditions are satisfied, the region of memory starting at _regionPointerLow and ending at
// _regionPointerHigh will be conservatively reported.
// This can only be used to report memory regions on the current stack and the structure must itself
// be located on the stack.
public struct ConservativelyReportedRegionDesc
{
internal const ulong MagicNumber64 = 0x87DF7A104F09E0A9UL;
internal const uint MagicNumber32 = 0x4F09E0A9;
internal UIntPtr _magic;
internal UIntPtr _regionPointerLow;
internal UIntPtr _regionPointerHigh;
internal UIntPtr _hash;
}
[RuntimeExport("RhInitializeConservativeReportingRegion")]
public static unsafe void RhInitializeConservativeReportingRegion(ConservativelyReportedRegionDesc* regionDesc, void* bufferBegin, int cbBuffer)
{
Debug.Assert((((int)bufferBegin) & (sizeof(IntPtr) - 1)) == 0, "Buffer not IntPtr aligned");
Debug.Assert((cbBuffer & (sizeof(IntPtr) - 1)) == 0, "Size of buffer not IntPtr aligned");
UIntPtr regionPointerLow = (UIntPtr)bufferBegin;
UIntPtr regionPointerHigh = (UIntPtr)(((byte*)bufferBegin) + cbBuffer);
// Setup pointers to start and end of region
regionDesc->_regionPointerLow = regionPointerLow;
regionDesc->_regionPointerHigh = regionPointerHigh;
// Activate the region for processing
#if BIT64
ulong hash = ConservativelyReportedRegionDesc.MagicNumber64;
hash = ((hash << 13) ^ hash) ^ (ulong)regionPointerLow;
hash = ((hash << 13) ^ hash) ^ (ulong)regionPointerHigh;
regionDesc->_hash = new UIntPtr(hash);
regionDesc->_magic = new UIntPtr(ConservativelyReportedRegionDesc.MagicNumber64);
#else
uint hash = ConservativelyReportedRegionDesc.MagicNumber32;
hash = ((hash << 13) ^ hash) ^ (uint)regionPointerLow;
hash = ((hash << 13) ^ hash) ^ (uint)regionPointerHigh;
regionDesc->_hash = new UIntPtr(hash);
regionDesc->_magic = new UIntPtr(ConservativelyReportedRegionDesc.MagicNumber32);
#endif
}
// Disable conservative reporting
[RuntimeExport("RhDisableConservativeReportingRegion")]
public static unsafe void RhDisableConservativeReportingRegion(ConservativelyReportedRegionDesc* regionDesc)
{
regionDesc->_magic = default(UIntPtr);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Globalization;
using Xunit;
namespace System.ComponentModel.Tests
{
public class TypeDescriptorTests
{
[Fact]
public void AddAndRemoveProvider()
{
var provider = new InvocationRecordingTypeDescriptionProvider();
var component = new DescriptorTestComponent();
TypeDescriptor.AddProvider(provider, component);
var retrievedProvider = TypeDescriptor.GetProvider(component);
retrievedProvider.GetCache(component);
Assert.True(provider.ReceivedCall);
provider.Reset();
TypeDescriptor.RemoveProvider(provider, component);
retrievedProvider = TypeDescriptor.GetProvider(component);
retrievedProvider.GetCache(component);
Assert.False(provider.ReceivedCall);
}
[Fact]
public void AddAttribute()
{
var component = new DescriptorTestComponent();
var addedAttribute = new DescriptorTestAttribute("expected string");
TypeDescriptor.AddAttributes(component.GetType(), addedAttribute);
AttributeCollection attributes = TypeDescriptor.GetAttributes(component);
Assert.True(attributes.Contains(addedAttribute));
}
[Fact]
public void CreateInstancePassesCtorParameters()
{
var expectedString = "expected string";
var component = TypeDescriptor.CreateInstance(null, typeof(DescriptorTestComponent), new[] { expectedString.GetType() }, new[] { expectedString });
Assert.NotNull(component);
Assert.IsType(typeof(DescriptorTestComponent), component);
Assert.Equal(expectedString, (component as DescriptorTestComponent).StringProperty);
}
[Fact]
public void GetAssociationReturnsExpectedObject()
{
var primaryObject = new DescriptorTestComponent();
var secondaryObject = new MockEventDescriptor();
TypeDescriptor.CreateAssociation(primaryObject, secondaryObject);
var associatedObject = TypeDescriptor.GetAssociation(secondaryObject.GetType(), primaryObject);
Assert.IsType(secondaryObject.GetType(), associatedObject);
Assert.Equal(secondaryObject, associatedObject);
}
[Fact]
public static void GetConverter()
{
foreach (Tuple<Type, Type> pair in s_typesWithConverters)
{
TypeConverter converter = TypeDescriptor.GetConverter(pair.Item1);
Assert.NotNull(converter);
Assert.Equal(pair.Item2, converter.GetType());
Assert.True(converter.CanConvertTo(typeof(string)));
}
}
[Fact]
public static void GetConverter_null()
{
Assert.Throws<ArgumentNullException>(() => TypeDescriptor.GetConverter(null));
}
[Fact]
public static void GetConverter_NotAvailable()
{
Assert.Throws<MissingMethodException>(
() => TypeDescriptor.GetConverter(typeof(ClassWithInvalidConverter)));
// GetConverter should throw MissingMethodException because parameterless constructor is missing in the InvalidConverter class.
}
[Fact]
public void GetEvents()
{
var component = new DescriptorTestComponent();
EventDescriptorCollection events = TypeDescriptor.GetEvents(component);
Assert.Equal(2, events.Count);
}
[Fact]
public void GetEventsFiltersByAttribute()
{
var defaultValueAttribute = new DefaultValueAttribute(null);
EventDescriptorCollection events = TypeDescriptor.GetEvents(typeof(DescriptorTestComponent), new[] { defaultValueAttribute });
Assert.Equal(1, events.Count);
}
[Fact]
public void GetPropertiesFiltersByAttribute()
{
var defaultValueAttribute = new DefaultValueAttribute(DescriptorTestComponent.DefaultPropertyValue);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(DescriptorTestComponent), new[] { defaultValueAttribute });
Assert.Equal(1, properties.Count);
}
[Fact]
public void RemoveAssociationsRemovesAllAssociations()
{
var primaryObject = new DescriptorTestComponent();
var firstAssociatedObject = new MockEventDescriptor();
var secondAssociatedObject = new MockPropertyDescriptor();
TypeDescriptor.CreateAssociation(primaryObject, firstAssociatedObject);
TypeDescriptor.CreateAssociation(primaryObject, secondAssociatedObject);
TypeDescriptor.RemoveAssociations(primaryObject);
// GetAssociation never returns null. The default implementation returns the
// primary object when an association doesn't exist. This isn't documented,
// however, so here we only verify that the formerly associated objects aren't returned.
var firstAssociation = TypeDescriptor.GetAssociation(firstAssociatedObject.GetType(), primaryObject);
Assert.NotEqual(firstAssociatedObject, firstAssociation);
var secondAssociation = TypeDescriptor.GetAssociation(secondAssociatedObject.GetType(), primaryObject);
Assert.NotEqual(secondAssociatedObject, secondAssociation);
}
[Fact]
public void RemoveSingleAssociation()
{
var primaryObject = new DescriptorTestComponent();
var firstAssociatedObject = new MockEventDescriptor();
var secondAssociatedObject = new MockPropertyDescriptor();
TypeDescriptor.CreateAssociation(primaryObject, firstAssociatedObject);
TypeDescriptor.CreateAssociation(primaryObject, secondAssociatedObject);
TypeDescriptor.RemoveAssociation(primaryObject, firstAssociatedObject);
// the second association should remain
var secondAssociation = TypeDescriptor.GetAssociation(secondAssociatedObject.GetType(), primaryObject);
Assert.Equal(secondAssociatedObject, secondAssociation);
// the first association should not
var firstAssociation = TypeDescriptor.GetAssociation(firstAssociatedObject.GetType(), primaryObject);
Assert.NotEqual(firstAssociatedObject, firstAssociation);
}
private class InvocationRecordingTypeDescriptionProvider : TypeDescriptionProvider
{
public bool ReceivedCall { get; private set; } = false;
public void Reset() => ReceivedCall = false;
public override object CreateInstance(IServiceProvider provider, Type objectType, Type[] argTypes, object[] args)
{
ReceivedCall = true;
return base.CreateInstance(provider, objectType, argTypes, args);
}
public override IDictionary GetCache(object instance)
{
ReceivedCall = true;
return base.GetCache(instance);
}
public override ICustomTypeDescriptor GetExtendedTypeDescriptor(object instance)
{
ReceivedCall = true;
return base.GetExtendedTypeDescriptor(instance);
}
public override string GetFullComponentName(object component)
{
ReceivedCall = true;
return base.GetFullComponentName(component);
}
public override Type GetReflectionType(Type objectType, object instance)
{
ReceivedCall = true;
return base.GetReflectionType(objectType, instance);
}
protected override IExtenderProvider[] GetExtenderProviders(object instance)
{
ReceivedCall = true;
return base.GetExtenderProviders(instance);
}
public override Type GetRuntimeType(Type reflectionType)
{
ReceivedCall = true;
return base.GetRuntimeType(reflectionType);
}
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
{
ReceivedCall = true;
return base.GetTypeDescriptor(objectType, instance);
}
public override bool IsSupportedType(Type type)
{
ReceivedCall = true;
return base.IsSupportedType(type);
}
}
private static Tuple<Type, Type>[] s_typesWithConverters =
{
new Tuple<Type, Type> (typeof(bool), typeof(BooleanConverter)),
new Tuple<Type, Type> (typeof(byte), typeof(ByteConverter)),
new Tuple<Type, Type> (typeof(SByte), typeof(SByteConverter)),
new Tuple<Type, Type> (typeof(char), typeof(CharConverter)),
new Tuple<Type, Type> (typeof(double), typeof(DoubleConverter)),
new Tuple<Type, Type> (typeof(string), typeof(StringConverter)),
new Tuple<Type, Type> (typeof(short), typeof(Int16Converter)),
new Tuple<Type, Type> (typeof(int), typeof(Int32Converter)),
new Tuple<Type, Type> (typeof(long), typeof(Int64Converter)),
new Tuple<Type, Type> (typeof(float), typeof(SingleConverter)),
new Tuple<Type, Type> (typeof(UInt16), typeof(UInt16Converter)),
new Tuple<Type, Type> (typeof(UInt32), typeof(UInt32Converter)),
new Tuple<Type, Type> (typeof(UInt64), typeof(UInt64Converter)),
new Tuple<Type, Type> (typeof(object), typeof(TypeConverter)),
new Tuple<Type, Type> (typeof(void), typeof(TypeConverter)),
new Tuple<Type, Type> (typeof(DateTime), typeof(DateTimeConverter)),
new Tuple<Type, Type> (typeof(DateTimeOffset), typeof(DateTimeOffsetConverter)),
new Tuple<Type, Type> (typeof(Decimal), typeof(DecimalConverter)),
new Tuple<Type, Type> (typeof(TimeSpan), typeof(TimeSpanConverter)),
new Tuple<Type, Type> (typeof(Guid), typeof(GuidConverter)),
new Tuple<Type, Type> (typeof(Array), typeof(ArrayConverter)),
new Tuple<Type, Type> (typeof(ICollection), typeof(CollectionConverter)),
new Tuple<Type, Type> (typeof(Enum), typeof(EnumConverter)),
new Tuple<Type, Type> (typeof(SomeEnum), typeof(EnumConverter)),
new Tuple<Type, Type> (typeof(SomeValueType?), typeof(NullableConverter)),
new Tuple<Type, Type> (typeof(int?), typeof(NullableConverter)),
new Tuple<Type, Type> (typeof(ClassWithNoConverter), typeof(TypeConverter)),
new Tuple<Type, Type> (typeof(BaseClass), typeof(BaseClassConverter)),
new Tuple<Type, Type> (typeof(DerivedClass), typeof(DerivedClassConverter)),
new Tuple<Type, Type> (typeof(IBase), typeof(IBaseConverter)),
new Tuple<Type, Type> (typeof(IDerived), typeof(IBaseConverter)),
new Tuple<Type, Type> (typeof(ClassIBase), typeof(IBaseConverter)),
new Tuple<Type, Type> (typeof(ClassIDerived), typeof(IBaseConverter)),
new Tuple<Type, Type> (typeof(Uri), typeof(UriTypeConverter)),
new Tuple<Type, Type> (typeof(CultureInfo), typeof(CultureInfoConverter))
};
}
}
| |
////////////////////////////////////////////////////////////////////////////////
// The MIT License (MIT)
//
// Copyright (c) 2015 Tim Stair
//
// 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.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using CardMaker.XML;
using Support.IO;
namespace CardMaker.Forms
{
partial class MDIProject
{
/// <summary>
/// Required designer variable.
/// </summary>
private IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.treeView = new System.Windows.Forms.TreeView();
this.contextMenuStripProject = new System.Windows.Forms.ContextMenuStrip(this.components);
this.addCardLayoutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.addCardLayoutFromTemplateToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripMenuItemSetProjectNameFormat = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripSeparator();
this.projectSettingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.contextMenuStripLayout = new System.Windows.Forms.ContextMenuStrip(this.components);
this.duplicateLayoutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.defineAsTemplateLayoutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.removeCardLayoutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator();
this.exportCardLayoutAsImagesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exportCardLayoutAsPDFToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripSeparator();
this.addReferenceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.addGoogleSpreadsheetReferenceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripMenuItemSetLayoutNameFormat = new System.Windows.Forms.ToolStripMenuItem();
this.contextMenuStripReference = new System.Windows.Forms.ContextMenuStrip(this.components);
this.setAsDefaultReferenceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.removeReferenceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.resizeLayoutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.duplicateLayoutCustomToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.contextMenuStripProject.SuspendLayout();
this.contextMenuStripLayout.SuspendLayout();
this.contextMenuStripReference.SuspendLayout();
this.SuspendLayout();
//
// treeView
//
this.treeView.AllowDrop = true;
this.treeView.ContextMenuStrip = this.contextMenuStripProject;
this.treeView.Dock = System.Windows.Forms.DockStyle.Fill;
this.treeView.HideSelection = false;
this.treeView.LabelEdit = true;
this.treeView.Location = new System.Drawing.Point(0, 0);
this.treeView.Name = "treeView";
this.treeView.ShowRootLines = false;
this.treeView.Size = new System.Drawing.Size(192, 335);
this.treeView.TabIndex = 1;
this.treeView.BeforeLabelEdit += new System.Windows.Forms.NodeLabelEditEventHandler(this.treeView_BeforeLabelEdit);
this.treeView.AfterLabelEdit += new System.Windows.Forms.NodeLabelEditEventHandler(this.treeView_AfterLabelEdit);
this.treeView.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.treeView_ItemDrag);
this.treeView.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView_AfterSelect);
this.treeView.DragDrop += new System.Windows.Forms.DragEventHandler(this.treeView_DragDrop);
this.treeView.DragEnter += new System.Windows.Forms.DragEventHandler(this.treeView_DragEnter);
this.treeView.MouseClick += new System.Windows.Forms.MouseEventHandler(this.treeView_MouseClick);
//
// contextMenuStripProject
//
this.contextMenuStripProject.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.addCardLayoutToolStripMenuItem,
this.addCardLayoutFromTemplateToolStripMenuItem,
this.toolStripMenuItem1,
this.toolStripMenuItemSetProjectNameFormat,
this.toolStripMenuItem5,
this.projectSettingsToolStripMenuItem});
this.contextMenuStripProject.Name = "contextMenuStripTreeView";
this.contextMenuStripProject.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
this.contextMenuStripProject.Size = new System.Drawing.Size(242, 104);
this.contextMenuStripProject.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStripTreeView_Opening);
//
// addCardLayoutToolStripMenuItem
//
this.addCardLayoutToolStripMenuItem.Name = "addCardLayoutToolStripMenuItem";
this.addCardLayoutToolStripMenuItem.Size = new System.Drawing.Size(241, 22);
this.addCardLayoutToolStripMenuItem.Text = "Add Card Layout...";
this.addCardLayoutToolStripMenuItem.Click += new System.EventHandler(this.addLayoutToolStripMenuItem_Click);
//
// addCardLayoutFromTemplateToolStripMenuItem
//
this.addCardLayoutFromTemplateToolStripMenuItem.Name = "addCardLayoutFromTemplateToolStripMenuItem";
this.addCardLayoutFromTemplateToolStripMenuItem.Size = new System.Drawing.Size(241, 22);
this.addCardLayoutFromTemplateToolStripMenuItem.Text = "Add Card Layout From Template...";
this.addCardLayoutFromTemplateToolStripMenuItem.Click += new System.EventHandler(this.addCardLayoutFromTemplateToolStripMenuItem_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(238, 6);
//
// toolStripMenuItemSetProjectNameFormat
//
this.toolStripMenuItemSetProjectNameFormat.Name = "toolStripMenuItemSetProjectNameFormat";
this.toolStripMenuItemSetProjectNameFormat.Size = new System.Drawing.Size(241, 22);
this.toolStripMenuItemSetProjectNameFormat.Text = "Set Name Format...";
this.toolStripMenuItemSetProjectNameFormat.Click += new System.EventHandler(this.setNameFormatToolStripMenuItem_Click);
//
// toolStripMenuItem5
//
this.toolStripMenuItem5.Name = "toolStripMenuItem5";
this.toolStripMenuItem5.Size = new System.Drawing.Size(238, 6);
//
// projectSettingsToolStripMenuItem
//
this.projectSettingsToolStripMenuItem.Name = "projectSettingsToolStripMenuItem";
this.projectSettingsToolStripMenuItem.Size = new System.Drawing.Size(241, 22);
this.projectSettingsToolStripMenuItem.Text = "Project Settings...";
this.projectSettingsToolStripMenuItem.Click += new System.EventHandler(this.projectSettingsToolStripMenuItem_Click);
//
// contextMenuStripLayout
//
this.contextMenuStripLayout.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.duplicateLayoutToolStripMenuItem,
this.duplicateLayoutCustomToolStripMenuItem,
this.resizeLayoutToolStripMenuItem,
this.defineAsTemplateLayoutToolStripMenuItem,
this.removeCardLayoutToolStripMenuItem,
this.toolStripMenuItem2,
this.exportCardLayoutAsImagesToolStripMenuItem,
this.exportCardLayoutAsPDFToolStripMenuItem,
this.toolStripMenuItem4,
this.addReferenceToolStripMenuItem,
this.addGoogleSpreadsheetReferenceToolStripMenuItem,
this.toolStripMenuItem3,
this.toolStripMenuItemSetLayoutNameFormat});
this.contextMenuStripLayout.Name = "contextMenuStripLayout";
this.contextMenuStripLayout.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
this.contextMenuStripLayout.Size = new System.Drawing.Size(259, 264);
//
// duplicateLayoutToolStripMenuItem
//
this.duplicateLayoutToolStripMenuItem.Name = "duplicateLayoutToolStripMenuItem";
this.duplicateLayoutToolStripMenuItem.Size = new System.Drawing.Size(258, 22);
this.duplicateLayoutToolStripMenuItem.Text = "Duplicate Layout";
this.duplicateLayoutToolStripMenuItem.Click += new System.EventHandler(this.duplicateLayoutToolStripMenuItem_Click);
//
// defineAsTemplateLayoutToolStripMenuItem
//
this.defineAsTemplateLayoutToolStripMenuItem.Name = "defineAsTemplateLayoutToolStripMenuItem";
this.defineAsTemplateLayoutToolStripMenuItem.Size = new System.Drawing.Size(258, 22);
this.defineAsTemplateLayoutToolStripMenuItem.Text = "Define As Template Layout...";
this.defineAsTemplateLayoutToolStripMenuItem.Click += new System.EventHandler(this.defineAsTemplateLayoutToolStripMenuItem_Click);
//
// removeCardLayoutToolStripMenuItem
//
this.removeCardLayoutToolStripMenuItem.Name = "removeCardLayoutToolStripMenuItem";
this.removeCardLayoutToolStripMenuItem.Size = new System.Drawing.Size(258, 22);
this.removeCardLayoutToolStripMenuItem.Text = "Remove Card Layout";
this.removeCardLayoutToolStripMenuItem.Click += new System.EventHandler(this.removeLayoutToolStripMenuItem_Click);
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size(255, 6);
//
// exportCardLayoutAsImagesToolStripMenuItem
//
this.exportCardLayoutAsImagesToolStripMenuItem.Name = "exportCardLayoutAsImagesToolStripMenuItem";
this.exportCardLayoutAsImagesToolStripMenuItem.Size = new System.Drawing.Size(258, 22);
this.exportCardLayoutAsImagesToolStripMenuItem.Text = "Export Card Layout as Images...";
this.exportCardLayoutAsImagesToolStripMenuItem.Click += new System.EventHandler(this.exportCardLayoutAsImagesToolStripMenuItem_Click);
//
// exportCardLayoutAsPDFToolStripMenuItem
//
this.exportCardLayoutAsPDFToolStripMenuItem.Name = "exportCardLayoutAsPDFToolStripMenuItem";
this.exportCardLayoutAsPDFToolStripMenuItem.Size = new System.Drawing.Size(258, 22);
this.exportCardLayoutAsPDFToolStripMenuItem.Text = "Export Card Layout as PDF...";
this.exportCardLayoutAsPDFToolStripMenuItem.Click += new System.EventHandler(this.exportCardLayoutAsPDFToolStripMenuItem_Click);
//
// toolStripMenuItem4
//
this.toolStripMenuItem4.Name = "toolStripMenuItem4";
this.toolStripMenuItem4.Size = new System.Drawing.Size(255, 6);
//
// addReferenceToolStripMenuItem
//
this.addReferenceToolStripMenuItem.Name = "addReferenceToolStripMenuItem";
this.addReferenceToolStripMenuItem.Size = new System.Drawing.Size(258, 22);
this.addReferenceToolStripMenuItem.Text = "Add Reference...";
this.addReferenceToolStripMenuItem.Click += new System.EventHandler(this.addReferenceToolStripMenuItem_Click);
//
// addGoogleSpreadsheetReferenceToolStripMenuItem
//
this.addGoogleSpreadsheetReferenceToolStripMenuItem.Name = "addGoogleSpreadsheetReferenceToolStripMenuItem";
this.addGoogleSpreadsheetReferenceToolStripMenuItem.Size = new System.Drawing.Size(258, 22);
this.addGoogleSpreadsheetReferenceToolStripMenuItem.Text = "Add Google Spreadsheet Reference...";
this.addGoogleSpreadsheetReferenceToolStripMenuItem.Click += new System.EventHandler(this.addGoogleSpreadsheetReferenceToolStripMenuItem_Click);
//
// toolStripMenuItem3
//
this.toolStripMenuItem3.Name = "toolStripMenuItem3";
this.toolStripMenuItem3.Size = new System.Drawing.Size(255, 6);
//
// toolStripMenuItemSetLayoutNameFormat
//
this.toolStripMenuItemSetLayoutNameFormat.Name = "toolStripMenuItemSetLayoutNameFormat";
this.toolStripMenuItemSetLayoutNameFormat.Size = new System.Drawing.Size(258, 22);
this.toolStripMenuItemSetLayoutNameFormat.Text = "Configure Layout Export...";
this.toolStripMenuItemSetLayoutNameFormat.Click += new System.EventHandler(this.setNameFormatToolStripMenuItem_Click);
//
// contextMenuStripReference
//
this.contextMenuStripReference.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.setAsDefaultReferenceToolStripMenuItem,
this.removeReferenceToolStripMenuItem});
this.contextMenuStripReference.Name = "contextMenuStripReference";
this.contextMenuStripReference.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
this.contextMenuStripReference.Size = new System.Drawing.Size(197, 48);
//
// setAsDefaultReferenceToolStripMenuItem
//
this.setAsDefaultReferenceToolStripMenuItem.Name = "setAsDefaultReferenceToolStripMenuItem";
this.setAsDefaultReferenceToolStripMenuItem.Size = new System.Drawing.Size(196, 22);
this.setAsDefaultReferenceToolStripMenuItem.Text = "Set As Default Reference";
this.setAsDefaultReferenceToolStripMenuItem.Click += new System.EventHandler(this.setAsDefaultReferenceToolStripMenuItem_Click);
//
// removeReferenceToolStripMenuItem
//
this.removeReferenceToolStripMenuItem.Name = "removeReferenceToolStripMenuItem";
this.removeReferenceToolStripMenuItem.Size = new System.Drawing.Size(196, 22);
this.removeReferenceToolStripMenuItem.Text = "Remove Reference";
this.removeReferenceToolStripMenuItem.Click += new System.EventHandler(this.removeReferenceToolStripMenuItem_Click);
//
// resizeLayoutToolStripMenuItem
//
this.resizeLayoutToolStripMenuItem.Name = "resizeLayoutToolStripMenuItem";
this.resizeLayoutToolStripMenuItem.Size = new System.Drawing.Size(258, 22);
this.resizeLayoutToolStripMenuItem.Text = "Resize Layout...";
this.resizeLayoutToolStripMenuItem.Click += new System.EventHandler(this.resizeLayoutToolStripMenuItem_Click);
//
// duplicateLayoutCustomToolStripMenuItem
//
this.duplicateLayoutCustomToolStripMenuItem.Name = "duplicateLayoutCustomToolStripMenuItem";
this.duplicateLayoutCustomToolStripMenuItem.Size = new System.Drawing.Size(258, 22);
this.duplicateLayoutCustomToolStripMenuItem.Text = "Duplicate Layout (Custom)...";
this.duplicateLayoutCustomToolStripMenuItem.Click += new System.EventHandler(this.duplicateLayoutCustomToolStripMenuItem_Click);
//
// MDIProject
//
this.ClientSize = new System.Drawing.Size(192, 335);
this.Controls.Add(this.treeView);
this.Name = "MDIProject";
this.ShowIcon = false;
this.Text = " Project";
this.contextMenuStripProject.ResumeLayout(false);
this.contextMenuStripLayout.ResumeLayout(false);
this.contextMenuStripReference.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private TreeView treeView;
private ContextMenuStrip contextMenuStripProject;
private ToolStripMenuItem addCardLayoutToolStripMenuItem;
private ToolStripMenuItem toolStripMenuItemSetProjectNameFormat;
private ToolStripMenuItem addCardLayoutFromTemplateToolStripMenuItem;
private ContextMenuStrip contextMenuStripLayout;
private ContextMenuStrip contextMenuStripReference;
private ToolStripMenuItem duplicateLayoutToolStripMenuItem;
private ToolStripMenuItem removeCardLayoutToolStripMenuItem;
private ToolStripMenuItem defineAsTemplateLayoutToolStripMenuItem;
private ToolStripMenuItem addReferenceToolStripMenuItem;
private ToolStripMenuItem exportCardLayoutAsImagesToolStripMenuItem;
private ToolStripMenuItem setAsDefaultReferenceToolStripMenuItem;
private ToolStripMenuItem removeReferenceToolStripMenuItem;
private ToolStripSeparator toolStripMenuItem1;
private ToolStripSeparator toolStripMenuItem3;
private ToolStripMenuItem toolStripMenuItemSetLayoutNameFormat;
private ToolStripSeparator toolStripMenuItem2;
private ToolStripSeparator toolStripMenuItem4;
private ToolStripMenuItem addGoogleSpreadsheetReferenceToolStripMenuItem;
private ToolStripMenuItem exportCardLayoutAsPDFToolStripMenuItem;
private ToolStripSeparator toolStripMenuItem5;
private ToolStripMenuItem projectSettingsToolStripMenuItem;
private ToolStripMenuItem resizeLayoutToolStripMenuItem;
private ToolStripMenuItem duplicateLayoutCustomToolStripMenuItem;
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Windows.Forms;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS;
namespace ToolbarMenu
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
public System.Windows.Forms.Button cmdAddSubMenu;
public System.Windows.Forms.Button cmdAddMenu;
public System.Windows.Forms.Label Label4;
public System.Windows.Forms.Label Label2;
public System.Windows.Forms.Label Label3;
public System.Windows.Forms.Label Label1;
private ESRI.ArcGIS.Controls.AxToolbarControl axToolbarControl1;
private ESRI.ArcGIS.Controls.AxMapControl axMapControl1;
private ESRI.ArcGIS.Controls.AxLicenseControl axLicenseControl1;
private IToolbarMenu m_navigationMenu = new ToolbarMenuClass();
public Label Label5;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
//Release COM objects
ESRI.ArcGIS.ADF.COMSupport.AOUninitialize.Shutdown();
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.cmdAddSubMenu = new System.Windows.Forms.Button();
this.cmdAddMenu = new System.Windows.Forms.Button();
this.Label4 = new System.Windows.Forms.Label();
this.Label2 = new System.Windows.Forms.Label();
this.Label3 = new System.Windows.Forms.Label();
this.Label1 = new System.Windows.Forms.Label();
this.axToolbarControl1 = new ESRI.ArcGIS.Controls.AxToolbarControl();
this.axMapControl1 = new ESRI.ArcGIS.Controls.AxMapControl();
this.axLicenseControl1 = new ESRI.ArcGIS.Controls.AxLicenseControl();
this.Label5 = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).BeginInit();
this.SuspendLayout();
//
// cmdAddSubMenu
//
this.cmdAddSubMenu.BackColor = System.Drawing.SystemColors.Control;
this.cmdAddSubMenu.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdAddSubMenu.Enabled = false;
this.cmdAddSubMenu.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cmdAddSubMenu.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdAddSubMenu.Location = new System.Drawing.Point(464, 272);
this.cmdAddSubMenu.Name = "cmdAddSubMenu";
this.cmdAddSubMenu.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdAddSubMenu.Size = new System.Drawing.Size(97, 33);
this.cmdAddSubMenu.TabIndex = 12;
this.cmdAddSubMenu.Text = "Add Sub Menu";
this.cmdAddSubMenu.UseVisualStyleBackColor = false;
this.cmdAddSubMenu.Click += new System.EventHandler(this.cmdAddSubMenu_Click);
//
// cmdAddMenu
//
this.cmdAddMenu.BackColor = System.Drawing.SystemColors.Control;
this.cmdAddMenu.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdAddMenu.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cmdAddMenu.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdAddMenu.Location = new System.Drawing.Point(464, 176);
this.cmdAddMenu.Name = "cmdAddMenu";
this.cmdAddMenu.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdAddMenu.Size = new System.Drawing.Size(97, 33);
this.cmdAddMenu.TabIndex = 11;
this.cmdAddMenu.Text = "Add Menu";
this.cmdAddMenu.UseVisualStyleBackColor = false;
this.cmdAddMenu.Click += new System.EventHandler(this.cmdAddMenu_Click);
//
// Label4
//
this.Label4.BackColor = System.Drawing.SystemColors.Control;
this.Label4.Cursor = System.Windows.Forms.Cursors.Default;
this.Label4.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Label4.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label4.Location = new System.Drawing.Point(440, 232);
this.Label4.Name = "Label4";
this.Label4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label4.Size = new System.Drawing.Size(137, 41);
this.Label4.TabIndex = 13;
this.Label4.Text = "Add a sub-menu to the Navigation menu.";
//
// Label2
//
this.Label2.BackColor = System.Drawing.SystemColors.Control;
this.Label2.Cursor = System.Windows.Forms.Cursors.Default;
this.Label2.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Label2.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label2.Location = new System.Drawing.Point(440, 40);
this.Label2.Name = "Label2";
this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label2.Size = new System.Drawing.Size(144, 33);
this.Label2.TabIndex = 10;
this.Label2.Text = "Browse to a map document to load into the MapControl.";
//
// Label3
//
this.Label3.BackColor = System.Drawing.SystemColors.Control;
this.Label3.Cursor = System.Windows.Forms.Cursors.Default;
this.Label3.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Label3.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label3.Location = new System.Drawing.Point(440, 136);
this.Label3.Name = "Label3";
this.Label3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label3.Size = new System.Drawing.Size(145, 33);
this.Label3.TabIndex = 9;
this.Label3.Text = "Add the Navigation menu onto the ToolbarControl.";
//
// Label1
//
this.Label1.BackColor = System.Drawing.SystemColors.Control;
this.Label1.Cursor = System.Windows.Forms.Cursors.Default;
this.Label1.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Label1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label1.Location = new System.Drawing.Point(440, 80);
this.Label1.Name = "Label1";
this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label1.Size = new System.Drawing.Size(137, 41);
this.Label1.TabIndex = 8;
this.Label1.Text = "Navigate around the data using the commands on the ToolbarControl.";
//
// axToolbarControl1
//
this.axToolbarControl1.Location = new System.Drawing.Point(8, 8);
this.axToolbarControl1.Name = "axToolbarControl1";
this.axToolbarControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axToolbarControl1.OcxState")));
this.axToolbarControl1.Size = new System.Drawing.Size(592, 28);
this.axToolbarControl1.TabIndex = 14;
//
// axMapControl1
//
this.axMapControl1.Location = new System.Drawing.Point(8, 40);
this.axMapControl1.Name = "axMapControl1";
this.axMapControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axMapControl1.OcxState")));
this.axMapControl1.Size = new System.Drawing.Size(424, 368);
this.axMapControl1.TabIndex = 15;
this.axMapControl1.OnMouseDown += new ESRI.ArcGIS.Controls.IMapControlEvents2_Ax_OnMouseDownEventHandler(this.axMapControl1_OnMouseDown);
//
// axLicenseControl1
//
this.axLicenseControl1.Enabled = true;
this.axLicenseControl1.Location = new System.Drawing.Point(24, 56);
this.axLicenseControl1.Name = "axLicenseControl1";
this.axLicenseControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axLicenseControl1.OcxState")));
this.axLicenseControl1.Size = new System.Drawing.Size(32, 32);
this.axLicenseControl1.TabIndex = 16;
//
// Label5
//
this.Label5.BackColor = System.Drawing.SystemColors.Control;
this.Label5.Cursor = System.Windows.Forms.Cursors.Default;
this.Label5.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Label5.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label5.Location = new System.Drawing.Point(439, 328);
this.Label5.Name = "Label5";
this.Label5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label5.Size = new System.Drawing.Size(145, 33);
this.Label5.TabIndex = 17;
this.Label5.Text = "Right click on the display to popup the Navigation menu";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(608, 414);
this.Controls.Add(this.Label5);
this.Controls.Add(this.axLicenseControl1);
this.Controls.Add(this.axMapControl1);
this.Controls.Add(this.axToolbarControl1);
this.Controls.Add(this.cmdAddSubMenu);
this.Controls.Add(this.cmdAddMenu);
this.Controls.Add(this.Label4);
this.Controls.Add(this.Label2);
this.Controls.Add(this.Label3);
this.Controls.Add(this.Label1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
if (!RuntimeManager.Bind(ProductCode.Engine))
{
if (!RuntimeManager.Bind(ProductCode.Desktop))
{
MessageBox.Show("Unable to bind to ArcGIS runtime. Application will be shut down.");
return;
}
}
Application.Run(new Form1());
}
private void Form1_Load(object sender, System.EventArgs e)
{
//Set buddy control
axToolbarControl1.SetBuddyControl(axMapControl1);
//Create UID's and add new items to the ToolbarControl
UID uID = new UIDClass();
uID.Value = "esriControls.ControlsOpenDocCommand";
axToolbarControl1.AddItem(uID, -1, -1, false, -1, esriCommandStyles.esriCommandStyleIconAndText);
uID.Value = "esriControls.ControlsMapZoomInTool";
axToolbarControl1.AddItem(uID, -1, -1, true, -1, esriCommandStyles.esriCommandStyleIconAndText);
uID.Value = "esriControls.ControlsMapZoomOutTool";
axToolbarControl1.AddItem(uID, -1, -1, false, -1, esriCommandStyles.esriCommandStyleIconAndText);
uID.Value = "esriControls.ControlsMapPanTool";
axToolbarControl1.AddItem(uID, -1, -1, false, -1, esriCommandStyles.esriCommandStyleIconAndText);
uID.Value = "esriControls.ControlsMapFullExtentCommand";
axToolbarControl1.AddItem(uID, -1, -1, false, -1, esriCommandStyles.esriCommandStyleIconAndText);
//Create a MenuDef object
IMenuDef menuDef = new NavigationMenu();
//Create a ToolbarMenu
m_navigationMenu.AddItem(menuDef, 0, -1, false, esriCommandStyles.esriCommandStyleIconAndText);
//Set the ToolbarMenu's hook
m_navigationMenu.SetHook(axToolbarControl1.Object);
//Set the ToolbarMenu's caption
m_navigationMenu.Caption ="Navigation";
}
private void cmdAddMenu_Click(object sender, System.EventArgs e)
{
//Add to the end of the Toolbar - it will be the 6th item
axToolbarControl1.AddItem(m_navigationMenu, -1, -1, false, 0, esriCommandStyles.esriCommandStyleMenuBar);
cmdAddMenu.Enabled = false;
cmdAddSubMenu.Enabled = true;
}
private void cmdAddSubMenu_Click(object sender, System.EventArgs e)
{
//Create a MenuDef object
IMenuDef menuDef = new ToolbarSubMenu();
//Get the menu, which is the 6th item on the toolbar (indexing from 0)
IToolbarItem toolbarItem = axToolbarControl1.GetItem(5);
IToolbarMenu toolbarMenu = toolbarItem.Menu;
//Add the sub-menu as the third item on the Navigation menu, making it start a new group
toolbarMenu.AddSubMenu(menuDef, 2, true);
cmdAddSubMenu.Enabled = false;
}
private void axMapControl1_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
{
if (e.button == 2)
//Popup the menu
m_navigationMenu.PopupMenu(e.x, e.y, axMapControl1.hWnd);
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Cluster.Codecs {
public class BackupQueryEncoder
{
public const ushort BLOCK_LENGTH = 16;
public const ushort TEMPLATE_ID = 77;
public const ushort SCHEMA_ID = 111;
public const ushort SCHEMA_VERSION = 7;
private BackupQueryEncoder _parentMessage;
private IMutableDirectBuffer _buffer;
protected int _offset;
protected int _limit;
public BackupQueryEncoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IMutableDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public BackupQueryEncoder Wrap(IMutableDirectBuffer buffer, int offset)
{
this._buffer = buffer;
this._offset = offset;
Limit(offset + BLOCK_LENGTH);
return this;
}
public BackupQueryEncoder WrapAndApplyHeader(
IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder)
{
headerEncoder
.Wrap(buffer, offset)
.BlockLength(BLOCK_LENGTH)
.TemplateId(TEMPLATE_ID)
.SchemaId(SCHEMA_ID)
.Version(SCHEMA_VERSION);
return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH);
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int CorrelationIdEncodingOffset()
{
return 0;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public BackupQueryEncoder CorrelationId(long value)
{
_buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian);
return this;
}
public static int ResponseStreamIdEncodingOffset()
{
return 8;
}
public static int ResponseStreamIdEncodingLength()
{
return 4;
}
public static int ResponseStreamIdNullValue()
{
return -2147483648;
}
public static int ResponseStreamIdMinValue()
{
return -2147483647;
}
public static int ResponseStreamIdMaxValue()
{
return 2147483647;
}
public BackupQueryEncoder ResponseStreamId(int value)
{
_buffer.PutInt(_offset + 8, value, ByteOrder.LittleEndian);
return this;
}
public static int VersionEncodingOffset()
{
return 12;
}
public static int VersionEncodingLength()
{
return 4;
}
public static int VersionNullValue()
{
return 0;
}
public static int VersionMinValue()
{
return 1;
}
public static int VersionMaxValue()
{
return 16777215;
}
public BackupQueryEncoder Version(int value)
{
_buffer.PutInt(_offset + 12, value, ByteOrder.LittleEndian);
return this;
}
public static int ResponseChannelId()
{
return 4;
}
public static string ResponseChannelCharacterEncoding()
{
return "US-ASCII";
}
public static string ResponseChannelMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int ResponseChannelHeaderLength()
{
return 4;
}
public BackupQueryEncoder PutResponseChannel(IDirectBuffer src, int srcOffset, int length)
{
if (length > 1073741824)
{
throw new InvalidOperationException("length > maxValue for type: " + length);
}
int headerLength = 4;
int limit = _parentMessage.Limit();
_parentMessage.Limit(limit + headerLength + length);
_buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian);
_buffer.PutBytes(limit + headerLength, src, srcOffset, length);
return this;
}
public BackupQueryEncoder PutResponseChannel(byte[] src, int srcOffset, int length)
{
if (length > 1073741824)
{
throw new InvalidOperationException("length > maxValue for type: " + length);
}
int headerLength = 4;
int limit = _parentMessage.Limit();
_parentMessage.Limit(limit + headerLength + length);
_buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian);
_buffer.PutBytes(limit + headerLength, src, srcOffset, length);
return this;
}
public BackupQueryEncoder ResponseChannel(string value)
{
int length = value.Length;
if (length > 1073741824)
{
throw new InvalidOperationException("length > maxValue for type: " + length);
}
int headerLength = 4;
int limit = _parentMessage.Limit();
_parentMessage.Limit(limit + headerLength + length);
_buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian);
_buffer.PutStringWithoutLengthAscii(limit + headerLength, value);
return this;
}
public static int EncodedCredentialsId()
{
return 5;
}
public static string EncodedCredentialsMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int EncodedCredentialsHeaderLength()
{
return 4;
}
public BackupQueryEncoder PutEncodedCredentials(IDirectBuffer src, int srcOffset, int length)
{
if (length > 1073741824)
{
throw new InvalidOperationException("length > maxValue for type: " + length);
}
int headerLength = 4;
int limit = _parentMessage.Limit();
_parentMessage.Limit(limit + headerLength + length);
_buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian);
_buffer.PutBytes(limit + headerLength, src, srcOffset, length);
return this;
}
public BackupQueryEncoder PutEncodedCredentials(byte[] src, int srcOffset, int length)
{
if (length > 1073741824)
{
throw new InvalidOperationException("length > maxValue for type: " + length);
}
int headerLength = 4;
int limit = _parentMessage.Limit();
_parentMessage.Limit(limit + headerLength + length);
_buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian);
_buffer.PutBytes(limit + headerLength, src, srcOffset, length);
return this;
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
BackupQueryDecoder writer = new BackupQueryDecoder();
writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION);
return writer.AppendTo(builder);
}
}
}
| |
// 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 System;
using System.Collections;
using System.Collections.Specialized;
using GenStrings;
namespace System.Collections.Specialized.Tests
{
public class SetItemObjObjTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
public void Test01()
{
IntlStrings intl;
HybridDictionary hd;
const int BIG_LENGTH = 100;
// simple string values
string[] valuesShort =
{
"",
" ",
"$%^#",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// keys for simple string values
string[] keysShort =
{
Int32.MaxValue.ToString(),
" ",
System.DateTime.Today.ToString(),
"",
"$%^#"
};
string[] valuesLong = new string[BIG_LENGTH];
string[] keysLong = new string[BIG_LENGTH];
int cnt = 0; // Count
Object itm; // Item
// initialize IntStrings
intl = new IntlStrings();
for (int i = 0; i < BIG_LENGTH; i++)
{
valuesLong[i] = "Item" + i;
keysLong[i] = "keY" + i;
}
// [] HybridDictionary is constructed as expected
//-----------------------------------------------------------------
hd = new HybridDictionary();
// [] set Item() on empty dictionary
//
cnt = hd.Count;
try
{
hd[null] = valuesShort[0];
Assert.False(true, string.Format("Error, no exception"));
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
Assert.False(true, string.Format("Error, unexpected exception: {0}", e.ToString()));
}
cnt = hd.Count;
hd["some_string"] = valuesShort[0];
if (hd.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, failed to add Item(some_string)"));
}
itm = hd["some_string"];
if (String.Compare(itm.ToString(), valuesShort[0]) != 0)
{
Assert.False(true, string.Format("Error, added wrong Item(some_string)"));
}
cnt = hd.Count;
Hashtable l = new Hashtable();
ArrayList bb = new ArrayList();
hd[l] = bb;
if (hd.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, failed to add Item(some_object)"));
}
itm = hd[l];
if (!itm.Equals(bb))
{
Assert.False(true, string.Format("Error, returned wrong Item(some_object)"));
}
// [] set Item() on short dictionary with simple strings
//
hd.Clear();
cnt = hd.Count;
int len = valuesShort.Length;
for (int i = 0; i < len; i++)
{
hd.Add(keysShort[i], valuesShort[i]);
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, valuesShort.Length));
}
//
for (int i = 0; i < len; i++)
{
cnt = hd.Count;
hd[keysShort[i]] = valuesLong[0];
if (hd.Count != cnt)
{
Assert.False(true, string.Format("Error, added item instead of setting", i));
}
itm = hd[keysShort[i]];
if (String.Compare(itm.ToString(), valuesLong[0]) != 0)
{
Assert.False(true, string.Format("Error, failed to set item", i));
}
}
// should add non-existing item
cnt = hd.Count;
hd[keysLong[0]] = valuesLong[0];
if (hd.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, didn't add non-existing item"));
}
itm = hd[keysLong[0]];
if (String.Compare(itm.ToString(), valuesLong[0]) != 0)
{
Assert.False(true, string.Format("Error, failed to set item"));
}
// [] set Item() on long dictionary with simple strings
//
hd.Clear();
cnt = hd.Count;
len = valuesLong.Length;
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i], valuesLong[i]);
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
}
//
for (int i = 0; i < len; i++)
{
cnt = hd.Count;
hd[keysLong[i]] = valuesShort[0];
if (hd.Count != cnt)
{
Assert.False(true, string.Format("Error, added item instead of setting", i));
}
itm = hd[keysLong[i]];
if (String.Compare(itm.ToString(), valuesShort[0]) != 0)
{
Assert.False(true, string.Format("Error, failed to set item", i));
}
}
// should add non-existing item
cnt = hd.Count;
hd[keysShort[0]] = valuesShort[0];
if (hd.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, didn't add non-existing item"));
}
itm = hd[keysShort[0]];
if (String.Compare(itm.ToString(), valuesShort[0]) != 0)
{
Assert.False(true, string.Format("Error, failed to set item"));
}
//
// [] set Item() on long dictionary with Intl strings
// Intl strings
//
len = valuesLong.Length;
string[] intlValues = new string[len * 2 + 1];
// fill array with unique strings
//
for (int i = 0; i < len * 2 + 1; i++)
{
string val = intl.GetRandomString(MAX_LEN);
while (Array.IndexOf(intlValues, val) != -1)
val = intl.GetRandomString(MAX_LEN);
intlValues[i] = val;
}
string toSet = intlValues[len * 2]; // string to set
cnt = hd.Count;
for (int i = 0; i < len; i++)
{
hd.Add(intlValues[i + len], intlValues[i]);
}
if (hd.Count != (cnt + len))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, cnt + len));
}
for (int i = 0; i < len; i++)
{
//
cnt = hd.Count;
hd[intlValues[i + len]] = toSet;
if (hd.Count != cnt)
{
Assert.False(true, string.Format("Error, added item instead of setting", i));
}
itm = hd[intlValues[i + len]];
if (String.Compare(itm.ToString(), toSet) != 0)
{
Assert.False(true, string.Format("Error, failed to set item", i));
}
}
// [] set Item() on short dictionary with Intl strings
//
len = valuesShort.Length;
hd.Clear();
cnt = hd.Count;
for (int i = 0; i < len; i++)
{
hd.Add(intlValues[i + len], intlValues[i]);
}
if (hd.Count != (cnt + len))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, cnt + len));
}
for (int i = 0; i < len; i++)
{
//
cnt = hd.Count;
hd[intlValues[i + len]] = toSet;
if (hd.Count != cnt)
{
Assert.False(true, string.Format("Error, added item instead of setting", i));
}
itm = hd[intlValues[i + len]];
if (String.Compare(itm.ToString(), toSet) != 0)
{
Assert.False(true, string.Format("Error, returned wrong item", i));
}
}
//
// Case sensitivity
// [] Case sensitivity - hashtable
//
len = valuesLong.Length;
hd.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i].ToUpper(), valuesLong[i].ToUpper()); // adding uppercase strings
}
//
for (int i = 0; i < len; i++)
{
// uppercase key
hd[keysLong[i].ToUpper()] = toSet;
itm = hd[keysLong[i].ToUpper()];
if (String.Compare(itm.ToString(), toSet) != 0)
{
Assert.False(true, string.Format("Error, failed to set", i));
}
}
hd.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i].ToUpper(), valuesLong[i].ToUpper()); // adding uppercase strings
}
// LD is case-sensitive by default - should add lowercase key
for (int i = 0; i < len; i++)
{
// lowercase key
cnt = hd.Count;
hd[keysLong[i].ToLower()] = toSet;
if (hd.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, failed to add when setting", i));
}
itm = hd[keysLong[i].ToLower()];
if (String.Compare(itm.ToString(), toSet) != 0)
{
Assert.False(true, string.Format("Error, failed to set item", i));
}
itm = hd[keysLong[i].ToUpper()];
if (String.Compare(itm.ToString(), valuesLong[i].ToUpper()) != 0)
{
Assert.False(true, string.Format("Error, failed to preserve item", i));
}
}
//
// [] Case sensitivity - list
len = valuesShort.Length;
hd.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i].ToUpper(), valuesLong[i].ToUpper()); // adding uppercase strings
}
//
for (int i = 0; i < len; i++)
{
// uppercase key
hd[keysLong[i].ToUpper()] = toSet;
itm = hd[keysLong[i].ToUpper()];
if (String.Compare(itm.ToString(), toSet) != 0)
{
Assert.False(true, string.Format("Error, failed to set", i));
}
}
hd.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i].ToUpper(), valuesLong[i].ToUpper()); // adding uppercase strings
}
// LD is case-sensitive by default - should add lowercase key
for (int i = 0; i < len; i++)
{
// lowercase key
cnt = hd.Count;
hd[keysLong[i].ToLower()] = toSet;
if (hd.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, failed to add when setting", i));
}
itm = hd[keysLong[i].ToLower()];
if (String.Compare(itm.ToString(), toSet) != 0)
{
Assert.False(true, string.Format("Error, failed to set item", i));
}
itm = hd[keysLong[i].ToUpper()];
if (String.Compare(itm.ToString(), valuesLong[i].ToUpper()) != 0)
{
Assert.False(true, string.Format("Error, failed to preserve item", i));
}
}
// [] set Item() on case-insensitive HD - list
//
hd = new HybridDictionary(true);
len = valuesShort.Length;
hd.Clear();
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i].ToLower(), valuesLong[i].ToLower());
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
}
for (int i = 0; i < len; i++)
{
hd[keysLong[i].ToUpper()] = toSet;
itm = hd[keysLong[i].ToUpper()];
if (String.Compare(itm.ToString(), toSet) != 0)
{
Assert.False(true, string.Format("Error, failed to set via uppercase key", i));
}
hd[keysLong[i].ToLower()] = valuesLong[0];
itm = hd[keysLong[i].ToLower()];
if (String.Compare(itm.ToString(), valuesLong[0]) != 0)
{
Assert.False(true, string.Format("Error, failed to set via lowercase key", i));
}
}
// [] set Item() on case-insensitive HD - hashtable
//
hd = new HybridDictionary(true);
len = valuesLong.Length;
hd.Clear();
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i].ToLower(), valuesLong[i].ToLower());
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
}
for (int i = 0; i < len; i++)
{
hd[keysLong[i].ToUpper()] = toSet;
itm = hd[keysLong[i].ToUpper()];
if (String.Compare(itm.ToString(), toSet) != 0)
{
Assert.False(true, string.Format("Error, failed to set via uppercase key", i));
}
hd[keysLong[i].ToLower()] = valuesLong[0];
itm = hd[keysLong[i].ToLower()];
if (String.Compare(itm.ToString(), valuesLong[0]) != 0)
{
Assert.False(true, string.Format("Error, failed to set via lowercase key", i));
}
}
//
// [] set Item(null) on filled HD - list
//
hd = new HybridDictionary();
len = valuesShort.Length;
hd.Clear();
for (int i = 0; i < len; i++)
{
hd.Add(keysShort[i], valuesShort[i]);
}
try
{
hd[null] = toSet;
Assert.False(true, string.Format("Error, no exception"));
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
Assert.False(true, string.Format("Error, unexpected exception: {0}", e.ToString()));
}
// [] set Item(null) on filled HD - hashtable
//
hd = new HybridDictionary();
len = valuesLong.Length;
hd.Clear();
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i], valuesLong[i]);
}
try
{
hd[null] = toSet;
Assert.False(true, string.Format("Error, no exception"));
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
Assert.False(true, string.Format("Error, unexpected exception: {0}", e.ToString()));
}
// [] set Item(special_object) on filled HD - list
//
hd = new HybridDictionary();
hd.Clear();
len = 2;
ArrayList[] b = new ArrayList[len];
Hashtable[] lbl = new Hashtable[len];
SortedList cb = new SortedList();
for (int i = 0; i < len; i++)
{
lbl[i] = new Hashtable();
b[i] = new ArrayList();
hd.Add(lbl[i], b[i]);
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
}
for (int i = 0; i < len; i++)
{
cnt = hd.Count;
hd[lbl[i]] = cb;
if (hd.Count != cnt)
{
Assert.False(true, string.Format("Error, added special object instead of setting"));
}
itm = hd[lbl[i]];
if (!itm.Equals(cb))
{
Assert.False(true, string.Format("Error, failed to set special object"));
}
}
cnt = hd.Count;
hd[cb] = lbl[0];
if (hd.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, failed to add non-existing special object"));
}
itm = hd[cb];
if (!itm.Equals(lbl[0]))
{
Assert.False(true, string.Format("Error, failed to set special object"));
}
// [] set Item(special_object) on filled HD - hashtable
//
hd = new HybridDictionary();
hd.Clear();
len = 40;
b = new ArrayList[len];
lbl = new Hashtable[len];
for (int i = 0; i < len; i++)
{
lbl[i] = new Hashtable();
b[i] = new ArrayList();
hd.Add(lbl[i], b[i]);
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
}
for (int i = 0; i < len; i++)
{
cnt = hd.Count;
hd[lbl[i]] = cb;
if (hd.Count != cnt)
{
Assert.False(true, string.Format("Error, added special object instead of setting"));
}
itm = hd[lbl[i]];
if (!itm.Equals(cb))
{
Assert.False(true, string.Format("Error, failed to set special object"));
}
}
cnt = hd.Count;
hd[cb] = lbl[0];
if (hd.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, failed to add non-existing special object"));
}
itm = hd[cb];
if (!itm.Equals(lbl[0]))
{
Assert.False(true, string.Format("Error, failed to set special object"));
}
// [] set Item() to null on filled HD - list
//
hd = new HybridDictionary();
hd.Clear();
len = valuesShort.Length;
for (int i = 0; i < len; i++)
{
hd.Add(keysShort[i], valuesShort[i]);
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
}
cnt = hd.Count;
hd[keysShort[0]] = null;
if (hd.Count != cnt)
{
Assert.False(true, string.Format("Error, added entry instead of setting"));
}
itm = hd[keysShort[0]];
if (itm != null)
{
Assert.False(true, string.Format("Error, failed to set to null"));
}
// [] set Item() to null on filled HD - hashtable
//
hd.Clear();
len = valuesLong.Length;
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i], valuesLong[i]);
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
}
cnt = hd.Count;
hd[keysLong[0]] = null;
if (hd.Count != cnt)
{
Assert.False(true, string.Format("Error, added entry instead of setting"));
}
itm = hd[keysLong[0]];
if (itm != null)
{
Assert.False(true, string.Format("Error, failed to set to null"));
}
}
[Fact]
public void SetItem_CaseInsensitiveDictionary_IgnoresCaseOfKey()
{
var hybridDictionary = new HybridDictionary(false);
hybridDictionary["key"] = "value";
Assert.Equal("value", hybridDictionary["key"]);
Assert.False(hybridDictionary.Contains("KEY"));
hybridDictionary = new HybridDictionary(true);
hybridDictionary["key"] = "value";
Assert.Equal("value", hybridDictionary["key"]);
Assert.Equal("value", hybridDictionary["KEY"]);
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: ErrorLogPage.cs addb64b2f0fa 2012-03-07 18:50:16Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CultureInfo = System.Globalization.CultureInfo;
using ArrayList = System.Collections.ArrayList;
#endregion
/// <summary>
/// Renders an HTML page displaying a page of errors from the error log.
/// </summary>
internal sealed class ErrorLogPage : ErrorPageBase
{
private int _pageIndex;
private int _pageSize;
private int _totalCount;
private ArrayList _errorEntryList;
private const int _defaultPageSize = 15;
private const int _maximumPageSize = 100;
protected override void OnLoad(EventArgs e)
{
//
// Get the page index and size parameters within their bounds.
//
_pageSize = Convert.ToInt32(this.Request.QueryString["size"], CultureInfo.InvariantCulture);
_pageSize = Math.Min(_maximumPageSize, Math.Max(0, _pageSize));
if (_pageSize == 0)
{
_pageSize = _defaultPageSize;
}
_pageIndex = Convert.ToInt32(this.Request.QueryString["page"], CultureInfo.InvariantCulture);
_pageIndex = Math.Max(1, _pageIndex) - 1;
//
// Read the error records.
//
_errorEntryList = new ArrayList(_pageSize);
_totalCount = this.ErrorLog.GetErrors(_pageIndex, _pageSize, _errorEntryList);
//
// Set the title of the page.
//
string hostName = Environment.TryGetMachineName(Context);
this.PageTitle = string.Format(
hostName.Length > 0
? "Error log for {0} on {2} (Page #{1})"
: "Error log for {0} (Page #{1})",
this.ApplicationName, (_pageIndex + 1).ToString("N0"), hostName);
base.OnLoad(e);
}
protected override void RenderHead(HtmlTextWriter writer)
{
if (writer == null)
throw new ArgumentNullException("writer");
base.RenderHead(writer);
//
// Write a <link> tag to relate the RSS feed.
//
#if NET_1_0 || NET_1_1
writer.AddAttribute("rel", HtmlLinkType.Alternate);
#else
writer.AddAttribute(HtmlTextWriterAttribute.Rel, HtmlLinkType.Alternate);
#endif
writer.AddAttribute(HtmlTextWriterAttribute.Type, "application/rss+xml");
writer.AddAttribute(HtmlTextWriterAttribute.Title, "RSS");
writer.AddAttribute(HtmlTextWriterAttribute.Href, this.BasePageName + "/rss");
writer.RenderBeginTag(HtmlTextWriterTag.Link);
writer.RenderEndTag();
writer.WriteLine();
//
// If on the first page, then enable auto-refresh every minute
// by issuing the following markup:
//
// <meta http-equiv="refresh" content="60">
//
if (_pageIndex == 0)
{
writer.AddAttribute("http-equiv", "refresh");
writer.AddAttribute("content", "60");
writer.RenderBeginTag(HtmlTextWriterTag.Meta);
writer.RenderEndTag();
writer.WriteLine();
}
}
protected override void RenderContents(HtmlTextWriter writer)
{
if (writer == null)
throw new ArgumentNullException("writer");
//
// Write out the page title and speed bar in the body.
//
RenderTitle(writer);
SpeedBar.Render(writer,
SpeedBar.RssFeed.Format(BasePageName),
SpeedBar.RssDigestFeed.Format(BasePageName),
SpeedBar.DownloadLog.Format(BasePageName),
SpeedBar.Help,
SpeedBar.About.Format(BasePageName));
if (_errorEntryList.Count != 0)
{
//
// Write error number range displayed on this page and the
// total available in the log, followed by stock
// page sizes.
//
writer.RenderBeginTag(HtmlTextWriterTag.P);
RenderStats(writer);
RenderStockPageSizes(writer);
writer.RenderEndTag(); // </p>
writer.WriteLine();
//
// Write out the main table to display the errors.
//
RenderErrors(writer);
//
// Write out page navigation links.
//
RenderPageNavigators(writer);
}
else
{
//
// No errors found in the log, so display a corresponding
// message.
//
RenderNoErrors(writer);
}
base.RenderContents(writer);
}
private void RenderPageNavigators(HtmlTextWriter writer)
{
Debug.Assert(writer != null);
//
// If not on the last page then render a link to the next page.
//
writer.RenderBeginTag(HtmlTextWriterTag.P);
int nextPageIndex = _pageIndex + 1;
bool moreErrors = nextPageIndex * _pageSize < _totalCount;
if (moreErrors)
RenderLinkToPage(writer, HtmlLinkType.Next, "Next errors", nextPageIndex);
//
// If not on the first page then render a link to the firs page.
//
if (_pageIndex > 0 && _totalCount > 0)
{
if (moreErrors)
writer.Write("; ");
RenderLinkToPage(writer, HtmlLinkType.Start, "Back to first page", 0);
}
writer.RenderEndTag(); // </p>
writer.WriteLine();
}
private void RenderStockPageSizes(HtmlTextWriter writer)
{
Debug.Assert(writer != null);
//
// Write out a set of stock page size choices. Note that
// selecting a stock page size re-starts the log
// display from the first page to get the right paging.
//
writer.Write("Start with ");
int[] stockSizes = new int[] { 10, 15, 20, 25, 30, 50, 100 };
for (int stockSizeIndex = 0; stockSizeIndex < stockSizes.Length; stockSizeIndex++)
{
int stockSize = stockSizes[stockSizeIndex];
if (stockSizeIndex > 0)
writer.Write(stockSizeIndex + 1 < stockSizes.Length ? ", " : " or ");
RenderLinkToPage(writer, HtmlLinkType.Start, stockSize.ToString(), 0, stockSize);
}
writer.Write(" errors per page.");
}
private void RenderStats(HtmlTextWriter writer)
{
Debug.Assert(writer != null);
int firstErrorNumber = _pageIndex * _pageSize + 1;
int lastErrorNumber = firstErrorNumber + _errorEntryList.Count - 1;
int totalPages = (int) Math.Ceiling((double) _totalCount / _pageSize);
writer.Write("Errors {0} to {1} of total {2} (page {3} of {4}). ",
firstErrorNumber.ToString("N0"),
lastErrorNumber.ToString("N0"),
_totalCount.ToString("N0"),
(_pageIndex + 1).ToString("N0"),
totalPages.ToString("N0"));
}
private void RenderTitle(HtmlTextWriter writer)
{
Debug.Assert(writer != null);
//
// If the application name matches the APPL_MD_PATH then its
// of the form /LM/W3SVC/.../<name>. In this case, use only the
// <name> part to reduce the noise. The full application name is
// still made available through a tooltip.
//
string simpleName = this.ApplicationName;
if (string.Compare(simpleName, this.Request.ServerVariables["APPL_MD_PATH"],
true, CultureInfo.InvariantCulture) == 0)
{
int lastSlashIndex = simpleName.LastIndexOf('/');
if (lastSlashIndex > 0)
simpleName = simpleName.Substring(lastSlashIndex + 1);
}
writer.AddAttribute(HtmlTextWriterAttribute.Id, "PageTitle");
writer.RenderBeginTag(HtmlTextWriterTag.H1);
writer.Write("Error Log for ");
writer.AddAttribute(HtmlTextWriterAttribute.Id, "ApplicationName");
writer.AddAttribute(HtmlTextWriterAttribute.Title, this.Server.HtmlEncode(this.ApplicationName));
writer.RenderBeginTag(HtmlTextWriterTag.Span);
Server.HtmlEncode(simpleName, writer);
string hostName = Environment.TryGetMachineName(Context);
if (hostName.Length > 0)
{
writer.Write(" on ");
Server.HtmlEncode(hostName, writer);
}
writer.RenderEndTag(); // </span>
writer.RenderEndTag(); // </h1>
writer.WriteLine();
}
private void RenderNoErrors(HtmlTextWriter writer)
{
Debug.Assert(writer != null);
writer.RenderBeginTag(HtmlTextWriterTag.P);
writer.Write("No errors found. ");
//
// It is possible that there are no error at the requested
// page in the log (especially if it is not the first page).
// However, if there are error in the log
//
if (_pageIndex > 0 && _totalCount > 0)
{
RenderLinkToPage(writer, HtmlLinkType.Start, "Go to first page", 0);
writer.Write(". ");
}
writer.RenderEndTag();
writer.WriteLine();
}
private void RenderErrors(HtmlTextWriter writer)
{
Debug.Assert(writer != null);
//
// Create a table to display error information in each row.
//
Table table = new Table();
table.ID = "ErrorLog";
table.CellSpacing = 0;
//
// Create the table row for headings.
//
TableRow headRow = new TableRow();
headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Host", "host-col"));
headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Application", "app-col"));
headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Code", "code-col"));
headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Type", "type-col"));
headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Error", "error-col"));
headRow.Cells.Add(FormatCell(new TableHeaderCell(), "User", "user-col"));
headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Date", "date-col"));
headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Time", "time-col"));
table.Rows.Add(headRow);
//
// Generate a table body row for each error.
//
for (int errorIndex = 0; errorIndex < _errorEntryList.Count; errorIndex++)
{
ErrorLogEntry errorEntry = (ErrorLogEntry) _errorEntryList[errorIndex];
Error error = errorEntry.Error;
TableRow bodyRow = new TableRow();
bodyRow.CssClass = errorIndex % 2 == 0 ? "even-row" : "odd-row";
//
// Format host and status code cells.
//
bodyRow.Cells.Add(FormatCell(new TableCell(), error.HostName, "host-col"));
bodyRow.Cells.Add(FormatCell(new TableCell(), error.ApplicationName, "app-col"));
bodyRow.Cells.Add(FormatCell(new TableCell(), error.StatusCode.ToString(), "code-col", Mask.NullString(HttpWorkerRequest.GetStatusDescription(error.StatusCode))));
bodyRow.Cells.Add(FormatCell(new TableCell(), ErrorDisplay.HumaneExceptionErrorType(error), "type-col", error.Type));
//
// Format the message cell, which contains the message
// text and a details link pointing to the page where
// all error details can be viewed.
//
TableCell messageCell = new TableCell();
messageCell.CssClass = "error-col";
Label messageLabel = new Label();
messageLabel.Text = this.Server.HtmlEncode(error.Message);
HyperLink detailsLink = new HyperLink();
detailsLink.NavigateUrl = BasePageName + "/detail?id=" + HttpUtility.UrlEncode(errorEntry.Id);
detailsLink.Text = "Details…";
messageCell.Controls.Add(messageLabel);
messageCell.Controls.Add(new LiteralControl(" "));
messageCell.Controls.Add(detailsLink);
bodyRow.Cells.Add(messageCell);
//
// Format the user, date and time cells.
//
bodyRow.Cells.Add(FormatCell(new TableCell(), error.User, "user-col"));
bodyRow.Cells.Add(FormatCell(new TableCell(), error.Time.ToShortDateString(), "date-col",
error.Time.ToLongDateString()));
bodyRow.Cells.Add(FormatCell(new TableCell(), error.Time.ToShortTimeString(), "time-col",
error.Time.ToLongTimeString()));
//
// Finally, add the row to the table.
//
table.Rows.Add(bodyRow);
}
table.RenderControl(writer);
}
private TableCell FormatCell(TableCell cell, string contents, string cssClassName)
{
return FormatCell(cell, contents, cssClassName, string.Empty);
}
private TableCell FormatCell(TableCell cell, string contents, string cssClassName, string toolTip)
{
Debug.Assert(cell != null);
Debug.AssertStringNotEmpty(cssClassName);
cell.Wrap = false;
cell.CssClass = cssClassName;
if (contents.Length == 0)
{
cell.Text = " ";
}
else
{
string encodedContents = this.Server.HtmlEncode(contents);
if (toolTip.Length == 0)
{
cell.Text = encodedContents;
}
else
{
Label label = new Label();
label.ToolTip = toolTip;
label.Text = encodedContents;
cell.Controls.Add(label);
}
}
return cell;
}
private void RenderLinkToPage(HtmlTextWriter writer, string type, string text, int pageIndex)
{
RenderLinkToPage(writer, type, text, pageIndex, _pageSize);
}
private void RenderLinkToPage(HtmlTextWriter writer, string type, string text, int pageIndex, int pageSize)
{
Debug.Assert(writer != null);
Debug.Assert(text != null);
Debug.Assert(pageIndex >= 0);
Debug.Assert(pageSize >= 0);
string href = string.Format("{0}?page={1}&size={2}",
BasePageName,
(pageIndex + 1).ToString(CultureInfo.InvariantCulture),
pageSize.ToString(CultureInfo.InvariantCulture));
writer.AddAttribute(HtmlTextWriterAttribute.Href, href);
if (type != null && type.Length > 0)
#if NET_1_0 || NET_1_1
writer.AddAttribute("rel", type);
#else
writer.AddAttribute(HtmlTextWriterAttribute.Rel, type);
#endif
writer.RenderBeginTag(HtmlTextWriterTag.A);
this.Server.HtmlEncode(text, writer);
writer.RenderEndTag();
}
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
namespace Krs.Ats.IBNet
{
/// <summary>
/// Class to describe a financial security.
/// </summary>
/// <seealso href="http://www.interactivebrokers.com/php/apiUsersGuide/apiguide/java/contract.htm">Interactive Brokers Contract Documentation</seealso>
[Serializable()]
public class Contract
{
#region Private Variables
private Collection<ComboLeg> comboLegs = new Collection<ComboLeg>();
private int contractId;
private String comboLegsDescription; // received in open order version 14 and up for all combos
private String currency;
private String exchange;
private String expiry;
private bool includeExpired; // can not be set to true for orders.
private String localSymbol;
private String multiplier;
private SecurityIdType secIdType; // CUSIP;SEDOL;ISIN;RIC
private String secId;
private String primaryExchange;
// pick a non-aggregate (ie not the SMART exchange) exchange that the contract trades on. DO NOT SET TO SMART.
private RightType right;
private SecurityType securityType;
private double strike;
private String symbol;
private UnderlyingComponent underlyingComponent;
private string tradingClass;
#endregion
#region Constructors
///<summary>
/// Undefined Contract Constructor
///</summary>
public Contract() :
this(0, null, SecurityType.Undefined, null, 0, RightType.Undefined, null, null, null, null, null, SecurityIdType.None, string.Empty)
{
}
/// <summary>
/// Futures Contract Constructor
/// </summary>
/// <param name="symbol">This is the symbol of the underlying asset.</param>
/// <param name="exchange">The order destination, such as Smart.</param>
/// <param name="securityType">This is the security type.</param>
/// <param name="currency">Specifies the currency.</param>
/// <param name="expiry">The expiration date. Use the format YYYYMM.</param>
public Contract(string symbol, string exchange, SecurityType securityType, string currency, string expiry) :
this(0, symbol, securityType, expiry, 0, RightType.Undefined, null, exchange, currency, null, null, SecurityIdType.None, string.Empty)
{
}
/// <summary>
/// Indice Contract Constructor
/// </summary>
/// <param name="symbol">This is the symbol of the underlying asset.</param>
/// <param name="exchange">The order destination, such as Smart.</param>
/// <param name="securityType">This is the security type.</param>
/// <param name="currency">Specifies the currency.</param>
public Contract(string symbol, string exchange, SecurityType securityType, string currency)
:
this(0, symbol, securityType, null, 0, RightType.Undefined, null, exchange, currency, null, null, SecurityIdType.None, string.Empty)
{
}
/// <summary>
/// Default Contract Constructor
/// </summary>
/// <param name="contractId">The unique contract identifier.</param>
/// <param name="symbol">This is the symbol of the underlying asset.</param>
/// <param name="securityType">This is the security type.</param>
/// <param name="expiry">The expiration date. Use the format YYYYMM.</param>
/// <param name="strike">The strike price.</param>
/// <param name="right">Specifies a Put or Call.</param>
/// <param name="multiplier">Allows you to specify a future or option contract multiplier.
/// This is only necessary when multiple possibilities exist.</param>
/// <param name="exchange">The order destination, such as Smart.</param>
/// <param name="currency">Specifies the currency.</param>
/// <param name="localSymbol">This is the local exchange symbol of the underlying asset.</param>
/// <param name="primaryExchange">Identifies the listing exchange for the contract (do not list SMART).</param>
/// <param name="secIdType">Security identifier, when querying contract details or when placing orders.</param>
/// <param name="secId">Unique identifier for the secIdType.</param>
public Contract(int contractId, String symbol, SecurityType securityType, String expiry, double strike, RightType right,
String multiplier, string exchange, string currency, string localSymbol, string primaryExchange,
SecurityIdType secIdType, string secId)
{
this.contractId = contractId;
this.symbol = symbol;
this.securityType = securityType;
this.expiry = expiry;
this.strike = strike;
this.right = right;
this.multiplier = multiplier;
this.exchange = exchange;
this.currency = currency;
this.localSymbol = localSymbol;
this.primaryExchange = primaryExchange;
this.secIdType = secIdType;
this.secId = secId;
}
/// <summary>
/// Get a Contract by its unique contractId
/// </summary>
/// <param name="contractId"></param>
public Contract(int contractId)
{
this.contractId = contractId;
}
#endregion
#region Properties
/// <summary>
/// This is the symbol of the underlying asset.
/// </summary>
public string Symbol
{
get { return symbol; }
set { symbol = value; }
}
/// <summary>
/// This is the security type.
/// </summary>
/// <remarks>Valid security types are:
/// <list type="bullet">
/// <item>Stock</item>
/// <item>Option</item>
/// <item>Future</item>
/// <item>Indice</item>
/// <item>Option on Future</item>
/// <item>Cash</item>
/// <item>Bag</item>
/// <item>Bond</item>
/// </list>
/// </remarks>
/// <seealso cref="IBNet.SecurityType"/>
public SecurityType SecurityType
{
get { return securityType; }
set { securityType = value; }
}
/// <summary>
/// The expiration date. Use the format YYYYMM or YYYYMMDD.
/// </summary>
public string Expiry
{
get { return expiry; }
set { expiry = value; }
}
/// <summary>
/// The strike price.
/// </summary>
public double Strike
{
get { return strike; }
set { strike = value; }
}
/// <summary>
/// Specifies a Put or Call.
/// </summary>
/// <remarks>Valid values are:
/// <list type="bullet">
/// <item>Put - the right to sell a security.</item>
/// <item>Call - the right to buy a security.</item>
/// </list>
/// </remarks>
/// <seealso cref="RightType"/>
public RightType Right
{
get { return right; }
set { right = value; }
}
/// <summary>
/// Allows you to specify a future or option contract multiplier.
/// This is only necessary when multiple possibilities exist.
/// </summary>
public string Multiplier
{
get { return multiplier; }
set { multiplier = value; }
}
/// <summary>
/// The order destination, such as Smart.
/// </summary>
public string Exchange
{
get { return exchange; }
set { exchange = value; }
}
/// <summary>
/// Specifies the currency.
/// </summary>
/// <remarks>
/// Ambiguities may require that this field be specified,
/// for example, when SMART is the exchange and IBM is being requested
/// (IBM can trade in GBP or USD). Given the existence of this kind of ambiguity,
/// it is a good idea to always specify the currency.
/// </remarks>
public string Currency
{
get { return currency; }
set { currency = value; }
}
/// <summary>
/// This is the local exchange symbol of the underlying asset.
/// </summary>
public string LocalSymbol
{
get { return localSymbol; }
set { localSymbol = value; }
}
/// <summary>
/// Identifies the listing exchange for the contract (do not list SMART).
/// </summary>
public string PrimaryExchange
{
get { return primaryExchange; }
set { primaryExchange = value; }
}
/// <summary>
/// If set to true, contract details requests and historical data queries
/// can be performed pertaining to expired contracts.
///
/// Historical data queries on expired contracts are limited to the
/// last year of the contracts life, and are initially only supported for
/// expired futures contracts,
/// </summary>
public bool IncludeExpired
{
get { return includeExpired; }
set { includeExpired = value; }
}
/// <summary>
/// Description for combo legs
/// </summary>
public string ComboLegsDescription
{
get { return comboLegsDescription; }
set { comboLegsDescription = value; }
}
/// <summary>
/// Dynamic memory structure used to store the leg definitions for this contract.
/// </summary>
public Collection<ComboLeg> ComboLegs
{
get { return comboLegs; }
set { comboLegs = value; }
}
/// <summary>
/// The unique contract identifier.
/// </summary>
public int ContractId
{
get { return contractId; }
set { contractId = value; }
}
/// <summary>
/// Underlying Component
/// </summary>
public UnderlyingComponent UnderlyingComponent
{
get { return underlyingComponent; }
set { underlyingComponent = value; }
}
/// <summary>
/// Security identifier, when querying contract details or when placing orders. Supported identifiers are:
/// ISIN (Example: Apple: US0378331005)
/// CUSIP (Example: Apple: 037833100)
/// SEDOL (Consists of 6-AN + check digit. Example: BAE: 0263494)
/// RIC (Consists of exchange-independent RIC Root and a suffix identifying the exchange. Example: AAPL.O for Apple on NASDAQ.)
/// </summary>
public SecurityIdType SecIdType
{
get { return secIdType; }
set { secIdType = value; }
}
/// <summary>
/// Unique identifier for the secIdType.
/// </summary>
public String SecId
{
get
{
return secId;
}
set
{
secId = value;
}
}
/// <summary>
/// The trading class name for this contract.
/// Available in TWS contract description window as well.For example, GBL Dec '13 future's trading class is "FGBL"
/// </summary>
public string TradingClass
{
get { return tradingClass; }
set { tradingClass = value; }
}
#endregion
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2013 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
#if !UNITY_IOS
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using MsgPack.Serialization.Reflection;
namespace MsgPack.Serialization.EmittingSerializers
{
// Reduce JIT
/// <summary>
/// Defines non-generic functions of <see cref="EmittingSerializerBuilder{T}"/>.
/// </summary>
internal static class EmittingSerializerBuilderLogics
{
private static readonly Type[] _delegateConstructorParameterTypes = new Type[] { typeof( object ), typeof( IntPtr ) };
#region -- Arrays --
public static SerializerEmitter CreateArraySerializerCore( SerializationContext context, Type targetType, EmitterFlavor emitterFlavor )
{
Contract.Requires( targetType != null );
Contract.Ensures( Contract.Result<SerializerEmitter>() != null );
var emitter = SerializationMethodGeneratorManager.Get().CreateEmitter( targetType, emitterFlavor );
var traits = targetType.GetCollectionTraits();
CreatePackArrayProceduresCore( targetType, emitter, traits );
CreateUnpackArrayProceduresCore( context, targetType, emitter, traits );
return emitter;
}
private static void CreatePackArrayProceduresCore( Type targetType, SerializerEmitter emitter, CollectionTraits traits )
{
var il = emitter.GetPackToMethodILGenerator();
var localHolder = new LocalVariableHolder( il );
try
{
// Array
if ( targetType.IsArray )
{
/*
* // array
* packer.PackArrayHeader( length );
* for( int i = 0; i < length; i++ )
* {
* this._serializer.PackTo( packer, collection[ i ] );
* }
*/
var length = localHolder.PackingCollectionCount;
il.EmitAnyLdarg( 2 );
il.EmitLdlen();
il.EmitAnyStloc( length );
il.EmitAnyLdarg( 1 );
il.EmitAnyLdloc( length );
il.EmitAnyCall( Metadata._Packer.PackArrayHeader );
il.EmitPop();
Emittion.EmitFor(
il,
length,
( il0, i ) =>
Emittion.EmitSerializeValue(
emitter,
il0,
1,
traits.ElementType,
null,
NilImplication.MemberDefault,
il1 =>
{
il1.EmitAnyLdarg( 2 );
il1.EmitAnyLdloc( i );
il1.EmitLdelem( traits.ElementType );
},
localHolder
)
);
}
else if ( traits.CountProperty == null )
{
/*
* array = collection.ToArray();
* packer.PackArrayHeader( length );
* for( int i = 0; i < length; i++ )
* {
* this._serializer.PackTo( packer, array[ i ] );
* }
*/
var array = localHolder.GetSerializingCollection( traits.ElementType.MakeArrayType() );
EmitLoadTarget( targetType, il, 2 );
il.EmitAnyCall( Metadata._Enumerable.ToArray1Method.MakeGenericMethod( traits.ElementType ) );
il.EmitAnyStloc( array );
var length = localHolder.PackingCollectionCount;
il.EmitAnyLdloc( array );
il.EmitLdlen();
il.EmitAnyStloc( length );
il.EmitAnyLdarg( 1 );
il.EmitAnyLdloc( length );
il.EmitAnyCall( Metadata._Packer.PackArrayHeader );
il.EmitPop();
Emittion.EmitFor(
il,
length,
( il0, i ) =>
Emittion.EmitSerializeValue(
emitter,
il0,
1,
traits.ElementType,
null,
NilImplication.MemberDefault,
il1 =>
{
il1.EmitAnyLdloc( array );
il1.EmitAnyLdloc( i );
il1.EmitLdelem( traits.ElementType );
},
localHolder
)
);
}
else
{
/*
* // Enumerable
* packer.PackArrayHeader( collection.Count );
* foreach( var item in list )
* {
* this._serializer.PackTo( packer, array[ i ] );
* }
*/
var collection = localHolder.GetSerializingCollection( targetType );
// This instruction always ldarg, not to be ldarga
il.EmitAnyLdarg( 2 );
il.EmitAnyStloc( collection );
var count = localHolder.PackingCollectionCount;
EmitLoadTarget( targetType, il, 2 );
il.EmitGetProperty( traits.CountProperty );
il.EmitAnyStloc( count );
il.EmitAnyLdarg( 1 );
il.EmitAnyLdloc( count );
il.EmitAnyCall( Metadata._Packer.PackArrayHeader );
il.EmitPop();
Emittion.EmitForEach(
il,
traits,
collection,
( il0, getCurrentEmitter ) =>
Emittion.EmitSerializeValue(
emitter,
il0,
1,
traits.ElementType,
null,
NilImplication.MemberDefault,
_ => getCurrentEmitter(),
localHolder
)
);
}
il.EmitRet();
}
finally
{
il.FlushTrace();
}
}
private static void CreateUnpackArrayProceduresCore( SerializationContext context, Type targetType, SerializerEmitter emitter, CollectionTraits traits )
{
CreateArrayUnpackFrom( context, targetType, emitter, traits );
CreateArrayUnpackTo( targetType, emitter, traits );
}
private static void CreateArrayUnpackFrom( SerializationContext context, Type targetType, SerializerEmitter emitter, CollectionTraits traits )
{
var il = emitter.GetUnpackFromMethodILGenerator();
var localHolder = new LocalVariableHolder( il );
var instanceType = targetType;
try
{
if ( targetType.IsInterface || targetType.IsAbstract )
{
instanceType = context.DefaultCollectionTypes.GetConcreteType( targetType );
if ( instanceType == null )
{
il.EmitTypeOf( targetType );
il.EmitAnyCall( SerializationExceptions.NewNotSupportedBecauseCannotInstanciateAbstractTypeMethod );
il.EmitThrow();
return;
}
}
/*
* if (!unpacker.IsArrayHeader)
* {
* throw SerializationExceptions.NewIsNotArrayHeader();
* }
*
* TCollection collection = new ...;
* this.UnpackToCore(unpacker, array);
* return collection;
*/
il.EmitAnyLdarg( 1 );
il.EmitGetProperty( Metadata._Unpacker.IsArrayHeader );
var endIf = il.DefineLabel( "END_IF" );
il.EmitBrtrue_S( endIf );
il.EmitAnyCall( SerializationExceptions.NewIsNotArrayHeaderMethod );
il.EmitThrow();
il.MarkLabel( endIf );
var collection = localHolder.GetDeserializingCollection( instanceType );
// Emit newobj, newarr, or call ValueType..ctor()
Emittion.EmitConstruction(
il,
collection,
il0 => Emittion.EmitGetUnpackerItemsCountAsInt32( il0, 1, localHolder )
);
EmitInvokeArrayUnpackToHelper( targetType, emitter, traits, il, 1, il0 => il0.EmitAnyLdloc( collection ) );
il.EmitAnyLdloc( collection );
il.EmitRet();
}
finally
{
il.FlushTrace();
}
}
private static void CreateArrayUnpackTo( Type targetType, SerializerEmitter emitter, CollectionTraits traits )
{
var il = emitter.GetUnpackToMethodILGenerator();
try
{
EmitInvokeArrayUnpackToHelper( targetType, emitter, traits, il, 1, il0 => il0.EmitAnyLdarg( 2 ) );
il.EmitRet();
}
finally
{
il.FlushTrace();
}
}
private static void EmitInvokeArrayUnpackToHelper( Type targetType, SerializerEmitter emitter, CollectionTraits traits, TracingILGenerator il, int unpackerArgumentIndex, Action<TracingILGenerator> loadCollectionEmitting )
{
il.EmitAnyLdarg( unpackerArgumentIndex );
var serializerGetting = emitter.RegisterSerializer( traits.ElementType );
if ( targetType.IsArray )
{
// Array
/*
* UnpackHelpers.UnpackArrayTo( unpacker, GET_SERIALIZER, collection );
*/
serializerGetting( il, 0 );
loadCollectionEmitting( il );
il.EmitAnyCall( Metadata._UnpackHelpers.UnpackArrayTo_1.MakeGenericMethod( traits.ElementType ) );
}
else if ( targetType.IsGenericType )
{
serializerGetting( il, 0 );
loadCollectionEmitting( il );
if ( targetType.IsValueType )
{
il.EmitBox( targetType );
}
if ( traits.AddMethod.ReturnType == null || traits.AddMethod.ReturnType == typeof( void ) )
{
// with void Add( T item )
/*
* Action<T> addition = TCollection.Add
* UnpackHelpers.UnpackCollectionTo( unpacker, GET_SERIALIZER, collection, addition );
*/
var itemType = traits.AddMethod.GetParameters()[ 0 ].ParameterType;
EmitNewDelegate( il, targetType, traits.AddMethod, loadCollectionEmitting, typeof( Action<> ).MakeGenericType( itemType ) );
il.EmitAnyCall( Metadata._UnpackHelpers.UnpackCollectionTo_1.MakeGenericMethod( itemType ) );
}
else
{
// with TDiscarded Add( T item )
/*
* Func<T, TDiscarded> addition = TCollection.Add
* UnpackHelpers.UnpackCollectionTo( unpacker, GET_SERIALIZER, collection, addition );
*/
var itemType = traits.AddMethod.GetParameters()[ 0 ].ParameterType;
var discardingType = traits.AddMethod.ReturnType;
EmitNewDelegate( il, targetType, traits.AddMethod, loadCollectionEmitting, typeof( Func<,> ).MakeGenericType( itemType, discardingType ) );
il.EmitAnyCall( Metadata._UnpackHelpers.UnpackCollectionTo_2.MakeGenericMethod( itemType, discardingType ) );
}
}
else
{
loadCollectionEmitting( il );
if ( targetType.IsValueType )
{
il.EmitBox( targetType );
}
if ( traits.AddMethod.ReturnType == null || traits.AddMethod.ReturnType == typeof( void ) )
{
// with void Add( object item )
/*
* Action<object> addition = TCollection.Add
* UnpackHelpers.UnpackCollectionTo( unpacker, collection, addition );
*/
EmitNewDelegate( il, targetType, traits.AddMethod, loadCollectionEmitting, typeof( Action<object> ) );
il.EmitAnyCall( Metadata._UnpackHelpers.UnpackNonGenericCollectionTo );
}
else
{
// with TDiscarded Add( object item )
/*
* Func<TDiscarded> addition = TCollection.Add
* UnpackHelpers.UnpackCollectionTo( unpacker, collection, addition );
*/
var discardingType = traits.AddMethod.ReturnType;
EmitNewDelegate( il, targetType, traits.AddMethod, loadCollectionEmitting, typeof( Func<,> ).MakeGenericType( typeof( object ), discardingType ) );
il.EmitAnyCall( Metadata._UnpackHelpers.UnpackNonGenericCollectionTo_1.MakeGenericMethod( discardingType ) );
}
}
}
private static void EmitNewDelegate( TracingILGenerator il, Type targetType, MethodInfo method, Action<TracingILGenerator> loadTargetEmitting, Type delegateType )
{
loadTargetEmitting( il );
if ( targetType.IsValueType )
{
il.EmitBox( targetType );
}
if ( method.IsStatic || method.IsFinal || !method.IsVirtual )
{
il.EmitLdftn( method );
}
else
{
il.EmitDup();
il.EmitLdvirtftn( method );
}
il.EmitNewobj( delegateType.GetConstructor( _delegateConstructorParameterTypes ) );
}
#endregion -- Arrays --
#region -- Maps --
public static SerializerEmitter CreateMapSerializerCore( SerializationContext context, Type targetType, EmitterFlavor emitterFlavor )
{
Contract.Requires( targetType != null );
Contract.Ensures( Contract.Result<SerializerEmitter>() != null );
var emitter = SerializationMethodGeneratorManager.Get().CreateEmitter( targetType, emitterFlavor );
var traits = targetType.GetCollectionTraits();
CreateMapPack(
targetType,
emitter,
traits
);
CreateMapUnpack(
context,
targetType,
emitter,
traits
);
return emitter;
}
private static void CreateMapPack( Type targetType, SerializerEmitter emiter, CollectionTraits traits )
{
var il = emiter.GetPackToMethodILGenerator();
var localHolder = new LocalVariableHolder( il );
try
{
/*
* int count = ((ICollection<KeyValuePair<string, DateTime>>)dictionary).Count;
* packer.PackMapHeader(count);
* foreach (KeyValuePair<string, DateTime> current in dictionary)
* {
* this._serializer0.PackTo(packer, current.Key);
* this._serializer1.PackTo(packer, current.Value);
* }
*/
var collection = localHolder.GetSerializingCollection( targetType );
var item = localHolder.GetSerializingCollectionItem( traits.ElementType );
var keyProperty = traits.ElementType.GetProperty( "Key" );
var valueProperty = traits.ElementType.GetProperty( "Value" );
// This instruction is always ldarg, not to be ldarga.
il.EmitAnyLdarg( 2 );
il.EmitAnyStloc( collection );
var count = localHolder.PackingCollectionCount;
EmitLoadTarget( targetType, il, collection );
il.EmitGetProperty( traits.CountProperty );
il.EmitAnyStloc( count );
il.EmitAnyLdarg( 1 );
il.EmitAnyLdloc( count );
il.EmitAnyCall( Metadata._Packer.PackMapHeader );
il.EmitPop();
Emittion.EmitForEach(
il,
traits,
collection,
( il0, getCurrentEmitter ) =>
{
if ( traits.ElementType.IsGenericType )
{
Contract.Assert( traits.ElementType.GetGenericTypeDefinition() == typeof( KeyValuePair<,> ) );
getCurrentEmitter();
il0.EmitAnyStloc( item );
Emittion.EmitSerializeValue(
emiter,
il0,
1,
traits.ElementType.GetGenericArguments()[ 0 ],
null,
NilImplication.MemberDefault,
il1 =>
{
il1.EmitAnyLdloca( item );
il1.EmitGetProperty( keyProperty );
},
localHolder
);
Emittion.EmitSerializeValue(
emiter,
il0,
1,
traits.ElementType.GetGenericArguments()[ 1 ],
null,
NilImplication.MemberDefault,
il1 =>
{
il1.EmitAnyLdloca( item );
il1.EmitGetProperty( valueProperty );
},
localHolder
);
}
else
{
Contract.Assert( traits.ElementType == typeof( DictionaryEntry ) );
getCurrentEmitter();
il0.EmitAnyStloc( item );
Emittion.EmitSerializeValue(
emiter,
il0,
1,
typeof( MessagePackObject ),
null,
NilImplication.MemberDefault,
il1 =>
{
il0.EmitAnyLdloca( item );
il0.EmitGetProperty( Metadata._DictionaryEntry.Key );
il0.EmitUnbox_Any( typeof( MessagePackObject ) );
},
localHolder
);
Emittion.EmitSerializeValue(
emiter,
il0,
1,
typeof( MessagePackObject ),
null,
NilImplication.MemberDefault,
il1 =>
{
il0.EmitAnyLdloca( item );
il0.EmitGetProperty( Metadata._DictionaryEntry.Value );
il0.EmitUnbox_Any( typeof( MessagePackObject ) );
},
localHolder
);
}
}
);
il.EmitRet();
}
finally
{
il.FlushTrace();
}
}
private static void CreateMapUnpack( SerializationContext context, Type targetType, SerializerEmitter emitter, CollectionTraits traits )
{
CreateMapUnpackFrom( context, targetType, emitter, traits );
CreateMapUnpackTo( targetType, emitter, traits );
}
private static void CreateMapUnpackFrom( SerializationContext context, Type targetType, SerializerEmitter emitter, CollectionTraits traits )
{
var il = emitter.GetUnpackFromMethodILGenerator();
var localHolder = new LocalVariableHolder( il );
var instanceType = targetType;
try
{
/*
* if (!unpacker.IsMapHeader)
* {
* throw SerializationExceptions.NewIsNotMapHeader();
* }
*
* TDictionary<TKey, TValue> dictionary = new ...;
* this.UnpackToCore(unpacker, dictionary);
* return dictionary;
*/
if ( targetType.IsInterface || targetType.IsAbstract )
{
instanceType = context.DefaultCollectionTypes.GetConcreteType( targetType );
if( instanceType == null )
{
il.EmitTypeOf( targetType );
il.EmitAnyCall( SerializationExceptions.NewNotSupportedBecauseCannotInstanciateAbstractTypeMethod );
il.EmitThrow();
return;
}
}
il.EmitAnyLdarg( 1 );
il.EmitGetProperty( Metadata._Unpacker.IsMapHeader );
var endIf = il.DefineLabel( "END_IF" );
il.EmitBrtrue_S( endIf );
il.EmitAnyCall( SerializationExceptions.NewIsNotMapHeaderMethod );
il.EmitThrow();
il.MarkLabel( endIf );
var collection = localHolder.GetDeserializingCollection( instanceType );
Emittion.EmitConstruction(
il,
collection,
il0 => Emittion.EmitGetUnpackerItemsCountAsInt32( il0, 1, localHolder )
);
EmitInvokeMapUnpackToHelper( targetType, emitter, traits, il, 1, il0 => il0.EmitAnyLdloc( collection ) );
il.EmitAnyLdloc( collection );
il.EmitRet();
}
finally
{
il.FlushTrace();
}
}
private static void CreateMapUnpackTo( Type targetType, SerializerEmitter emitter, CollectionTraits traits )
{
var il = emitter.GetUnpackToMethodILGenerator();
try
{
EmitInvokeMapUnpackToHelper( targetType, emitter, traits, il, 1, il0 => il0.EmitAnyLdarg( 2 ) );
il.EmitRet();
}
finally
{
il.FlushTrace();
}
}
private static void EmitInvokeMapUnpackToHelper( Type targetType, SerializerEmitter emitter, CollectionTraits traits, TracingILGenerator il, int unpackerArgumentIndex, Action<TracingILGenerator> loadCollectionEmitting )
{
il.EmitAnyLdarg( unpackerArgumentIndex );
if ( traits.ElementType.IsGenericType )
{
var keyType = traits.ElementType.GetGenericArguments()[ 0 ];
var valueType = traits.ElementType.GetGenericArguments()[ 1 ];
var keySerializerGetting = emitter.RegisterSerializer( keyType );
var valueSerializerGetting = emitter.RegisterSerializer( valueType );
keySerializerGetting( il, 0 );
valueSerializerGetting( il, 0 );
loadCollectionEmitting( il );
if ( targetType.IsValueType )
{
il.EmitBox( targetType );
}
il.EmitAnyCall( Metadata._UnpackHelpers.UnpackMapTo_2.MakeGenericMethod( keyType, valueType ) );
}
else
{
loadCollectionEmitting( il );
if ( targetType.IsValueType )
{
il.EmitBox( targetType );
}
il.EmitAnyCall( Metadata._UnpackHelpers.UnpackNonGenericMapTo );
}
}
#endregion -- Maps --
#region -- Miscs --
private static void EmitLoadTarget( Type targetType, TracingILGenerator il, int parameterIndex )
{
if ( targetType.IsValueType )
{
il.EmitAnyLdarga( parameterIndex );
}
else
{
il.EmitAnyLdarg( parameterIndex );
}
}
private static void EmitLoadTarget( Type targetType, TracingILGenerator il, LocalBuilder local )
{
if ( targetType.IsValueType )
{
il.EmitAnyLdloca( local );
}
else
{
il.EmitAnyLdloc( local );
}
}
#endregion -- Miscs --
}
}
#endif
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace SharpDX.XAudio2
{
public partial class XAudio2
{
private EngineCallbackImpl engineCallbackImpl;
private IntPtr engineShadowPtr;
///// <summary>Constant None.</summary>
private static Guid CLSID_XAudio27 = new Guid("5a508685-a254-4fba-9b82-9a24b00306af");
///// <summary>Constant None.</summary>
private static Guid CLSID_XAudio27_Debug = new Guid("db05ea35-0329-4d4b-a53a-6dead03d3852");
///// <summary>Constant None.</summary>
private static Guid IID_IXAudio2 = new Guid("8bcf1f58-9fe7-4583-8ac6-e2adc465c8bb");
/// <summary>
/// Called by XAudio2 just before an audio processing pass begins.
/// </summary>
public event EventHandler ProcessingPassStart;
/// <summary>
/// Called by XAudio2 just after an audio processing pass ends.
/// </summary>
public event EventHandler ProcessingPassEnd;
/// <summary>
/// Called if a critical system error occurs that requires XAudio2 to be closed down and restarted.
/// </summary>
public event EventHandler<ErrorEventArgs> CriticalError;
/// <summary>
/// Initializes a new instance of the <see cref="XAudio2"/> class.
/// </summary>
public XAudio2()
: this(XAudio2Version.Default)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="XAudio2" /> class.
/// </summary>
/// <param name="requestedVersion">The requested version.</param>
public XAudio2(XAudio2Version requestedVersion)
: this(XAudio2Flags.None, ProcessorSpecifier.DefaultProcessor, requestedVersion)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="XAudio2" /> class.
/// </summary>
/// <param name="flags">Specify a Debug or Normal XAudio2 instance.</param>
/// <param name="processorSpecifier">The processor specifier.</param>
/// <param name="requestedVersion">The requestedVersion to use (auto, 2.7 or 2.8).</param>
/// <exception cref="System.InvalidOperationException">XAudio2 requestedVersion [ + requestedVersion + ] is not installed</exception>
public XAudio2(XAudio2Flags flags, ProcessorSpecifier processorSpecifier, XAudio2Version requestedVersion = XAudio2Version.Default)
: base(IntPtr.Zero)
{
var tryVersions = requestedVersion == XAudio2Version.Default
? new[] { XAudio2Version.Version29, XAudio2Version.Version28, XAudio2Version.Version27 }
: new[] { requestedVersion };
foreach (var tryVersion in tryVersions)
{
switch (tryVersion)
{
#if DESKTOP_APP
case XAudio2Version.Version27:
Guid clsid = ((int)flags == 1) ? CLSID_XAudio27_Debug : CLSID_XAudio27;
if ((requestedVersion == XAudio2Version.Default || requestedVersion == XAudio2Version.Version27) && Utilities.TryCreateComInstance(clsid, Utilities.CLSCTX.ClsctxInprocServer, IID_IXAudio2, this))
{
SetupVtblFor27();
// Initialize XAudio2
Initialize(0, processorSpecifier);
Version = XAudio2Version.Version27;
}
break;
#endif
case XAudio2Version.Version28:
try
{
XAudio28Functions.XAudio2Create(this, 0, (int)processorSpecifier);
Version = XAudio2Version.Version28;
}
catch (DllNotFoundException) { }
break;
#if STORE_APP_10
case XAudio2Version.Version29:
try
{
XAudio29Functions.XAudio2Create(this, 0, (int)processorSpecifier);
Version = XAudio2Version.Version29;
}
catch (DllNotFoundException) { }
break;
#endif
}
// Early exit if we found a requestedVersion
if (Version != XAudio2Version.Default)
{
break;
}
}
if (Version == XAudio2Version.Default)
{
throw new DllNotFoundException(string.Format("Unable to find XAudio2 dlls for requested versions [{0}], not installed on this machine", requestedVersion == XAudio2Version.Default ? "2.7, 2.8 or 2.9" : requestedVersion.ToString()));
}
// Register engine callback
engineCallbackImpl = new EngineCallbackImpl(this);
engineShadowPtr = EngineShadow.ToIntPtr(engineCallbackImpl);
RegisterForCallbacks_(engineShadowPtr);
}
/// <summary>
/// Gets the requestedVersion of this XAudio2 instance, once a <see cref="XAudio2"/> device has been instanciated.
/// </summary>
/// <value>The requestedVersion.</value>
public XAudio2Version Version { get; private set; }
// ---------------------------------------------------------------------------------
// Start handling 2.7 requestedVersion here
// ---------------------------------------------------------------------------------
/// <summary>
/// Setups the VTBL for XAudio 2.7. The 2.7 verions had 3 methods starting at VTBL[3]:
/// - GetDeviceCount
/// - GetDeviceDetails
/// - Initialize
/// </summary>
private void SetupVtblFor27()
{
RegisterForCallbacks___vtbl_index += 3;
UnregisterForCallbacks___vtbl_index += 3;
CreateSourceVoice___vtbl_index += 3;
CreateSubmixVoice__vtbl_index += 3;
CreateMasteringVoice__vtbl_index += 3;
StartEngine__vtbl_index += 3;
StopEngine__vtbl_index += 3;
CommitChanges__vtbl_index += 3;
GetPerformanceData__vtbl_index += 3;
SetDebugConfiguration__vtbl_index += 3;
}
private void CheckVersion27()
{
if (Version != XAudio2Version.Version27)
{
throw new InvalidOperationException("This method is only valid on the XAudio 2.7 requestedVersion [Current is: " + Version + "]");
}
}
/// <summary>
/// No documentation.
/// </summary>
/// <!-- No matching elements were found for the following include tag --><include file="Documentation\CodeComments.xml" path="/comments/comment[@id='IXAudio2::GetDeviceCount']/*" />
/// <unmanaged>GetDeviceCount</unmanaged>
/// <unmanaged-short>GetDeviceCount</unmanaged-short>
/// <unmanaged>HRESULT IXAudio2::GetDeviceCount([Out] unsigned int* pCount)</unmanaged>
public int DeviceCount
{
get
{
CheckVersion27();
int result;
this.GetDeviceCount(out result);
return result;
}
}
/// <summary>
/// No documentation.
/// </summary>
/// <param name="countRef">No documentation.</param>
/// <returns>No documentation.</returns>
/// <!-- No matching elements were found for the following include tag --><include file="Documentation\CodeComments.xml" path="/comments/comment[@id='IXAudio2::GetDeviceCount']/*" />
/// <unmanaged>HRESULT IXAudio2::GetDeviceCount([Out] unsigned int* pCount)</unmanaged>
/// <unmanaged-short>IXAudio2::GetDeviceCount</unmanaged-short>
private unsafe void GetDeviceCount(out int countRef)
{
Result result;
fixed (void* ptr = &countRef)
{
result = LocalInterop.Calliint(this._nativePointer, ptr, *(*(void***)this._nativePointer + 3));
}
result.CheckError();
}
internal unsafe void CreateMasteringVoice27(MasteringVoice masteringVoiceOut, int inputChannels, int inputSampleRate, int flags, int deviceIndex, EffectChain? effectChainRef)
{
IntPtr zero = IntPtr.Zero;
EffectChain value;
if (effectChainRef.HasValue)
{
value = effectChainRef.Value;
}
Result result = LocalInterop.Calliint(this._nativePointer, (void*)&zero, inputChannels, inputSampleRate, flags, deviceIndex, effectChainRef.HasValue ? ((void*)(&value)) : ((void*)IntPtr.Zero), *(*(void***)this._nativePointer + 10));
masteringVoiceOut.NativePointer = zero;
result.CheckError();
}
/// <summary>
/// Returns information about an audio output device.
/// </summary>
/// <param name="index">[in] Index of the device to be queried. This value must be less than the count returned by <see cref="SharpDX.XAudio2.XAudio2.GetDeviceCount"/>. </param>
/// <returns>On success, pointer to an <see cref="SharpDX.XAudio2.DeviceDetails"/> structure that is returned. </returns>
/// <unmanaged>HRESULT IXAudio2::GetDeviceDetails([None] UINT32 Index,[Out] XAUDIO2_DEVICE_DETAILS* pDeviceDetails)</unmanaged>
public SharpDX.XAudio2.DeviceDetails GetDeviceDetails(int index)
{
CheckVersion27();
DeviceDetails details;
GetDeviceDetails(index, out details);
return details;
}
private unsafe void GetDeviceDetails(int index, out DeviceDetails deviceDetailsRef)
{
DeviceDetails.__Native _Native = default(DeviceDetails.__Native);
Result result = LocalInterop.Calliint(this._nativePointer, index, &_Native, *(*(void***)this._nativePointer + 4));
deviceDetailsRef = default(DeviceDetails);
deviceDetailsRef.__MarshalFrom(ref _Native);
result.CheckError();
}
private unsafe void Initialize(int flags, ProcessorSpecifier xAudio2Processor)
{
var result = (Result)LocalInterop.Calliint(this._nativePointer, (int)flags, (int)xAudio2Processor, *(*(void***)this._nativePointer + 5));
result.CheckError();
}
// ---------------------------------------------------------------------------------
// End handling 2.7 requestedVersion here
// ---------------------------------------------------------------------------------
/// <summary>
/// Calculate a decibel from a volume.
/// </summary>
/// <param name="volume">The volume.</param>
/// <returns>a dB value</returns>
public static float AmplitudeRatioToDecibels(float volume)
{
if (volume == 0f)
return float.MinValue;
return (float)(Math.Log10(volume) * 20);
}
/// <summary>
/// Calculate radians from a cutoffs frequency.
/// </summary>
/// <param name="cutoffFrequency">The cutoff frequency.</param>
/// <param name="sampleRate">The sample rate.</param>
/// <returns>radian</returns>
public static float CutoffFrequencyToRadians(float cutoffFrequency, int sampleRate)
{
if (((int)cutoffFrequency * 6.0) >= sampleRate)
return 1f;
return (float)(Math.Sin(cutoffFrequency*Math.PI/sampleRate)*2);
}
/// <summary>
/// Calculate a cutoff frequency from a radian.
/// </summary>
/// <param name="radians">The radians.</param>
/// <param name="sampleRate">The sample rate.</param>
/// <returns>cutoff frequency</returns>
public static float RadiansToCutoffFrequency(float radians, float sampleRate)
{
return (float)((Math.Asin(radians * 0.5) * sampleRate) / Math.PI);
}
/// <summary>
/// Calculate a volume from a decibel
/// </summary>
/// <param name="decibels">a dB value</param>
/// <returns>an amplitude value</returns>
public static float DecibelsToAmplitudeRatio(float decibels)
{
return (float)Math.Pow(10, decibels / 20);
}
/// <summary>
/// Calculate semitones from a Frequency ratio
/// </summary>
/// <param name="frequencyRatio">The frequency ratio.</param>
/// <returns>semitones</returns>
public static float FrequencyRatioToSemitones(float frequencyRatio)
{
return (float)(Math.Log10(frequencyRatio) * 12 * Math.PI);
}
/// <summary>
/// Calculate frequency from semitones.
/// </summary>
/// <param name="semitones">The semitones.</param>
/// <returns>the frequency</returns>
public static float SemitonesToFrequencyRatio(float semitones)
{
return (float)Math.Pow(2, semitones / 12);
}
/// <summary>
/// Atomically applies a set of operations for all pending operations.
/// </summary>
/// <unmanaged>HRESULT IXAudio2::CommitChanges([None] UINT32 OperationSet)</unmanaged>
public void CommitChanges()
{
this.CommitChanges(0);
}
protected override void Dispose(bool disposing)
{
if (engineShadowPtr != IntPtr.Zero)
UnregisterForCallbacks_(engineShadowPtr);
if (disposing)
{
if (engineCallbackImpl != null)
engineCallbackImpl.Dispose();
}
Version = XAudio2Version.Default;
base.Dispose(disposing);
}
private class EngineCallbackImpl : CallbackBase, EngineCallback
{
XAudio2 XAudio2 { get; set; }
public EngineCallbackImpl(XAudio2 xAudio2)
{
XAudio2 = xAudio2;
}
public void OnProcessingPassStart()
{
EventHandler handler = XAudio2.ProcessingPassStart;
if (handler != null) handler(this, EventArgs.Empty);
}
public void OnProcessingPassEnd()
{
EventHandler handler = XAudio2.ProcessingPassEnd;
if (handler != null) handler(this, EventArgs.Empty);
}
public void OnCriticalError(Result error)
{
EventHandler<ErrorEventArgs> handler = XAudio2.CriticalError;
if (handler != null) handler(this, new ErrorEventArgs(error));
}
IDisposable ICallbackable.Shadow { get; set; }
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.