context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using log4net;
using NetGore.Collections;
using NetGore.Content;
using NetGore.IO;
using SFML.Graphics;
namespace NetGore.Graphics
{
/// <summary>
/// Holds the <see cref="GrhData"/>s and related methods.
/// </summary>
public static class GrhInfo
{
static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
const string _animatedGrhDatasNodeName = "Animated";
const string _autoAnimatedGrhDatasNodeName = "AutomaticAnimated";
const string _nonAnimatedGrhDatasNodeName = "Stationary";
const string _rootNodeName = "GrhDatas";
/// <summary>
/// Dictionary of the <see cref="SpriteCategory"/>, and a dictionary of all the <see cref="SpriteTitle"/>s
/// and the corresponding <see cref="GrhData"/> for that <see cref="SpriteTitle"/> under the
/// <see cref="SpriteCategory"/>.
/// </summary>
static readonly Dictionary<SpriteCategory, Dictionary<SpriteTitle, GrhData>> _catDic;
static Func<GrhData, ContentLevel> _contentLevelDecider = DefaultContentLevelDecider;
/// <summary>
/// List of all the <see cref="GrhData"/> where the array index is the <see cref="GrhIndex"/>.
/// </summary>
static DArray<GrhData> _grhDatas;
static bool _isLoaded = false;
/// <summary>
/// If the <see cref="GrhData"/>s are currently being loaded
/// </summary>
static bool _isLoading;
/// <summary>
/// Initializes the <see cref="GrhInfo"/> class.
/// </summary>
static GrhInfo()
{
_catDic = new Dictionary<SpriteCategory, Dictionary<SpriteTitle, GrhData>>();
Debug.Assert(EqualityComparer<SpriteCategory>.Default.Equals("asdf", "ASDF"),
"Sprite category must not be case sensitive.");
Debug.Assert(EqualityComparer<SpriteTitle>.Default.Equals("asdf", "ASDF"), "Sprite title must not be case sensitive.");
}
/// <summary>
/// Notifies listeners when a <see cref="GrhData"/> has been added. This includes
/// <see cref="GrhData"/>s added from loading.
/// </summary>
public static event TypedEventHandler<GrhData> Added;
/// <summary>
/// Notifies listeners when a new <see cref="GrhData"/> has been added. This does not include
/// <see cref="GrhData"/>s added from loading.
/// </summary>
public static event TypedEventHandler<GrhData> AddedNew;
/// <summary>
/// Notifies listeners when a <see cref="GrhData"/> has been removed.
/// </summary>
public static event TypedEventHandler<GrhData> Removed;
/// <summary>
/// Gets or sets a func used to determine the <see cref="ContentLevel"/>
/// for a <see cref="GrhData"/>. This value should be set before calling <see cref="GrhInfo.Load"/>
/// for best results.
/// </summary>
public static Func<GrhData, ContentLevel> ContentLevelDecider
{
get { return _contentLevelDecider; }
set { _contentLevelDecider = value ?? DefaultContentLevelDecider; }
}
/// <summary>
/// Gets or sets the <see cref="GenericValueIOFormat"/> to use for when an instance of this class
/// writes itself out to a new <see cref="GenericValueWriter"/>. If null, the format to use
/// will be inherited from <see cref="GenericValueWriter.DefaultFormat"/>.
/// Default value is null.
/// </summary>
public static GenericValueIOFormat? EncodingFormat { get; set; }
/// <summary>
/// Gets an IEnumerable of all of the <see cref="GrhData"/>s.
/// </summary>
public static IEnumerable<GrhData> GrhDatas
{
get
{
if (_grhDatas == null)
return Enumerable.Empty<GrhData>();
return _grhDatas;
}
}
/// <summary>
/// Gets if the <see cref="GrhData"/>s have already been loaded.
/// </summary>
public static bool IsLoaded
{
get { return _isLoaded; }
}
/// <summary>
/// Adds a <see cref="GrhData"/> to the list of <see cref="GrhData"/>s at the index assigned to it.
/// </summary>
/// <param name="gd"><see cref="GrhData"/> to add.</param>
/// <exception cref="ArgumentNullException"><paramref name="gd" /> is <c>null</c>.</exception>
internal static void AddGrhData(GrhData gd)
{
if (gd == null)
throw new ArgumentNullException("gd");
var index = gd.GrhIndex;
AssertGrhIndexIsFree(index, gd);
_grhDatas[(int)index] = gd;
// Make sure the GrhData is only in the list once
Debug.Assert(GrhDatas.Count(x => x == gd) == 1,
"The GrhData should be in the list only once. Somehow, its in there either more times, or not at all.");
}
/// <summary>
/// Handles when a <see cref="GrhData"/> is added to the <see cref="GrhData"/>s DArray.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="NetGore.Collections.DArrayEventArgs{T}"/> instance containing the event data.</param>
static void AddHandler(DArray<GrhData> sender, DArrayEventArgs<GrhData> e)
{
Debug.Assert(e.Index != GrhIndex.Invalid);
var gd = e.Item;
if (gd == null)
{
Debug.Fail("gd is null.");
return;
}
// Set the categorization event so we can keep up with any changes to the categorization.
gd.CategorizationChanged -= ChangeCategorizationHandler;
gd.CategorizationChanged += ChangeCategorizationHandler;
AddToDictionary(gd);
if (Added != null)
Added.Raise(gd, EventArgs.Empty);
if (!_isLoading)
{
if (AddedNew != null)
AddedNew.Raise(gd, EventArgs.Empty);
}
}
/// <summary>
/// Adds a <see cref="GrhData"/> to the dictionary.
/// </summary>
/// <param name="gd"><see cref="GrhData"/> to add to the dictionary.</param>
static void AddToDictionary(GrhData gd)
{
Dictionary<SpriteTitle, GrhData> titleDic;
// Check if the category exists
if (!_catDic.TryGetValue(gd.Categorization.Category, out titleDic))
{
// Category does not exist, so create and add it
titleDic = new Dictionary<SpriteTitle, GrhData>();
_catDic.Add(gd.Categorization.Category, titleDic);
}
// Add the GrhData to the sub-dictionary by its title
titleDic.Add(gd.Categorization.Title, gd);
}
/// <summary>
/// Asserts that a given <see cref="GrhIndex"/> is not already occupied.
/// </summary>
/// <param name="index">The <see cref="GrhIndex"/> to check.</param>
/// <param name="ignoreWhen">When the <see cref="GrhData"/> at the <paramref name="index"/> is equal to this value,
/// and this value is not null, no errors will be raised.</param>
[Conditional("DEBUG")]
static void AssertGrhIndexIsFree(GrhIndex index, GrhData ignoreWhen)
{
// Make sure we can even get the index
if (!_grhDatas.CanGet((int)index))
return;
// Get the current GrhData
var currentGD = GetData(index);
// Check if occupied
if (currentGD != null && (ignoreWhen == null || currentGD != ignoreWhen))
Debug.Fail("Existing GrhData is going to be overwritten. This is likely not what was intended.");
}
/// <summary>
/// Handles when the category of a <see cref="GrhData"/> in the DArray changes.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="NetGore.EventArgs{SpriteCategorization}"/> instance containing the event data.</param>
static void ChangeCategorizationHandler(GrhData sender, EventArgs<SpriteCategorization> e)
{
var gd = sender;
if (gd == null)
{
Debug.Fail("gd is null.");
return;
}
RemoveFromDictionary(gd);
AddToDictionary(gd);
}
/// <summary>
/// Creates a new <see cref="AutomaticAnimatedGrhData"/>. This should only be called from the
/// AutomaticGrhDataUpdater.
/// </summary>
/// <param name="contentManager">The content manager.</param>
/// <param name="categorization">The categorization for the <see cref="AutomaticAnimatedGrhData"/>.</param>
/// <param name="index">If specified, the GrhIndex to use for the new GrhData.</param>
/// <returns>The new <see cref="AutomaticAnimatedGrhData"/>, or null if none created.</returns>
public static AutomaticAnimatedGrhData CreateAutomaticAnimatedGrhData(IContentManager contentManager, SpriteCategorization categorization, GrhIndex? index = null)
{
// Check if the GrhData already exists
if (GetData(categorization) != null)
return null;
if (!index.HasValue)
index = NextFreeIndex();
var gd = new AutomaticAnimatedGrhData(contentManager, index.Value, categorization);
AddGrhData(gd);
return gd;
}
public static AnimatedGrhData CreateGrhData(IEnumerable<GrhIndex> frames, float speed, SpriteCategorization categorization)
{
var grhIndex = NextFreeIndex();
var gd = new AnimatedGrhData(grhIndex, categorization);
gd.SetSpeed(speed);
gd.SetFrames(frames);
AddGrhData(gd);
return gd;
}
public static StationaryGrhData CreateGrhData(IContentManager contentManager, SpriteCategorization categorization,
string texture, Vector2 pos, Vector2 size)
{
return CreateGrhData(NextFreeIndex(), contentManager, categorization, texture, pos, size);
}
public static StationaryGrhData CreateGrhData(IContentManager contentManager, SpriteCategorization categorization,
string texture, GrhIndex? index = null)
{
return CreateGrhData(index ?? NextFreeIndex(), contentManager, categorization, texture, null, null);
}
public static StationaryGrhData CreateGrhData(IContentManager contentManager, SpriteCategory category)
{
var index = NextFreeIndex();
var title = GetUniqueTitle(category, "tmp" + index);
var categorization = new SpriteCategorization(category, title);
return CreateGrhData(index, contentManager, categorization, string.Empty, Vector2.Zero, Vector2.Zero);
}
static StationaryGrhData CreateGrhData(GrhIndex grhIndex, IContentManager contentManager,
SpriteCategorization categorization, string texture, Vector2? pos, Vector2? size)
{
Debug.Assert(!grhIndex.IsInvalid);
Rectangle? source;
if (pos == null || size == null)
source = null;
else
source = new Rectangle(pos.Value.X, pos.Value.Y, size.Value.X, size.Value.Y);
var gd = new StationaryGrhData(contentManager, grhIndex, categorization, texture, source);
AddGrhData(gd);
return gd;
}
/// <summary>
/// Decides the <see cref="ContentLevel"/> to use for <see cref="GrhData"/>s.
/// </summary>
/// <param name="grhData">The <see cref="GrhData"/> to get the <see cref="ContentLevel"/> for.</param>
/// <returns>The <see cref="ContentLevel"/> for the <paramref name="grhData"/>.</returns>
static ContentLevel DefaultContentLevelDecider(GrhData grhData)
{
return ContentLevel.Map;
}
/// <summary>
/// Deletes a <see cref="GrhData"/>.
/// </summary>
/// <param name="grhData"><see cref="GrhData"/> to delete.</param>
/// <exception cref="ArgumentNullException"><paramref name="grhData" /> is <c>null</c>.</exception>
public static void Delete(GrhData grhData)
{
if (grhData == null)
throw new ArgumentNullException("grhData");
var grhIndex = grhData.GrhIndex;
if (grhIndex.IsInvalid)
return;
// Insure the index is valid
if (!_grhDatas.CanGet((int)grhIndex))
{
const string errmsg = "Attempted to delete GrhData `{0}`, but GrhIndex `{1}` could not be acquired.";
if (log.IsErrorEnabled)
log.ErrorFormat(errmsg, grhData, grhIndex);
Debug.Fail(string.Format(errmsg, grhData, grhIndex));
return;
}
// Make sure we are deleting the correct GrhData
var i = (int)grhIndex;
if (_grhDatas[i] != grhData)
{
const string errmsg =
"Attempted to delete GrhData `{0}`, but GrhIndex `{1}` is already in use by" +
" a different GrhData `{2}`. Most likely, the GrhData we tried to delete is already deleted, and" +
" the GrhIndex has been recycled to a new GrhData. Stop trying to delete dead stuff, will ya!?";
if (log.IsErrorEnabled)
log.ErrorFormat(errmsg, grhData, grhIndex, _grhDatas[i]);
Debug.Fail(string.Format(errmsg, grhData, grhIndex, _grhDatas[i]));
return;
}
// Remove the GrhData from the collection
_grhDatas.RemoveAt((int)grhIndex);
// If a stationary GrhData and auto-size is set, delete the texture, too
try
{
var sgd = grhData as StationaryGrhData;
if (sgd != null && sgd.AutomaticSize)
{
// Make sure no other GrhData is using the texture
var origTexture = sgd.GetOriginalTexture();
if (GrhDatas.OfType<StationaryGrhData>().All(x => origTexture != x.GetOriginalTexture()))
{
// Dispose of the texture then recycle the file
origTexture.Dispose();
try
{
sgd.TextureName.RecycleFile();
}
catch
{
}
}
}
}
catch (Exception ex)
{
const string errmsg = "Failed to recycle texture file for GrhData `{0}`. Exception: {1}";
if (log.IsErrorEnabled)
log.ErrorFormat(errmsg, grhData, ex);
Debug.Fail(string.Format(errmsg, grhData, ex));
}
}
/// <summary>
/// Gets an IEnumerable of all the <see cref="GrhData"/> categories.
/// </summary>
/// <returns>An IEnumerable of all the <see cref="GrhData"/> categories.</returns>
public static IEnumerable<SpriteCategory> GetCategories()
{
return _catDic.Keys;
}
/// <summary>
/// Gets a <see cref="IContentManager"/>.
/// </summary>
/// <returns>A <see cref="IContentManager"/>.</returns>
static IContentManager GetContentManager()
{
return GrhDatas.OfType<StationaryGrhData>().First(x => x.ContentManager != null).ContentManager;
}
/// <summary>
/// Gets the <see cref="GrhData"/> by the given categorization information.
/// </summary>
/// <param name="category">Category of the <see cref="GrhData"/>.</param>
/// <param name="title">Title of the <see cref="GrhData"/>.</param>
/// <returns><see cref="GrhData"/> matching the given information if found, or null if no matches.</returns>
public static GrhData GetData(SpriteCategory category, SpriteTitle title)
{
// Get the dictionary for the category
var titleDic = GetDatas(category);
// If we failed to get it, return null
if (titleDic == null)
return null;
// Try and get the GrhData for the given title, returning the GrhData
// if it exists, or null if it does not exist in the dictionary
GrhData ret;
if (titleDic.TryGetValue(title, out ret))
return ret;
else
return null;
}
/// <summary>
/// Gets the <see cref="GrhData"/> by the given categorization information.
/// </summary>
/// <param name="categorization">Categorization of the <see cref="GrhData"/>.</param>
/// <returns><see cref="GrhData"/> matching the given information if found, or null if no matches.</returns>
public static GrhData GetData(SpriteCategorization categorization)
{
return GetData(categorization.Category, categorization.Title);
}
/// <summary>
/// Gets the GrhData by the given information
/// </summary>
/// <param name="grhIndex">GrhIndex of the GrhData</param>
/// <returns>GrhData matching the given information if found, or null if no matches</returns>
public static GrhData GetData(GrhIndex grhIndex)
{
if (grhIndex.IsInvalid)
return null;
if (_grhDatas.CanGet((int)grhIndex))
return _grhDatas[(int)grhIndex];
else
return null;
}
/// <summary>
/// Gets the <see cref="GrhData"/>s by the given information.
/// </summary>
/// <param name="category">Category of the <see cref="GrhData"/>s.</param>
/// <returns>All <see cref="GrhData"/>s from the given category with their Title as the key, or
/// null if the <paramref name="category"/> was invalid.</returns>
public static IDictionary<SpriteTitle, GrhData> GetDatas(SpriteCategory category)
{
Dictionary<SpriteTitle, GrhData> titleDic;
// Return the whole dictionary for the given catgory, or null if it does not exist
if (_catDic.TryGetValue(category, out titleDic))
return titleDic;
else
return null;
}
/// <summary>
/// Gets the absolute file path to the GrhData file.
/// </summary>
/// <param name="contentPath">ContentPath to use.</param>
/// <returns>The absolute file path to the GrhData file.</returns>
public static string GetGrhDataFilePath(ContentPaths contentPath)
{
return contentPath.Data.Join("grhdata" + EngineSettings.DataFileSuffix);
}
/// <summary>
/// Gets a unique category based off of an existing category.
/// </summary>
/// <param name="category">The category to base the new category name off of.</param>
/// <returns>A unique, unused category.</returns>
public static SpriteCategory GetUniqueCategory(SpriteCategory category)
{
return GetUniqueCategory(category.ToString());
}
/// <summary>
/// Gets a unique category based off of an existing category.
/// </summary>
/// <param name="category">The category to base the new category name off of.</param>
/// <returns>A unique, unused category.</returns>
public static SpriteCategory GetUniqueCategory(string category)
{
var copyNum = 1;
SpriteCategory newCategory;
IDictionary<SpriteTitle, GrhData> coll;
do
{
newCategory = new SpriteCategory(category + " (" + ++copyNum + ")");
}
while ((coll = GetDatas(newCategory)) != null && !coll.IsEmpty());
return newCategory;
}
/// <summary>
/// Gets a unique title for a <see cref="GrhData"/> in the given category.
/// </summary>
/// <param name="category">The category.</param>
/// <param name="title">The string to base the new title off of.</param>
/// <returns>A unique title for the given <paramref name="category"/>.</returns>
public static SpriteTitle GetUniqueTitle(SpriteCategory category, SpriteTitle title)
{
return GetUniqueTitle(category, title.ToString());
}
/// <summary>
/// Gets a unique title for a <see cref="GrhData"/> in the given category.
/// </summary>
/// <param name="category">The category.</param>
/// <param name="title">The string to base the new title off of.</param>
/// <returns>A unique title for the given <paramref name="category"/>.</returns>
public static SpriteTitle GetUniqueTitle(SpriteCategory category, string title)
{
if (!string.IsNullOrEmpty(title))
title = SpriteTitle.Sanitize(title);
if (!SpriteTitle.IsValid(title))
title = "tmp";
// Check if the given title is already free
var sTitle = new SpriteTitle(title);
if (GetData(category, sTitle) == null)
return sTitle;
// Find next free number for the title suffix
var copyNum = 1;
SpriteTitle sNewTitle;
do
{
copyNum++;
sNewTitle = new SpriteTitle(title + " (" + copyNum + ")");
}
while (GetData(category, sNewTitle) != null);
return sNewTitle;
}
/// <summary>
/// Loads the <see cref="GrhData"/>s. This must be called before trying to access or use any
/// <see cref="GrhData"/>s.
/// </summary>
/// <param name="contentPath">The <see cref="ContentPaths"/> to load the <see cref="GrhData"/>s from.</param>
/// <param name="cm">The <see cref="IContentManager"/> to use for loaded <see cref="GrhData"/>s.</param>
/// <exception cref="ArgumentNullException"><paramref name="cm" /> is <c>null</c>.</exception>
/// <exception cref="FileNotFoundException">GrhData data file not found.</exception>
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "GrhData")]
public static void Load(ContentPaths contentPath, IContentManager cm)
{
if (IsLoaded)
return;
_isLoaded = true;
var path = GetGrhDataFilePath(contentPath);
if (cm == null)
throw new ArgumentNullException("cm");
if (!File.Exists(path))
throw new FileNotFoundException("GrhData data file not found.", path);
_isLoading = true;
try
{
// Create the GrhData DArray
if (_grhDatas == null)
_grhDatas = new DArray<GrhData>(256);
else
_grhDatas.Clear();
_catDic.Clear();
_grhDatas.ItemAdded -= AddHandler;
_grhDatas.ItemAdded += AddHandler;
_grhDatas.ItemRemoved -= RemoveHandler;
_grhDatas.ItemRemoved += RemoveHandler;
// Read and add the GrhDatas in order by their type
var reader = GenericValueReader.CreateFromFile(path, _rootNodeName);
LoadGrhDatas(reader, _nonAnimatedGrhDatasNodeName, x => StationaryGrhData.Read(x, cm));
LoadGrhDatas(reader, _animatedGrhDatasNodeName, AnimatedGrhData.Read);
LoadGrhDatas(reader, _autoAnimatedGrhDatasNodeName, x => AutomaticAnimatedGrhData.Read(x, cm));
// Trim down the GrhData array, mainly for the client since it will never add/remove any GrhDatas
// while in the Client, and the Client is what counts, baby!
_grhDatas.Trim();
}
finally
{
_isLoading = false;
}
}
/// <summary>
/// Handles loading a group of <see cref="GrhData"/>s from an <see cref="IValueReader"/>.
/// </summary>
/// <typeparam name="T">The type of <see cref="GrhData"/> being loaded.</typeparam>
/// <param name="reader">The <see cref="IValueReader"/> to read from.</param>
/// <param name="nodeName">The name of the node to read.</param>
/// <param name="loader">The <see cref="ReadManyNodesHandler{T}"/> used to load each <see cref="GrhData"/>
/// of type <typeparamref name="T"/>.</param>
static void LoadGrhDatas<T>(IValueReader reader, string nodeName, ReadManyNodesHandler<T> loader) where T : GrhData
{
const string errmsgFailedLoads =
"Failed to load the following indices from the GrhData file (\\DevContent\\Data\\grhdata.dat) for GrhData type `{2}`:{0}{1}{0}" +
"Note that these indices are NOT the GrhIndex, but the index of the Xml node." +
" Often times, this error means that you manually deleted one or more GrhDatas from this file," +
"in which case you can ignore it.";
// Create our "read key failed" handler for when a node for a GrhData is invalid
var failedLoads = new List<KeyValuePair<int, Exception>>();
Action<int, Exception> grhLoadFailHandler = (i, ex) => failedLoads.Add(new KeyValuePair<int, Exception>(i, ex));
// Load the GrhDatas
var loadedGrhDatas = reader.ReadManyNodes(nodeName, loader, grhLoadFailHandler);
// Add the GrhDatas to the global collection
foreach (var grhData in loadedGrhDatas)
{
if (grhData == null)
continue;
var index = (int)grhData.GrhIndex;
Debug.Assert(!_grhDatas.CanGet(index) || _grhDatas[index] == null, "Index already occupied!");
if (!grhData.GrhIndex.IsInvalid)
_grhDatas[index] = grhData;
else
{
const string errmsg = "Tried to add GrhData `{0}` which has an invalid GrhIndex.";
var err = string.Format(errmsg, grhData);
log.Fatal(err);
Debug.Fail(err);
}
}
// Notify when any of the nodes failed to load
if (failedLoads.Count > 0)
{
if (log.IsErrorEnabled)
log.ErrorFormat(errmsgFailedLoads, Environment.NewLine, failedLoads.Select(x => x.Key).Implode(), typeof(T).Name);
Debug.Fail(string.Format(errmsgFailedLoads, Environment.NewLine, failedLoads.Select(x => x.Key).Implode(), typeof(T).Name));
failedLoads.Clear();
}
}
/// <summary>
/// Finds the next free <see cref="GrhIndex"/>.
/// </summary>
/// <returns>The next free <see cref="GrhIndex"/>.</returns>
public static GrhIndex NextFreeIndex()
{
if (_grhDatas.TrackFree)
return new GrhIndex(_grhDatas.NextFreeIndex());
// Start at the first index
var i = GrhIndex.MinValue;
// Just loop through the indicies until we find one thats not in use or
// passes the length of the GrhDatas array (which means its obviously not in use)
while (_grhDatas.CanGet(i) && _grhDatas[i] != null)
{
i++;
}
Debug.Assert(i != GrhIndex.Invalid);
return new GrhIndex(i);
}
/// <summary>
/// Removes a <see cref="GrhData"/> from the dictionary.
/// </summary>
/// <param name="gd"><see cref="GrhData"/> to remove.</param>
static void RemoveFromDictionary(GrhData gd)
{
Dictionary<SpriteTitle, GrhData> titleDic;
if (!_catDic.TryGetValue(gd.Categorization.Category, out titleDic))
{
const string errmsg =
"Tried to remove GrhData `{0}` from the categorization dictionary with the" +
" categorization of `{1}`, but the whole category does not exist!" +
" This likely means some bad issue in the GrhInfo class...";
var err = string.Format(errmsg, gd, gd.Categorization);
log.Fatal(err);
Debug.Fail(err);
return;
}
if (!titleDic.Remove(gd.Categorization.Title))
{
const string errmsg =
"Tried to remove GrhData `{0}` from the categorization dictionary with the" +
" categorization of `{1}`, but the GrhData did not exist in the title dictionary!" +
" This likely means some bad issue in the GrhInfo class...";
var err = string.Format(errmsg, gd, gd.Categorization);
log.Fatal(err);
Debug.Fail(err);
}
}
/// <summary>
/// Handles when a GrhData is removed from the DArray
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="NetGore.Collections.DArrayEventArgs{T}"/> instance containing the event data.</param>
static void RemoveHandler(object sender, DArrayEventArgs<GrhData> e)
{
Debug.Assert(e.Index != GrhIndex.Invalid);
RemoveFromDictionary(e.Item);
if (Removed != null)
Removed.Raise(e.Item, EventArgs.Empty);
}
/// <summary>
/// Replaces an existing GrhData with a new <see cref="AnimatedGrhData"/>.
/// </summary>
/// <param name="grhIndex">The index of the <see cref="GrhData"/> to convert.</param>
/// <returns>The created <see cref="AnimatedGrhData"/>, or null if the replacement failed.</returns>
public static AnimatedGrhData ReplaceExistingWithAnimated(GrhIndex grhIndex)
{
var gd = GetData(grhIndex);
if (gd == null)
return null;
if (gd is AnimatedGrhData)
return (AnimatedGrhData)gd;
var newGD = new AnimatedGrhData(gd.GrhIndex, gd.Categorization);
Delete(gd);
AddGrhData(newGD);
return newGD;
}
/// <summary>
/// Replaces an existing GrhData with a new <see cref="StationaryGrhData"/>.
/// </summary>
/// <param name="grhIndex">The index of the <see cref="GrhData"/> to convert.</param>
/// <returns>The created <see cref="StationaryGrhData"/>, or null if the replacement failed.</returns>
public static StationaryGrhData ReplaceExistingWithStationary(GrhIndex grhIndex)
{
var gd = GetData(grhIndex);
if (gd == null)
return null;
if (gd is StationaryGrhData)
return (StationaryGrhData)gd;
var newGD = new StationaryGrhData(GetContentManager(), gd.GrhIndex, gd.Categorization, null, null);
Delete(gd);
AddGrhData(newGD);
return newGD;
}
/// <summary>
/// Saves all of the GrhData information to the specified file.
/// </summary>
/// <param name="contentPath">ContentPath to save the GrhData to.</param>
public static void Save(ContentPaths contentPath)
{
// Grab the GrhDatas by their type
var gds = GrhDatas.Where(x => x != null).OrderBy(x => x.Categorization.ToString(), StringComparer.OrdinalIgnoreCase);
var stationaryGrhDatas = gds.OfType<StationaryGrhData>().ToImmutable();
var animatedGrhDatas = gds.OfType<AnimatedGrhData>().ToImmutable();
var autoAnimatedGrhDatas = gds.OfType<AutomaticAnimatedGrhData>().ToImmutable();
// Write
var path = GetGrhDataFilePath(contentPath);
using (IValueWriter writer = GenericValueWriter.Create(path, _rootNodeName, EncodingFormat))
{
writer.WriteManyNodes(_nonAnimatedGrhDatasNodeName, stationaryGrhDatas, ((w, item) => item.Write(w)));
writer.WriteManyNodes(_animatedGrhDatasNodeName, animatedGrhDatas, ((w, item) => item.Write(w)));
writer.WriteManyNodes(_autoAnimatedGrhDatasNodeName, autoAnimatedGrhDatas, ((w, item) => item.Write(w)));
}
}
}
}
| |
/*Copyright 2015 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.?*/
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.JTX;
using ESRI.ArcGIS.JTX.Utilities;
using ESRI.ArcGIS.JTXUI;
namespace JTXSamples
{
[Guid("CDC6ACDA-F9D2-4A7F-B4DB-1772284057B1")]
public class CreateChildJobsAdvanced : IJTXCustomStep
{
#region Registration Code
[ComRegisterFunction()]
static void Reg(String regKey)
{
ESRI.ArcGIS.JTX.Utilities.JTXUtilities.RegisterJTXCustomStep(regKey);
}
[ComUnregisterFunction()]
static void Unreg(String regKey)
{
ESRI.ArcGIS.JTX.Utilities.JTXUtilities.UnregisterJTXCustomStep(regKey);
}
#endregion
#region Private Members
////////////////////////////////////////////////////////////////////////
// DECLARE: Data Members
private IJTXDatabase m_ipDatabase = null;
private readonly string[] m_ExpectedArgs = {
"jobtypename",
"assigngroup",
"assignuser",
"dependThisStep",
"dependNextStep",
"dependStatus",
"useparentaoi",
"aoiOverlapFeatureClassName",
"numberChildJobs",
"createVersionSetting",
"assignVersionSetting",
"setChildExtendedProps",
"dueDate",
"jobDuration"
};
private IJTXJobSet m_ipJobs = null;
private string m_paramJobTypeName = null;
private string m_paramAssignToGroup = null;
private string m_paramAssignToUser = null;
private bool m_paramDependThisStep = false;
private bool m_paramDependNextStep = false;
private string m_paramStatusType = null;
private bool m_paramHasStatusType = false;
private bool m_paramUseParentAOI = false;
private string m_AOIOverlapFeatureClassName = null;
private int m_paramNumberChildJobs = 1;
private CreateVersionType m_paramCreateVersionType = CreateVersionType.None;
private AssignVersionType m_paramAssignVersionType = AssignVersionType.None;
private string m_paramExtendedProperties = null;
private DateTime m_dueDate = Constants.NullDate;
private int m_duration = -1;
#endregion
#region Enums and Structs
private enum CreateVersionType
{
UseParentJobsVersion,
UseParentJobsParentVersion,
UseParentJobsDefaultVersion,
UseJobTypeDefaultSettings,
None
};
private enum AssignVersionType
{
UseParentJobsVersion,
None
};
public struct ExtendedPropertyIdentifier
{
public string LongTableName;
public string TableName;
public string FieldName;
public string Value;
public ExtendedPropertyIdentifier(string longTableName, string tableName, string fieldName, string value)
{
LongTableName = longTableName;
TableName = tableName;
FieldName = fieldName;
Value = value;
}
}
#endregion
#region IJTXCustomStep Members
/// <summary>
/// A description of the expected arguments for the step type. This should
/// include the syntax of the argument, whether or not it is required/optional,
/// and any return codes coming from the step type.
/// </summary>
public string ArgumentDescriptions
{
get
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(@"Job Type Name:");
sb.AppendFormat("\t/{0}:<job type name> (required)\r\n\r\n", m_ExpectedArgs[0]);
sb.AppendLine(@"Assign To Group:");
sb.AppendFormat("\t/{0}:<group to assign to> (optional)\r\n", m_ExpectedArgs[1]);
sb.AppendLine(@"Assign To User:");
sb.AppendFormat("\t/{0}:<username to assign to> (optional)\r\n", m_ExpectedArgs[2]);
sb.AppendLine(@"Dependency will be created and current job held at this step:");
sb.AppendFormat("\t/{0} (optional)\r\n", m_ExpectedArgs[3]);
sb.AppendLine(@"Dependency will be created and current job held at the next step in the workflow:");
sb.AppendFormat("\t/{0} (optional)\r\n", m_ExpectedArgs[4]);
sb.AppendLine(@"Dependency status (current job held until child job reaches this status):");
sb.AppendFormat("\t/{0}:<Status Type Name> (optional)\r\n", m_ExpectedArgs[5]);
sb.AppendLine(@"Use the parent job's AOI as the child job's AOI:");
sb.AppendFormat("\t/{0} (optional)\r\n", m_ExpectedArgs[6]);
sb.AppendLine(@"Create child jobs based on the overlap between the parent job's AOI and this feature class:");
sb.AppendFormat("\t/{0}:<fully qualified feature class name> (optional)\r\n", m_ExpectedArgs[7]);
sb.AppendLine(@"Default number of child jobs to create:");
sb.AppendFormat("\t/{0}:<number of jobs to create> (optional)\r\n", m_ExpectedArgs[8]);
sb.AppendLine(@"A version will be created for the child job(s) based on this selection:");
sb.AppendFormat("\t/{0}:<the version to use as the parent version> (optional)\r\n", m_ExpectedArgs[9]);
sb.AppendLine(@"A version will be assigned to the child job(s) based on this selection:");
sb.AppendFormat("\t/{0}:<the existing version the job will be assigned to> (optional)\r\n", m_ExpectedArgs[10]);
sb.AppendLine(@"Child job(s) extended properties value will be set to: one of the parent job's extended properties values (specified by JTX Token) or to the given string value:");
sb.AppendFormat("\t/{0}:<ChildJobFullyQualifiedExtendedPropertiesTableName.FieldName=[JOBEX:ParentJobFullyQualifiedExtendedPropertiesTableName.FieldName]> (optional)\r\n", m_ExpectedArgs[11]);
return sb.ToString();
}
}
/// <summary>
/// Called when a step of this type is executed in the workflow.
/// </summary>
/// <param name="JobID">ID of the job being executed</param>
/// <param name="StepID">ID of the step being executed</param>
/// <param name="argv">Array of arguments passed into the step's execution</param>
/// <param name="ipFeedback">Feedback object to return status messages and files</param>
/// <returns>Return code of execution for workflow path traversal</returns>
public int Execute(int JobID, int stepID, ref object[] argv, ref IJTXCustomStepFeedback ipFeedback)
{
System.Diagnostics.Debug.Assert(m_ipDatabase != null);
if (!ConfigurationCache.IsInitialized)
ConfigurationCache.InitializeCache(m_ipDatabase);
IJTXJobManager jobMan = m_ipDatabase.JobManager;
IJTXJob2 m_ParentJob = (IJTXJob2)jobMan.GetJob(JobID);
if (!GetInputParams(argv))
return 0;
return CreateJobs(m_ParentJob);
}
/// <summary>
/// Invoke an editor tool for managing custom step arguments. This is
/// an optional feature of the custom step and may not be implemented.
/// </summary>
/// <param name="hWndParent">Handle to the parent application window</param>
/// <param name="argsIn">Array of arguments already configured for this custom step</param>
/// <returns>Returns a list of newely configured arguments as specified via the editor tool</returns>
public object[] InvokeEditor(int hWndParent, object[] argsIn)
{
JTXSamples.CreateChildJobsArgEditor editorForm = new JTXSamples.CreateChildJobsArgEditor(m_ipDatabase, m_ExpectedArgs);
object[] newArgs = null;
return (editorForm.ShowDialog(argsIn, out newArgs) == DialogResult.OK) ? newArgs : argsIn;
}
/// <summary>
/// Called when the step is instantiated in the workflow.
/// </summary>
/// <param name="ipDatabase">Database connection to the JTX repository.</param>
public void OnCreate(IJTXDatabase ipDatabase)
{
m_ipDatabase = ipDatabase;
}
/// <summary>
/// Method to validate the configured arguments for the step type. The
/// logic of this method depends on the implementation of the custom step
/// but typically checks for proper argument names and syntax.
/// </summary>
/// <param name="argv">Array of arguments configured for the step type</param>
/// <returns>Returns 'true' if arguments are valid, 'false' if otherwise</returns>
public bool ValidateArguments(ref object[] argv)
{
string strValue = "";
if (!StepUtilities.GetArgument(ref argv, m_ExpectedArgs[0], true, out strValue)) { return false; }
return StepUtilities.AreArgumentNamesValid(ref argv, m_ExpectedArgs);
}
#endregion
#region Private Methods
////////////////////////////////////////////////////////////////////////
// METHOD: GetInputParams
private bool GetInputParams(object [] argv)
{
string sTemp = "";
// Job Type
StepUtilities.GetArgument(ref argv, m_ExpectedArgs[0], true, out m_paramJobTypeName);
// Job Assignment
StepUtilities.GetArgument(ref argv, m_ExpectedArgs[1], true, out m_paramAssignToGroup);
StepUtilities.GetArgument(ref argv, m_ExpectedArgs[2], true, out m_paramAssignToUser);
// Job Dependencies
m_paramDependThisStep = StepUtilities.GetArgument(ref argv, m_ExpectedArgs[3], true, out sTemp);
m_paramDependNextStep = StepUtilities.GetArgument(ref argv, m_ExpectedArgs[4], true, out sTemp);
m_paramHasStatusType = StepUtilities.GetArgument(ref argv, m_ExpectedArgs[5], true, out m_paramStatusType);
// Number of Jobs and AOI Definition
m_paramUseParentAOI = StepUtilities.GetArgument(ref argv, m_ExpectedArgs[6], true, out sTemp);
StepUtilities.GetArgument(ref argv, m_ExpectedArgs[7], true, out m_AOIOverlapFeatureClassName);
if (StepUtilities.GetArgument(ref argv, m_ExpectedArgs[8], true, out sTemp))
m_paramNumberChildJobs = Convert.ToInt16(sTemp);
// Versioning
StepUtilities.GetArgument(ref argv, m_ExpectedArgs[9], true, out sTemp);
if (string.IsNullOrEmpty(sTemp))
m_paramCreateVersionType = CreateVersionType.None;
else if (sTemp.Equals("The parent job's version"))
m_paramCreateVersionType = CreateVersionType.UseParentJobsVersion;
else if (sTemp.Equals("The parent job's parent version"))
m_paramCreateVersionType = CreateVersionType.UseParentJobsParentVersion;
else if (sTemp.Equals("The parent job's DEFAULT version"))
m_paramCreateVersionType = CreateVersionType.UseParentJobsDefaultVersion;
else if (sTemp.Equals("The job type's default properties parent version"))
m_paramCreateVersionType = CreateVersionType.UseJobTypeDefaultSettings;
StepUtilities.GetArgument(ref argv, m_ExpectedArgs[10], true, out sTemp);
if (string.IsNullOrEmpty(sTemp))
m_paramAssignVersionType = AssignVersionType.None;
else if (sTemp.Equals("The parent job's version"))
m_paramAssignVersionType = AssignVersionType.UseParentJobsVersion;
// Extended Properties
StepUtilities.GetArgument(ref argv, m_ExpectedArgs[11], true, out m_paramExtendedProperties);
StepUtilities.GetArgument(ref argv, m_ExpectedArgs[12], true, out sTemp);
if (!String.IsNullOrEmpty(sTemp))
m_dueDate = JTXUtilities.GenerateDateString(m_ipDatabase.JTXWorkspace, sTemp, false);
StepUtilities.GetArgument(ref argv, m_ExpectedArgs[13], true, out sTemp);
if (!String.IsNullOrEmpty(sTemp))
int.TryParse(sTemp, out m_duration);
return true;
}
////////////////////////////////////////////////////////////////////////
// METHOD: CreateJobs
private int CreateJobs(IJTXJob2 pParentJob)
{
try
{
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
bool bAutoCommit = ConfigurationCache.AutoCommitWorkflow;
m_ipDatabase.LogMessage(5, 2000, "CreateJobs");
// Set the job template values
IJTXJobManager2 pJobMan = m_ipDatabase.JobManager as IJTXJobManager2;
IJTXJobDescription pJobDescription = new JTXJobDescriptionClass();
pJobDescription.Description = pParentJob.Description;
pJobDescription.Priority = pParentJob.Priority;
pJobDescription.ParentJobId = pParentJob.ID;
pJobDescription.StartDate = pParentJob.StartDate;
if (m_dueDate != Constants.NullDate)
pJobDescription.DueDate = m_dueDate;
else if (m_duration > 0)
pJobDescription.DueDate = System.DateTime.Now.AddDays(m_duration);
else
pJobDescription.DueDate = pParentJob.DueDate;
if (!String.IsNullOrEmpty(m_paramAssignToGroup))
{
pJobDescription.AssignedType = jtxAssignmentType.jtxAssignmentTypeGroup;
pJobDescription.AssignedTo = m_paramAssignToGroup;
}
else if (!String.IsNullOrEmpty(m_paramAssignToUser))
{
pJobDescription.AssignedType = jtxAssignmentType.jtxAssignmentTypeUser;
pJobDescription.AssignedTo = m_paramAssignToUser;
}
else
{
pJobDescription.AssignedType = jtxAssignmentType.jtxAssignmentTypeUnassigned;
}
pJobDescription.OwnedBy = ConfigurationCache.GetCurrentJTXUser().UserName;
if (pParentJob.ActiveDatabase != null)
pJobDescription.DataWorkspaceID = pParentJob.ActiveDatabase.DatabaseID;
// Set the parent version. This only makes sense if the active workspace has been set
if (pJobDescription.DataWorkspaceID != null)
{
if (m_paramCreateVersionType == CreateVersionType.None
|| m_paramCreateVersionType == CreateVersionType.UseParentJobsVersion)
pJobDescription.ParentVersionName = pParentJob.VersionName; // This has to be set here because setting the job workspace resets the value
else if (m_paramCreateVersionType == CreateVersionType.UseJobTypeDefaultSettings)
{
IJTXJobType pJobType = m_ipDatabase.ConfigurationManager.GetJobType(m_paramJobTypeName);
if (pJobType != null)
pJobDescription.ParentVersionName = pJobType.DefaultParentVersionName;
}
else if (m_paramCreateVersionType == CreateVersionType.UseParentJobsDefaultVersion)
pJobDescription.ParentVersionName = pParentJob.JobType.DefaultParentVersionName;
else if (m_paramCreateVersionType == CreateVersionType.UseParentJobsParentVersion)
pJobDescription.ParentVersionName = pParentJob.ParentVersion;
}
// Determine the number of jobs to make
m_ipDatabase.LogMessage(5, 2000, "Before Determining Number of Jobs");
IArray aoiList = null;
int numJobs;
if (!GetNumberOfJobs(pParentJob, ref aoiList, out numJobs))
return 1;
if (numJobs <= 0)
{
MessageBox.Show(Properties.Resources.ZeroJobCount);
return 0;
}
pJobDescription.AOIList = aoiList;
m_ipDatabase.LogMessage(5, 2000, "After Determining Number of Jobs");
// Create the job objects
m_ipDatabase.LogMessage(5, 2000, "Before CreateJobs");
pJobDescription.JobTypeName = m_paramJobTypeName;
IJTXExecuteInfo pExecInfo;
m_ipJobs = pJobMan.CreateJobsFromDescription(pJobDescription, numJobs, true, out pExecInfo);
m_ipDatabase.LogMessage(5, 2000, "After CreateJobs");
// Populate the job data
for (int i = 0; i < m_ipJobs.Count; ++i)
{
IJTXJob pJob = m_ipJobs.get_Item(i);
SetJobProperties(pJobMan, pJob, pParentJob);
}
return 1;
}
catch (COMException ex)
{
if (ex.ErrorCode == (int)fdoError.FDO_E_SE_INVALID_COLUMN_VALUE)
{
MessageBox.Show(Properties.Resources.InvalidColumn, Properties.Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
MessageBox.Show(ex.Message);
}
return 0;
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message, Properties.Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return 0;
}
finally
{
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
}
}
////////////////////////////////////////////////////////////////////////
// METHOD: GetNumberOfJobs
private bool GetNumberOfJobs(IJTXJob2 pParentJob, ref IArray aoiList, out int numJobs)
{
bool AOIFromOverlap = false;
bool AOIFromParent = false;
numJobs = -1;
// Then use defaults
AOIFromOverlap = !string.IsNullOrEmpty(m_AOIOverlapFeatureClassName);
AOIFromParent = m_paramUseParentAOI;
numJobs = m_paramNumberChildJobs;
if (AOIFromOverlap)
{
if (!PopulateAOIListUsingOverlapFeatureClass(pParentJob, ref aoiList))
{
return false;
}
numJobs = aoiList.Count;
}
else if (AOIFromParent)
{
if (!PopulateAOIListUsingParent(pParentJob, ref aoiList, numJobs))
{
return false;
}
}
return true;
}
////////////////////////////////////////////////////////////////////////
// METHOD: PopulateAOIListUsingOverlapFeatureClass
private bool PopulateAOIListUsingOverlapFeatureClass(IJTXJob2 pParentJob, ref IArray aoiList)
{
try
{
// Make sure all the information exists to get the data workspace
if (pParentJob.ActiveDatabase == null)
{
MessageBox.Show("Unable to proceed: Please set the data workspace for this job.");
return false;
}
if (pParentJob.AOIExtent == null)
{
MessageBox.Show("Unable to proceed: Please assign the AOI for this job.");
return false;
}
// Get the feature workspace from the current data workspace
IJTXDatabase2 pJTXDB = (IJTXDatabase2)m_ipDatabase;
string activeDBID = pParentJob.ActiveDatabase.DatabaseID;
IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)pJTXDB.GetDataWorkspace(activeDBID, pParentJob.VersionExists() ? pParentJob.VersionName : "");
if (featureWorkspace == null)
{
MessageBox.Show("Unable to connect to Data Workspace");
return false;
}
IFeatureClass featureClass = null;
try
{
featureClass = featureWorkspace.OpenFeatureClass(m_AOIOverlapFeatureClassName);
}
catch (Exception ex)
{
MessageBox.Show("Unable to connect to feature class to generate AOIs: " +
m_AOIOverlapFeatureClassName + "\n Error: " + ex.ToString());
return false;
}
// Get all features that intersect the parent job's AOI
//
// Note: The parent job's AOI is shrunk very slightly so features that merely adjoin the parent's AOI
// are *not* returned. Only features that have some part of their actual area intersecting the parent's
// AOI are returned.
ISpatialFilter spatialFilter = new SpatialFilterClass();
ITopologicalOperator topOp = (ITopologicalOperator)pParentJob.AOIExtent;
IPolygon slightlySmallerExtent = (IPolygon)topOp.Buffer(-0.0001);
spatialFilter.Geometry = slightlySmallerExtent;
spatialFilter.GeometryField = featureClass.ShapeFieldName;
spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
IFeatureCursor featureCursor = featureClass.Search(spatialFilter, false);
aoiList = new ArrayClass();
IFeature feature = null;
while ((feature = featureCursor.NextFeature()) != null)
{
aoiList.Add(feature.Shape);
}
// Explicitly release the cursor.
Marshal.ReleaseComObject(featureCursor);
}
catch (Exception ex)
{
throw new Exception("Unable to create AOIs based on feature class: " + m_AOIOverlapFeatureClassName + ". " + ex.ToString());
}
return true;
}
////////////////////////////////////////////////////////////////////////
// METHOD: PopulateAOIListUsingParent
private bool PopulateAOIListUsingParent(IJTXJob2 pParentJob, ref IArray aoiList, int numCopies)
{
try
{
aoiList = new ArrayClass();
for (int i = 0; i < numCopies; i++)
{
aoiList.Add(pParentJob.AOIExtent);
}
}
catch (Exception ex)
{
throw new Exception("Unable to create AOIs based on parent job's AOI: " + ex.Message);
}
return true;
}
////////////////////////////////////////////////////////////////////////
// METHOD: SetJobProperties
private IJTXJob SetJobProperties(IJTXJobManager pJobMan, IJTXJob pJob, IJTXJob2 pParentJob)
{
m_ipDatabase.LogMessage(5, 2000, "Before LogJobAction (CreateJobs)");
IJTXActivityType pActType = m_ipDatabase.ConfigurationManager.GetActivityType(Constants.ACTTYPE_COMMENT);
pParentJob.LogJobAction(pActType, null,
String.Format(Properties.Resources.ActTypeMessage, pJob.ID.ToString()));
if (!string.IsNullOrEmpty(m_paramExtendedProperties))
{
m_ipDatabase.LogMessage(5, 2000, "Before Create Extended Properties");
ExtendedPropertyIdentifier childExProps = new ExtendedPropertyIdentifier();
try
{
ParseExtendedPropertiesParam(out childExProps);
}
catch (Exception ex)
{
string msg = string.Format(
"Unable to read parent job's extended property. Job ID: {0} ERROR: {1}",
pParentJob.ID, ex.Message);
m_ipDatabase.LogMessage(3, 1000, msg);
}
try
{
CreateExtendedPropertyRecord(pJob, childExProps);
}
catch (Exception ex)
{
string msg = string.Format(
"Unable to set child job's extended property. Child Job ID: {0} ERROR: {1}",
pJob.ID, ex.Message);
m_ipDatabase.LogMessage(3, 1000, msg);
}
m_ipDatabase.LogMessage(5, 2000, "After Create Extended Properties");
}
// Create dependencies on parent job if configured
m_ipDatabase.LogMessage(5, 2000, "Before Setting Dependencies");
if (m_paramDependNextStep || m_paramDependThisStep)
{
IJTXJobDependencies ipDependencyManager = pJobMan as IJTXJobDependencies;
CreateDependencyOnParentJob(ipDependencyManager, pParentJob, pJob.ID);
}
m_ipDatabase.LogMessage(5, 2000, "After Setting Dependencies");
// Create or assign version if configured
m_ipDatabase.LogMessage(5, 2000, "Before Versioning");
if (m_paramCreateVersionType != CreateVersionType.None)
{
if (pParentJob.ActiveDatabase != null && !String.IsNullOrEmpty(pJob.ParentVersion) &&
(m_paramCreateVersionType != CreateVersionType.UseParentJobsVersion || pParentJob.VersionExists()))
CreateChildVersion(ref pJob);
else
MessageBox.Show("Could not create version. Please ensure parent data workspace and versions are set correctly", Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else if (m_paramAssignVersionType != AssignVersionType.None)
{
if (pParentJob.ActiveDatabase != null)
AssignChildVersion(pParentJob, ref pJob);
else
MessageBox.Show("Could not assign version. Please ensure parent data workspace is set correctly", Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
m_ipDatabase.LogMessage(5, 2000, "After Versioning");
// Store the job and save the changes
m_ipDatabase.LogMessage(5, 2000, "Before Storing Job");
pJob.Store();
m_ipDatabase.LogMessage(5, 2000, "After Storing Job");
return pJob;
}
////////////////////////////////////////////////////////////////////////
// METHOD: ParseExtendedPropertiesParam
private bool ParseExtendedPropertiesParam(out ExtendedPropertyIdentifier child)
{
string[] props = m_paramExtendedProperties.Split('=');
string childInfo = props[0];
int lastDot = childInfo.LastIndexOf('.');
child.FieldName = childInfo.Substring(lastDot + 1, childInfo.Length - (lastDot + 1));
child.LongTableName = childInfo.Substring(0, lastDot);
lastDot = child.LongTableName.LastIndexOf('.');
if (lastDot >= 0)
{
child.TableName = child.LongTableName.Substring(lastDot + 1);
}
else
{
child.TableName = child.LongTableName;
}
child.Value = props[1];
return true;
}
////////////////////////////////////////////////////////////////////////
// METHOD: CreateExtendedPropertyRecord
private bool CreateExtendedPropertyRecord(IJTXJob job, ExtendedPropertyIdentifier child)
{
IJTXAuxProperties pAuxProps = (IJTXAuxProperties)job;
IJTXAuxRecordContainer pAuxContainer = pAuxProps.GetRecordContainer(child.LongTableName);
if (!string.IsNullOrEmpty(m_paramExtendedProperties) && pAuxContainer == null)
{
string msg = string.Format(
"Unable to set extended property for child job {0}. Unable to find child job's extended property table: {1}",
job.ID, child.LongTableName);
m_ipDatabase.LogMessage(3, 2000, msg);
}
System.Array contNames = pAuxProps.ContainerNames;
System.Collections.IEnumerator contNamesEnum = contNames.GetEnumerator();
contNamesEnum.Reset();
while (contNamesEnum.MoveNext())
{
try
{
string strContainerName = (string)contNamesEnum.Current;
if (!string.IsNullOrEmpty(m_paramExtendedProperties) && (strContainerName.ToUpper()).Equals(child.LongTableName.ToUpper()))
{
pAuxContainer = pAuxProps.GetRecordContainer(strContainerName);
if (pAuxContainer.RelationshipType != esriRelCardinality.esriRelCardinalityOneToOne)
{
throw new Exception("The table relationship is not one-to-one.");
}
IJTXAuxRecord childRecord = pAuxContainer.GetRecords().get_Item(0);//pAuxContainer.CreateRecord();
SetExtendedPropertyValues(childRecord, child);
JobUtilities.LogJobAction(m_ipDatabase, job, Constants.ACTTYPE_UPDATE_EXT_PROPS, "", null);
}
}
catch (Exception ex)
{
string msg = string.Format(
"Unable to create extended property {0} in record for jobid {1}. ERROR: {2}",
child.FieldName, job.ID, ex.Message);
m_ipDatabase.LogMessage(3, 2000, msg);
}
}
return true;
}
////////////////////////////////////////////////////////////////////////
// METHOD: SetExtendedPropertyValues
private bool SetExtendedPropertyValues(IJTXAuxRecord childRecord, ExtendedPropertyIdentifier exPropIdentifier)
{
int fieldIndex = GetFieldIndex(childRecord, exPropIdentifier);
childRecord.set_Data(fieldIndex, exPropIdentifier.Value);
childRecord.Store();
return true;
}
////////////////////////////////////////////////////////////////////////
// METHOD: GetFieldIndex
private int GetFieldIndex(IJTXAuxRecord record, ExtendedPropertyIdentifier exPropIdentifier)
{
for (int i = 0; i < record.Count; i++)
{
string propertyName = record.get_PropName(i).ToUpper();
if (propertyName.Equals(exPropIdentifier.FieldName.ToUpper()))
{
return i;
}
}
throw new Exception("Unable to find field name " + exPropIdentifier.FieldName + " in " + exPropIdentifier.TableName);
}
////////////////////////////////////////////////////////////////////////
// METHOD: CreateDependencyOnParentJob
private void CreateDependencyOnParentJob(IJTXJobDependencies dependencyManager, IJTXJob2 pParentJob, int childJobID)
{
IJTXJobDependency dependency = dependencyManager.CreateDependency(pParentJob.ID);
dependency.DepJobID = childJobID;
dependency.DepOnType = jtxDependencyType.jtxDependencyTypeStatus;
IJTXStatus statusType = null;
if (!m_paramHasStatusType) statusType = m_ipDatabase.ConfigurationManager.GetStatus("Closed");
else statusType = m_ipDatabase.ConfigurationManager.GetStatus(m_paramStatusType);
dependency.DepOnValue = statusType.ID;
dependency.HeldOnType = jtxDependencyType.jtxDependencyTypeStep;
IJTXWorkflowExecution parentWorkflow = pParentJob as IJTXWorkflowExecution;
int[] currentSteps = parentWorkflow.GetCurrentSteps();
int dependentStep = currentSteps[0];
if (m_paramDependNextStep)
{
IJTXWorkflowConfiguration workflowConf = pParentJob as IJTXWorkflowConfiguration;
try
{
dependentStep = workflowConf.GetAllNextSteps(currentSteps[0])[0];
}
catch (IndexOutOfRangeException)
{
MessageBox.Show(Properties.Resources.NoNextStep, Properties.Resources.Error,
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
}
dependency.HeldOnValue = dependentStep;
dependency.Store();
IPropertySet props = new PropertySetClass();
props.SetProperty("[DEPENDENCY]", dependency.ID);
JobUtilities.LogJobAction(m_ipDatabase, pParentJob, Constants.ACTTYPE_ADD_DEPENDENCY, "", props);
}
////////////////////////////////////////////////////////////////////////
// METHOD: AssignChildVersion
private bool AssignChildVersion(IJTXJob2 pParentJob, ref IJTXJob pJob)
{
if (m_paramAssignVersionType == AssignVersionType.UseParentJobsVersion)
{
((IJTXJob2)pJob).SetActiveDatabase(pParentJob.ActiveDatabase.DatabaseID);
pJob.ParentVersion = pParentJob.ParentVersion;
pJob.VersionName = pParentJob.VersionName;
}
return true;
}
////////////////////////////////////////////////////////////////////////
// METHOD: CreateChildVersion
private bool CreateChildVersion(ref IJTXJob pJob)
{
IVersion pNewVersion = null;
try
{
string strVersionName = pJob.VersionName;
int index = strVersionName.IndexOf(".", 0);
if (index >= 0)
{
strVersionName = strVersionName.Substring(index + 1);
}
pJob.VersionName = strVersionName;
pNewVersion = pJob.CreateVersion(esriVersionAccess.esriVersionAccessPublic);
if (pNewVersion == null)
{
m_ipDatabase.LogMessage(3, 1000, "Unable to create version for child job ID: " + pJob.ID);
}
else
{
IPropertySet pOverrides = new PropertySetClass();
pOverrides.SetProperty("[VERSION]", pNewVersion.VersionName);
JobUtilities.LogJobAction(m_ipDatabase, pJob, Constants.ACTTYPE_CREATE_VERSION, "", pOverrides);
JTXUtilities.SendNotification(Constants.NOTIF_VERSION_CREATED, m_ipDatabase, pJob, pOverrides);
}
}
catch (Exception ex)
{
m_ipDatabase.LogMessage(3, 1000, "Unable to create version for child job ID: " + pJob.ID + ". ERROR: " + ex.Message);
}
finally
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(pNewVersion);
}
return true;
}
#endregion
} // End Class
} // End Namespace
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Globalization;
using System.Reflection;
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Resources
{
// Resource Manager exposes an assembly's resources to an application for
// the correct CultureInfo. An example would be localizing text for a
// user-visible message. Create a set of resource files listing a name
// for a message and its value, compile them using ResGen, put them in
// an appropriate place (your assembly manifest(?)), then create a Resource
// Manager and query for the name of the message you want. The Resource
// Manager will use CultureInfo.GetCurrentUICulture() to look
// up a resource for your user's locale settings.
//
// Users should ideally create a resource file for every culture, or
// at least a meaningful subset. The filenames will follow the naming
// scheme:
//
// basename.culture name.resources
//
// The base name can be the name of your application, or depending on
// the granularity desired, possibly the name of each class. The culture
// name is determined from CultureInfo's Name property.
// An example file name may be MyApp.en-US.resources for
// MyApp's US English resources.
//
// -----------------
// Refactoring Notes
// -----------------
// In Feb 08, began first step of refactoring ResourceManager to improve
// maintainability (sd changelist 3012100). This resulted in breaking
// apart the InternalGetResourceSet "big loop" so that the file-based
// and manifest-based lookup was located in separate methods.
// In Apr 08, continued refactoring so that file-based and manifest-based
// concerns are encapsulated by separate classes. At construction, the
// ResourceManager creates one of these classes based on whether the
// RM will need to use file-based or manifest-based resources, and
// afterwards refers to this through the interface IResourceGroveler.
//
// Serialization Compat: Ideally, we could have refactored further but
// this would have broken serialization compat. For example, the
// ResourceManager member UseManifest and UseSatelliteAssem are no
// longer relevant on ResourceManager. Similarly, other members could
// ideally be moved to the file-based or manifest-based classes
// because they are only relevant for those types of lookup.
//
// Solution now / in the future:
// For now, we simply use a mediator class so that we can keep these
// members on ResourceManager but allow the file-based and manifest-
// based classes to access/set these members in a uniform way. See
// ResourceManagerMediator.
// We encapsulate fallback logic in a fallback iterator class, so that
// this logic isn't duplicated in several methods.
//
// In the future, we can also look into further factoring and better
// design of IResourceGroveler interface to accommodate unused parameters
// that don't make sense for either file-based or manifest-based lookup paths.
//
// Benefits of this refactoring:
// - Makes it possible to understand what the ResourceManager does,
// which is key for maintainability.
// - Makes the ResourceManager more extensible by identifying and
// encapsulating what varies
// - Unearthed a bug that's been lurking a while in file-based
// lookup paths for InternalGetResourceSet if createIfNotExists is
// false.
// - Reuses logic, e.g. by breaking apart the culture fallback into
// the fallback iterator class, we don't have to repeat the
// sometimes confusing fallback logic across multiple methods
// - Fxcop violations reduced to 1/5th of original count. Most
// importantly, code complexity violations disappeared.
// - Finally, it got rid of dead code paths. Because the big loop was
// so confusing, it masked unused chunks of code. Also, dividing
// between file-based and manifest-based allowed functionaliy
// unused in silverlight to fall out.
//
// Note: this type is integral to the construction of exception objects,
// and sometimes this has to be done in low memory situtations (OOM) or
// to create TypeInitializationExceptions due to failure of a static class
// constructor. This type needs to be extremely careful and assume that
// any type it references may have previously failed to construct, so statics
// belonging to that type may not be initialized. FrameworkEventSource.Log
// is one such example.
//
public partial class ResourceManager
{
internal class CultureNameResourceSetPair
{
public string? lastCultureName;
public ResourceSet? lastResourceSet;
}
protected string BaseNameField;
protected Assembly? MainAssembly; // Need the assembly manifest sometimes.
private Dictionary<string, ResourceSet>? _resourceSets;
private string? _moduleDir; // For assembly-ignorant directory location
private Type? _locationInfo; // For Assembly or type-based directory layout
private Type? _userResourceSet; // Which ResourceSet instance to create
private CultureInfo? _neutralResourcesCulture; // For perf optimizations.
private CultureNameResourceSetPair? _lastUsedResourceCache;
private bool _ignoreCase; // Whether case matters in GetString & GetObject
private bool _useManifest; // Use Assembly manifest, or grovel disk.
// Whether to fall back to the main assembly or a particular
// satellite for the neutral resources.
private UltimateResourceFallbackLocation _fallbackLoc;
// Version number of satellite assemblies to look for. May be null.
private Version? _satelliteContractVersion;
private bool _lookedForSatelliteContractVersion;
private IResourceGroveler _resourceGroveler = null!;
public static readonly int MagicNumber = unchecked((int)0xBEEFCACE); // If only hex had a K...
// Version number so ResMgr can get the ideal set of classes for you.
// ResMgr header is:
// 1) MagicNumber (little endian Int32)
// 2) HeaderVersionNumber (little endian Int32)
// 3) Num Bytes to skip past ResMgr header (little endian Int32)
// 4) IResourceReader type name for this file (bytelength-prefixed UTF-8 String)
// 5) ResourceSet type name for this file (bytelength-prefixed UTF8 String)
public static readonly int HeaderVersionNumber = 1;
//
//It would be better if we could use _neutralCulture instead of calling
//CultureInfo.InvariantCulture everywhere, but we run into problems with the .cctor. CultureInfo
//initializes assembly, which initializes ResourceManager, which tries to get a CultureInfo which isn't
//there yet because CultureInfo's class initializer hasn't finished. If we move SystemResMgr off of
//Assembly (or at least make it an internal property) we should be able to circumvent this problem.
//
// private static CultureInfo _neutralCulture = null;
// This is our min required ResourceSet type.
private static readonly Type s_minResourceSet = typeof(ResourceSet);
// These Strings are used to avoid using Reflection in CreateResourceSet.
internal const string ResReaderTypeName = "System.Resources.ResourceReader";
internal const string ResSetTypeName = "System.Resources.RuntimeResourceSet";
internal const string ResFileExtension = ".resources";
internal const int ResFileExtensionLength = 10;
protected ResourceManager()
{
_lastUsedResourceCache = new CultureNameResourceSetPair();
ResourceManagerMediator mediator = new ResourceManagerMediator(this);
_resourceGroveler = new ManifestBasedResourceGroveler(mediator);
BaseNameField = string.Empty;
}
// Constructs a Resource Manager for files beginning with
// baseName in the directory specified by resourceDir
// or in the current directory. This Assembly-ignorant constructor is
// mostly useful for testing your own ResourceSet implementation.
//
// A good example of a baseName might be "Strings". BaseName
// should not end in ".resources".
//
// Note: System.Windows.Forms uses this method at design time.
//
private ResourceManager(string baseName, string resourceDir, Type? userResourceSet)
{
if (null == baseName)
throw new ArgumentNullException(nameof(baseName));
if (null == resourceDir)
throw new ArgumentNullException(nameof(resourceDir));
BaseNameField = baseName;
_moduleDir = resourceDir;
_userResourceSet = userResourceSet;
_resourceSets = new Dictionary<string, ResourceSet>();
_lastUsedResourceCache = new CultureNameResourceSetPair();
_useManifest = false;
ResourceManagerMediator mediator = new ResourceManagerMediator(this);
_resourceGroveler = new FileBasedResourceGroveler(mediator);
}
public ResourceManager(string baseName, Assembly assembly)
{
if (null == baseName)
throw new ArgumentNullException(nameof(baseName));
if (null == assembly)
throw new ArgumentNullException(nameof(assembly));
if (!assembly.IsRuntimeImplemented())
throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly);
MainAssembly = assembly;
BaseNameField = baseName;
CommonAssemblyInit();
}
public ResourceManager(string baseName, Assembly assembly, Type? usingResourceSet)
{
if (null == baseName)
throw new ArgumentNullException(nameof(baseName));
if (null == assembly)
throw new ArgumentNullException(nameof(assembly));
if (!assembly.IsRuntimeImplemented())
throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly);
MainAssembly = assembly;
BaseNameField = baseName;
if (usingResourceSet != null && (usingResourceSet != s_minResourceSet) && !(usingResourceSet.IsSubclassOf(s_minResourceSet)))
throw new ArgumentException(SR.Arg_ResMgrNotResSet, nameof(usingResourceSet));
_userResourceSet = usingResourceSet;
CommonAssemblyInit();
}
public ResourceManager(Type resourceSource)
{
if (null == resourceSource)
throw new ArgumentNullException(nameof(resourceSource));
if (!resourceSource.IsRuntimeImplemented())
throw new ArgumentException(SR.Argument_MustBeRuntimeType);
_locationInfo = resourceSource;
MainAssembly = _locationInfo.Assembly;
BaseNameField = resourceSource.Name;
CommonAssemblyInit();
}
// Trying to unify code as much as possible, even though having to do a
// security check in each constructor prevents it.
private void CommonAssemblyInit()
{
#if FEATURE_APPX || ENABLE_WINRT
SetUapConfiguration();
#endif
// Now we can use the managed resources even when using PRI's to support the APIs GetObject, GetStream...etc.
_useManifest = true;
_resourceSets = new Dictionary<string, ResourceSet>();
_lastUsedResourceCache = new CultureNameResourceSetPair();
ResourceManagerMediator mediator = new ResourceManagerMediator(this);
_resourceGroveler = new ManifestBasedResourceGroveler(mediator);
Debug.Assert(MainAssembly != null);
_neutralResourcesCulture = ManifestBasedResourceGroveler.GetNeutralResourcesLanguage(MainAssembly, out _fallbackLoc);
}
// Gets the base name for the ResourceManager.
public virtual string BaseName
{
get { return BaseNameField; }
}
// Whether we should ignore the capitalization of resources when calling
// GetString or GetObject.
public virtual bool IgnoreCase
{
get { return _ignoreCase; }
set { _ignoreCase = value; }
}
// Returns the Type of the ResourceSet the ResourceManager uses
// to construct ResourceSets.
public virtual Type ResourceSetType
{
get { return (_userResourceSet == null) ? typeof(RuntimeResourceSet) : _userResourceSet; }
}
protected UltimateResourceFallbackLocation FallbackLocation
{
get { return _fallbackLoc; }
set { _fallbackLoc = value; }
}
// Tells the ResourceManager to call Close on all ResourceSets and
// release all resources. This will shrink your working set by
// potentially a substantial amount in a running application. Any
// future resource lookups on this ResourceManager will be as
// expensive as the very first lookup, since it will need to search
// for files and load resources again.
//
// This may be useful in some complex threading scenarios, where
// creating a new ResourceManager isn't quite the correct behavior.
public virtual void ReleaseAllResources()
{
Debug.Assert(_resourceSets != null);
Dictionary<string, ResourceSet> localResourceSets = _resourceSets;
// If any calls to Close throw, at least leave ourselves in a
// consistent state.
_resourceSets = new Dictionary<string, ResourceSet>();
_lastUsedResourceCache = new CultureNameResourceSetPair();
lock (localResourceSets)
{
foreach ((_, ResourceSet resourceSet) in localResourceSets)
{
resourceSet.Close();
}
}
}
public static ResourceManager CreateFileBasedResourceManager(string baseName, string resourceDir, Type? usingResourceSet)
{
return new ResourceManager(baseName, resourceDir, usingResourceSet);
}
// Given a CultureInfo, GetResourceFileName generates the name for
// the binary file for the given CultureInfo. This method uses
// CultureInfo's Name property as part of the file name for all cultures
// other than the invariant culture. This method does not touch the disk,
// and is used only to construct what a resource file name (suitable for
// passing to the ResourceReader constructor) or a manifest resource file
// name should look like.
//
// This method can be overriden to look for a different extension,
// such as ".ResX", or a completely different format for naming files.
protected virtual string GetResourceFileName(CultureInfo culture)
{
// If this is the neutral culture, don't include the culture name.
if (culture.HasInvariantCultureName)
{
return BaseNameField + ResFileExtension;
}
else
{
CultureInfo.VerifyCultureName(culture.Name, throwException: true);
return BaseNameField + "." + culture.Name + ResFileExtension;
}
}
// WARNING: This function must be kept in sync with ResourceFallbackManager.GetEnumerator()
// Return the first ResourceSet, based on the first culture ResourceFallbackManager would return
internal ResourceSet? GetFirstResourceSet(CultureInfo culture)
{
// Logic from ResourceFallbackManager.GetEnumerator()
if (_neutralResourcesCulture != null && culture.Name == _neutralResourcesCulture.Name)
{
culture = CultureInfo.InvariantCulture;
}
if (_lastUsedResourceCache != null)
{
lock (_lastUsedResourceCache)
{
if (culture.Name == _lastUsedResourceCache.lastCultureName)
return _lastUsedResourceCache.lastResourceSet;
}
}
// Look in the ResourceSet table
Dictionary<string, ResourceSet>? localResourceSets = _resourceSets;
ResourceSet? rs = null;
if (localResourceSets != null)
{
lock (localResourceSets)
{
localResourceSets.TryGetValue(culture.Name, out rs);
}
}
if (rs != null)
{
// update the cache with the most recent ResourceSet
if (_lastUsedResourceCache != null)
{
lock (_lastUsedResourceCache)
{
_lastUsedResourceCache.lastCultureName = culture.Name;
_lastUsedResourceCache.lastResourceSet = rs;
}
}
return rs;
}
return null;
}
// Looks up a set of resources for a particular CultureInfo. This is
// not useful for most users of the ResourceManager - call
// GetString() or GetObject() instead.
//
// The parameters let you control whether the ResourceSet is created
// if it hasn't yet been loaded and if parent CultureInfos should be
// loaded as well for resource inheritance.
//
public virtual ResourceSet? GetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents)
{
if (null == culture)
throw new ArgumentNullException(nameof(culture));
Dictionary<string, ResourceSet>? localResourceSets = _resourceSets;
ResourceSet? rs;
if (localResourceSets != null)
{
lock (localResourceSets)
{
if (localResourceSets.TryGetValue(culture.Name, out rs))
return rs;
}
}
if (_useManifest && culture.HasInvariantCultureName)
{
string fileName = GetResourceFileName(culture);
Debug.Assert(MainAssembly != null);
Stream? stream = MainAssembly.GetManifestResourceStream(_locationInfo!, fileName);
if (createIfNotExists && stream != null)
{
rs = ((ManifestBasedResourceGroveler)_resourceGroveler).CreateResourceSet(stream, MainAssembly);
Debug.Assert(localResourceSets != null);
AddResourceSet(localResourceSets, culture.Name, ref rs);
return rs;
}
}
return InternalGetResourceSet(culture, createIfNotExists, tryParents);
}
// InternalGetResourceSet is a non-threadsafe method where all the logic
// for getting a resource set lives. Access to it is controlled by
// threadsafe methods such as GetResourceSet, GetString, & GetObject.
// This will take a minimal number of locks.
protected virtual ResourceSet? InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents)
{
Debug.Assert(culture != null, "culture != null");
Debug.Assert(_resourceSets != null);
Dictionary<string, ResourceSet> localResourceSets = _resourceSets;
ResourceSet? rs = null;
CultureInfo? foundCulture = null;
lock (localResourceSets)
{
if (localResourceSets.TryGetValue(culture.Name, out rs))
{
return rs;
}
}
ResourceFallbackManager mgr = new ResourceFallbackManager(culture, _neutralResourcesCulture, tryParents);
foreach (CultureInfo currentCultureInfo in mgr)
{
lock (localResourceSets)
{
if (localResourceSets.TryGetValue(currentCultureInfo.Name, out rs))
{
// we need to update the cache if we fellback
if (culture != currentCultureInfo) foundCulture = currentCultureInfo;
break;
}
}
// InternalGetResourceSet will never be threadsafe. However, it must
// be protected against reentrancy from the SAME THREAD. (ie, calling
// GetSatelliteAssembly may send some window messages or trigger the
// Assembly load event, which could fail then call back into the
// ResourceManager). It's happened.
rs = _resourceGroveler.GrovelForResourceSet(currentCultureInfo, localResourceSets,
tryParents, createIfNotExists);
// found a ResourceSet; we're done
if (rs != null)
{
foundCulture = currentCultureInfo;
break;
}
}
if (rs != null && foundCulture != null)
{
// add entries to the cache for the cultures we have gone through
// currentCultureInfo now refers to the culture that had resources.
// update cultures starting from requested culture up to the culture
// that had resources.
foreach (CultureInfo updateCultureInfo in mgr)
{
AddResourceSet(localResourceSets, updateCultureInfo.Name, ref rs);
// stop when we've added current or reached invariant (top of chain)
if (updateCultureInfo == foundCulture)
{
break;
}
}
}
return rs;
}
// Simple helper to ease maintenance and improve readability.
private static void AddResourceSet(Dictionary<string, ResourceSet> localResourceSets, string cultureName, ref ResourceSet rs)
{
// InternalGetResourceSet is both recursive and reentrant -
// assembly load callbacks in particular are a way we can call
// back into the ResourceManager in unexpectedly on the same thread.
lock (localResourceSets)
{
// If another thread added this culture, return that.
ResourceSet? lostRace;
if (localResourceSets.TryGetValue(cultureName, out lostRace))
{
if (!object.ReferenceEquals(lostRace, rs))
{
// Note: In certain cases, we can be trying to add a ResourceSet for multiple
// cultures on one thread, while a second thread added another ResourceSet for one
// of those cultures. If there is a race condition we must make sure our ResourceSet
// isn't in our dictionary before closing it.
if (!localResourceSets.ContainsValue(rs))
rs.Dispose();
rs = lostRace;
}
}
else
{
localResourceSets.Add(cultureName, rs);
}
}
}
protected static Version? GetSatelliteContractVersion(Assembly a)
{
// Ensure that the assembly reference is not null
if (a == null)
{
throw new ArgumentNullException(nameof(a), SR.ArgumentNull_Assembly);
}
string? v = a.GetCustomAttribute<SatelliteContractVersionAttribute>()?.Version;
if (v == null)
{
// Return null. The calling code will use the assembly version instead to avoid potential type
// and library loads caused by CA lookup.
return null;
}
if (!Version.TryParse(v, out Version? version))
{
throw new ArgumentException(SR.Format(SR.Arg_InvalidSatelliteContract_Asm_Ver, a, v));
}
return version;
}
protected static CultureInfo GetNeutralResourcesLanguage(Assembly a)
{
// This method should be obsolete - replace it with the one below.
// Unfortunately, we made it protected.
return ManifestBasedResourceGroveler.GetNeutralResourcesLanguage(a, out _);
}
// IGNORES VERSION
internal static bool IsDefaultType(string asmTypeName,
string typeName)
{
Debug.Assert(asmTypeName != null, "asmTypeName was unexpectedly null");
// First, compare type names
int comma = asmTypeName.IndexOf(',');
if (((comma == -1) ? asmTypeName.Length : comma) != typeName.Length)
return false;
// case sensitive
if (string.Compare(asmTypeName, 0, typeName, 0, typeName.Length, StringComparison.Ordinal) != 0)
return false;
if (comma == -1)
return true;
// Now, compare assembly display names (IGNORES VERSION AND PROCESSORARCHITECTURE)
// also, for mscorlib ignores everything, since that's what the binder is going to do
while (char.IsWhiteSpace(asmTypeName[++comma])) ;
// case insensitive
AssemblyName an = new AssemblyName(asmTypeName.Substring(comma));
// to match IsMscorlib() in VM
return string.Equals(an.Name, "mscorlib", StringComparison.OrdinalIgnoreCase);
}
// Looks up a resource value for a particular name. Looks in the
// current thread's CultureInfo, and if not found, all parent CultureInfos.
// Returns null if the resource wasn't found.
//
public virtual string? GetString(string name)
{
return GetString(name, null);
}
// Looks up a resource value for a particular name. Looks in the
// specified CultureInfo, and if not found, all parent CultureInfos.
// Returns null if the resource wasn't found.
//
public virtual string? GetString(string name, CultureInfo? culture)
{
if (null == name)
throw new ArgumentNullException(nameof(name));
#if FEATURE_APPX || ENABLE_WINRT
if (_useUapResourceManagement)
{
// Throws WinRT hresults.
Debug.Assert(_neutralResourcesCulture != null);
return GetStringFromPRI(name, culture, _neutralResourcesCulture.Name);
}
#endif
if (culture == null)
{
culture = CultureInfo.CurrentUICulture;
}
ResourceSet? last = GetFirstResourceSet(culture);
if (last != null)
{
string? value = last.GetString(name, _ignoreCase);
if (value != null)
return value;
}
// This is the CultureInfo hierarchy traversal code for resource
// lookups, similar but necessarily orthogonal to the ResourceSet
// lookup logic.
ResourceFallbackManager mgr = new ResourceFallbackManager(culture, _neutralResourcesCulture, true);
foreach (CultureInfo currentCultureInfo in mgr)
{
ResourceSet? rs = InternalGetResourceSet(currentCultureInfo, true, true);
if (rs == null)
break;
if (rs != last)
{
string? value = rs.GetString(name, _ignoreCase);
if (value != null)
{
// update last used ResourceSet
if (_lastUsedResourceCache != null)
{
lock (_lastUsedResourceCache)
{
_lastUsedResourceCache.lastCultureName = currentCultureInfo.Name;
_lastUsedResourceCache.lastResourceSet = rs;
}
}
return value;
}
last = rs;
}
}
return null;
}
// Looks up a resource value for a particular name. Looks in the
// current thread's CultureInfo, and if not found, all parent CultureInfos.
// Returns null if the resource wasn't found.
//
public virtual object? GetObject(string name)
{
return GetObject(name, null, true);
}
// Looks up a resource value for a particular name. Looks in the
// specified CultureInfo, and if not found, all parent CultureInfos.
// Returns null if the resource wasn't found.
public virtual object? GetObject(string name, CultureInfo? culture)
{
return GetObject(name, culture, true);
}
private object? GetObject(string name, CultureInfo? culture, bool wrapUnmanagedMemStream)
{
if (null == name)
throw new ArgumentNullException(nameof(name));
if (null == culture)
{
culture = CultureInfo.CurrentUICulture;
}
ResourceSet? last = GetFirstResourceSet(culture);
if (last != null)
{
object? value = last.GetObject(name, _ignoreCase);
if (value != null)
{
if (value is UnmanagedMemoryStream stream && wrapUnmanagedMemStream)
return new UnmanagedMemoryStreamWrapper(stream);
else
return value;
}
}
// This is the CultureInfo hierarchy traversal code for resource
// lookups, similar but necessarily orthogonal to the ResourceSet
// lookup logic.
ResourceFallbackManager mgr = new ResourceFallbackManager(culture, _neutralResourcesCulture, true);
foreach (CultureInfo currentCultureInfo in mgr)
{
ResourceSet? rs = InternalGetResourceSet(currentCultureInfo, true, true);
if (rs == null)
break;
if (rs != last)
{
object? value = rs.GetObject(name, _ignoreCase);
if (value != null)
{
// update the last used ResourceSet
if (_lastUsedResourceCache != null)
{
lock (_lastUsedResourceCache)
{
_lastUsedResourceCache.lastCultureName = currentCultureInfo.Name;
_lastUsedResourceCache.lastResourceSet = rs;
}
}
if (value is UnmanagedMemoryStream stream && wrapUnmanagedMemStream)
return new UnmanagedMemoryStreamWrapper(stream);
else
return value;
}
last = rs;
}
}
return null;
}
public UnmanagedMemoryStream? GetStream(string name)
{
return GetStream(name, null);
}
public UnmanagedMemoryStream? GetStream(string name, CultureInfo? culture)
{
object? obj = GetObject(name, culture, false);
UnmanagedMemoryStream? ums = obj as UnmanagedMemoryStream;
if (ums == null && obj != null)
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotStream_Name, name));
return ums;
}
internal class ResourceManagerMediator
{
private ResourceManager _rm;
internal ResourceManagerMediator(ResourceManager rm)
{
if (rm == null)
{
throw new ArgumentNullException(nameof(rm));
}
_rm = rm;
}
// NEEDED ONLY BY FILE-BASED
internal string? ModuleDir
{
get { return _rm._moduleDir; }
}
// NEEDED BOTH BY FILE-BASED AND ASSEMBLY-BASED
internal Type? LocationInfo
{
get { return _rm._locationInfo; }
}
internal Type? UserResourceSet
{
get { return _rm._userResourceSet; }
}
internal string? BaseNameField
{
get { return _rm.BaseNameField; }
}
internal CultureInfo? NeutralResourcesCulture
{
get { return _rm._neutralResourcesCulture; }
set { _rm._neutralResourcesCulture = value; }
}
internal string GetResourceFileName(CultureInfo culture)
{
return _rm.GetResourceFileName(culture);
}
// NEEDED ONLY BY ASSEMBLY-BASED
internal bool LookedForSatelliteContractVersion
{
get { return _rm._lookedForSatelliteContractVersion; }
set { _rm._lookedForSatelliteContractVersion = value; }
}
internal Version? SatelliteContractVersion
{
get { return _rm._satelliteContractVersion; }
set { _rm._satelliteContractVersion = value; }
}
internal Version? ObtainSatelliteContractVersion(Assembly a)
{
return ResourceManager.GetSatelliteContractVersion(a);
}
internal UltimateResourceFallbackLocation FallbackLoc
{
get { return _rm.FallbackLocation; }
set { _rm._fallbackLoc = value; }
}
internal Assembly? MainAssembly
{
get { return _rm.MainAssembly; }
}
// this is weird because we have BaseNameField accessor above, but we're sticking
// with it for compat.
internal string BaseName
{
get { return _rm.BaseName; }
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Agent.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Services.ServiceEndpoints.Common;
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
using Microsoft.VisualStudio.Services.Agent.Worker.Release.Artifacts.Definition;
using Microsoft.VisualStudio.Services.ReleaseManagement.WebApi.Contracts;
using ServiceEndpointContracts = Microsoft.VisualStudio.Services.ServiceEndpoints.WebApi;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.VisualStudio.Services.Agent.Worker.Release.Artifacts
{
public class CustomArtifact : AgentService, IArtifactExtension
{
public Type ExtensionType => typeof(IArtifactExtension);
public AgentArtifactType ArtifactType => AgentArtifactType.Custom;
public async Task DownloadAsync(IExecutionContext executionContext, ArtifactDefinition artifactDefinition, string downloadFolderPath)
{
ArgUtil.NotNull(executionContext, nameof(executionContext));
ArgUtil.NotNull(artifactDefinition, nameof(artifactDefinition));
EnsureVersionBelongsToLinkedDefinition(artifactDefinition);
var customArtifactDetails = artifactDefinition.Details as CustomArtifactDetails;
if (customArtifactDetails != null)
{
IEnumerable<string> artifactDetails = new EndpointProxy().QueryEndpoint(
ToServiceEndpoint(customArtifactDetails.Endpoint),
customArtifactDetails.ArtifactsUrl,
null,
customArtifactDetails.ResultSelector,
customArtifactDetails.ResultTemplate,
customArtifactDetails.AuthorizationHeaders?.Select(header => ToAuthorizationHeader(header)).ToList(),
customArtifactDetails.ArtifactVariables);
var artifactDownloadDetailList = new List<CustomArtifactDownloadDetails>();
artifactDetails.ToList().ForEach(x => artifactDownloadDetailList.Add(JToken.Parse(x).ToObject<CustomArtifactDownloadDetails>()));
if (artifactDownloadDetailList.Count <= 0)
{
executionContext.Warning(StringUtil.Loc("NoArtifactsFound", artifactDefinition.Version));
return;
}
foreach (CustomArtifactDownloadDetails artifactDownloadDetails in artifactDownloadDetailList)
{
executionContext.Output(StringUtil.Loc("StartingArtifactDownload", artifactDownloadDetails.DownloadUrl));
await DownloadArtifact(executionContext, HostContext, downloadFolderPath, customArtifactDetails, artifactDownloadDetails);
}
}
}
public IArtifactDetails GetArtifactDetails(IExecutionContext context, AgentArtifactDefinition agentArtifactDefinition)
{
ArgUtil.NotNull(context, nameof(context));
ArgUtil.NotNull(agentArtifactDefinition, nameof(agentArtifactDefinition));
var artifactDetails = JsonConvert.DeserializeObject<Dictionary<string, string>>(agentArtifactDefinition.Details);
string connectionName;
string relativePath = string.Empty;
string customArtifactDetails = string.Empty;
if (!(artifactDetails.TryGetValue("ConnectionName", out connectionName)
&& artifactDetails.TryGetValue("RelativePath", out relativePath)
&& artifactDetails.TryGetValue("ArtifactDetails", out customArtifactDetails)))
{
throw new InvalidOperationException(StringUtil.Loc("RMArtifactDetailsIncomplete"));
}
var customEndpoint = context.Endpoints.FirstOrDefault((e => string.Equals(e.Name, connectionName, StringComparison.OrdinalIgnoreCase)));
if (customEndpoint == null)
{
throw new InvalidOperationException(StringUtil.Loc("RMCustomEndpointNotFound", agentArtifactDefinition.Name));
}
var details = JToken.Parse(customArtifactDetails).ToObject<CustomArtifactDetails>();
details.RelativePath = relativePath;
details.Endpoint = new ServiceEndpoint
{
Url = customEndpoint.Url,
Authorization = customEndpoint.Authorization
};
return details;
}
private async Task DownloadArtifact(
IExecutionContext executionContext,
IHostContext hostContext,
string localFolderPath,
CustomArtifactDetails customArtifactDetails,
CustomArtifactDownloadDetails artifact)
{
IDictionary<string, string> artifactTypeStreamMapping = customArtifactDetails.ArtifactTypeStreamMapping;
string streamType = GetArtifactStreamType(artifact, artifactTypeStreamMapping);
if (string.Equals(streamType, WellKnownStreamTypes.FileShare, StringComparison.OrdinalIgnoreCase))
{
if (!PlatformUtil.RunningOnWindows)
{
throw new NotSupportedException(StringUtil.Loc("RMFileShareArtifactErrorOnNonWindowsAgent"));
}
var fileShareArtifact = new FileShareArtifact();
customArtifactDetails.RelativePath = artifact.RelativePath ?? string.Empty;
var location = artifact.FileShareLocation ?? artifact.DownloadUrl;
await fileShareArtifact.DownloadArtifactAsync(executionContext, hostContext, new ArtifactDefinition { Details = customArtifactDetails }, new Uri(location).LocalPath, localFolderPath);
}
else if (string.Equals(streamType, WellKnownStreamTypes.Zip, StringComparison.OrdinalIgnoreCase))
{
try
{
IEndpointAuthorizer authorizer = SchemeBasedAuthorizerFactory.GetEndpointAuthorizer(
ToServiceEndpoint(customArtifactDetails.Endpoint),
customArtifactDetails.AuthorizationHeaders?.Select(header => ToAuthorizationHeader(header)).ToList());
using (HttpWebResponse webResponse = GetWebResponse(executionContext, artifact.DownloadUrl, authorizer))
{
var zipStreamDownloader = HostContext.GetService<IZipStreamDownloader>();
await zipStreamDownloader.DownloadFromStream(
executionContext,
webResponse.GetResponseStream(),
string.Empty,
artifact.RelativePath ?? string.Empty,
localFolderPath);
}
}
catch (WebException)
{
executionContext.Output(StringUtil.Loc("ArtifactDownloadFailed", artifact.DownloadUrl));
throw;
}
}
else
{
string resourceType = streamType;
var warningMessage = StringUtil.Loc("RMStreamTypeNotSupported", resourceType);
executionContext.Warning(warningMessage);
}
}
private static string GetArtifactStreamType(CustomArtifactDownloadDetails artifact, IDictionary<string, string> artifactTypeStreamMapping)
{
string streamType = artifact.StreamType;
if (artifactTypeStreamMapping == null)
{
return streamType;
}
var artifactTypeStreamMappings = new Dictionary<string, string>(artifactTypeStreamMapping, StringComparer.OrdinalIgnoreCase);
if (artifactTypeStreamMappings.ContainsKey(artifact.StreamType))
{
streamType = artifactTypeStreamMappings[artifact.StreamType];
}
return streamType;
}
private static HttpWebResponse GetWebResponse(IExecutionContext executionContext, string url, IEndpointAuthorizer authorizer)
{
var request = WebRequest.Create(url) as HttpWebRequest;
if (request == null)
{
string errorMessage = StringUtil.Loc("RMArtifactDownloadRequestCreationFailed", url);
executionContext.Output(errorMessage);
throw new InvalidOperationException(errorMessage);
}
authorizer.AuthorizeRequest(request, null);
var webResponse = request.GetResponseAsync().Result as HttpWebResponse;
return webResponse;
}
private void EnsureVersionBelongsToLinkedDefinition(ArtifactDefinition artifactDefinition)
{
var customArtifactDetails = artifactDefinition.Details as CustomArtifactDetails;
if (customArtifactDetails != null && !string.IsNullOrEmpty(customArtifactDetails.VersionsUrl))
{
// Query for all artifact versions for given artifact source id, these parameters are contained in customArtifactDetails.ArtifactVariables
var versionBelongsToDefinition = false;
IEnumerable<string> versions = new EndpointProxy().QueryEndpoint(
ToServiceEndpoint(customArtifactDetails.Endpoint),
customArtifactDetails.VersionsUrl,
null,
customArtifactDetails.VersionsResultSelector,
customArtifactDetails.VersionsResultTemplate,
customArtifactDetails.AuthorizationHeaders?.Select(header => ToAuthorizationHeader(header)).ToList(),
customArtifactDetails.ArtifactVariables);
foreach (var version in versions)
{
var versionDetails = JToken.Parse(version).ToObject<CustomArtifactVersionDetails>();
if (versionDetails != null && versionDetails.Value.Equals(artifactDefinition.Version, StringComparison.OrdinalIgnoreCase))
{
versionBelongsToDefinition = true;
break;
}
}
if (!versionBelongsToDefinition)
{
throw new ArtifactDownloadException(
StringUtil.Loc("RMArtifactVersionNotBelongToArtifactSource", artifactDefinition.Version, customArtifactDetails.ArtifactVariables["definition"]));
}
}
}
private ServiceEndpointContracts.ServiceEndpoint ToServiceEndpoint(ServiceEndpoint legacyServiceEndpoint)
{
if (legacyServiceEndpoint == null)
{
return null;
}
var serviceEndpoint = new ServiceEndpointContracts.ServiceEndpoint
{
Authorization = ToEndpointAuthorization(legacyServiceEndpoint.Authorization),
CreatedBy = legacyServiceEndpoint.CreatedBy,
Data = legacyServiceEndpoint.Data,
Description = legacyServiceEndpoint.Description,
Id = legacyServiceEndpoint.Id,
IsReady = legacyServiceEndpoint.IsReady,
Name = legacyServiceEndpoint.Name,
OperationStatus = legacyServiceEndpoint.OperationStatus,
Type = legacyServiceEndpoint.Type,
Url = legacyServiceEndpoint.Url
};
return serviceEndpoint;
}
private static ServiceEndpointContracts.EndpointAuthorization ToEndpointAuthorization(EndpointAuthorization legacyEndpointAuthorization)
{
if (legacyEndpointAuthorization == null)
{
return null;
}
var endpointAuthorization = new ServiceEndpointContracts.EndpointAuthorization
{
Scheme = legacyEndpointAuthorization.Scheme
};
foreach (var param in legacyEndpointAuthorization.Parameters)
{
endpointAuthorization.Parameters.Add(param.Key, param.Value);
}
return endpointAuthorization;
}
private static ServiceEndpointContracts.AuthorizationHeader ToAuthorizationHeader(AuthorizationHeader legacyAuthorizationHeader)
{
if (legacyAuthorizationHeader == null)
{
return null;
}
var authorizationHeader = new ServiceEndpointContracts.AuthorizationHeader
{
Name = legacyAuthorizationHeader.Name,
Value = legacyAuthorizationHeader.Value
};
return authorizationHeader;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using AxiomCoders.PdfTemplateEditor.Common;
namespace AxiomCoders.PdfTemplateEditor.EditorStuff
{
public class GridLine
{
public GridLine()
{
}
public float x1, x2;
public float y1, y2;
}
public class EditorGrid
{
private MeasureUnits unit = MeasureUnits.inch;
private bool snap;
private Color lineColor = Color.DarkGray;
private Pen majorLinePen;
private Pen minorLinePen;
private float lineWidth = 1.0F;
private bool showGrid;
private bool showMinorLines = true;
private float subdivisions = 4.0F;
private bool linesMaked;
private float gridInterval = -1;
private System.Drawing.Drawing2D.DashStyle lineStyle = System.Drawing.Drawing2D.DashStyle.Solid;
private List<GridLine> majorHorizontal = new List<GridLine>();
private List<GridLine> majorVertical = new List<GridLine>();
private List<GridLine> minorHorizontal = new List<GridLine>();
private List<GridLine> minorVertical = new List<GridLine>();
public EditorGrid()
{
majorLinePen = new Pen(AppOptions.Instance.GridColor, lineWidth);
majorLinePen.DashStyle = lineStyle;
minorLinePen = new Pen(AppOptions.Instance.GridColor, lineWidth);
minorLinePen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
}
public MeasureUnits Unit
{
get { return unit; }
set
{
if(unit != value)
{
unit = value;
MakeAllLines();
}
}
}
public System.Drawing.Drawing2D.DashStyle LineStyle
{
get { return lineStyle; }
set { lineStyle = value; majorLinePen.DashStyle = lineStyle; }
}
public bool Snap
{
get { return snap; }
set { snap = value; }
}
public Color LineColor
{
get { return lineColor; }
set
{
lineColor = value;
majorLinePen.Brush = new SolidBrush(lineColor);
minorLinePen.Brush = new SolidBrush(lineColor);
}
}
public float LineWidth
{
get { return lineWidth; }
set
{
lineWidth = value;
majorLinePen.Width = lineWidth;
minorLinePen.Width = lineWidth;
}
}
private void MakeAllLines()
{
majorHorizontal.Clear();
majorVertical.Clear();
minorHorizontal.Clear();
minorVertical.Clear();
float endWidth = UnitsManager.Instance.ConvertUnit(EditorController.Instance.EditorProject.ReportPage.WidthInPixels, MeasureUnits.pixel, this.unit);
float endHeighit = UnitsManager.Instance.ConvertUnit(EditorController.Instance.EditorProject.ReportPage.HeightInPixels, MeasureUnits.pixel, this.unit);
int numOfHLines = (int)(endHeighit / this.gridInterval);
int numOfVLines = (int)(endWidth / this.gridInterval);
//Make major lines
for(int i = 0; i <= numOfHLines; i++)
{
GridLine tmpLine = new GridLine();
float result = 0.0F;
result = (float)i * this.gridInterval;
tmpLine.x1 = 0.0F;
tmpLine.y1 = result;
tmpLine.x2 = endWidth;
tmpLine.y2 = result;
majorHorizontal.Add(tmpLine);
}
for(int i = 0; i <= numOfVLines; i++)
{
GridLine tmpLine = new GridLine();
float result = 0.0F;
result = (float)i * this.gridInterval;
tmpLine.x1 = result;
tmpLine.y1 = 0.0F;
tmpLine.x2 = result;
tmpLine.y2 = endHeighit;
majorVertical.Add(tmpLine);
}
//Make minor lines
int counter = 0;
for(int i = 0; i <= (numOfHLines + 1)* subdivisions; i++)
{
if(counter == 0)
{
counter++;
continue;
}
else
{
if(counter == (int)subdivisions)
{
counter = 1;
continue;
}
else
{
GridLine tmpLine = new GridLine();
float result = 0.0F;
result = (float)i * this.gridInterval / subdivisions;
if(result < endHeighit)
{
tmpLine.x1 = 0.0F;
tmpLine.y1 = result;
tmpLine.x2 = endWidth;
tmpLine.y2 = result;
minorHorizontal.Add(tmpLine);
}
counter++;
}
}
}
counter = 0;
for(int i = 0; i <= (numOfVLines + 1) * subdivisions; i++)
{
if(counter == 0)
{
counter++;
continue;
}
else
{
if(counter == (int)subdivisions)
{
counter = 1;
continue;
}
else
{
GridLine tmpLine = new GridLine();
float result = 0.0F;
result = (float)i * this.gridInterval / subdivisions;
if(result < endWidth)
{
tmpLine.x1 = result;
tmpLine.y1 = 0.0F;
tmpLine.x2 = result;
tmpLine.y2 = endHeighit;
minorVertical.Add(tmpLine);
}
counter++;
}
}
}
linesMaked = true;
}
private void UpdateGridOptions()
{
if((gridInterval != AppOptions.Instance.GridInterval) ||
(this.subdivisions != AppOptions.Instance.GridSubdivisions))
{
gridInterval = AppOptions.Instance.GridInterval;
subdivisions = AppOptions.Instance.GridSubdivisions;
MakeAllLines();
}
majorLinePen.Color = AppOptions.Instance.GridColor;
minorLinePen.Color = AppOptions.Instance.GridColor;
switch (AppOptions.Instance.GridLineStyle)
{
case 0: LineStyle = System.Drawing.Drawing2D.DashStyle.Solid; break;
case 1: LineStyle = System.Drawing.Drawing2D.DashStyle.Dash; break;
case 2: LineStyle = System.Drawing.Drawing2D.DashStyle.Dot; break;
}
switch (AppOptions.Instance.GridUnit)
{
case 0: Unit = MeasureUnits.inch; break;
case 1: Unit = MeasureUnits.cm; break;
case 2: Unit = MeasureUnits.mm; break;
case 3: Unit = MeasureUnits.pixel; break;
}
}
public void Draw(Graphics gc)
{
if (!AppOptions.Instance.ShowGrid)
{
return;
}
UpdateGridOptions();
DrawMinorLines(gc);
DrawMajorLines(gc);
}
private void DrawMajorLines(Graphics gc)
{
gc.Transform = EditorController.Instance.EditorProject.CurrentReportPage.LastDrawMatrix;
foreach(GridLine tmpLine in majorHorizontal)
{
float zoom = (float)EditorController.Instance.EditorProject.CurrentReportPage.ZoomLevel / 100.0f;
majorLinePen.Width = 1.0f / zoom;
gc.DrawLine(majorLinePen, UnitsManager.Instance.ConvertUnit(tmpLine.x1, this.Unit, MeasureUnits.pixel),
UnitsManager.Instance.ConvertUnit(tmpLine.y1, this.Unit, MeasureUnits.pixel),
UnitsManager.Instance.ConvertUnit(tmpLine.x2, this.Unit, MeasureUnits.pixel),
UnitsManager.Instance.ConvertUnit(tmpLine.y2, this.Unit, MeasureUnits.pixel));
}
foreach(GridLine tmpLine in majorVertical)
{
float zoom = (float)EditorController.Instance.EditorProject.CurrentReportPage.ZoomLevel / 100.0f;
majorLinePen.Width = 1.0f / zoom;
gc.DrawLine(majorLinePen, UnitsManager.Instance.ConvertUnit(tmpLine.x1, this.Unit, MeasureUnits.pixel),
UnitsManager.Instance.ConvertUnit(tmpLine.y1, this.Unit, MeasureUnits.pixel),
UnitsManager.Instance.ConvertUnit(tmpLine.x2, this.Unit, MeasureUnits.pixel),
UnitsManager.Instance.ConvertUnit(tmpLine.y2, this.Unit, MeasureUnits.pixel));
}
}
private void DrawMinorLines(Graphics gc)
{
if(!AppOptions.Instance.ShowGridMinorLines)
{
return;
}
gc.Transform = EditorController.Instance.EditorProject.ReportPage.LastDrawMatrix;
foreach(GridLine tmpLine in minorHorizontal)
{
float zoom = (float)EditorController.Instance.EditorProject.CurrentReportPage.ZoomLevel / 100.0f;
minorLinePen.Width = 1.0f / zoom;
gc.DrawLine(minorLinePen, UnitsManager.Instance.ConvertUnit(tmpLine.x1, this.Unit, MeasureUnits.pixel),
UnitsManager.Instance.ConvertUnit(tmpLine.y1, this.Unit, MeasureUnits.pixel),
UnitsManager.Instance.ConvertUnit(tmpLine.x2, this.Unit, MeasureUnits.pixel),
UnitsManager.Instance.ConvertUnit(tmpLine.y2, this.Unit, MeasureUnits.pixel));
}
foreach(GridLine tmpLine in minorVertical)
{
float zoom = (float)EditorController.Instance.EditorProject.CurrentReportPage.ZoomLevel / 100.0f;
minorLinePen.Width = 1.0f / zoom;
gc.DrawLine(minorLinePen, UnitsManager.Instance.ConvertUnit(tmpLine.x1, this.Unit, MeasureUnits.pixel),
UnitsManager.Instance.ConvertUnit(tmpLine.y1, this.Unit, MeasureUnits.pixel),
UnitsManager.Instance.ConvertUnit(tmpLine.x2, this.Unit, MeasureUnits.pixel),
UnitsManager.Instance.ConvertUnit(tmpLine.y2, this.Unit, MeasureUnits.pixel));
}
}
}
}
| |
using System.IO;
namespace Lucene.Net.Search.Payloads
{
using Lucene.Net.Index;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using Bits = Lucene.Net.Util.Bits;
using BytesRef = Lucene.Net.Util.BytesRef;
using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum;
using Similarity = Lucene.Net.Search.Similarities.Similarity;
using SpanQuery = Lucene.Net.Search.Spans.SpanQuery;
using SpanScorer = Lucene.Net.Search.Spans.SpanScorer;
using SpanTermQuery = Lucene.Net.Search.Spans.SpanTermQuery;
using SpanWeight = Lucene.Net.Search.Spans.SpanWeight;
using Term = Lucene.Net.Index.Term;
using TermSpans = Lucene.Net.Search.Spans.TermSpans;
/// <summary>
/// this class is very similar to
/// <seealso cref="Lucene.Net.Search.Spans.SpanTermQuery"/> except that it factors
/// in the value of the payload located at each of the positions where the
/// <seealso cref="Lucene.Net.Index.Term"/> occurs.
/// <p/>
/// NOTE: In order to take advantage of this with the default scoring implementation
/// (<seealso cref="DefaultSimilarity"/>), you must override <seealso cref="DefaultSimilarity#scorePayload(int, int, int, BytesRef)"/>,
/// which returns 1 by default.
/// <p/>
/// Payload scores are aggregated using a pluggable <seealso cref="PayloadFunction"/>. </summary>
/// <seealso cref= Lucene.Net.Search.Similarities.Similarity.SimScorer#computePayloadFactor(int, int, int, BytesRef)
/// </seealso>
public class PayloadTermQuery : SpanTermQuery
{
protected internal PayloadFunction Function;
private bool IncludeSpanScore;
public PayloadTermQuery(Term term, PayloadFunction function)
: this(term, function, true)
{
}
public PayloadTermQuery(Term term, PayloadFunction function, bool includeSpanScore)
: base(term)
{
this.Function = function;
this.IncludeSpanScore = includeSpanScore;
}
public override Weight CreateWeight(IndexSearcher searcher)
{
return new PayloadTermWeight(this, this, searcher);
}
protected internal class PayloadTermWeight : SpanWeight
{
private readonly PayloadTermQuery OuterInstance;
public PayloadTermWeight(PayloadTermQuery outerInstance, PayloadTermQuery query, IndexSearcher searcher)
: base(query, searcher)
{
this.OuterInstance = outerInstance;
}
public override Scorer Scorer(AtomicReaderContext context, Bits acceptDocs)
{
return new PayloadTermSpanScorer(this, (TermSpans)query.GetSpans(context, acceptDocs, TermContexts), this, Similarity.DoSimScorer(Stats, context));
}
protected internal class PayloadTermSpanScorer : SpanScorer
{
private readonly PayloadTermQuery.PayloadTermWeight OuterInstance;
protected internal BytesRef Payload;
protected internal float PayloadScore_Renamed;
protected internal int PayloadsSeen;
internal readonly TermSpans TermSpans;
public PayloadTermSpanScorer(PayloadTermQuery.PayloadTermWeight outerInstance, TermSpans spans, Weight weight, Similarity.SimScorer docScorer)
: base(spans, weight, docScorer)
{
this.OuterInstance = outerInstance;
TermSpans = spans;
}
protected internal override bool SetFreqCurrentDoc()
{
if (!More)
{
return false;
}
Doc = Spans.Doc();
Freq_Renamed = 0.0f;
NumMatches = 0;
PayloadScore_Renamed = 0;
PayloadsSeen = 0;
while (More && Doc == Spans.Doc())
{
int matchLength = Spans.End() - Spans.Start();
Freq_Renamed += DocScorer.ComputeSlopFactor(matchLength);
NumMatches++;
ProcessPayload(OuterInstance.Similarity);
More = Spans.Next(); // this moves positions to the next match in this
// document
}
return More || (Freq_Renamed != 0);
}
protected internal virtual void ProcessPayload(Similarity similarity)
{
if (TermSpans.PayloadAvailable)
{
DocsAndPositionsEnum postings = TermSpans.Postings;
Payload = postings.Payload;
if (Payload != null)
{
PayloadScore_Renamed = OuterInstance.OuterInstance.Function.CurrentScore(Doc, OuterInstance.OuterInstance.Term.Field, Spans.Start(), Spans.End(), PayloadsSeen, PayloadScore_Renamed, DocScorer.ComputePayloadFactor(Doc, Spans.Start(), Spans.End(), Payload));
}
else
{
PayloadScore_Renamed = OuterInstance.OuterInstance.Function.CurrentScore(Doc, OuterInstance.OuterInstance.Term.Field, Spans.Start(), Spans.End(), PayloadsSeen, PayloadScore_Renamed, 1F);
}
PayloadsSeen++;
}
else
{
// zero out the payload?
}
}
///
/// <returns> <seealso cref="#getSpanScore()"/> * <seealso cref="#getPayloadScore()"/> </returns>
/// <exception cref="IOException"> if there is a low-level I/O error </exception>
public override float Score()
{
return OuterInstance.OuterInstance.IncludeSpanScore ? SpanScore * PayloadScore : PayloadScore;
}
/// <summary>
/// Returns the SpanScorer score only.
/// <p/>
/// Should not be overridden without good cause!
/// </summary>
/// <returns> the score for just the Span part w/o the payload </returns>
/// <exception cref="IOException"> if there is a low-level I/O error
/// </exception>
/// <seealso cref= #score() </seealso>
protected internal virtual float SpanScore
{
get
{
return base.Score();
}
}
/// <summary>
/// The score for the payload
/// </summary>
/// <returns> The score, as calculated by
/// <seealso cref="PayloadFunction#docScore(int, String, int, float)"/> </returns>
protected internal virtual float PayloadScore
{
get
{
return OuterInstance.OuterInstance.Function.DocScore(Doc, OuterInstance.OuterInstance.Term.Field, PayloadsSeen, PayloadScore_Renamed);
}
}
}
public override Explanation Explain(AtomicReaderContext context, int doc)
{
PayloadTermSpanScorer scorer = (PayloadTermSpanScorer)Scorer(context, (context.AtomicReader).LiveDocs);
if (scorer != null)
{
int newDoc = scorer.Advance(doc);
if (newDoc == doc)
{
float freq = scorer.SloppyFreq();
Similarity.SimScorer docScorer = Similarity.DoSimScorer(Stats, context);
Explanation expl = new Explanation();
expl.Description = "weight(" + Query + " in " + doc + ") [" + Similarity.GetType().Name + "], result of:";
Explanation scoreExplanation = docScorer.Explain(doc, new Explanation(freq, "phraseFreq=" + freq));
expl.AddDetail(scoreExplanation);
expl.Value = scoreExplanation.Value;
// now the payloads part
// QUESTION: Is there a way to avoid this skipTo call? We need to know
// whether to load the payload or not
// GSI: I suppose we could toString the payload, but I don't think that
// would be a good idea
string field = ((SpanQuery)Query).Field;
Explanation payloadExpl = OuterInstance.Function.Explain(doc, field, scorer.PayloadsSeen, scorer.PayloadScore_Renamed);
payloadExpl.Value = scorer.PayloadScore;
// combined
ComplexExplanation result = new ComplexExplanation();
if (OuterInstance.IncludeSpanScore)
{
result.AddDetail(expl);
result.AddDetail(payloadExpl);
result.Value = expl.Value * payloadExpl.Value;
result.Description = "btq, product of:";
}
else
{
result.AddDetail(payloadExpl);
result.Value = payloadExpl.Value;
result.Description = "btq(includeSpanScore=false), result of:";
}
result.Match = true; // LUCENE-1303
return result;
}
}
return new ComplexExplanation(false, 0.0f, "no matching term");
}
}
public override int GetHashCode()
{
const int prime = 31;
int result = base.GetHashCode();
result = prime * result + ((Function == null) ? 0 : Function.GetHashCode());
result = prime * result + (IncludeSpanScore ? 1231 : 1237);
return result;
}
public override bool Equals(object obj)
{
if (this == obj)
{
return true;
}
if (!base.Equals(obj))
{
return false;
}
if (this.GetType() != obj.GetType())
{
return false;
}
PayloadTermQuery other = (PayloadTermQuery)obj;
if (Function == null)
{
if (other.Function != null)
{
return false;
}
}
else if (!Function.Equals(other.Function))
{
return false;
}
if (IncludeSpanScore != other.IncludeSpanScore)
{
return false;
}
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Orleans.Runtime;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
//
// Number of #ifs can be reduced (or removed), once we separate test projects by feature/area, otherwise we are ending up with ambigous types and build errors.
//
#if ORLEANS_CLUSTERING
namespace Orleans.Clustering.AzureStorage
#elif ORLEANS_PERSISTENCE
namespace Orleans.Persistence.AzureStorage
#elif ORLEANS_REMINDERS
namespace Orleans.Reminders.AzureStorage
#elif ORLEANS_STREAMING
namespace Orleans.Streaming.AzureStorage
#elif ORLEANS_EVENTHUBS
namespace Orleans.Streaming.EventHubs
#elif TESTER_AZUREUTILS
namespace Orleans.Tests.AzureUtils
#elif ORLEANS_TRANSACTIONS
namespace Orleans.Transactions.AzureStorage
#else
// No default namespace intentionally to cause compile errors if something is not defined
#endif
{
/// <summary>
/// Utility class to encapsulate row-based access to Azure table storage.
/// </summary>
/// <remarks>
/// These functions are mostly intended for internal usage by Orleans runtime, but due to certain assembly packaging constrants this class needs to have public visibility.
/// </remarks>
/// <typeparam name="T">Table data entry used by this table / manager.</typeparam>
public class AzureTableDataManager<T> where T : class, ITableEntity, new()
{
/// <summary> Name of the table this instance is managing. </summary>
public string TableName { get; private set; }
/// <summary> Logger for this table manager instance. </summary>
protected internal ILogger Logger { get; private set; }
/// <summary> Connection string for the Azure storage account used to host this table. </summary>
protected string ConnectionString { get; set; }
private CloudTable tableReference;
public CloudTable Table => tableReference;
#if !ORLEANS_TRANSACTIONS
private readonly CounterStatistic numServerBusy = CounterStatistic.FindOrCreate(StatisticNames.AZURE_SERVER_BUSY, true);
#endif
/// <summary>
/// Constructor
/// </summary>
/// <param name="tableName">Name of the table to be connected to.</param>
/// <param name="storageConnectionString">Connection string for the Azure storage account used to host this table.</param>
/// <param name="loggerFactory">Logger factory to use.</param>
public AzureTableDataManager(string tableName, string storageConnectionString, ILoggerFactory loggerFactory)
{
Logger = loggerFactory.CreateLogger<AzureTableDataManager<T>>();
TableName = tableName;
ConnectionString = storageConnectionString;
AzureStorageUtils.ValidateTableName(tableName);
}
/// <summary>
/// Connects to, or creates and initializes a new Azure table if it does not already exist.
/// </summary>
/// <returns>Completion promise for this operation.</returns>
public async Task InitTableAsync()
{
const string operation = "InitTable";
var startTime = DateTime.UtcNow;
try
{
CloudTableClient tableCreationClient = GetCloudTableCreationClient();
CloudTable tableRef = tableCreationClient.GetTableReference(TableName);
bool didCreate = await tableRef.CreateIfNotExistsAsync();
Logger.Info((int)Utilities.ErrorCode.AzureTable_01, "{0} Azure storage table {1}", (didCreate ? "Created" : "Attached to"), TableName);
CloudTableClient tableOperationsClient = GetCloudTableOperationsClient();
tableReference = tableOperationsClient.GetTableReference(TableName);
}
catch (Exception exc)
{
Logger.Error((int)Utilities.ErrorCode.AzureTable_02, $"Could not initialize connection to storage table {TableName}", exc);
throw;
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
/// <summary>
/// Deletes the Azure table.
/// </summary>
/// <returns>Completion promise for this operation.</returns>
public async Task DeleteTableAsync()
{
const string operation = "DeleteTable";
var startTime = DateTime.UtcNow;
try
{
CloudTableClient tableCreationClient = GetCloudTableCreationClient();
CloudTable tableRef = tableCreationClient.GetTableReference(TableName);
bool didDelete = await tableRef.DeleteIfExistsAsync();
if (didDelete)
{
Logger.Info((int)Utilities.ErrorCode.AzureTable_03, "Deleted Azure storage table {0}", TableName);
}
}
catch (Exception exc)
{
Logger.Error((int)Utilities.ErrorCode.AzureTable_04, "Could not delete storage table {0}", exc);
throw;
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
/// <summary>
/// Deletes all entities the Azure table.
/// </summary>
/// <returns>Completion promise for this operation.</returns>
public async Task ClearTableAsync()
{
IEnumerable<Tuple<T,string>> items = await ReadAllTableEntriesAsync();
IEnumerable<Task> work = items.GroupBy(item => item.Item1.PartitionKey)
.SelectMany(partition => partition.ToBatch(AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS))
.Select(batch => DeleteTableEntriesAsync(batch.ToList()));
await Task.WhenAll(work);
}
/// <summary>
/// Create a new data entry in the Azure table (insert new, not update existing).
/// Fails if the data already exists.
/// </summary>
/// <param name="data">Data to be inserted into the table.</param>
/// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns>
public async Task<string> CreateTableEntryAsync(T data)
{
const string operation = "CreateTableEntry";
var startTime = DateTime.UtcNow;
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Creating {0} table entry: {1}", TableName, data);
try
{
// WAS:
// svc.AddObject(TableName, data);
// SaveChangesOptions.None
try
{
// Presumably FromAsync(BeginExecute, EndExecute) has a slightly better performance then CreateIfNotExistsAsync.
var opResult = await tableReference.ExecuteAsync(TableOperation.Insert(data));
return opResult.Etag;
}
catch (Exception exc)
{
CheckAlertWriteError(operation, data, null, exc);
throw;
}
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
/// <summary>
/// Inserts a data entry in the Azure table: creates a new one if does not exists or overwrites (without eTag) an already existing version (the "update in place" semantincs).
/// </summary>
/// <param name="data">Data to be inserted or replaced in the table.</param>
/// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns>
public async Task<string> UpsertTableEntryAsync(T data)
{
const string operation = "UpsertTableEntry";
var startTime = DateTime.UtcNow;
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} entry {1} into table {2}", operation, data, TableName);
try
{
try
{
// WAS:
// svc.AttachTo(TableName, data, null);
// svc.UpdateObject(data);
// SaveChangesOptions.ReplaceOnUpdate,
var opResult = await tableReference.ExecuteAsync(TableOperation.InsertOrReplace(data));
return opResult.Etag;
}
catch (Exception exc)
{
Logger.Warn((int)Utilities.ErrorCode.AzureTable_06,
$"Intermediate error upserting entry {(data == null ? "null" : data.ToString())} to the table {TableName}", exc);
throw;
}
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
/// <summary>
/// Merges a data entry in the Azure table.
/// </summary>
/// <param name="data">Data to be merged in the table.</param>
/// <param name="eTag">ETag to apply.</param>
/// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns>
internal async Task<string> MergeTableEntryAsync(T data, string eTag)
{
const string operation = "MergeTableEntry";
var startTime = DateTime.UtcNow;
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} entry {1} into table {2}", operation, data, TableName);
try
{
try
{
// WAS:
// svc.AttachTo(TableName, data, ANY_ETAG);
// svc.UpdateObject(data);
data.ETag = eTag;
// Merge requires an ETag (which may be the '*' wildcard).
var opResult = await tableReference.ExecuteAsync(TableOperation.Merge(data));
return opResult.Etag;
}
catch (Exception exc)
{
Logger.Warn((int)Utilities.ErrorCode.AzureTable_07,
$"Intermediate error merging entry {(data == null ? "null" : data.ToString())} to the table {TableName}", exc);
throw;
}
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
/// <summary>
/// Updates a data entry in the Azure table: updates an already existing data in the table, by using eTag.
/// Fails if the data does not already exist or of eTag does not match.
/// </summary>
/// <param name="data">Data to be updated into the table.</param>
/// /// <param name="dataEtag">ETag to use.</param>
/// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns>
public async Task<string> UpdateTableEntryAsync(T data, string dataEtag)
{
const string operation = "UpdateTableEntryAsync";
var startTime = DateTime.UtcNow;
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} table {1} entry {2}", operation, TableName, data);
try
{
try
{
data.ETag = dataEtag;
var opResult = await tableReference.ExecuteAsync(TableOperation.Replace(data));
//The ETag of data is needed in further operations.
return opResult.Etag;
}
catch (Exception exc)
{
CheckAlertWriteError(operation, data, null, exc);
throw;
}
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
/// <summary>
/// Deletes an already existing data in the table, by using eTag.
/// Fails if the data does not already exist or if eTag does not match.
/// </summary>
/// <param name="data">Data entry to be deleted from the table.</param>
/// <param name="eTag">ETag to use.</param>
/// <returns>Completion promise for this storage operation.</returns>
public async Task DeleteTableEntryAsync(T data, string eTag)
{
const string operation = "DeleteTableEntryAsync";
var startTime = DateTime.UtcNow;
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} table {1} entry {2}", operation, TableName, data);
try
{
data.ETag = eTag;
try
{
await tableReference.ExecuteAsync(TableOperation.Delete(data));
}
catch (Exception exc)
{
Logger.Warn((int)Utilities.ErrorCode.AzureTable_08,
$"Intermediate error deleting entry {data} from the table {TableName}.", exc);
throw;
}
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
/// <summary>
/// Read a single table entry from the storage table.
/// </summary>
/// <param name="partitionKey">The partition key for the entry.</param>
/// <param name="rowKey">The row key for the entry.</param>
/// <returns>Value promise for tuple containing the data entry and its corresponding etag.</returns>
public async Task<Tuple<T, string>> ReadSingleTableEntryAsync(string partitionKey, string rowKey)
{
const string operation = "ReadSingleTableEntryAsync";
var startTime = DateTime.UtcNow;
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} table {1} partitionKey {2} rowKey = {3}", operation, TableName, partitionKey, rowKey);
T retrievedResult = default(T);
try
{
try
{
string queryString = TableQueryFilterBuilder.MatchPartitionKeyAndRowKeyFilter(partitionKey, rowKey);
var query = new TableQuery<T>().Where(queryString);
TableQuerySegment<T> segment = await tableReference.ExecuteQuerySegmentedAsync(query, null);
retrievedResult = segment.Results.SingleOrDefault();
}
catch (StorageException exception)
{
if (!AzureStorageUtils.TableStorageDataNotFound(exception))
throw;
}
//The ETag of data is needed in further operations.
if (retrievedResult != null) return new Tuple<T, string>(retrievedResult, retrievedResult.ETag);
if (Logger.IsEnabled(LogLevel.Debug)) Logger.Debug("Could not find table entry for PartitionKey={0} RowKey={1}", partitionKey, rowKey);
return null; // No data
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
/// <summary>
/// Read all entries in one partition of the storage table.
/// NOTE: This could be an expensive and slow operation for large table partitions!
/// </summary>
/// <param name="partitionKey">The key for the partition to be searched.</param>
/// <returns>Enumeration of all entries in the specified table partition.</returns>
public Task<IEnumerable<Tuple<T, string>>> ReadAllTableEntriesForPartitionAsync(string partitionKey)
{
string query = TableQuery.GenerateFilterCondition(nameof(ITableEntity.PartitionKey), QueryComparisons.Equal, partitionKey);
return ReadTableEntriesAndEtagsAsync(query);
}
/// <summary>
/// Read all entries in the table.
/// NOTE: This could be a very expensive and slow operation for large tables!
/// </summary>
/// <returns>Enumeration of all entries in the table.</returns>
public Task<IEnumerable<Tuple<T, string>>> ReadAllTableEntriesAsync()
{
return ReadTableEntriesAndEtagsAsync(null);
}
/// <summary>
/// Deletes a set of already existing data entries in the table, by using eTag.
/// Fails if the data does not already exist or if eTag does not match.
/// </summary>
/// <param name="collection">Data entries and their corresponding etags to be deleted from the table.</param>
/// <returns>Completion promise for this storage operation.</returns>
public async Task DeleteTableEntriesAsync(IReadOnlyCollection<Tuple<T, string>> collection)
{
const string operation = "DeleteTableEntries";
var startTime = DateTime.UtcNow;
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Deleting {0} table entries: {1}", TableName, Utils.EnumerableToString(collection));
if (collection == null) throw new ArgumentNullException("collection");
if (collection.Count > AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS)
{
throw new ArgumentOutOfRangeException("collection", collection.Count,
"Too many rows for bulk delete - max " + AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS);
}
if (collection.Count == 0)
{
return;
}
try
{
var entityBatch = new TableBatchOperation();
foreach (var tuple in collection)
{
// WAS:
// svc.AttachTo(TableName, tuple.Item1, tuple.Item2);
// svc.DeleteObject(tuple.Item1);
// SaveChangesOptions.ReplaceOnUpdate | SaveChangesOptions.Batch,
T item = tuple.Item1;
item.ETag = tuple.Item2;
entityBatch.Delete(item);
}
try
{
await tableReference.ExecuteBatchAsync(entityBatch);
}
catch (Exception exc)
{
Logger.Warn((int)Utilities.ErrorCode.AzureTable_08,
$"Intermediate error deleting entries {Utils.EnumerableToString(collection)} from the table {TableName}.", exc);
throw;
}
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
/// <summary>
/// Read data entries and their corresponding eTags from the Azure table.
/// </summary>
/// <param name="filter">Filter string to use for querying the table and filtering the results.</param>
/// <returns>Enumeration of entries in the table which match the query condition.</returns>
public async Task<IEnumerable<Tuple<T, string>>> ReadTableEntriesAndEtagsAsync(string filter)
{
const string operation = "ReadTableEntriesAndEtags";
var startTime = DateTime.UtcNow;
try
{
TableQuery<T> cloudTableQuery = filter == null
? new TableQuery<T>()
: new TableQuery<T>().Where(filter);
try
{
Func<Task<List<T>>> executeQueryHandleContinuations = async () =>
{
TableQuerySegment<T> querySegment = null;
var list = new List<T>();
//ExecuteSegmentedAsync not supported in "WindowsAzure.Storage": "7.2.1" yet
while (querySegment == null || querySegment.ContinuationToken != null)
{
querySegment = await tableReference.ExecuteQuerySegmentedAsync(cloudTableQuery, querySegment?.ContinuationToken);
list.AddRange(querySegment);
}
return list;
};
#if !ORLEANS_TRANSACTIONS
IBackoffProvider backoff = new FixedBackoff(AzureTableDefaultPolicies.PauseBetweenTableOperationRetries);
List<T> results = await AsyncExecutorWithRetries.ExecuteWithRetries(
counter => executeQueryHandleContinuations(),
AzureTableDefaultPolicies.MaxTableOperationRetries,
(exc, counter) => AzureStorageUtils.AnalyzeReadException(exc.GetBaseException(), counter, TableName, Logger),
AzureTableDefaultPolicies.TableOperationTimeout,
backoff);
#else
List<T> results = await executeQueryHandleContinuations();
#endif
// Data was read successfully if we got to here
return results.Select(i => Tuple.Create(i, i.ETag)).ToList();
}
catch (Exception exc)
{
// Out of retries...
var errorMsg = $"Failed to read Azure storage table {TableName}: {exc.Message}";
if (!AzureStorageUtils.TableStorageDataNotFound(exc))
{
Logger.Warn((int)Utilities.ErrorCode.AzureTable_09, errorMsg, exc);
}
throw new OrleansException(errorMsg, exc);
}
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
/// <summary>
/// Inserts a set of new data entries into the table.
/// Fails if the data does already exists.
/// </summary>
/// <param name="collection">Data entries to be inserted into the table.</param>
/// <returns>Completion promise for this storage operation.</returns>
public async Task BulkInsertTableEntries(IReadOnlyCollection<T> collection)
{
const string operation = "BulkInsertTableEntries";
if (collection == null) throw new ArgumentNullException("collection");
if (collection.Count > AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS)
{
throw new ArgumentOutOfRangeException("collection", collection.Count,
"Too many rows for bulk update - max " + AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS);
}
if (collection.Count == 0)
{
return;
}
var startTime = DateTime.UtcNow;
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Bulk inserting {0} entries to {1} table", collection.Count, TableName);
try
{
// WAS:
// svc.AttachTo(TableName, entry);
// svc.UpdateObject(entry);
// SaveChangesOptions.None | SaveChangesOptions.Batch,
// SaveChangesOptions.None == Insert-or-merge operation, SaveChangesOptions.Batch == Batch transaction
// http://msdn.microsoft.com/en-us/library/hh452241.aspx
var entityBatch = new TableBatchOperation();
foreach (T entry in collection)
{
entityBatch.Insert(entry);
}
try
{
// http://msdn.microsoft.com/en-us/library/hh452241.aspx
await tableReference.ExecuteBatchAsync(entityBatch);
}
catch (Exception exc)
{
Logger.Warn((int)Utilities.ErrorCode.AzureTable_37,
$"Intermediate error bulk inserting {collection.Count} entries in the table {TableName}", exc);
}
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
#region Internal functions
internal async Task<Tuple<string, string>> InsertTwoTableEntriesConditionallyAsync(T data1, T data2, string data2Etag)
{
const string operation = "InsertTableEntryConditionally";
string data2Str = (data2 == null ? "null" : data2.ToString());
var startTime = DateTime.UtcNow;
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} into table {1} data1 {2} data2 {3}", operation, TableName, data1, data2Str);
try
{
try
{
// WAS:
// Only AddObject, do NOT AttachTo. If we did both UpdateObject and AttachTo, it would have been equivalent to InsertOrReplace.
// svc.AddObject(TableName, data);
// ---
// svc.AttachTo(TableName, tableVersion, tableVersionEtag);
// svc.UpdateObject(tableVersion);
// SaveChangesOptions.ReplaceOnUpdate | SaveChangesOptions.Batch,
// EntityDescriptor dataResult = svc.GetEntityDescriptor(data);
// return dataResult.ETag;
var entityBatch = new TableBatchOperation();
entityBatch.Add(TableOperation.Insert(data1));
data2.ETag = data2Etag;
entityBatch.Add(TableOperation.Replace(data2));
var opResults = await tableReference.ExecuteBatchAsync(entityBatch);
//The batch results are returned in order of execution,
//see reference at https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.table.cloudtable.executebatch.aspx.
//The ETag of data is needed in further operations.
return new Tuple<string, string>(opResults[0].Etag, opResults[1].Etag);
}
catch (Exception exc)
{
CheckAlertWriteError(operation, data1, data2Str, exc);
throw;
}
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
internal async Task<Tuple<string, string>> UpdateTwoTableEntriesConditionallyAsync(T data1, string data1Etag, T data2, string data2Etag)
{
const string operation = "UpdateTableEntryConditionally";
string data2Str = (data2 == null ? "null" : data2.ToString());
var startTime = DateTime.UtcNow;
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} table {1} data1 {2} data2 {3}", operation, TableName, data1, data2Str);
try
{
try
{
// WAS:
// Only AddObject, do NOT AttachTo. If we did both UpdateObject and AttachTo, it would have been equivalent to InsertOrReplace.
// svc.AttachTo(TableName, data, dataEtag);
// svc.UpdateObject(data);
// ----
// svc.AttachTo(TableName, tableVersion, tableVersionEtag);
// svc.UpdateObject(tableVersion);
// SaveChangesOptions.ReplaceOnUpdate | SaveChangesOptions.Batch,
// EntityDescriptor dataResult = svc.GetEntityDescriptor(data);
// return dataResult.ETag;
var entityBatch = new TableBatchOperation();
data1.ETag = data1Etag;
entityBatch.Add(TableOperation.Replace(data1));
if (data2 != null && data2Etag != null)
{
data2.ETag = data2Etag;
entityBatch.Add(TableOperation.Replace(data2));
}
var opResults = await tableReference.ExecuteBatchAsync(entityBatch);
//The batch results are returned in order of execution,
//see reference at https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.table.cloudtable.executebatch.aspx.
//The ETag of data is needed in further operations.
return new Tuple<string, string>(opResults[0].Etag, opResults[1].Etag);
}
catch (Exception exc)
{
CheckAlertWriteError(operation, data1, data2Str, exc);
throw;
}
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
// Utility methods
private CloudTableClient GetCloudTableOperationsClient()
{
try
{
CloudStorageAccount storageAccount = AzureStorageUtils.GetCloudStorageAccount(ConnectionString);
CloudTableClient operationsClient = storageAccount.CreateCloudTableClient();
operationsClient.DefaultRequestOptions.RetryPolicy = AzureTableDefaultPolicies.TableOperationRetryPolicy;
operationsClient.DefaultRequestOptions.ServerTimeout = AzureTableDefaultPolicies.TableOperationTimeout;
// Values supported can be AtomPub, Json, JsonFullMetadata or JsonNoMetadata with Json being the default value
operationsClient.DefaultRequestOptions.PayloadFormat = TablePayloadFormat.JsonNoMetadata;
return operationsClient;
}
catch (Exception exc)
{
Logger.Error((int)Utilities.ErrorCode.AzureTable_17, "Error creating CloudTableOperationsClient.", exc);
throw;
}
}
private CloudTableClient GetCloudTableCreationClient()
{
try
{
CloudStorageAccount storageAccount = AzureStorageUtils.GetCloudStorageAccount(ConnectionString);
CloudTableClient creationClient = storageAccount.CreateCloudTableClient();
creationClient.DefaultRequestOptions.RetryPolicy = AzureTableDefaultPolicies.TableCreationRetryPolicy;
creationClient.DefaultRequestOptions.ServerTimeout = AzureTableDefaultPolicies.TableCreationTimeout;
// Values supported can be AtomPub, Json, JsonFullMetadata or JsonNoMetadata with Json being the default value
creationClient.DefaultRequestOptions.PayloadFormat = TablePayloadFormat.JsonNoMetadata;
return creationClient;
}
catch (Exception exc)
{
Logger.Error((int)Utilities.ErrorCode.AzureTable_18, "Error creating CloudTableCreationClient.", exc);
throw;
}
}
private void CheckAlertWriteError(string operation, object data1, string data2, Exception exc)
{
HttpStatusCode httpStatusCode;
string restStatus;
if(AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus) && AzureStorageUtils.IsContentionError(httpStatusCode))
{
// log at Verbose, since failure on conditional is not not an error. Will analyze and warn later, if required.
if(Logger.IsEnabled(LogLevel.Debug)) Logger.Debug((int)Utilities.ErrorCode.AzureTable_13,
$"Intermediate Azure table write error {operation} to table {TableName} data1 {(data1 ?? "null")} data2 {(data2 ?? "null")}", exc);
}
else
{
Logger.Error((int)Utilities.ErrorCode.AzureTable_14,
$"Azure table access write error {operation} to table {TableName} entry {data1}", exc);
}
}
private void CheckAlertSlowAccess(DateTime startOperation, string operation)
{
var timeSpan = DateTime.UtcNow - startOperation;
if (timeSpan > AzureTableDefaultPolicies.TableOperationTimeout)
{
Logger.Warn((int)Utilities.ErrorCode.AzureTable_15, "Slow access to Azure Table {0} for {1}, which took {2}.", TableName, operation, timeSpan);
}
}
#endregion
/// <summary>
/// Helper functions for building table queries.
/// </summary>
private class TableQueryFilterBuilder
{
/// <summary>
/// Builds query string to match partitionkey
/// </summary>
/// <param name="partitionKey"></param>
/// <returns></returns>
public static string MatchPartitionKeyFilter(string partitionKey)
{
return TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey);
}
/// <summary>
/// Builds query string to match rowkey
/// </summary>
/// <param name="rowKey"></param>
/// <returns></returns>
public static string MatchRowKeyFilter(string rowKey)
{
return TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, rowKey);
}
/// <summary>
/// Builds a query string that matches a specific partitionkey and rowkey.
/// </summary>
/// <param name="partitionKey"></param>
/// <param name="rowKey"></param>
/// <returns></returns>
public static string MatchPartitionKeyAndRowKeyFilter(string partitionKey, string rowKey)
{
return TableQuery.CombineFilters(MatchPartitionKeyFilter(partitionKey), TableOperators.And,
MatchRowKeyFilter(rowKey));
}
}
}
internal static class TableDataManagerInternalExtensions
{
internal static IEnumerable<IEnumerable<TItem>> ToBatch<TItem>(this IEnumerable<TItem> source, int size)
{
using (IEnumerator<TItem> enumerator = source.GetEnumerator())
while (enumerator.MoveNext())
yield return Take(enumerator, size);
}
private static IEnumerable<TItem> Take<TItem>(IEnumerator<TItem> source, int size)
{
int i = 0;
do
yield return source.Current;
while (++i < size && source.MoveNext());
}
}
}
| |
using System;
using UnityEngine;
namespace UnitySampleAssets.ImageEffects
{
[ExecuteInEditMode]
[RequireComponent (typeof(Camera))]
[AddComponentMenu ("Image Effects/Bloom and Glow/Bloom")]
public class Bloom : PostEffectsBase
{
public enum LensFlareStyle
{
Ghosting = 0,
Anamorphic = 1,
Combined = 2,
}
public enum TweakMode
{
Basic = 0,
Complex = 1,
}
public enum HDRBloomMode
{
Auto = 0,
On = 1,
Off = 2,
}
public enum BloomScreenBlendMode
{
Screen = 0,
Add = 1,
}
public enum BloomQuality
{
Cheap = 0,
High = 1,
}
public TweakMode tweakMode = 0;
public BloomScreenBlendMode screenBlendMode = BloomScreenBlendMode.Add;
public HDRBloomMode hdr = HDRBloomMode.Auto;
private bool doHdr = false;
public float sepBlurSpread = 2.5f;
public BloomQuality quality = BloomQuality.High;
public float bloomIntensity = 0.5f;
public float bloomThreshhold = 0.5f;
public Color bloomThreshholdColor = Color.white;
public int bloomBlurIterations = 2;
public int hollywoodFlareBlurIterations = 2;
public float flareRotation = 0.0f;
public LensFlareStyle lensflareMode = (LensFlareStyle) 1;
public float hollyStretchWidth = 2.5f;
public float lensflareIntensity = 0.0f;
public float lensflareThreshhold = 0.3f;
public float lensFlareSaturation = 0.75f;
public Color flareColorA = new Color (0.4f, 0.4f, 0.8f, 0.75f);
public Color flareColorB = new Color (0.4f, 0.8f, 0.8f, 0.75f);
public Color flareColorC = new Color (0.8f, 0.4f, 0.8f, 0.75f);
public Color flareColorD = new Color (0.8f, 0.4f, 0.0f, 0.75f);
public Texture2D lensFlareVignetteMask;
public Shader lensFlareShader;
private Material lensFlareMaterial;
public Shader screenBlendShader;
private Material screenBlend;
public Shader blurAndFlaresShader;
private Material blurAndFlaresMaterial;
public Shader brightPassFilterShader;
private Material brightPassFilterMaterial;
public override bool CheckResources ()
{
CheckSupport (false);
screenBlend = CheckShaderAndCreateMaterial (screenBlendShader, screenBlend);
lensFlareMaterial = CheckShaderAndCreateMaterial(lensFlareShader,lensFlareMaterial);
blurAndFlaresMaterial = CheckShaderAndCreateMaterial (blurAndFlaresShader, blurAndFlaresMaterial);
brightPassFilterMaterial = CheckShaderAndCreateMaterial(brightPassFilterShader, brightPassFilterMaterial);
if (!isSupported)
ReportAutoDisable ();
return isSupported;
}
public void OnRenderImage (RenderTexture source, RenderTexture destination)
{
if (CheckResources()==false)
{
Graphics.Blit (source, destination);
return;
}
// screen blend is not supported when HDR is enabled (will cap values)
doHdr = false;
if (hdr == HDRBloomMode.Auto)
doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent<Camera>().hdr;
else {
doHdr = hdr == HDRBloomMode.On;
}
doHdr = doHdr && supportHDRTextures;
BloomScreenBlendMode realBlendMode = screenBlendMode;
if (doHdr)
realBlendMode = BloomScreenBlendMode.Add;
var rtFormat= (doHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.Default;
var rtW2= source.width/2;
var rtH2= source.height/2;
var rtW4= source.width/4;
var rtH4= source.height/4;
float widthOverHeight = (1.0f * source.width) / (1.0f * source.height);
float oneOverBaseSize = 1.0f / 512.0f;
// downsample
RenderTexture quarterRezColor = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
RenderTexture halfRezColorDown = RenderTexture.GetTemporary (rtW2, rtH2, 0, rtFormat);
if (quality > BloomQuality.Cheap) {
Graphics.Blit (source, halfRezColorDown, screenBlend, 2);
RenderTexture rtDown4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
Graphics.Blit (halfRezColorDown, rtDown4, screenBlend, 2);
Graphics.Blit (rtDown4, quarterRezColor, screenBlend, 6);
RenderTexture.ReleaseTemporary(rtDown4);
}
else {
Graphics.Blit (source, halfRezColorDown);
Graphics.Blit (halfRezColorDown, quarterRezColor, screenBlend, 6);
}
RenderTexture.ReleaseTemporary (halfRezColorDown);
// cut colors (threshholding)
RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
BrightFilter (bloomThreshhold * bloomThreshholdColor, quarterRezColor, secondQuarterRezColor);
// blurring
if (bloomBlurIterations < 1) bloomBlurIterations = 1;
else if (bloomBlurIterations > 10) bloomBlurIterations = 10;
for (int iter = 0; iter < bloomBlurIterations; iter++ ) {
float spreadForPass = (1.0f + (iter * 0.25f)) * sepBlurSpread;
// vertical blur
RenderTexture blur4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (0.0f, spreadForPass * oneOverBaseSize, 0.0f, 0.0f));
Graphics.Blit (secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4);
RenderTexture.ReleaseTemporary(secondQuarterRezColor);
secondQuarterRezColor = blur4;
// horizontal blur
blur4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 ((spreadForPass / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit (secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4);
RenderTexture.ReleaseTemporary (secondQuarterRezColor);
secondQuarterRezColor = blur4;
if (quality > BloomQuality.Cheap) {
if (iter == 0)
{
Graphics.SetRenderTarget(quarterRezColor);
GL.Clear(false, true, Color.black); // Clear to avoid RT restore
Graphics.Blit (secondQuarterRezColor, quarterRezColor);
}
else
{
quarterRezColor.MarkRestoreExpected(); // using max blending, RT restore expected
Graphics.Blit (secondQuarterRezColor, quarterRezColor, screenBlend, 10);
}
}
}
if (quality > BloomQuality.Cheap)
{
Graphics.SetRenderTarget(secondQuarterRezColor);
GL.Clear(false, true, Color.black); // Clear to avoid RT restore
Graphics.Blit (quarterRezColor, secondQuarterRezColor, screenBlend, 6);
}
// lens flares: ghosting, anamorphic or both (ghosted anamorphic flares)
if (lensflareIntensity > Mathf.Epsilon) {
RenderTexture rtFlares4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
if (lensflareMode == 0) {
// ghosting only
BrightFilter (lensflareThreshhold, secondQuarterRezColor, rtFlares4);
if (quality > BloomQuality.Cheap) {
// smooth a little
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (0.0f, (1.5f) / (1.0f * quarterRezColor.height), 0.0f, 0.0f));
Graphics.SetRenderTarget(quarterRezColor);
GL.Clear(false, true, Color.black); // Clear to avoid RT restore
Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4);
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 ((1.5f) / (1.0f * quarterRezColor.width), 0.0f, 0.0f, 0.0f));
Graphics.SetRenderTarget(rtFlares4);
GL.Clear(false, true, Color.black); // Clear to avoid RT restore
Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4);
}
// no ugly edges!
Vignette (0.975f, rtFlares4, rtFlares4);
BlendFlares (rtFlares4, secondQuarterRezColor);
}
else {
//Vignette (0.975ff, rtFlares4, rtFlares4);
//DrawBorder(rtFlares4, screenBlend, 8);
float flareXRot = 1.0f * Mathf.Cos(flareRotation);
float flareyRot = 1.0f * Mathf.Sin(flareRotation);
float stretchWidth = (hollyStretchWidth * 1.0f / widthOverHeight) * oneOverBaseSize;
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (flareXRot, flareyRot, 0.0f, 0.0f));
blurAndFlaresMaterial.SetVector ("_Threshhold", new Vector4 (lensflareThreshhold, 1.0f, 0.0f, 0.0f));
blurAndFlaresMaterial.SetVector ("_TintColor", new Vector4 (flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * flareColorA.a * lensflareIntensity);
blurAndFlaresMaterial.SetFloat ("_Saturation", lensFlareSaturation);
// "pre and cut"
quarterRezColor.DiscardContents();
Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 2);
// "post"
rtFlares4.DiscardContents();
Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 3);
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (flareXRot * stretchWidth, flareyRot * stretchWidth, 0.0f, 0.0f));
// stretch 1st
blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth);
quarterRezColor.DiscardContents();
Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1);
// stretch 2nd
blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth * 2.0f);
rtFlares4.DiscardContents();
Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 1);
// stretch 3rd
blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth * 4.0f);
quarterRezColor.DiscardContents();
Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1);
// additional blur passes
for (int iter = 0; iter < hollywoodFlareBlurIterations; iter++ ) {
stretchWidth = (hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize;
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (stretchWidth * flareXRot, stretchWidth * flareyRot, 0.0f, 0.0f));
rtFlares4.DiscardContents();
Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4);
blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (stretchWidth * flareXRot, stretchWidth * flareyRot, 0.0f, 0.0f));
quarterRezColor.DiscardContents();
Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4);
}
if (lensflareMode == (LensFlareStyle) 1)
// anamorphic lens flares
AddTo (1.0f, quarterRezColor, secondQuarterRezColor);
else {
// "combined" lens flares
Vignette (1.0f, quarterRezColor, rtFlares4);
BlendFlares (rtFlares4, quarterRezColor);
AddTo (1.0f, quarterRezColor, secondQuarterRezColor);
}
}
RenderTexture.ReleaseTemporary (rtFlares4);
}
int blendPass = (int) realBlendMode;
//if (Mathf.Abs(chromaticBloom) < Mathf.Epsilon)
// blendPass += 4;
screenBlend.SetFloat ("_Intensity", bloomIntensity);
screenBlend.SetTexture ("_ColorBuffer", source);
if (quality > BloomQuality.Cheap) {
RenderTexture halfRezColorUp = RenderTexture.GetTemporary (rtW2, rtH2, 0, rtFormat);
Graphics.Blit (secondQuarterRezColor, halfRezColorUp);
Graphics.Blit (halfRezColorUp, destination, screenBlend, blendPass);
RenderTexture.ReleaseTemporary (halfRezColorUp);
}
else
Graphics.Blit (secondQuarterRezColor, destination, screenBlend, blendPass);
RenderTexture.ReleaseTemporary (quarterRezColor);
RenderTexture.ReleaseTemporary (secondQuarterRezColor);
}
private void AddTo (float intensity_, RenderTexture from, RenderTexture to)
{
screenBlend.SetFloat ("_Intensity", intensity_);
to.MarkRestoreExpected(); // additive blending, RT restore expected
Graphics.Blit (from, to, screenBlend, 9);
}
private void BlendFlares (RenderTexture from, RenderTexture to)
{
lensFlareMaterial.SetVector ("colorA", new Vector4 (flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * lensflareIntensity);
lensFlareMaterial.SetVector ("colorB", new Vector4 (flareColorB.r, flareColorB.g, flareColorB.b, flareColorB.a) * lensflareIntensity);
lensFlareMaterial.SetVector ("colorC", new Vector4 (flareColorC.r, flareColorC.g, flareColorC.b, flareColorC.a) * lensflareIntensity);
lensFlareMaterial.SetVector ("colorD", new Vector4 (flareColorD.r, flareColorD.g, flareColorD.b, flareColorD.a) * lensflareIntensity);
to.MarkRestoreExpected(); // additive blending, RT restore expected
Graphics.Blit (from, to, lensFlareMaterial);
}
private void BrightFilter (float thresh, RenderTexture from, RenderTexture to)
{
brightPassFilterMaterial.SetVector ("_Threshhold", new Vector4 (thresh, thresh, thresh, thresh));
Graphics.Blit (from, to, brightPassFilterMaterial, 0);
}
private void BrightFilter (Color threshColor, RenderTexture from, RenderTexture to)
{
brightPassFilterMaterial.SetVector ("_Threshhold", threshColor);
Graphics.Blit (from, to, brightPassFilterMaterial, 1);
}
private void Vignette (float amount, RenderTexture from, RenderTexture to)
{
if (lensFlareVignetteMask)
{
screenBlend.SetTexture ("_ColorBuffer", lensFlareVignetteMask);
to.MarkRestoreExpected(); // using blending, RT restore expected
Graphics.Blit (from == to ? null : from, to, screenBlend, from == to ? 7 : 3);
}
else if (from != to)
{
Graphics.SetRenderTarget (to);
GL.Clear(false, true, Color.black); // clear destination to avoid RT restore
Graphics.Blit (from, to);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.NetCore.Analyzers.Runtime
{
using static MicrosoftNetCoreAnalyzersResources;
/// <summary>
/// CA2016: Forward CancellationToken to invocations.
///
/// Conditions for positive cases:
/// - The containing method signature receives a ct parameter. It can be a method, a nested method, an action or a func.
/// - The invocation method is not receiving a ct argument, and...
/// - The invocation method either:
/// - Has no overloads but its current signature receives an optional ct=default, currently implicit, or...
/// - Has a method overload with the exact same arguments in the same order, plus one ct parameter at the end.
///
/// Conditions for negative cases:
/// - The containing method signature does not receive a ct parameter.
/// - The invocation method signature receives a ct and one is already being explicitly passed, or...
/// - The invocation method does not have an overload with the exact same arguments that also receives a ct, or...
/// - The invocation method only has overloads that receive more than one ct.
/// - The invocation method return types are not implicitly convertable to one another.
/// </summary>
public abstract class ForwardCancellationTokenToInvocationsAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA2016";
// Try to get the name of the method from the specified invocation
protected abstract SyntaxNode? GetInvocationMethodNameNode(SyntaxNode invocationNode);
// Check if any of the other arguments is implicit or a named argument
protected abstract bool ArgumentsImplicitOrNamed(INamedTypeSymbol cancellationTokenType, ImmutableArray<IArgumentOperation> arguments);
internal static readonly DiagnosticDescriptor ForwardCancellationTokenToInvocationsRule = DiagnosticDescriptorHelper.Create(
RuleId,
CreateLocalizableResourceString(nameof(ForwardCancellationTokenToInvocationsTitle)),
CreateLocalizableResourceString(nameof(ForwardCancellationTokenToInvocationsMessage)),
DiagnosticCategory.Reliability,
RuleLevel.IdeSuggestion,
CreateLocalizableResourceString(nameof(ForwardCancellationTokenToInvocationsDescription)),
isPortedFxCopRule: false,
isDataflowRule: false
);
internal const string ShouldFix = "ShouldFix";
internal const string ArgumentName = "ArgumentName";
internal const string ParameterName = "ParameterName";
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
ImmutableArray.Create(ForwardCancellationTokenToInvocationsRule);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(context => AnalyzeCompilationStart(context));
}
private void AnalyzeCompilationStart(CompilationStartAnalysisContext context)
{
if (!context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingCancellationToken, out INamedTypeSymbol? cancellationTokenType))
{
return;
}
// We don't care if these symbols are not defined in our compilation. They are used to special case the Task<T> <-> ValueTask<T> logic
context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTask1, out INamedTypeSymbol? genericTask);
context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksValueTask1, out INamedTypeSymbol? genericValueTask);
context.RegisterOperationAction(context =>
{
IInvocationOperation invocation = (IInvocationOperation)context.Operation;
if (context.ContainingSymbol is not IMethodSymbol containingMethod)
{
return;
}
if (!ShouldDiagnose(
context.Compilation,
invocation,
containingMethod,
cancellationTokenType,
genericTask,
genericValueTask,
out int shouldFix,
out string? cancellationTokenArgumentName,
out string? invocationTokenParameterName))
{
return;
}
// Underline only the method name, if possible
SyntaxNode? nodeToDiagnose = GetInvocationMethodNameNode(context.Operation.Syntax) ?? context.Operation.Syntax;
ImmutableDictionary<string, string?>.Builder properties = ImmutableDictionary.CreateBuilder<string, string?>(StringComparer.Ordinal);
properties.Add(ShouldFix, $"{shouldFix}");
properties.Add(ArgumentName, cancellationTokenArgumentName); // The new argument to pass to the invocation
properties.Add(ParameterName, invocationTokenParameterName); // If the passed argument should be named, then this will be non-null
context.ReportDiagnostic(
nodeToDiagnose.CreateDiagnostic(
rule: ForwardCancellationTokenToInvocationsRule,
properties: properties.ToImmutable(),
args: new object[] { cancellationTokenArgumentName, invocation.TargetMethod.Name }));
},
OperationKind.Invocation);
}
// Determines if an invocation should trigger a diagnostic for this rule or not.
private bool ShouldDiagnose(
Compilation compilation,
IInvocationOperation invocation,
IMethodSymbol containingSymbol,
INamedTypeSymbol cancellationTokenType,
INamedTypeSymbol? genericTask,
INamedTypeSymbol? genericValueTask,
out int shouldFix, [NotNullWhen(returnValue: true)] out string? ancestorTokenParameterName, out string? invocationTokenParameterName)
{
shouldFix = 1;
ancestorTokenParameterName = null;
invocationTokenParameterName = null;
IMethodSymbol method = invocation.TargetMethod;
// Verify that the current invocation is not passing an explicit token already
if (AnyArgument(invocation.Arguments,
a => a.Parameter.Type.Equals(cancellationTokenType) && !a.IsImplicit))
{
return false;
}
IMethodSymbol? overload = null;
// Check if the invocation's method has either an optional implicit ct at the end not being used, or a params ct parameter at the end not being used
if (InvocationMethodTakesAToken(method, invocation.Arguments, cancellationTokenType))
{
if (ArgumentsImplicitOrNamed(cancellationTokenType, invocation.Arguments))
{
invocationTokenParameterName = method.Parameters[^1].Name;
}
}
// or an overload that takes a ct at the end
else if (MethodHasCancellationTokenOverload(compilation, method, cancellationTokenType, genericTask, genericValueTask, out overload))
{
if (ArgumentsImplicitOrNamed(cancellationTokenType, invocation.Arguments))
{
invocationTokenParameterName = overload.Parameters[^1].Name;
}
}
else
{
return false;
}
// Check if there is an ancestor method that has a ct that we can pass to the invocation
if (!TryGetClosestAncestorThatTakesAToken(
invocation, containingSymbol, cancellationTokenType,
out shouldFix, out IMethodSymbol? ancestor, out ancestorTokenParameterName))
{
return false;
}
// Finally, if the ct is in an overload method, but adding the ancestor's ct to the current
// invocation would cause the new signature to become a recursive call, avoid creating a diagnostic
if (overload != null && overload == ancestor)
{
ancestorTokenParameterName = null;
return false;
}
return true;
}
// Try to find the most immediate containing symbol (anonymous or local function). Returns true.
// If none is found, return the context containing symbol. Returns false.
private static bool TryGetClosestAncestorThatTakesAToken(
IInvocationOperation invocation,
IMethodSymbol containingSymbol,
INamedTypeSymbol cancellationTokenType,
out int shouldFix,
[NotNullWhen(returnValue: true)] out IMethodSymbol? ancestor,
[NotNullWhen(returnValue: true)] out string? cancellationTokenParameterName)
{
shouldFix = 1;
IOperation currentOperation = invocation.Parent;
while (currentOperation != null)
{
ancestor = null;
if (currentOperation.Kind == OperationKind.AnonymousFunction)
{
ancestor = ((IAnonymousFunctionOperation)currentOperation).Symbol;
}
else if (currentOperation.Kind == OperationKind.LocalFunction)
{
ancestor = ((ILocalFunctionOperation)currentOperation).Symbol;
}
// When the current ancestor does not contain a ct, will continue with the next ancestor
if (ancestor != null)
{
if (TryGetTokenParamName(ancestor, cancellationTokenType, out cancellationTokenParameterName))
{
return true;
}
// If no token param was found in the previous check, return false if the current operation is an anonymous function,
// we don't want to keep checking the superior ancestors because the ct may be unrelated
if (currentOperation.Kind == OperationKind.AnonymousFunction)
{
return false;
}
// If the current operation is a local static function, and is not passing a ct, but the parent is, then the
// ct cannot be passed to the inner invocations of the static local method, but we want to continue trying
// to find the ancestor method passing a ct so that we still trigger a diagnostic, we just won't offer a fix
if (currentOperation.Kind == OperationKind.LocalFunction && ancestor.IsStatic)
{
shouldFix = 0;
}
}
currentOperation = currentOperation.Parent;
}
// Last resort: fallback to the containing symbol
ancestor = containingSymbol;
return TryGetTokenParamName(ancestor, cancellationTokenType, out cancellationTokenParameterName);
}
// Check if the method only takes one ct and is the last parameter in the method signature.
// We want to compare the current method signature to any others with the exact same arguments in the exact same order.
private static bool TryGetTokenParamName(
IMethodSymbol methodDeclaration,
INamedTypeSymbol cancellationTokenType,
[NotNullWhen(returnValue: true)] out string? cancellationTokenParameterName)
{
if (methodDeclaration.Parameters.Count(x => x.Type.Equals(cancellationTokenType)) == 1 &&
methodDeclaration.Parameters[^1] is IParameterSymbol lastParameter &&
lastParameter.Type.Equals(cancellationTokenType)) // Covers the case when using an alias for ct
{
cancellationTokenParameterName = lastParameter.Name;
return true;
}
cancellationTokenParameterName = null;
return false;
}
// Checks if the invocation has an optional ct argument at the end or a params ct array at the end.
private static bool InvocationMethodTakesAToken(
IMethodSymbol method,
ImmutableArray<IArgumentOperation> arguments,
INamedTypeSymbol cancellationTokenType)
{
return
!method.Parameters.IsEmpty &&
method.Parameters[^1] is IParameterSymbol lastParameter &&
(InvocationIgnoresOptionalCancellationToken(lastParameter, arguments, cancellationTokenType) ||
InvocationIsUsingParamsCancellationToken(lastParameter, arguments, cancellationTokenType));
}
// Checks if the arguments enumerable has any elements that satisfy the provided condition,
// starting the lookup with the last element since tokens tend to be added as the last argument.
private static bool AnyArgument(ImmutableArray<IArgumentOperation> arguments, Func<IArgumentOperation, bool> predicate)
{
for (int i = arguments.Length - 1; i >= 0; i--)
{
if (predicate(arguments[i]))
{
return true;
}
}
return false;
}
// Check if the currently used overload is the one that takes the ct, but is utilizing the default value offered in the method signature.
// We want to offer a diagnostic for this case, so the user explicitly passes the ancestor's ct.
private static bool InvocationIgnoresOptionalCancellationToken(
IParameterSymbol lastParameter,
ImmutableArray<IArgumentOperation> arguments,
INamedTypeSymbol cancellationTokenType)
{
if (lastParameter.Type.Equals(cancellationTokenType) &&
lastParameter.IsOptional) // Has a default value being used
{
// Find out if the ct argument is using the default value
// Need to check among all arguments in case the user is passing them named and unordered (despite the ct being defined as the last parameter)
return AnyArgument(
arguments,
a => a.Parameter.Type.Equals(cancellationTokenType) && a.ArgumentKind == ArgumentKind.DefaultValue);
}
return false;
}
// Checks if the method has a `params CancellationToken[]` argument in the last position and ensure no ct is being passed.
private static bool InvocationIsUsingParamsCancellationToken(
IParameterSymbol lastParameter,
ImmutableArray<IArgumentOperation> arguments,
INamedTypeSymbol cancellationTokenType)
{
if (lastParameter.IsParams &&
lastParameter.Type is IArrayTypeSymbol arrayTypeSymbol &&
arrayTypeSymbol.ElementType.Equals(cancellationTokenType))
{
IArgumentOperation? paramsArgument = arguments.FirstOrDefault(a => a.ArgumentKind == ArgumentKind.ParamArray);
if (paramsArgument?.Value is IArrayCreationOperation arrayOperation)
{
// Do not offer a diagnostic if the user already passed a ct to the params
return arrayOperation.Initializer.ElementValues.IsEmpty;
}
}
return false;
}
// Check if there's a method overload with the same parameters as this one, in the same order, plus a ct at the end.
private static bool MethodHasCancellationTokenOverload(
Compilation compilation,
IMethodSymbol method,
ITypeSymbol cancellationTokenType,
INamedTypeSymbol? genericTask,
INamedTypeSymbol? genericValueTask,
[NotNullWhen(returnValue: true)] out IMethodSymbol? overload)
{
overload = method.ContainingType
.GetMembers(method.Name)
.OfType<IMethodSymbol>()
.FirstOrDefault(methodToCompare =>
HasSameParametersPlusCancellationToken(compilation, cancellationTokenType, genericTask, genericValueTask, method, methodToCompare));
return overload != null;
// Checks if the parameters of the two passed methods only differ in a ct.
static bool HasSameParametersPlusCancellationToken(
Compilation compilation,
ITypeSymbol cancellationTokenType,
INamedTypeSymbol? genericTask,
INamedTypeSymbol? genericValueTask,
IMethodSymbol originalMethod,
IMethodSymbol methodToCompare)
{
// Avoid comparing to itself, or when there are no parameters, or when the last parameter is not a ct
if (originalMethod.Equals(methodToCompare) ||
methodToCompare.Parameters.Count(p => p.Type.Equals(cancellationTokenType)) != 1 ||
!methodToCompare.Parameters[^1].Type.Equals(cancellationTokenType))
{
return false;
}
IMethodSymbol originalMethodWithAllParameters = (originalMethod.ReducedFrom ?? originalMethod).OriginalDefinition;
IMethodSymbol methodToCompareWithAllParameters = (methodToCompare.ReducedFrom ?? methodToCompare).OriginalDefinition;
// Ensure parameters only differ by one - the ct
if (originalMethodWithAllParameters.Parameters.Length != methodToCompareWithAllParameters.Parameters.Length - 1)
{
return false;
}
// Now compare the types of all parameters before the ct
// The largest i is the number of parameters in the method that has fewer parameters
for (int i = 0; i < originalMethodWithAllParameters.Parameters.Length; i++)
{
IParameterSymbol originalParameter = originalMethodWithAllParameters.Parameters[i];
IParameterSymbol comparedParameter = methodToCompareWithAllParameters.Parameters[i];
if (!originalParameter.Type.Equals(comparedParameter.Type))
{
return false;
}
}
// Overload is valid if its return type is implicitly convertable
var toCompareReturnType = methodToCompareWithAllParameters.ReturnType;
var originalReturnType = originalMethodWithAllParameters.ReturnType;
if (!toCompareReturnType.IsAssignableTo(originalReturnType, compilation))
{
// Generic Task-like types are special since awaiting them essentially erases the task-like type.
// If both types are Task-like we will warn if their generic arguments are convertable to each other.
if (IsTaskLikeType(originalReturnType) && IsTaskLikeType(toCompareReturnType) &&
originalReturnType is INamedTypeSymbol originalNamedType &&
toCompareReturnType is INamedTypeSymbol toCompareNamedType &&
TypeArgumentsAreConvertable(originalNamedType, toCompareNamedType))
{
return true;
}
return false;
}
return true;
bool IsTaskLikeType(ITypeSymbol typeSymbol)
{
if (genericTask is not null &&
typeSymbol.OriginalDefinition.Equals(genericTask))
{
return true;
}
if (genericValueTask is not null &&
typeSymbol.OriginalDefinition.Equals(genericValueTask))
{
return true;
}
return false;
}
bool TypeArgumentsAreConvertable(INamedTypeSymbol left, INamedTypeSymbol right)
{
if (left.Arity != 1 ||
right.Arity != 1 ||
left.Arity != right.Arity)
{
return false;
}
var leftTypeArgument = left.TypeArguments[0];
var rightTypeArgument = right.TypeArguments[0];
if (!leftTypeArgument.IsAssignableTo(rightTypeArgument, compilation))
{
return false;
}
return true;
}
}
}
}
}
| |
namespace android.content.pm
{
[global::MonoJavaBridge.JavaClass()]
public partial class PackageItemInfo : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static PackageItemInfo()
{
InitJNI();
}
protected PackageItemInfo(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public partial class DisplayNameComparator : java.lang.Object, java.util.Comparator
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static DisplayNameComparator()
{
InitJNI();
}
protected DisplayNameComparator(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _compare1962;
public virtual int compare(android.content.pm.PackageItemInfo arg0, android.content.pm.PackageItemInfo arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.content.pm.PackageItemInfo.DisplayNameComparator._compare1962, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.pm.PackageItemInfo.DisplayNameComparator.staticClass, global::android.content.pm.PackageItemInfo.DisplayNameComparator._compare1962, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _compare1963;
public virtual int compare(java.lang.Object arg0, java.lang.Object arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.content.pm.PackageItemInfo.DisplayNameComparator._compare1963, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.pm.PackageItemInfo.DisplayNameComparator.staticClass, global::android.content.pm.PackageItemInfo.DisplayNameComparator._compare1963, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _DisplayNameComparator1964;
public DisplayNameComparator(android.content.pm.PackageManager arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.pm.PackageItemInfo.DisplayNameComparator.staticClass, global::android.content.pm.PackageItemInfo.DisplayNameComparator._DisplayNameComparator1964, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.content.pm.PackageItemInfo.DisplayNameComparator.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/pm/PackageItemInfo$DisplayNameComparator"));
global::android.content.pm.PackageItemInfo.DisplayNameComparator._compare1962 = @__env.GetMethodIDNoThrow(global::android.content.pm.PackageItemInfo.DisplayNameComparator.staticClass, "compare", "(Landroid/content/pm/PackageItemInfo;Landroid/content/pm/PackageItemInfo;)I");
global::android.content.pm.PackageItemInfo.DisplayNameComparator._compare1963 = @__env.GetMethodIDNoThrow(global::android.content.pm.PackageItemInfo.DisplayNameComparator.staticClass, "compare", "(Ljava/lang/Object;Ljava/lang/Object;)I");
global::android.content.pm.PackageItemInfo.DisplayNameComparator._DisplayNameComparator1964 = @__env.GetMethodIDNoThrow(global::android.content.pm.PackageItemInfo.DisplayNameComparator.staticClass, "<init>", "(Landroid/content/pm/PackageManager;)V");
}
}
internal static global::MonoJavaBridge.MethodId _writeToParcel1965;
public virtual void writeToParcel(android.os.Parcel arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.pm.PackageItemInfo._writeToParcel1965, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.pm.PackageItemInfo.staticClass, global::android.content.pm.PackageItemInfo._writeToParcel1965, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _loadLabel1966;
public virtual global::java.lang.CharSequence loadLabel(android.content.pm.PackageManager arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.pm.PackageItemInfo._loadLabel1966, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.pm.PackageItemInfo.staticClass, global::android.content.pm.PackageItemInfo._loadLabel1966, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence;
}
internal static global::MonoJavaBridge.MethodId _loadIcon1967;
public virtual global::android.graphics.drawable.Drawable loadIcon(android.content.pm.PackageManager arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.pm.PackageItemInfo._loadIcon1967, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.drawable.Drawable;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.pm.PackageItemInfo.staticClass, global::android.content.pm.PackageItemInfo._loadIcon1967, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.drawable.Drawable;
}
internal static global::MonoJavaBridge.MethodId _loadXmlMetaData1968;
public virtual global::android.content.res.XmlResourceParser loadXmlMetaData(android.content.pm.PackageManager arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.content.res.XmlResourceParser>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.pm.PackageItemInfo._loadXmlMetaData1968, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.content.res.XmlResourceParser;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.content.res.XmlResourceParser>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.pm.PackageItemInfo.staticClass, global::android.content.pm.PackageItemInfo._loadXmlMetaData1968, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.content.res.XmlResourceParser;
}
internal static global::MonoJavaBridge.MethodId _dumpFront1969;
protected virtual void dumpFront(android.util.Printer arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.pm.PackageItemInfo._dumpFront1969, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.pm.PackageItemInfo.staticClass, global::android.content.pm.PackageItemInfo._dumpFront1969, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _dumpBack1970;
protected virtual void dumpBack(android.util.Printer arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.content.pm.PackageItemInfo._dumpBack1970, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.pm.PackageItemInfo.staticClass, global::android.content.pm.PackageItemInfo._dumpBack1970, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _PackageItemInfo1971;
public PackageItemInfo() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.pm.PackageItemInfo.staticClass, global::android.content.pm.PackageItemInfo._PackageItemInfo1971);
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _PackageItemInfo1972;
public PackageItemInfo(android.content.pm.PackageItemInfo arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.pm.PackageItemInfo.staticClass, global::android.content.pm.PackageItemInfo._PackageItemInfo1972, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _PackageItemInfo1973;
protected PackageItemInfo(android.os.Parcel arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.pm.PackageItemInfo.staticClass, global::android.content.pm.PackageItemInfo._PackageItemInfo1973, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.FieldId _name1974;
public global::java.lang.String name
{
get
{
return default(global::java.lang.String);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _packageName1975;
public global::java.lang.String packageName
{
get
{
return default(global::java.lang.String);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _labelRes1976;
public int labelRes
{
get
{
return default(int);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _nonLocalizedLabel1977;
public global::java.lang.CharSequence nonLocalizedLabel
{
get
{
return default(global::java.lang.CharSequence);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _icon1978;
public int icon
{
get
{
return default(int);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _metaData1979;
public global::android.os.Bundle metaData
{
get
{
return default(global::android.os.Bundle);
}
set
{
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.content.pm.PackageItemInfo.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/pm/PackageItemInfo"));
global::android.content.pm.PackageItemInfo._writeToParcel1965 = @__env.GetMethodIDNoThrow(global::android.content.pm.PackageItemInfo.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V");
global::android.content.pm.PackageItemInfo._loadLabel1966 = @__env.GetMethodIDNoThrow(global::android.content.pm.PackageItemInfo.staticClass, "loadLabel", "(Landroid/content/pm/PackageManager;)Ljava/lang/CharSequence;");
global::android.content.pm.PackageItemInfo._loadIcon1967 = @__env.GetMethodIDNoThrow(global::android.content.pm.PackageItemInfo.staticClass, "loadIcon", "(Landroid/content/pm/PackageManager;)Landroid/graphics/drawable/Drawable;");
global::android.content.pm.PackageItemInfo._loadXmlMetaData1968 = @__env.GetMethodIDNoThrow(global::android.content.pm.PackageItemInfo.staticClass, "loadXmlMetaData", "(Landroid/content/pm/PackageManager;Ljava/lang/String;)Landroid/content/res/XmlResourceParser;");
global::android.content.pm.PackageItemInfo._dumpFront1969 = @__env.GetMethodIDNoThrow(global::android.content.pm.PackageItemInfo.staticClass, "dumpFront", "(Landroid/util/Printer;Ljava/lang/String;)V");
global::android.content.pm.PackageItemInfo._dumpBack1970 = @__env.GetMethodIDNoThrow(global::android.content.pm.PackageItemInfo.staticClass, "dumpBack", "(Landroid/util/Printer;Ljava/lang/String;)V");
global::android.content.pm.PackageItemInfo._PackageItemInfo1971 = @__env.GetMethodIDNoThrow(global::android.content.pm.PackageItemInfo.staticClass, "<init>", "()V");
global::android.content.pm.PackageItemInfo._PackageItemInfo1972 = @__env.GetMethodIDNoThrow(global::android.content.pm.PackageItemInfo.staticClass, "<init>", "(Landroid/content/pm/PackageItemInfo;)V");
global::android.content.pm.PackageItemInfo._PackageItemInfo1973 = @__env.GetMethodIDNoThrow(global::android.content.pm.PackageItemInfo.staticClass, "<init>", "(Landroid/os/Parcel;)V");
}
}
}
| |
#region MigraDoc - Creating Documents on the Fly
//
// Authors:
// Stefan Lange (mailto:[email protected])
// Klaus Potzesny (mailto:[email protected])
// David Stephensen (mailto:[email protected])
//
// Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://www.migradoc.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using MigraDoc.DocumentObjectModel.Internals;
namespace MigraDoc.DocumentObjectModel.Shapes
{
/// <summary>
/// Base Class for all positionable Classes.
/// </summary>
public class Shape : DocumentObject
{
/// <summary>
/// Initializes a new instance of the Shape class.
/// </summary>
public Shape()
{
}
/// <summary>
/// Initializes a new instance of the Shape class with the specified parent.
/// </summary>
internal Shape(DocumentObject parent) : base(parent) { }
#region Methods
/// <summary>
/// Creates a deep copy of this object.
/// </summary>
public new Shape Clone()
{
return (Shape)DeepCopy();
}
/// <summary>
/// Implements the deep copy of the object.
/// </summary>
protected override object DeepCopy()
{
Shape shape = (Shape)base.DeepCopy();
if (shape.wrapFormat != null)
{
shape.wrapFormat = shape.wrapFormat.Clone();
shape.wrapFormat.parent = shape;
}
if (shape.lineFormat != null)
{
shape.lineFormat = shape.lineFormat.Clone();
shape.lineFormat.parent = shape;
}
if (shape.fillFormat != null)
{
shape.fillFormat = shape.fillFormat.Clone();
shape.fillFormat.parent = shape;
}
return shape;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the wrapping format of the shape.
/// </summary>
public WrapFormat WrapFormat
{
get
{
if (this.wrapFormat == null)
this.wrapFormat = new WrapFormat(this);
return this.wrapFormat;
}
set
{
SetParent(value);
this.wrapFormat = value;
}
}
[DV]
internal WrapFormat wrapFormat;
/// <summary>
/// Gets or sets the reference point of the Top property.
/// </summary>
public RelativeVertical RelativeVertical
{
get { return (RelativeVertical)this.relativeVertical.Value; }
set { this.relativeVertical.Value = (int)value; }
}
[DV(Type = typeof(RelativeVertical))]
internal NEnum relativeVertical = NEnum.NullValue(typeof(RelativeVertical));
/// <summary>
/// Gets or sets the reference point of the Left property.
/// </summary>
public RelativeHorizontal RelativeHorizontal
{
get { return (RelativeHorizontal)this.relativeHorizontal.Value; }
set { this.relativeHorizontal.Value = (int)value; }
}
[DV(Type = typeof(RelativeHorizontal))]
internal NEnum relativeHorizontal = NEnum.NullValue(typeof(RelativeHorizontal));
/// <summary>
/// Gets or sets the position of the top side of the shape.
/// </summary>
public TopPosition Top
{
get { return this.top; }
set { this.top = value; }
}
[DV]
internal TopPosition top = TopPosition.NullValue;
/// <summary>
/// Gets or sets the position of the left side of the shape.
/// </summary>
public LeftPosition Left
{
get { return this.left; }
set { this.left = value; }
}
[DV]
internal LeftPosition left = LeftPosition.NullValue;
/// <summary>
/// Gets the line format of the shape's border.
/// </summary>
public LineFormat LineFormat
{
get
{
if (this.lineFormat == null)
this.lineFormat = new LineFormat(this);
return this.lineFormat;
}
set
{
SetParent(value);
this.lineFormat = value;
}
}
[DV]
internal LineFormat lineFormat;
/// <summary>
/// Gets the background filling format of the shape.
/// </summary>
public FillFormat FillFormat
{
get
{
if (this.fillFormat == null)
this.fillFormat = new FillFormat(this);
return this.fillFormat;
}
set
{
SetParent(value);
this.fillFormat = value;
}
}
[DV]
internal FillFormat fillFormat;
/// <summary>
/// Gets or sets the height of the shape.
/// </summary>
public Unit Height
{
get { return this.height; }
set { this.height = value; }
}
[DV]
internal Unit height = Unit.NullValue;
/// <summary>
/// Gets or sets the width of the shape.
/// </summary>
public Unit Width
{
get { return this.width; }
set { this.width = value; }
}
[DV]
internal Unit width = Unit.NullValue;
#endregion
#region Internal
/// <summary>
/// Converts Shape into DDL.
/// </summary>
internal override void Serialize(Serializer serializer)
{
if (!this.height.IsNull)
serializer.WriteSimpleAttribute("Height", this.Height);
if (!this.width.IsNull)
serializer.WriteSimpleAttribute("Width", this.Width);
if (!this.relativeHorizontal.IsNull)
serializer.WriteSimpleAttribute("RelativeHorizontal", this.RelativeHorizontal);
if (!this.relativeVertical.IsNull)
serializer.WriteSimpleAttribute("RelativeVertical", this.RelativeVertical);
if (!this.IsNull("Left"))
this.left.Serialize(serializer);
if (!this.IsNull("Top"))
this.top.Serialize(serializer);
if (!this.IsNull("WrapFormat"))
this.wrapFormat.Serialize(serializer);
if (!this.IsNull("LineFormat"))
this.lineFormat.Serialize(serializer);
if (!this.IsNull("FillFormat"))
this.fillFormat.Serialize(serializer);
}
/// <summary>
/// Returns the meta object of this instance.
/// </summary>
internal override Meta Meta
{
get
{
if (meta == null)
meta = new Meta(typeof(Shape));
return meta;
}
}
static Meta meta;
#endregion
}
}
| |
// PhysX Plug-in
//
// Copyright 2015 University of Central Florida
//
//
// This plug-in uses NVIDIA's PhysX library to handle physics for OpenSim.
// Its goal is to provide all the functions that the Bullet plug-in does.
//
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Text;
using OpenSim.Region.Physics.Manager;
using OpenMetaverse;
using OpenSim.Framework;
namespace OpenSim.Region.Physics.PhysXPlugin
{
public class PxVMotor : PxMotor
{
/// <summary>
/// The timescale value of this PxVMotor instance, which indicates
/// how much time a step is.
/// </summary>
private float m_timeScale;
/// <summary>
/// The vector3 current value of this PxVMotor instance, which
/// indicates the current value of the vector3 we are
/// stepping/iterating.
/// </summary>
private Vector3 m_currentValue;
/// <summary>
/// The vector3 target value of this PxVMotor instance, which
/// indicates the upper limit of stepping/iterating the current
/// value to.
/// </summary>
private Vector3 m_targetValue;
/// <summary>
/// The vector3 value that represents the difference in the target
/// value and the current value at the current timestep.
/// </summary>
private Vector3 m_lastError;
/// <summary>
/// The float value that represents the efficiency in achieving the
/// target value from the current value.
/// </summary>
private float m_efficiency;
/// <summary>
/// Getter and setter for the timescale value of this PxVMotor.
/// </summary>
public float TimeScale
{
get
{
return m_timeScale;
}
set
{
m_timeScale = value;
}
}
/// <summary>
/// Getter and setter for the vector3 value that this PxMotor is
/// currently at the current moment in time.
/// </summary>
public Vector3 CurrentValue
{
get
{
return m_currentValue;
}
protected set
{
m_currentValue = value;
}
}
/// <summary>
/// Getter and setter for the vector3 value that this PxVMotor is
/// to step up and reach a step (timestep) at a time.
/// </summary>
public Vector3 TargetValue
{
get
{
return m_targetValue;
}
protected set
{
m_targetValue = value;
}
}
/// <summary>
/// Getter and setter for the vector3 value that represents the
/// difference in the target value and the current value.
/// </summary>
public Vector3 LastError
{
get
{
return m_lastError;
}
protected set
{
m_lastError = value;
}
}
/// <summary>
/// Getter and setter for the float value that represents the
/// efficiency or step size of this PxMotor.
/// </summary>
public float Efficiency
{
get
{
return m_efficiency;
}
set
{
m_efficiency = value;
}
}
/// <summary>
/// The rate of decaying the timescale to slow down the stepping
/// of the current value up to the target value.
/// </summary>
public virtual float TargetValueDecayTimeScale { get; set; }
/// <summary>
/// The threshold of the tolerance in calculating the error.
/// </summary>
public virtual float ErrorZeroThreshold { get; set; }
/// <summary>
/// Determines and returns if the last error calculated is
/// zero, because of floats.
/// </summary>
public virtual bool ErrorIsZero()
{
// Return the result of checking if the last error was zero
return ErrorIsZero(LastError);
}
/// <summary>
/// Determines and returns if the float passed in as the assumed error
/// is zero or not.
/// </summary>
public virtual bool ErrorIsZero(Vector3 err)
{
// Return the result of checking if the error is within our threshold
return (err == Vector3.Zero || err.ApproxEquals(Vector3.Zero, ErrorZeroThreshold));
}
/// <summary>
/// The default constructor for the vector motor.
/// </summary>
public PxVMotor()
{
// Set the timescale, decay, efficiency, and current values
// as default
TimeScale = TargetValueDecayTimeScale = PxMotor.Infinite;
Efficiency = 1.0f;
CurrentValue = TargetValue = Vector3.Zero;
ErrorZeroThreshold = 0.001f;
}
/// <summary>
/// The constructor for the PxVMotor to iterate a float to the
/// proper target value.
/// </summary>
/// <param name="timeScale"> The timescale of the timestep </param>
/// <param name="decayTimescale"> The rate at which the timestep slows </param>
/// <param name="efficiency"> The efficiency at which it steps the
/// current value </param>
public PxVMotor(float timeScale, float decayTimescale,
float efficiency) : base()
{
// Set the timescale, decay, and efficiency as given
TimeScale = timeScale;
TargetValueDecayTimeScale = decayTimescale;
Efficiency = efficiency;
// The defaults for the current and target value are zero
// and we go ahead and set our zero threshold to 0.001f
CurrentValue = TargetValue = Vector3.Zero;
ErrorZeroThreshold = 0.001f;
}
/// <summary>
/// Set the current value of this PxVMotor as passed in.
/// </summary>
/// <param name="current"> The updated current value </param>
public void SetCurrent(Vector3 current)
{
// Set the CurrentValue to the given current value
CurrentValue = current;
}
/// <summary>
/// Set the target value of this PxVMotor as passed in.
/// </summary>
/// <param name="target"> The updated target value </param>
public void SetTarget(Vector3 target)
{
// Set the TargetValue to the given target value
TargetValue = target;
}
/// <summary>
/// Reset and zero out both the target value and the current value
/// of this PxVMotor.
/// </summary>
public override void Zero()
{
// Go ahead and set the target and current value to zero
CurrentValue = TargetValue = Vector3.Zero;
}
/// <summary>
/// Step the motor and return the resulting current value.
/// </summary>
/// <param name="timeStep"> The current timestep of the scene </param>
public virtual Vector3 Step(float timeStep)
{
Vector3 errorValue, correctionValue;
float decayFactor;
// If the motor is not enabled, we assume that we
// have reached the target value, so simply just
// return the target value that we have
if (!Enabled)
{
return TargetValue;
}
// Calculate the difference in the current and target values
errorValue = TargetValue - CurrentValue;
correctionValue = Vector3.Zero;
// If the calculated error value is not zero
if (!ErrorIsZero(errorValue))
{
// Calculate the error correction value
// and add it to the current value
correctionValue = StepError(timeStep, errorValue);
CurrentValue += correctionValue;
// The desired value reduces to zero which also reduces the
// difference with current
// If the decay timescale is not infinite, we decay
if (TargetValueDecayTimeScale != PxMotor.Infinite)
{
decayFactor = (1.0f / TargetValueDecayTimeScale) * timeStep;
TargetValue *= (1f - decayFactor);
}
}
else
{
// Difference between what we have and target is small, Motor
// is done
if (TargetValue.ApproxEquals(Vector3.Zero, ErrorZeroThreshold))
{
// The target can step down to nearly zero but not get
// there If close to zero it is really zero
TargetValue = Vector3.Zero;
}
// If the motor is done, set the current value to the target value
CurrentValue = TargetValue;
}
// Update the last error as the most recently calculated error
LastError = errorValue;
return correctionValue;
}
/// <summary>
/// A method that will set the current value before doing the next
/// physics step.
/// <summary>
/// <param name="timeStep">The current timestep of the scene</param>
/// <param name="current">The new current value that will be used in
/// this physics step</param>
public virtual Vector3 Step(float timeStep, Vector3 current)
{
// Set the current value and then call the usual step method
CurrentValue = current;
return Step(timeStep);
}
/// <summary>
/// Calculate and return the resulting correction in the error
/// for the current timestep.
/// </summary>
/// <param name="timeStep"> The current timestep of the scene</param>
/// <param name="error"> The difference in the current value and
/// target</param>
public virtual Vector3 StepError(float timeStep, Vector3 error)
{
Vector3 returnCorrection, correctionAmount;
// If this PxVMotor is not enabled, simply return 0.0f
if (!Enabled)
{
return Vector3.Zero;
}
// Initialize the return correction, and the correction amount
// to a float value of zero, so that it is initialized
returnCorrection = Vector3.Zero;
correctionAmount = Vector3.Zero;
// If the given error is not zero, we should calculate the
// correction to be returned
if (!ErrorIsZero(error))
{
// If the timescale is zero, or infinity, then the correction
// amount is equal to the error * the timestep
if (TimeScale == 0.0f || TimeScale == PxMotor.Infinite)
{
correctionAmount = error * timeStep;
}
else
{
// Otherwise, we can use the timescale so that it does not
// result in a divide by zero error
correctionAmount = error / TimeScale * timeStep;
}
// Set the returned correction to the calculated correction
// amount
returnCorrection = correctionAmount;
}
return returnCorrection;
}
/// <summary>
/// Return a representation of the current values on the motor as
/// a string.
/// </summary>
public override string ToString()
{
// Return a formatted string with the values existing on this motor
return String.Format("<curr={0},targ={1},lastErr={2},decayTS={3}>",
CurrentValue, TargetValue, LastError,
TargetValueDecayTimeScale);
}
/// <summary>
/// Reset and zero out both the target value of this motor, as
/// well as the current value of this motor.
/// </summary>>
public override void Reset()
{
Zero();
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmCustomerTransaction
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmCustomerTransaction() : base()
{
Load += frmCustomerTransaction_Load;
FormClosed += frmCustomerTransaction_FormClosed;
KeyDown += frmCustomerTransaction_KeyDown;
Resize += frmCustomerTransaction_Resize;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
public System.Windows.Forms.TextBox txtTotalAmount;
private System.Windows.Forms.TextBox withEventsField_txtSettlement;
public System.Windows.Forms.TextBox txtSettlement {
get { return withEventsField_txtSettlement; }
set {
if (withEventsField_txtSettlement != null) {
withEventsField_txtSettlement.Enter -= txtSettlement_Enter;
withEventsField_txtSettlement.KeyPress -= txtSettlement_KeyPress;
withEventsField_txtSettlement.Leave -= txtSettlement_Leave;
}
withEventsField_txtSettlement = value;
if (withEventsField_txtSettlement != null) {
withEventsField_txtSettlement.Enter += txtSettlement_Enter;
withEventsField_txtSettlement.KeyPress += txtSettlement_KeyPress;
withEventsField_txtSettlement.Leave += txtSettlement_Leave;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdProcess;
public System.Windows.Forms.Button cmdProcess {
get { return withEventsField_cmdProcess; }
set {
if (withEventsField_cmdProcess != null) {
withEventsField_cmdProcess.Click -= cmdProcess_Click;
withEventsField_cmdProcess.Enter -= cmdProcess_Enter;
}
withEventsField_cmdProcess = value;
if (withEventsField_cmdProcess != null) {
withEventsField_cmdProcess.Click += cmdProcess_Click;
withEventsField_cmdProcess.Enter += cmdProcess_Enter;
}
}
}
private System.Windows.Forms.TextBox withEventsField_txtAmount;
public System.Windows.Forms.TextBox txtAmount {
get { return withEventsField_txtAmount; }
set {
if (withEventsField_txtAmount != null) {
withEventsField_txtAmount.Enter -= txtAmount_Enter;
withEventsField_txtAmount.KeyPress -= txtAmount_KeyPress;
withEventsField_txtAmount.Leave -= txtAmount_Leave;
}
withEventsField_txtAmount = value;
if (withEventsField_txtAmount != null) {
withEventsField_txtAmount.Enter += txtAmount_Enter;
withEventsField_txtAmount.KeyPress += txtAmount_KeyPress;
withEventsField_txtAmount.Leave += txtAmount_Leave;
}
}
}
private System.Windows.Forms.TextBox withEventsField_txtNotes;
public System.Windows.Forms.TextBox txtNotes {
get { return withEventsField_txtNotes; }
set {
if (withEventsField_txtNotes != null) {
withEventsField_txtNotes.Enter -= txtNotes_Enter;
}
withEventsField_txtNotes = value;
if (withEventsField_txtNotes != null) {
withEventsField_txtNotes.Enter += txtNotes_Enter;
}
}
}
private System.Windows.Forms.TextBox withEventsField_txtNarrative;
public System.Windows.Forms.TextBox txtNarrative {
get { return withEventsField_txtNarrative; }
set {
if (withEventsField_txtNarrative != null) {
withEventsField_txtNarrative.Enter -= txtNarrative_Enter;
}
withEventsField_txtNarrative = value;
if (withEventsField_txtNarrative != null) {
withEventsField_txtNarrative.Enter += txtNarrative_Enter;
}
}
}
public System.Windows.Forms.TextBox _txtFields_2;
public System.Windows.Forms.TextBox _txtFields_3;
public System.Windows.Forms.TextBox _txtFields_4;
public System.Windows.Forms.TextBox _txtFields_5;
public System.Windows.Forms.TextBox _txtFields_6;
public System.Windows.Forms.TextBox _txtFields_7;
public System.Windows.Forms.TextBox _txtFields_8;
public System.Windows.Forms.TextBox _txtFields_9;
public System.Windows.Forms.TextBox _txtFields_10;
public System.Windows.Forms.TextBox _txtFloat_12;
public System.Windows.Forms.TextBox _txtFloat_13;
public System.Windows.Forms.TextBox _txtFloat_14;
public System.Windows.Forms.TextBox _txtFloat_15;
public System.Windows.Forms.TextBox _txtFloat_16;
public System.Windows.Forms.TextBox _txtFloat_17;
public System.Windows.Forms.TextBox _txtFloat_18;
private System.Windows.Forms.Button withEventsField_cmdStatement;
public System.Windows.Forms.Button cmdStatement {
get { return withEventsField_cmdStatement; }
set {
if (withEventsField_cmdStatement != null) {
withEventsField_cmdStatement.Click -= cmdStatement_Click;
}
withEventsField_cmdStatement = value;
if (withEventsField_cmdStatement != null) {
withEventsField_cmdStatement.Click += cmdStatement_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdCancel;
public System.Windows.Forms.Button cmdCancel {
get { return withEventsField_cmdCancel; }
set {
if (withEventsField_cmdCancel != null) {
withEventsField_cmdCancel.Click -= cmdCancel_Click;
}
withEventsField_cmdCancel = value;
if (withEventsField_cmdCancel != null) {
withEventsField_cmdCancel.Click += cmdCancel_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdClose;
public System.Windows.Forms.Button cmdClose {
get { return withEventsField_cmdClose; }
set {
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click -= cmdClose_Click;
}
withEventsField_cmdClose = value;
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click += cmdClose_Click;
}
}
}
public System.Windows.Forms.Panel picButtons;
public System.Windows.Forms.Label Label2;
public System.Windows.Forms.Label lblSett;
public System.Windows.Forms.Label _lblLabels_20;
public System.Windows.Forms.Label _lblLabels_19;
public System.Windows.Forms.Label _lblLabels_11;
public System.Windows.Forms.Label _lblLabels_1;
public System.Windows.Forms.Label _lblLabels_0;
public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_2;
public System.Windows.Forms.Label _lbl_2;
public System.Windows.Forms.Label _lbl_1;
public System.Windows.Forms.Label _lbl_0;
public System.Windows.Forms.Label _lblLabels_2;
public System.Windows.Forms.Label _lblLabels_3;
public System.Windows.Forms.Label _lblLabels_4;
public System.Windows.Forms.Label _lblLabels_5;
public System.Windows.Forms.Label _lblLabels_6;
public System.Windows.Forms.Label _lblLabels_7;
public System.Windows.Forms.Label _lblLabels_8;
public System.Windows.Forms.Label _lblLabels_9;
public System.Windows.Forms.Label _lblLabels_10;
public System.Windows.Forms.Label _lblLabels_12;
public System.Windows.Forms.Label _lblLabels_13;
public System.Windows.Forms.Label _lblLabels_14;
public System.Windows.Forms.Label _lblLabels_15;
public System.Windows.Forms.Label _lblLabels_16;
public System.Windows.Forms.Label _lblLabels_17;
public System.Windows.Forms.Label _lblLabels_18;
public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_0;
public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_1;
//Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents lblLabels As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents txtFields As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray
//Public WithEvents txtFloat As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray
public RectangleShapeArray Shape1;
public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
this._Shape1_2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
this._Shape1_0 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
this._Shape1_1 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
this.txtTotalAmount = new System.Windows.Forms.TextBox();
this.txtSettlement = new System.Windows.Forms.TextBox();
this.cmdProcess = new System.Windows.Forms.Button();
this.txtAmount = new System.Windows.Forms.TextBox();
this.txtNotes = new System.Windows.Forms.TextBox();
this.txtNarrative = new System.Windows.Forms.TextBox();
this._txtFields_2 = new System.Windows.Forms.TextBox();
this._txtFields_3 = new System.Windows.Forms.TextBox();
this._txtFields_4 = new System.Windows.Forms.TextBox();
this._txtFields_5 = new System.Windows.Forms.TextBox();
this._txtFields_6 = new System.Windows.Forms.TextBox();
this._txtFields_7 = new System.Windows.Forms.TextBox();
this._txtFields_8 = new System.Windows.Forms.TextBox();
this._txtFields_9 = new System.Windows.Forms.TextBox();
this._txtFields_10 = new System.Windows.Forms.TextBox();
this._txtFloat_12 = new System.Windows.Forms.TextBox();
this._txtFloat_13 = new System.Windows.Forms.TextBox();
this._txtFloat_14 = new System.Windows.Forms.TextBox();
this._txtFloat_15 = new System.Windows.Forms.TextBox();
this._txtFloat_16 = new System.Windows.Forms.TextBox();
this._txtFloat_17 = new System.Windows.Forms.TextBox();
this._txtFloat_18 = new System.Windows.Forms.TextBox();
this.picButtons = new System.Windows.Forms.Panel();
this.cmdStatement = new System.Windows.Forms.Button();
this.cmdCancel = new System.Windows.Forms.Button();
this.cmdClose = new System.Windows.Forms.Button();
this.Label2 = new System.Windows.Forms.Label();
this.lblSett = new System.Windows.Forms.Label();
this._lblLabels_20 = new System.Windows.Forms.Label();
this._lblLabels_19 = new System.Windows.Forms.Label();
this._lblLabels_11 = new System.Windows.Forms.Label();
this._lblLabels_1 = new System.Windows.Forms.Label();
this._lblLabels_0 = new System.Windows.Forms.Label();
this._lbl_2 = new System.Windows.Forms.Label();
this._lbl_1 = new System.Windows.Forms.Label();
this._lbl_0 = new System.Windows.Forms.Label();
this._lblLabels_2 = new System.Windows.Forms.Label();
this._lblLabels_3 = new System.Windows.Forms.Label();
this._lblLabels_4 = new System.Windows.Forms.Label();
this._lblLabels_5 = new System.Windows.Forms.Label();
this._lblLabels_6 = new System.Windows.Forms.Label();
this._lblLabels_7 = new System.Windows.Forms.Label();
this._lblLabels_8 = new System.Windows.Forms.Label();
this._lblLabels_9 = new System.Windows.Forms.Label();
this._lblLabels_10 = new System.Windows.Forms.Label();
this._lblLabels_12 = new System.Windows.Forms.Label();
this._lblLabels_13 = new System.Windows.Forms.Label();
this._lblLabels_14 = new System.Windows.Forms.Label();
this._lblLabels_15 = new System.Windows.Forms.Label();
this._lblLabels_16 = new System.Windows.Forms.Label();
this._lblLabels_17 = new System.Windows.Forms.Label();
this._lblLabels_18 = new System.Windows.Forms.Label();
this.Shape1 = new _4PosBackOffice.NET.RectangleShapeArray(this.components);
this.picButtons.SuspendLayout();
((System.ComponentModel.ISupportInitialize)this.Shape1).BeginInit();
this.SuspendLayout();
//
//ShapeContainer1
//
this.ShapeContainer1.Location = new System.Drawing.Point(0, 0);
this.ShapeContainer1.Margin = new System.Windows.Forms.Padding(0);
this.ShapeContainer1.Name = "ShapeContainer1";
this.ShapeContainer1.Shapes.AddRange(new Microsoft.VisualBasic.PowerPacks.Shape[] {
this._Shape1_2,
this._Shape1_0,
this._Shape1_1
});
this.ShapeContainer1.Size = new System.Drawing.Size(661, 346);
this.ShapeContainer1.TabIndex = 52;
this.ShapeContainer1.TabStop = false;
//
//_Shape1_2
//
this._Shape1_2.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(255)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)));
this._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
this._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText;
this._Shape1_2.FillColor = System.Drawing.Color.Black;
this.Shape1.SetIndex(this._Shape1_2, Convert.ToInt16(2));
this._Shape1_2.Location = new System.Drawing.Point(342, 183);
this._Shape1_2.Name = "_Shape1_2";
this._Shape1_2.Size = new System.Drawing.Size(310, 158);
//
//_Shape1_0
//
this._Shape1_0.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Shape1_0.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
this._Shape1_0.BorderColor = System.Drawing.SystemColors.WindowText;
this._Shape1_0.FillColor = System.Drawing.Color.Black;
this.Shape1.SetIndex(this._Shape1_0, Convert.ToInt16(0));
this._Shape1_0.Location = new System.Drawing.Point(342, 57);
this._Shape1_0.Name = "_Shape1_0";
this._Shape1_0.Size = new System.Drawing.Size(310, 103);
//
//_Shape1_1
//
this._Shape1_1.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Shape1_1.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
this._Shape1_1.BorderColor = System.Drawing.SystemColors.WindowText;
this._Shape1_1.FillColor = System.Drawing.Color.Black;
this.Shape1.SetIndex(this._Shape1_1, Convert.ToInt16(1));
this._Shape1_1.Location = new System.Drawing.Point(6, 57);
this._Shape1_1.Name = "_Shape1_1";
this._Shape1_1.Size = new System.Drawing.Size(328, 280);
//
//txtTotalAmount
//
this.txtTotalAmount.AcceptsReturn = true;
this.txtTotalAmount.BackColor = System.Drawing.SystemColors.Window;
this.txtTotalAmount.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtTotalAmount.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtTotalAmount.Enabled = false;
this.txtTotalAmount.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtTotalAmount.Location = new System.Drawing.Point(442, 314);
this.txtTotalAmount.MaxLength = 0;
this.txtTotalAmount.Name = "txtTotalAmount";
this.txtTotalAmount.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtTotalAmount.Size = new System.Drawing.Size(111, 19);
this.txtTotalAmount.TabIndex = 45;
this.txtTotalAmount.Text = "0.00";
this.txtTotalAmount.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//txtSettlement
//
this.txtSettlement.AcceptsReturn = true;
this.txtSettlement.BackColor = System.Drawing.SystemColors.Window;
this.txtSettlement.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtSettlement.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtSettlement.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtSettlement.Location = new System.Drawing.Point(442, 294);
this.txtSettlement.MaxLength = 0;
this.txtSettlement.Name = "txtSettlement";
this.txtSettlement.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtSettlement.Size = new System.Drawing.Size(111, 19);
this.txtSettlement.TabIndex = 44;
this.txtSettlement.Text = "0.00";
this.txtSettlement.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//cmdProcess
//
this.cmdProcess.BackColor = System.Drawing.SystemColors.Control;
this.cmdProcess.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdProcess.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.cmdProcess.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdProcess.Location = new System.Drawing.Point(560, 308);
this.cmdProcess.Name = "cmdProcess";
this.cmdProcess.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdProcess.Size = new System.Drawing.Size(79, 25);
this.cmdProcess.TabIndex = 46;
this.cmdProcess.Text = "&Process";
this.cmdProcess.UseVisualStyleBackColor = false;
//
//txtAmount
//
this.txtAmount.AcceptsReturn = true;
this.txtAmount.BackColor = System.Drawing.SystemColors.Window;
this.txtAmount.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtAmount.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtAmount.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtAmount.Location = new System.Drawing.Point(442, 273);
this.txtAmount.MaxLength = 0;
this.txtAmount.Name = "txtAmount";
this.txtAmount.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtAmount.Size = new System.Drawing.Size(111, 19);
this.txtAmount.TabIndex = 40;
this.txtAmount.Text = "0.00";
this.txtAmount.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//txtNotes
//
this.txtNotes.AcceptsReturn = true;
this.txtNotes.BackColor = System.Drawing.SystemColors.Window;
this.txtNotes.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtNotes.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtNotes.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtNotes.Location = new System.Drawing.Point(408, 219);
this.txtNotes.MaxLength = 0;
this.txtNotes.Multiline = true;
this.txtNotes.Name = "txtNotes";
this.txtNotes.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtNotes.Size = new System.Drawing.Size(232, 49);
this.txtNotes.TabIndex = 39;
//
//txtNarrative
//
this.txtNarrative.AcceptsReturn = true;
this.txtNarrative.BackColor = System.Drawing.SystemColors.Window;
this.txtNarrative.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtNarrative.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtNarrative.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtNarrative.Location = new System.Drawing.Point(408, 195);
this.txtNarrative.MaxLength = 0;
this.txtNarrative.Name = "txtNarrative";
this.txtNarrative.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtNarrative.Size = new System.Drawing.Size(232, 19);
this.txtNarrative.TabIndex = 38;
//
//_txtFields_2
//
this._txtFields_2.AcceptsReturn = true;
this._txtFields_2.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_2.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_2.Enabled = false;
this._txtFields_2.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_2.Location = new System.Drawing.Point(102, 63);
this._txtFields_2.MaxLength = 0;
this._txtFields_2.Name = "_txtFields_2";
this._txtFields_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_2.Size = new System.Drawing.Size(226, 19);
this._txtFields_2.TabIndex = 5;
//
//_txtFields_3
//
this._txtFields_3.AcceptsReturn = true;
this._txtFields_3.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_3.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_3.Enabled = false;
this._txtFields_3.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_3.Location = new System.Drawing.Point(102, 84);
this._txtFields_3.MaxLength = 0;
this._txtFields_3.Name = "_txtFields_3";
this._txtFields_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_3.Size = new System.Drawing.Size(226, 19);
this._txtFields_3.TabIndex = 7;
//
//_txtFields_4
//
this._txtFields_4.AcceptsReturn = true;
this._txtFields_4.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_4.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_4.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_4.Enabled = false;
this._txtFields_4.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_4.Location = new System.Drawing.Point(15, 126);
this._txtFields_4.MaxLength = 0;
this._txtFields_4.Name = "_txtFields_4";
this._txtFields_4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_4.Size = new System.Drawing.Size(157, 19);
this._txtFields_4.TabIndex = 9;
//
//_txtFields_5
//
this._txtFields_5.AcceptsReturn = true;
this._txtFields_5.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_5.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_5.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_5.Enabled = false;
this._txtFields_5.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_5.Location = new System.Drawing.Point(174, 126);
this._txtFields_5.MaxLength = 0;
this._txtFields_5.Name = "_txtFields_5";
this._txtFields_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_5.Size = new System.Drawing.Size(154, 19);
this._txtFields_5.TabIndex = 11;
//
//_txtFields_6
//
this._txtFields_6.AcceptsReturn = true;
this._txtFields_6.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_6.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_6.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_6.Enabled = false;
this._txtFields_6.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_6.Location = new System.Drawing.Point(15, 234);
this._txtFields_6.MaxLength = 0;
this._txtFields_6.Multiline = true;
this._txtFields_6.Name = "_txtFields_6";
this._txtFields_6.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_6.Size = new System.Drawing.Size(157, 98);
this._txtFields_6.TabIndex = 19;
//
//_txtFields_7
//
this._txtFields_7.AcceptsReturn = true;
this._txtFields_7.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_7.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_7.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_7.Enabled = false;
this._txtFields_7.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_7.Location = new System.Drawing.Point(174, 234);
this._txtFields_7.MaxLength = 0;
this._txtFields_7.Name = "_txtFields_7";
this._txtFields_7.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_7.Size = new System.Drawing.Size(154, 98);
this._txtFields_7.TabIndex = 21;
//
//_txtFields_8
//
this._txtFields_8.AcceptsReturn = true;
this._txtFields_8.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_8.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_8.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_8.Enabled = false;
this._txtFields_8.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_8.Location = new System.Drawing.Point(102, 156);
this._txtFields_8.MaxLength = 0;
this._txtFields_8.Name = "_txtFields_8";
this._txtFields_8.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_8.Size = new System.Drawing.Size(226, 19);
this._txtFields_8.TabIndex = 13;
//
//_txtFields_9
//
this._txtFields_9.AcceptsReturn = true;
this._txtFields_9.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_9.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_9.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_9.Enabled = false;
this._txtFields_9.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_9.Location = new System.Drawing.Point(102, 177);
this._txtFields_9.MaxLength = 0;
this._txtFields_9.Name = "_txtFields_9";
this._txtFields_9.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_9.Size = new System.Drawing.Size(226, 19);
this._txtFields_9.TabIndex = 15;
//
//_txtFields_10
//
this._txtFields_10.AcceptsReturn = true;
this._txtFields_10.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_10.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_10.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_10.Enabled = false;
this._txtFields_10.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_10.Location = new System.Drawing.Point(102, 198);
this._txtFields_10.MaxLength = 0;
this._txtFields_10.Name = "_txtFields_10";
this._txtFields_10.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_10.Size = new System.Drawing.Size(226, 19);
this._txtFields_10.TabIndex = 17;
//
//_txtFloat_12
//
this._txtFloat_12.AcceptsReturn = true;
this._txtFloat_12.BackColor = System.Drawing.SystemColors.Window;
this._txtFloat_12.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFloat_12.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFloat_12.Enabled = false;
this._txtFloat_12.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFloat_12.Location = new System.Drawing.Point(423, 63);
this._txtFloat_12.MaxLength = 0;
this._txtFloat_12.Name = "_txtFloat_12";
this._txtFloat_12.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFloat_12.Size = new System.Drawing.Size(79, 19);
this._txtFloat_12.TabIndex = 24;
this._txtFloat_12.Text = "9,999,999.00";
this._txtFloat_12.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//_txtFloat_13
//
this._txtFloat_13.AcceptsReturn = true;
this._txtFloat_13.BackColor = System.Drawing.SystemColors.Window;
this._txtFloat_13.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFloat_13.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFloat_13.Enabled = false;
this._txtFloat_13.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFloat_13.Location = new System.Drawing.Point(423, 84);
this._txtFloat_13.MaxLength = 0;
this._txtFloat_13.Name = "_txtFloat_13";
this._txtFloat_13.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFloat_13.Size = new System.Drawing.Size(79, 19);
this._txtFloat_13.TabIndex = 26;
this._txtFloat_13.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//_txtFloat_14
//
this._txtFloat_14.AcceptsReturn = true;
this._txtFloat_14.BackColor = System.Drawing.SystemColors.Window;
this._txtFloat_14.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFloat_14.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFloat_14.Enabled = false;
this._txtFloat_14.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFloat_14.Location = new System.Drawing.Point(567, 87);
this._txtFloat_14.MaxLength = 0;
this._txtFloat_14.Name = "_txtFloat_14";
this._txtFloat_14.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFloat_14.Size = new System.Drawing.Size(79, 19);
this._txtFloat_14.TabIndex = 32;
this._txtFloat_14.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//_txtFloat_15
//
this._txtFloat_15.AcceptsReturn = true;
this._txtFloat_15.BackColor = System.Drawing.SystemColors.Window;
this._txtFloat_15.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFloat_15.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFloat_15.Enabled = false;
this._txtFloat_15.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFloat_15.Location = new System.Drawing.Point(423, 108);
this._txtFloat_15.MaxLength = 0;
this._txtFloat_15.Name = "_txtFloat_15";
this._txtFloat_15.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFloat_15.Size = new System.Drawing.Size(79, 19);
this._txtFloat_15.TabIndex = 28;
this._txtFloat_15.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//_txtFloat_16
//
this._txtFloat_16.AcceptsReturn = true;
this._txtFloat_16.BackColor = System.Drawing.SystemColors.Window;
this._txtFloat_16.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFloat_16.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFloat_16.Enabled = false;
this._txtFloat_16.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFloat_16.Location = new System.Drawing.Point(567, 108);
this._txtFloat_16.MaxLength = 0;
this._txtFloat_16.Name = "_txtFloat_16";
this._txtFloat_16.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFloat_16.Size = new System.Drawing.Size(79, 19);
this._txtFloat_16.TabIndex = 34;
this._txtFloat_16.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//_txtFloat_17
//
this._txtFloat_17.AcceptsReturn = true;
this._txtFloat_17.BackColor = System.Drawing.SystemColors.Window;
this._txtFloat_17.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFloat_17.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFloat_17.Enabled = false;
this._txtFloat_17.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFloat_17.Location = new System.Drawing.Point(423, 129);
this._txtFloat_17.MaxLength = 0;
this._txtFloat_17.Name = "_txtFloat_17";
this._txtFloat_17.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFloat_17.Size = new System.Drawing.Size(79, 19);
this._txtFloat_17.TabIndex = 30;
this._txtFloat_17.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//_txtFloat_18
//
this._txtFloat_18.AcceptsReturn = true;
this._txtFloat_18.BackColor = System.Drawing.SystemColors.Window;
this._txtFloat_18.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFloat_18.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFloat_18.Enabled = false;
this._txtFloat_18.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFloat_18.Location = new System.Drawing.Point(567, 129);
this._txtFloat_18.MaxLength = 0;
this._txtFloat_18.Name = "_txtFloat_18";
this._txtFloat_18.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFloat_18.Size = new System.Drawing.Size(79, 19);
this._txtFloat_18.TabIndex = 36;
this._txtFloat_18.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//picButtons
//
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picButtons.Controls.Add(this.cmdStatement);
this.picButtons.Controls.Add(this.cmdCancel);
this.picButtons.Controls.Add(this.cmdClose);
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText;
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.Name = "picButtons";
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Size = new System.Drawing.Size(661, 38);
this.picButtons.TabIndex = 2;
//
//cmdStatement
//
this.cmdStatement.BackColor = System.Drawing.SystemColors.Control;
this.cmdStatement.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdStatement.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdStatement.Location = new System.Drawing.Point(99, 3);
this.cmdStatement.Name = "cmdStatement";
this.cmdStatement.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdStatement.Size = new System.Drawing.Size(73, 29);
this.cmdStatement.TabIndex = 47;
this.cmdStatement.TabStop = false;
this.cmdStatement.Text = "&Statement";
this.cmdStatement.UseVisualStyleBackColor = false;
//
//cmdCancel
//
this.cmdCancel.BackColor = System.Drawing.SystemColors.Control;
this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdCancel.Location = new System.Drawing.Point(4, 2);
this.cmdCancel.Name = "cmdCancel";
this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdCancel.Size = new System.Drawing.Size(73, 29);
this.cmdCancel.TabIndex = 0;
this.cmdCancel.TabStop = false;
this.cmdCancel.Text = "&Undo";
this.cmdCancel.UseVisualStyleBackColor = false;
//
//cmdClose
//
this.cmdClose.BackColor = System.Drawing.SystemColors.Control;
this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdClose.Location = new System.Drawing.Point(576, 3);
this.cmdClose.Name = "cmdClose";
this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdClose.Size = new System.Drawing.Size(73, 29);
this.cmdClose.TabIndex = 1;
this.cmdClose.TabStop = false;
this.cmdClose.Text = "E&xit";
this.cmdClose.UseVisualStyleBackColor = false;
//
//Label2
//
this.Label2.BackColor = System.Drawing.Color.Transparent;
this.Label2.Cursor = System.Windows.Forms.Cursors.Default;
this.Label2.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.Label2.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label2.Location = new System.Drawing.Point(356, 318);
this.Label2.Name = "Label2";
this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label2.Size = new System.Drawing.Size(85, 17);
this.Label2.TabIndex = 51;
this.Label2.Text = "Total Amount:";
//
//lblSett
//
this.lblSett.BackColor = System.Drawing.Color.Transparent;
this.lblSett.Cursor = System.Windows.Forms.Cursors.Default;
this.lblSett.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lblSett.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblSett.Location = new System.Drawing.Point(370, 298);
this.lblSett.Name = "lblSett";
this.lblSett.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblSett.Size = new System.Drawing.Size(67, 13);
this.lblSett.TabIndex = 50;
this.lblSett.Text = "Settlement:";
//
//_lblLabels_20
//
this._lblLabels_20.AutoSize = true;
this._lblLabels_20.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_20.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_20.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._lblLabels_20.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_20.Location = new System.Drawing.Point(0, 0);
this._lblLabels_20.Name = "_lblLabels_20";
this._lblLabels_20.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_20.Size = new System.Drawing.Size(54, 14);
this._lblLabels_20.TabIndex = 49;
this._lblLabels_20.Text = "Amount:";
this._lblLabels_20.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_19
//
this._lblLabels_19.AutoSize = true;
this._lblLabels_19.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_19.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_19.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._lblLabels_19.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_19.Location = new System.Drawing.Point(0, 0);
this._lblLabels_19.Name = "_lblLabels_19";
this._lblLabels_19.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_19.Size = new System.Drawing.Size(54, 14);
this._lblLabels_19.TabIndex = 48;
this._lblLabels_19.Text = "Amount:";
this._lblLabels_19.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_11
//
this._lblLabels_11.AutoSize = true;
this._lblLabels_11.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_11.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_11.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._lblLabels_11.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_11.Location = new System.Drawing.Point(388, 278);
this._lblLabels_11.Name = "_lblLabels_11";
this._lblLabels_11.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_11.Size = new System.Drawing.Size(54, 14);
this._lblLabels_11.TabIndex = 43;
this._lblLabels_11.Text = "Amount:";
this._lblLabels_11.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_1
//
this._lblLabels_1.AutoSize = true;
this._lblLabels_1.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_1.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_1.Location = new System.Drawing.Point(372, 219);
this._lblLabels_1.Name = "_lblLabels_1";
this._lblLabels_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_1.Size = new System.Drawing.Size(38, 13);
this._lblLabels_1.TabIndex = 42;
this._lblLabels_1.Text = "Notes:";
this._lblLabels_1.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_0
//
this._lblLabels_0.AutoSize = true;
this._lblLabels_0.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_0.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._lblLabels_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_0.Location = new System.Drawing.Point(346, 198);
this._lblLabels_0.Name = "_lblLabels_0";
this._lblLabels_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_0.Size = new System.Drawing.Size(59, 14);
this._lblLabels_0.TabIndex = 41;
this._lblLabels_0.Text = "Narrative:";
this._lblLabels_0.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lbl_2
//
this._lbl_2.AutoSize = true;
this._lbl_2.BackColor = System.Drawing.Color.Transparent;
this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_2.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_2.Location = new System.Drawing.Point(342, 168);
this._lbl_2.Name = "_lbl_2";
this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_2.Size = new System.Drawing.Size(83, 14);
this._lbl_2.TabIndex = 37;
this._lbl_2.Text = "&3. Transaction";
//
//_lbl_1
//
this._lbl_1.AutoSize = true;
this._lbl_1.BackColor = System.Drawing.Color.Transparent;
this._lbl_1.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._lbl_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_1.Location = new System.Drawing.Point(6, 42);
this._lbl_1.Name = "_lbl_1";
this._lbl_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_1.Size = new System.Drawing.Size(62, 14);
this._lbl_1.TabIndex = 3;
this._lbl_1.Text = "&1. General";
//
//_lbl_0
//
this._lbl_0.AutoSize = true;
this._lbl_0.BackColor = System.Drawing.Color.Transparent;
this._lbl_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_0.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._lbl_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_0.Location = new System.Drawing.Point(342, 42);
this._lbl_0.Name = "_lbl_0";
this._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_0.Size = new System.Drawing.Size(73, 14);
this._lbl_0.TabIndex = 22;
this._lbl_0.Text = "&2. Financials";
//
//_lblLabels_2
//
this._lblLabels_2.AutoSize = true;
this._lblLabels_2.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_2.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_2.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._lblLabels_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_2.Location = new System.Drawing.Point(12, 63);
this._lblLabels_2.Name = "_lblLabels_2";
this._lblLabels_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_2.Size = new System.Drawing.Size(83, 14);
this._lblLabels_2.TabIndex = 4;
this._lblLabels_2.Text = "Invoice Name:";
this._lblLabels_2.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_3
//
this._lblLabels_3.AutoSize = true;
this._lblLabels_3.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_3.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_3.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_3.Location = new System.Drawing.Point(36, 84);
this._lblLabels_3.Name = "_lblLabels_3";
this._lblLabels_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_3.Size = new System.Drawing.Size(65, 13);
this._lblLabels_3.TabIndex = 6;
this._lblLabels_3.Text = "Department:";
this._lblLabels_3.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_4
//
this._lblLabels_4.AutoSize = true;
this._lblLabels_4.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_4.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_4.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._lblLabels_4.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_4.Location = new System.Drawing.Point(10, 114);
this._lblLabels_4.Name = "_lblLabels_4";
this._lblLabels_4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_4.Size = new System.Drawing.Size(156, 14);
this._lblLabels_4.TabIndex = 8;
this._lblLabels_4.Text = "Responsible Person Name:";
this._lblLabels_4.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_5
//
this._lblLabels_5.AutoSize = true;
this._lblLabels_5.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_5.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_5.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._lblLabels_5.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_5.Location = new System.Drawing.Point(174, 114);
this._lblLabels_5.Name = "_lblLabels_5";
this._lblLabels_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_5.Size = new System.Drawing.Size(60, 14);
this._lblLabels_5.TabIndex = 10;
this._lblLabels_5.Text = "Surname:";
this._lblLabels_5.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_6
//
this._lblLabels_6.AutoSize = true;
this._lblLabels_6.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_6.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_6.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_6.Location = new System.Drawing.Point(10, 222);
this._lblLabels_6.Name = "_lblLabels_6";
this._lblLabels_6.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_6.Size = new System.Drawing.Size(90, 13);
this._lblLabels_6.TabIndex = 18;
this._lblLabels_6.Text = "Physical Address:";
this._lblLabels_6.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_7
//
this._lblLabels_7.AutoSize = true;
this._lblLabels_7.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_7.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_7.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_7.Location = new System.Drawing.Point(171, 222);
this._lblLabels_7.Name = "_lblLabels_7";
this._lblLabels_7.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_7.Size = new System.Drawing.Size(80, 13);
this._lblLabels_7.TabIndex = 20;
this._lblLabels_7.Text = "Postal Address:";
this._lblLabels_7.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_8
//
this._lblLabels_8.AutoSize = true;
this._lblLabels_8.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_8.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_8.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_8.Location = new System.Drawing.Point(39, 156);
this._lblLabels_8.Name = "_lblLabels_8";
this._lblLabels_8.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_8.Size = new System.Drawing.Size(61, 13);
this._lblLabels_8.TabIndex = 12;
this._lblLabels_8.Text = "Telephone:";
this._lblLabels_8.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_9
//
this._lblLabels_9.AutoSize = true;
this._lblLabels_9.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_9.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_9.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_9.Location = new System.Drawing.Point(75, 177);
this._lblLabels_9.Name = "_lblLabels_9";
this._lblLabels_9.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_9.Size = new System.Drawing.Size(27, 13);
this._lblLabels_9.TabIndex = 14;
this._lblLabels_9.Text = "Fax:";
this._lblLabels_9.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_10
//
this._lblLabels_10.AutoSize = true;
this._lblLabels_10.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_10.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_10.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_10.Location = new System.Drawing.Point(66, 198);
this._lblLabels_10.Name = "_lblLabels_10";
this._lblLabels_10.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_10.Size = new System.Drawing.Size(35, 13);
this._lblLabels_10.TabIndex = 16;
this._lblLabels_10.Text = "Email:";
this._lblLabels_10.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_12
//
this._lblLabels_12.AutoSize = true;
this._lblLabels_12.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_12.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_12.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_12.Location = new System.Drawing.Point(363, 66);
this._lblLabels_12.Name = "_lblLabels_12";
this._lblLabels_12.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_12.Size = new System.Drawing.Size(61, 13);
this._lblLabels_12.TabIndex = 23;
this._lblLabels_12.Text = "Credit Limit:";
this._lblLabels_12.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_13
//
this._lblLabels_13.AutoSize = true;
this._lblLabels_13.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_13.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_13.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_13.Location = new System.Drawing.Point(381, 87);
this._lblLabels_13.Name = "_lblLabels_13";
this._lblLabels_13.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_13.Size = new System.Drawing.Size(44, 13);
this._lblLabels_13.TabIndex = 25;
this._lblLabels_13.Text = "Current:";
this._lblLabels_13.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_14
//
this._lblLabels_14.AutoSize = true;
this._lblLabels_14.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_14.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_14.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_14.Location = new System.Drawing.Point(519, 87);
this._lblLabels_14.Name = "_lblLabels_14";
this._lblLabels_14.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_14.Size = new System.Drawing.Size(49, 13);
this._lblLabels_14.TabIndex = 31;
this._lblLabels_14.Text = "30 Days:";
this._lblLabels_14.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_15
//
this._lblLabels_15.AutoSize = true;
this._lblLabels_15.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_15.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_15.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_15.Location = new System.Drawing.Point(375, 111);
this._lblLabels_15.Name = "_lblLabels_15";
this._lblLabels_15.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_15.Size = new System.Drawing.Size(49, 13);
this._lblLabels_15.TabIndex = 27;
this._lblLabels_15.Text = "60 Days:";
this._lblLabels_15.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_16
//
this._lblLabels_16.AutoSize = true;
this._lblLabels_16.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_16.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_16.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_16.Location = new System.Drawing.Point(519, 108);
this._lblLabels_16.Name = "_lblLabels_16";
this._lblLabels_16.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_16.Size = new System.Drawing.Size(49, 13);
this._lblLabels_16.TabIndex = 33;
this._lblLabels_16.Text = "90 Days:";
this._lblLabels_16.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_17
//
this._lblLabels_17.AutoSize = true;
this._lblLabels_17.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_17.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_17.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_17.Location = new System.Drawing.Point(369, 132);
this._lblLabels_17.Name = "_lblLabels_17";
this._lblLabels_17.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_17.Size = new System.Drawing.Size(55, 13);
this._lblLabels_17.TabIndex = 29;
this._lblLabels_17.Text = "120 Days:";
this._lblLabels_17.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lblLabels_18
//
this._lblLabels_18.AutoSize = true;
this._lblLabels_18.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_18.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_18.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_18.Location = new System.Drawing.Point(513, 129);
this._lblLabels_18.Name = "_lblLabels_18";
this._lblLabels_18.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_18.Size = new System.Drawing.Size(55, 13);
this._lblLabels_18.TabIndex = 35;
this._lblLabels_18.Text = "150 Days:";
this._lblLabels_18.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//frmCustomerTransaction
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(224)), Convert.ToInt32(Convert.ToByte(224)), Convert.ToInt32(Convert.ToByte(224)));
this.ClientSize = new System.Drawing.Size(661, 346);
this.ControlBox = false;
this.Controls.Add(this.txtTotalAmount);
this.Controls.Add(this.txtSettlement);
this.Controls.Add(this.cmdProcess);
this.Controls.Add(this.txtAmount);
this.Controls.Add(this.txtNotes);
this.Controls.Add(this.txtNarrative);
this.Controls.Add(this._txtFields_2);
this.Controls.Add(this._txtFields_3);
this.Controls.Add(this._txtFields_4);
this.Controls.Add(this._txtFields_5);
this.Controls.Add(this._txtFields_6);
this.Controls.Add(this._txtFields_7);
this.Controls.Add(this._txtFields_8);
this.Controls.Add(this._txtFields_9);
this.Controls.Add(this._txtFields_10);
this.Controls.Add(this._txtFloat_12);
this.Controls.Add(this._txtFloat_13);
this.Controls.Add(this._txtFloat_14);
this.Controls.Add(this._txtFloat_15);
this.Controls.Add(this._txtFloat_16);
this.Controls.Add(this._txtFloat_17);
this.Controls.Add(this._txtFloat_18);
this.Controls.Add(this.picButtons);
this.Controls.Add(this.Label2);
this.Controls.Add(this.lblSett);
this.Controls.Add(this._lblLabels_20);
this.Controls.Add(this._lblLabels_19);
this.Controls.Add(this._lblLabels_11);
this.Controls.Add(this._lblLabels_1);
this.Controls.Add(this._lblLabels_0);
this.Controls.Add(this._lbl_2);
this.Controls.Add(this._lbl_1);
this.Controls.Add(this._lbl_0);
this.Controls.Add(this._lblLabels_2);
this.Controls.Add(this._lblLabels_3);
this.Controls.Add(this._lblLabels_4);
this.Controls.Add(this._lblLabels_5);
this.Controls.Add(this._lblLabels_6);
this.Controls.Add(this._lblLabels_7);
this.Controls.Add(this._lblLabels_8);
this.Controls.Add(this._lblLabels_9);
this.Controls.Add(this._lblLabels_10);
this.Controls.Add(this._lblLabels_12);
this.Controls.Add(this._lblLabels_13);
this.Controls.Add(this._lblLabels_14);
this.Controls.Add(this._lblLabels_15);
this.Controls.Add(this._lblLabels_16);
this.Controls.Add(this._lblLabels_17);
this.Controls.Add(this._lblLabels_18);
this.Controls.Add(this.ShapeContainer1);
this.Cursor = System.Windows.Forms.Cursors.Default;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.KeyPreview = true;
this.Location = new System.Drawing.Point(73, 22);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "frmCustomerTransaction";
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Customer Transaction";
this.picButtons.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)this.Shape1).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private void frmCustomerTransaction_Load(object sender, System.EventArgs e)
{
txtFloat.AddRange(new TextBox[] {
_txtFloat_12,
_txtFloat_13,
_txtFloat_14,
_txtFloat_15,
_txtFloat_16,
_txtFloat_17,
_txtFloat_18
});
txtFields.AddRange(new TextBox[] {
_txtFields_10,
_txtFields_2,
_txtFields_3,
_txtFields_4,
_txtFields_5,
_txtFields_6,
_txtFields_7,
_txtFields_8,
_txtFields_9
});
TextBox tb = new TextBox();
foreach (TextBox tb_loopVariable in txtFloat) {
tb = tb_loopVariable;
tb.Enter += txtFloat_Enter;
tb.KeyPress += txtFloat_KeyPress;
}
foreach (TextBox tb_loopVariable in txtFields) {
tb = tb_loopVariable;
tb.Enter += txtFields_Enter;
}
}
}
}
| |
/*
* Copyright 2012-2016 The Pkcs11Interop Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <[email protected]>
*/
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.LowLevelAPI81;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace Net.Pkcs11Interop.Tests.LowLevelAPI81
{
/// <summary>
/// Helper methods for LowLevelAPI tests.
/// </summary>
public static class Helpers
{
/// <summary>
/// Finds slot containing the token that matches criteria specified in Settings class
/// </summary>
/// <param name='pkcs11'>Initialized PKCS11 wrapper</param>
/// <returns>Slot containing the token that matches criteria</returns>
public static ulong GetUsableSlot(Pkcs11 pkcs11)
{
CKR rv = CKR.CKR_OK;
// Get list of available slots with token present
ulong slotCount = 0;
rv = pkcs11.C_GetSlotList(true, null, ref slotCount);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(slotCount > 0);
ulong[] slotList = new ulong[slotCount];
rv = pkcs11.C_GetSlotList(true, slotList, ref slotCount);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Return first slot with token present when both TokenSerial and TokenLabel are null...
if (Settings.TokenSerial == null && Settings.TokenLabel == null)
return slotList[0];
// First slot with token present is OK...
ulong? matchingSlot = slotList[0];
// ...unless there are matching criteria specified in Settings class
if (Settings.TokenSerial != null || Settings.TokenLabel != null)
{
matchingSlot = null;
foreach (uint slot in slotList)
{
CK_TOKEN_INFO tokenInfo = new CK_TOKEN_INFO();
rv = pkcs11.C_GetTokenInfo(slot, ref tokenInfo);
if (rv != CKR.CKR_OK)
{
if (rv == CKR.CKR_TOKEN_NOT_RECOGNIZED || rv == CKR.CKR_TOKEN_NOT_PRESENT)
continue;
else
Assert.Fail(rv.ToString());
}
if (!string.IsNullOrEmpty(Settings.TokenSerial))
if (0 != string.Compare(Settings.TokenSerial, ConvertUtils.BytesToUtf8String(tokenInfo.SerialNumber, true), StringComparison.Ordinal))
continue;
if (!string.IsNullOrEmpty(Settings.TokenLabel))
if (0 != string.Compare(Settings.TokenLabel, ConvertUtils.BytesToUtf8String(tokenInfo.Label, true), StringComparison.Ordinal))
continue;
matchingSlot = slot;
break;
}
}
Assert.IsTrue(matchingSlot != null, "Token matching criteria specified in Settings class is not present");
return matchingSlot.Value;
}
/// <summary>
/// Creates the data object.
/// </summary>
/// <param name='pkcs11'>Initialized PKCS11 wrapper</param>
/// <param name='session'>Read-write session with user logged in</param>
/// <param name='objectId'>Output parameter for data object handle</param>
/// <returns>Return value of C_CreateObject</returns>
public static CKR CreateDataObject(Pkcs11 pkcs11, ulong session, ref ulong objectId)
{
CKR rv = CKR.CKR_OK;
// Prepare attribute template of new data object
CK_ATTRIBUTE[] template = new CK_ATTRIBUTE[5];
template[0] = CkaUtils.CreateAttribute(CKA.CKA_CLASS, CKO.CKO_DATA);
template[1] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true);
template[2] = CkaUtils.CreateAttribute(CKA.CKA_APPLICATION, Settings.ApplicationName);
template[3] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName);
template[4] = CkaUtils.CreateAttribute(CKA.CKA_VALUE, "Data object content");
// Create object
rv = pkcs11.C_CreateObject(session, template, Convert.ToUInt64(template.Length), ref objectId);
// In LowLevelAPI caller has to free unmanaged memory taken by attributes
for (int i = 0; i < template.Length; i++)
{
UnmanagedMemory.Free(ref template[i].value);
template[i].valueLen = 0;
}
return rv;
}
/// <summary>
/// Generates symetric key.
/// </summary>
/// <param name='pkcs11'>Initialized PKCS11 wrapper</param>
/// <param name='session'>Read-write session with user logged in</param>
/// <param name='keyId'>Output parameter for key object handle</param>
/// <returns>Return value of C_GenerateKey</returns>
public static CKR GenerateKey(Pkcs11 pkcs11, ulong session, ref ulong keyId)
{
CKR rv = CKR.CKR_OK;
// Prepare attribute template of new key
CK_ATTRIBUTE[] template = new CK_ATTRIBUTE[6];
template[0] = CkaUtils.CreateAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY);
template[1] = CkaUtils.CreateAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3);
template[2] = CkaUtils.CreateAttribute(CKA.CKA_ENCRYPT, true);
template[3] = CkaUtils.CreateAttribute(CKA.CKA_DECRYPT, true);
template[4] = CkaUtils.CreateAttribute(CKA.CKA_DERIVE, true);
template[5] = CkaUtils.CreateAttribute(CKA.CKA_EXTRACTABLE, true);
// Specify key generation mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_KEY_GEN);
// Generate key
rv = pkcs11.C_GenerateKey(session, ref mechanism, template, Convert.ToUInt64(template.Length), ref keyId);
// In LowLevelAPI we have to free unmanaged memory taken by attributes
for (int i = 0; i < template.Length; i++)
{
UnmanagedMemory.Free(ref template[i].value);
template[i].valueLen = 0;
}
return rv;
}
/// <summary>
/// Generates asymetric key pair.
/// </summary>
/// <param name='pkcs11'>Initialized PKCS11 wrapper</param>
/// <param name='session'>Read-write session with user logged in</param>
/// <param name='pubKeyId'>Output parameter for public key object handle</param>
/// <param name='privKeyId'>Output parameter for private key object handle</param>
/// <returns>Return value of C_GenerateKeyPair</returns>
public static CKR GenerateKeyPair(Pkcs11 pkcs11, ulong session, ref ulong pubKeyId, ref ulong privKeyId)
{
CKR rv = CKR.CKR_OK;
// The CKA_ID attribute is intended as a means of distinguishing multiple key pairs held by the same subject
byte[] ckaId = new byte[20];
rv = pkcs11.C_GenerateRandom(session, ckaId, Convert.ToUInt64(ckaId.Length));
if (rv != CKR.CKR_OK)
return rv;
// Prepare attribute template of new public key
CK_ATTRIBUTE[] pubKeyTemplate = new CK_ATTRIBUTE[10];
pubKeyTemplate[0] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true);
pubKeyTemplate[1] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, false);
pubKeyTemplate[2] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName);
pubKeyTemplate[3] = CkaUtils.CreateAttribute(CKA.CKA_ID, ckaId);
pubKeyTemplate[4] = CkaUtils.CreateAttribute(CKA.CKA_ENCRYPT, true);
pubKeyTemplate[5] = CkaUtils.CreateAttribute(CKA.CKA_VERIFY, true);
pubKeyTemplate[6] = CkaUtils.CreateAttribute(CKA.CKA_VERIFY_RECOVER, true);
pubKeyTemplate[7] = CkaUtils.CreateAttribute(CKA.CKA_WRAP, true);
pubKeyTemplate[8] = CkaUtils.CreateAttribute(CKA.CKA_MODULUS_BITS, 1024);
pubKeyTemplate[9] = CkaUtils.CreateAttribute(CKA.CKA_PUBLIC_EXPONENT, new byte[] { 0x01, 0x00, 0x01 });
// Prepare attribute template of new private key
CK_ATTRIBUTE[] privKeyTemplate = new CK_ATTRIBUTE[9];
privKeyTemplate[0] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true);
privKeyTemplate[1] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, true);
privKeyTemplate[2] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName);
privKeyTemplate[3] = CkaUtils.CreateAttribute(CKA.CKA_ID, ckaId);
privKeyTemplate[4] = CkaUtils.CreateAttribute(CKA.CKA_SENSITIVE, true);
privKeyTemplate[5] = CkaUtils.CreateAttribute(CKA.CKA_DECRYPT, true);
privKeyTemplate[6] = CkaUtils.CreateAttribute(CKA.CKA_SIGN, true);
privKeyTemplate[7] = CkaUtils.CreateAttribute(CKA.CKA_SIGN_RECOVER, true);
privKeyTemplate[8] = CkaUtils.CreateAttribute(CKA.CKA_UNWRAP, true);
// Specify key generation mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_RSA_PKCS_KEY_PAIR_GEN);
// Generate key pair
rv = pkcs11.C_GenerateKeyPair(session, ref mechanism, pubKeyTemplate, Convert.ToUInt64(pubKeyTemplate.Length), privKeyTemplate, Convert.ToUInt64(privKeyTemplate.Length), ref pubKeyId, ref privKeyId);
// In LowLevelAPI we have to free unmanaged memory taken by attributes
for (int i = 0; i < privKeyTemplate.Length; i++)
{
UnmanagedMemory.Free(ref privKeyTemplate[i].value);
privKeyTemplate[i].valueLen = 0;
}
for (int i = 0; i < pubKeyTemplate.Length; i++)
{
UnmanagedMemory.Free(ref pubKeyTemplate[i].value);
pubKeyTemplate[i].valueLen = 0;
}
return rv;
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Controller class for LAB_Temp_ResultadoEncabezado
/// </summary>
[System.ComponentModel.DataObject]
public partial class LabTempResultadoEncabezadoController
{
// Preload our schema..
LabTempResultadoEncabezado thisSchemaLoad = new LabTempResultadoEncabezado();
private string userName = String.Empty;
protected string UserName
{
get
{
if (userName.Length == 0)
{
if (System.Web.HttpContext.Current != null)
{
userName=System.Web.HttpContext.Current.User.Identity.Name;
}
else
{
userName=System.Threading.Thread.CurrentPrincipal.Identity.Name;
}
}
return userName;
}
}
[DataObjectMethod(DataObjectMethodType.Select, true)]
public LabTempResultadoEncabezadoCollection FetchAll()
{
LabTempResultadoEncabezadoCollection coll = new LabTempResultadoEncabezadoCollection();
Query qry = new Query(LabTempResultadoEncabezado.Schema);
coll.LoadAndCloseReader(qry.ExecuteReader());
return coll;
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public LabTempResultadoEncabezadoCollection FetchByID(object IdProtocolo)
{
LabTempResultadoEncabezadoCollection coll = new LabTempResultadoEncabezadoCollection().Where("idProtocolo", IdProtocolo).Load();
return coll;
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public LabTempResultadoEncabezadoCollection FetchByQuery(Query qry)
{
LabTempResultadoEncabezadoCollection coll = new LabTempResultadoEncabezadoCollection();
coll.LoadAndCloseReader(qry.ExecuteReader());
return coll;
}
[DataObjectMethod(DataObjectMethodType.Delete, true)]
public bool Delete(object IdProtocolo)
{
return (LabTempResultadoEncabezado.Delete(IdProtocolo) == 1);
}
[DataObjectMethod(DataObjectMethodType.Delete, false)]
public bool Destroy(object IdProtocolo)
{
return (LabTempResultadoEncabezado.Destroy(IdProtocolo) == 1);
}
[DataObjectMethod(DataObjectMethodType.Delete, true)]
public bool Delete(int IdProtocolo,int IdEfector)
{
Query qry = new Query(LabTempResultadoEncabezado.Schema);
qry.QueryType = QueryType.Delete;
qry.AddWhere("IdProtocolo", IdProtocolo).AND("IdEfector", IdEfector);
qry.Execute();
return (true);
}
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
[DataObjectMethod(DataObjectMethodType.Insert, true)]
public void Insert(int IdProtocolo,int IdEfector,string Apellido,string Nombre,int Edad,string UnidadEdad,string FechaNacimiento,string Sexo,int NumeroDocumento,string Fecha,DateTime Fecha1,string Domicilio,int Hc,string Prioridad,string Origen,string Numero,bool? Hiv,string Solicitante,string Sector,string Sala,string Cama,string Embarazo,string EfectorSolicitante,int? IdSolicitudScreening,DateTime? FechaRecibeScreening,string ObservacionesResultados,string TipoMuestra)
{
LabTempResultadoEncabezado item = new LabTempResultadoEncabezado();
item.IdProtocolo = IdProtocolo;
item.IdEfector = IdEfector;
item.Apellido = Apellido;
item.Nombre = Nombre;
item.Edad = Edad;
item.UnidadEdad = UnidadEdad;
item.FechaNacimiento = FechaNacimiento;
item.Sexo = Sexo;
item.NumeroDocumento = NumeroDocumento;
item.Fecha = Fecha;
item.Fecha1 = Fecha1;
item.Domicilio = Domicilio;
item.Hc = Hc;
item.Prioridad = Prioridad;
item.Origen = Origen;
item.Numero = Numero;
item.Hiv = Hiv;
item.Solicitante = Solicitante;
item.Sector = Sector;
item.Sala = Sala;
item.Cama = Cama;
item.Embarazo = Embarazo;
item.EfectorSolicitante = EfectorSolicitante;
item.IdSolicitudScreening = IdSolicitudScreening;
item.FechaRecibeScreening = FechaRecibeScreening;
item.ObservacionesResultados = ObservacionesResultados;
item.TipoMuestra = TipoMuestra;
item.Save(UserName);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
[DataObjectMethod(DataObjectMethodType.Update, true)]
public void Update(int IdProtocolo,int IdEfector,string Apellido,string Nombre,int Edad,string UnidadEdad,string FechaNacimiento,string Sexo,int NumeroDocumento,string Fecha,DateTime Fecha1,string Domicilio,int Hc,string Prioridad,string Origen,string Numero,bool? Hiv,string Solicitante,string Sector,string Sala,string Cama,string Embarazo,string EfectorSolicitante,int? IdSolicitudScreening,DateTime? FechaRecibeScreening,string ObservacionesResultados,string TipoMuestra)
{
LabTempResultadoEncabezado item = new LabTempResultadoEncabezado();
item.MarkOld();
item.IsLoaded = true;
item.IdProtocolo = IdProtocolo;
item.IdEfector = IdEfector;
item.Apellido = Apellido;
item.Nombre = Nombre;
item.Edad = Edad;
item.UnidadEdad = UnidadEdad;
item.FechaNacimiento = FechaNacimiento;
item.Sexo = Sexo;
item.NumeroDocumento = NumeroDocumento;
item.Fecha = Fecha;
item.Fecha1 = Fecha1;
item.Domicilio = Domicilio;
item.Hc = Hc;
item.Prioridad = Prioridad;
item.Origen = Origen;
item.Numero = Numero;
item.Hiv = Hiv;
item.Solicitante = Solicitante;
item.Sector = Sector;
item.Sala = Sala;
item.Cama = Cama;
item.Embarazo = Embarazo;
item.EfectorSolicitante = EfectorSolicitante;
item.IdSolicitudScreening = IdSolicitudScreening;
item.FechaRecibeScreening = FechaRecibeScreening;
item.ObservacionesResultados = ObservacionesResultados;
item.TipoMuestra = TipoMuestra;
item.Save(UserName);
}
}
}
| |
using System;
using System.Collections;
namespace Foundation.Tasks
{
/// <summary>
/// A task encapsulates future work that may be waited on.
/// - Support running actions in background threads
/// - Supports running coroutines with return results
/// - Use the WaitForRoutine method to wait for the task in a coroutine
/// </summary>
/// <example>
/// <code>
/// var task = Task.Run(() =>
/// {
/// //Debug.Log does not work in
/// Debug.Log("Sleeping...");
/// Task.Delay(2000);
/// Debug.Log("Slept");
/// });
/// // wait for it
/// yield return StartCoroutine(task.WaitRoutine());
///
/// // check exceptions
/// if(task.IsFaulted)
/// Debug.LogException(task.Exception)
///</code>
///</example>
public partial class UnityTask
{
#region Task
/// <summary>
/// Creates a new running task
/// </summary>
public static UnityTask Run(Action action)
{
var task = new UnityTask(action);
task.Start();
return task;
}
/// <summary>
/// Creates a new running task
/// </summary>
public static UnityTask RunOnMain(Action action)
{
var task = new UnityTask(action, TaskStrategy.MainThread);
task.Start();
return task;
}
/// <summary>
/// Creates a new running task
/// </summary>
public static UnityTask RunOnCurrent(Action action)
{
var task = new UnityTask(action, TaskStrategy.CurrentThread);
task.Start();
return task;
}
/// <summary>
/// Creates a new running task
/// </summary>
public static UnityTask Run<TP>(Action<TP> action, TP param)
{
var task = new UnityTask(action, param, TaskStrategy.CurrentThread);
task.Start();
return task;
}
/// <summary>
/// Creates a new running task
/// </summary>
public static UnityTask RunOnMain<TP>(Action<TP> action, TP param)
{
var task = new UnityTask(action, param, TaskStrategy.MainThread);
task.Start();
return task;
}
/// <summary>
/// Creates a new running task
/// </summary>
public static UnityTask RunOnCurrent<TP>(Action<TP> action, TP param)
{
var task = new UnityTask(action, param, TaskStrategy.CurrentThread);
task.Start();
return task;
}
#endregion
#region Coroutine
/// <summary>
/// Creates a new running task
/// </summary>
public static UnityTask RunCoroutine(IEnumerator function)
{
var task = new UnityTask(function);
task.Start();
return task;
}
/// <summary>
/// Creates a new running task
/// </summary>
public static UnityTask RunCoroutine(Func<IEnumerator> function)
{
var task = new UnityTask(function());
task.Start();
return task;
}
/// <summary>
/// Creates a new running task
/// </summary>
public static UnityTask RunCoroutine(Func<UnityTask, IEnumerator> function)
{
var task = new UnityTask();
task.Strategy = TaskStrategy.Coroutine;
task._routine = function(task);
task.Start();
return task;
}
#endregion
#region Task With Result
/// <summary>
/// Creates a new running task
/// </summary>
public static UnityTask<TResult> Run<TResult>(Func<TResult> function)
{
var task = new UnityTask<TResult>(function);
task.Start();
return task;
}
/// <summary>
/// Creates a new running task
/// </summary>
public static UnityTask<TResult> Run<TParam, TResult>(Func<TParam, TResult> function, TParam param)
{
var task = new UnityTask<TResult>(function, param);
task.Start();
return task;
}
/// <summary>
/// Creates a new running task
/// </summary>
public static UnityTask<TResult> RunOnMain<TResult>(Func<TResult> function)
{
var task = new UnityTask<TResult>(function, TaskStrategy.MainThread);
task.Start();
return task;
}
/// <summary>
/// Creates a new running task
/// </summary>
public static UnityTask<TResult> RunOnMain<TParam, TResult>(Func<TParam, TResult> function, TParam param)
{
var task = new UnityTask<TResult>(function, param, TaskStrategy.MainThread);
task.Start();
return task;
}
/// <summary>
/// Creates a new running task
/// </summary>
public static UnityTask<TResult> RunOnCurrent<TResult>(Func<TResult> function)
{
var task = new UnityTask<TResult>(function, TaskStrategy.CurrentThread);
task.Start();
return task;
}
/// <summary>
/// Creates a new running task
/// </summary>
public static UnityTask<TResult> RunOnCurrent<TParam, TResult>(Func<TParam, TResult> function, TParam param)
{
var task = new UnityTask<TResult>(function, param, TaskStrategy.CurrentThread);
task.Start();
return task;
}
/// <summary>
/// Creates a new running task
/// </summary>
public static UnityTask<TResult> RunCoroutine<TResult>(IEnumerator function)
{
var task = new UnityTask<TResult>(function);
task.Start();
return task;
}
/// <summary>
/// Creates a task which passes the task as a parameter
/// </summary>
public static UnityTask<TResult> RunCoroutine<TResult>(Func<UnityTask<TResult>, IEnumerator> function)
{
var task = new UnityTask<TResult>();
task.Strategy = TaskStrategy.Coroutine;
task.Paramater = task;
task._routine = function(task);
task.Start();
return task;
}
#endregion
#region success / fails
/// <summary>
/// A default task in the success state
/// </summary>
static UnityTask _successTask = new UnityTask(TaskStrategy.Custom) { Status = TaskStatus.Success };
/// <summary>
/// A default task in the success state
/// </summary>
public static UnityTask<T> SuccessTask<T>(T result)
{
return new UnityTask<T>(TaskStrategy.Custom) { Status = TaskStatus.Success, Result = result };
}
/// <summary>
/// A default task in the faulted state
/// </summary>
public static UnityTask SuccessTask()
{
return _successTask;
}
/// <summary>
/// A default task in the faulted state
/// </summary>
public static UnityTask FailedTask(string exception)
{
return FailedTask(new Exception(exception));
}
/// <summary>
/// A default task in the faulted state
/// </summary>
public static UnityTask FailedTask(Exception ex)
{
return new UnityTask(TaskStrategy.Custom) { Status = TaskStatus.Faulted, Exception = ex };
}
/// <summary>
/// A default task in the faulted state
/// </summary>
public static UnityTask<T> FailedTask<T>(string exception)
{
return FailedTask<T>(new Exception(exception));
}
/// <summary>
/// A default task in the faulted state
/// </summary>
public static UnityTask<T> FailedTask<T>(Exception ex)
{
return new UnityTask<T>(TaskStrategy.Custom) { Status = TaskStatus.Faulted, Exception = ex };
}
/// <summary>
/// A default task in the faulted state
/// </summary>
public static UnityTask<T> FailedTask<T>(string exception, T result)
{
return FailedTask(new Exception(exception), result);
}
/// <summary>
/// A default task in the faulted state
/// </summary>
public static UnityTask<T> FailedTask<T>(Exception ex, T result)
{
return new UnityTask<T>(TaskStrategy.Custom) { Status = TaskStatus.Faulted, Exception = ex, Result = result };
}
#endregion
}
}
| |
/***************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
***************************************************************************/
using System;
using System.Globalization;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.Samples.VisualStudio.IDE.ToolWindow
{
/// <summary>
/// This class keeps track of the position, size and dockable state of the
/// window it is associated with. By registering an instance of this class
/// with a window frame (this can be a tool window or a document window)
/// Visual Studio will call back the IVsWindowFrameNotify3 methods when
/// changes occur.
/// </summary>
public sealed class WindowStatus : IVsWindowFrameNotify3
{
// Private fields to keep track of the last known state
private int x = 0;
private int y = 0;
private int width = 0;
private int height = 0;
private bool dockable = false;
// Output window service
IVsOutputWindowPane outputPane = null;
// IVsWindowFrame associated with this status monitor
IVsWindowFrame frame;
#region Public properties
/// <summary>
/// Return the current horizontal position of the window
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public int X
{
get { return x; }
}
/// <summary>
/// Return the current vertical position of the window
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public int Y
{
get { return y; }
}
/// <summary>
/// Return the current width of the window
/// </summary>
public int Width
{
get { return width; }
}
/// <summary>
/// Return the current height of the window
/// </summary>
public int Height
{
get { return height; }
}
/// <summary>
/// Is the window dockable
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public bool IsDockable
{
get { return dockable; }
}
/// <summary>
/// Event that gets fired when the position or the docking state of the window changes
/// </summary>
public event EventHandler<EventArgs> StatusChange;
#endregion
/// <summary>
/// WindowStatus Constructor.
/// </summary>
/// <param name="outputWindowPane">Events will be reported in the output pane if this interface is provided.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702")]
public WindowStatus(IVsOutputWindowPane outputWindowPane, IVsWindowFrame frame)
{
outputPane = outputWindowPane;
this.frame = frame;
if (frame != null)
{
VSSETFRAMEPOS[] pos = new VSSETFRAMEPOS[1];
int x;
int y;
int width;
int height;
Guid unused;
frame.GetFramePos(pos, out unused, out x, out y, out width, out height);
dockable = (pos[0] & VSSETFRAMEPOS.SFP_fFloat) != VSSETFRAMEPOS.SFP_fFloat;
}
}
#region IVsWindowFrameNotify3 Members
/// <summary>
/// This is called when the window is being closed
/// </summary>
/// <param name="pgrfSaveOptions">Should the document be saved and should the user be prompted.</param>
/// <returns>HRESULT</returns>
public int OnClose(ref uint pgrfSaveOptions)
{
if (outputPane != null)
return outputPane.OutputString(" IVsWindowFrameNotify3.OnClose()\n");
else
return Microsoft.VisualStudio.VSConstants.S_OK;
}
/// <summary>
/// This is called when a window "dock state" changes. This could be the
/// result of dragging the window to result in the dock state changing
/// or this could be as a result of changing the dock style (tabbed, mdi,
/// dockable, floating,...).
/// This will likely also result in a different position/size
/// </summary>
/// <param name="fDockable">Is the window dockable with an other window</param>
/// <param name="x">New horizontal position</param>
/// <param name="y">New vertical position</param>
/// <param name="w">New width</param>
/// <param name="h">New Height</param>
/// <returns>HRESULT</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "y"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "x")]
public int OnDockableChange(int fDockable, int x, int y, int w, int h)
{
this.x = x;
this.y = y;
width = w;
height = h;
dockable = (fDockable != 0);
GenerateStatusChangeEvent(this, new EventArgs());
return Microsoft.VisualStudio.VSConstants.S_OK;
}
/// <summary>
/// This is called when the window is moved
/// </summary>
/// <param name="x">New horizontal position</param>
/// <param name="y">New vertical position</param>
/// <param name="w">New width</param>
/// <param name="h">New Height</param>
/// <returns>HRESULT</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "y"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "x")]
public int OnMove(int x, int y, int w, int h)
{
this.x = x;
this.y = y;
width = w;
height = h;
GenerateStatusChangeEvent(this, new EventArgs());
return Microsoft.VisualStudio.VSConstants.S_OK;
}
/// <summary>
/// This is called when the window is shown or hidden
/// </summary>
/// <param name="fShow">State of the window</param>
/// <returns>HRESULT</returns>
public int OnShow(int fShow)
{
__FRAMESHOW state = (__FRAMESHOW)fShow;
if (outputPane != null)
return outputPane.OutputString(string.Format(CultureInfo.CurrentCulture, " IVsWindowFrameNotify3.OnShow({0})\n", state.ToString()));
else
return Microsoft.VisualStudio.VSConstants.S_OK;
}
/// <summary>
/// This is called when the window is resized
/// </summary>
/// <param name="x">New horizontal position</param>
/// <param name="y">New vertical position</param>
/// <param name="w">New width</param>
/// <param name="h">New Height</param>
/// <returns>HRESULT</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "x"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "y")]
public int OnSize(int x, int y, int w, int h)
{
this.x = x;
this.y = y;
width = w;
height = h;
GenerateStatusChangeEvent(this, new EventArgs());
return Microsoft.VisualStudio.VSConstants.S_OK;
}
#endregion
/// <summary>
/// Generate the event if someone is listening to it
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="arguments">Event arguments</param>
private void GenerateStatusChangeEvent(object sender, EventArgs arguments)
{
if (StatusChange != null)
StatusChange.Invoke(this, new EventArgs());
}
}
}
| |
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
using UnityEngine.Serialization;
using UnityEditor;
using System.Collections.Generic;
using System.Linq;
namespace Fungus.EditorUtils
{
/// <summary>
/// Temp hidden object which lets us use the entire inspector window to inspect the block command list.
/// </summary>
public class BlockInspector : ScriptableObject
{
[FormerlySerializedAs("sequence")]
public Block block;
}
/// <summary>
/// Custom editor for the temp hidden object.
/// </summary>
[CustomEditor (typeof(BlockInspector), true)]
public class BlockInspectorEditor : Editor
{
protected Vector2 blockScrollPos;
protected Vector2 commandScrollPos;
protected bool resize = false;
protected bool clamp = false;
#if UNITY_2019_1_OR_NEWER
protected float topPanelHeight = 0;
#else
protected float topPanelHeight = 48;
#endif
protected float windowHeight = 0f;
// Cache the block and command editors so we only create and destroy them
// when a different block / command is selected.
protected BlockEditor activeBlockEditor;
protected CommandEditor activeCommandEditor;
protected Command activeCommand; // Command currently being inspected
// Cached command editors to avoid creating / destroying editors more than necessary
// This list is static so persists between
protected static List<CommandEditor> cachedCommandEditors = new List<CommandEditor>();
protected void OnDestroy()
{
ClearEditors();
}
protected void OnEnable()
{
ClearEditors();
}
protected void OnDisable()
{
ClearEditors();
}
protected void ClearEditors()
{
foreach (CommandEditor commandEditor in cachedCommandEditors)
{
DestroyImmediate(commandEditor);
}
cachedCommandEditors.Clear();
activeCommandEditor = null;
}
public override void OnInspectorGUI ()
{
BlockInspector blockInspector = target as BlockInspector;
if (blockInspector.block == null)
{
return;
}
var block = blockInspector.block;
if (block == null)
{
return;
}
var flowchart = (Flowchart)block.GetFlowchart();
if (flowchart.SelectedBlocks.Count > 1)
{
GUILayout.Label("Multiple blocks selected");
return;
}
if (activeBlockEditor == null ||
!block.Equals(activeBlockEditor.target))
{
DestroyImmediate(activeBlockEditor);
activeBlockEditor = Editor.CreateEditor(block) as BlockEditor;
}
UpdateWindowHeight();
float width = EditorGUIUtility.currentViewWidth;
blockScrollPos = GUILayout.BeginScrollView(blockScrollPos, GUILayout.Height(flowchart.BlockViewHeight));
activeBlockEditor.DrawBlockName(flowchart);
activeBlockEditor.DrawBlockGUI(flowchart);
GUILayout.EndScrollView();
Command inspectCommand = null;
if (flowchart.SelectedCommands.Count == 1)
{
inspectCommand = flowchart.SelectedCommands[0];
}
if (Application.isPlaying &&
inspectCommand != null &&
!inspectCommand.ParentBlock.Equals(block))
{
Repaint();
return;
}
// Only change the activeCommand at the start of the GUI call sequence
if (Event.current.type == EventType.Layout)
{
activeCommand = inspectCommand;
}
DrawCommandUI(flowchart, inspectCommand);
}
/// <summary>
/// In Unity 5.4, Screen.height returns the pixel height instead of the point height
/// of the inspector window. We can use EditorGUIUtility.currentViewWidth to get the window width
/// but we have to use this horrible hack to find the window height.
/// For one frame the windowheight will be 0, but it doesn't seem to be noticeable.
/// </summary>
protected void UpdateWindowHeight()
{
windowHeight = Screen.height * EditorGUIUtility.pixelsPerPoint;
}
public void DrawCommandUI(Flowchart flowchart, Command inspectCommand)
{
ResizeScrollView(flowchart);
EditorGUILayout.Space();
activeBlockEditor.DrawButtonToolbar();
commandScrollPos = GUILayout.BeginScrollView(commandScrollPos);
if (inspectCommand != null)
{
if (activeCommandEditor == null ||
!inspectCommand.Equals(activeCommandEditor.target))
{
// See if we have a cached version of the command editor already,
var editors = (from e in cachedCommandEditors where (e != null && (e.target.Equals(inspectCommand))) select e);
if (editors.Count() > 0)
{
// Use cached editor
activeCommandEditor = editors.First();
}
else
{
// No cached editor, so create a new one.
activeCommandEditor = Editor.CreateEditor((Command)inspectCommand) as CommandEditor;
cachedCommandEditors.Add(activeCommandEditor);
}
}
if (activeCommandEditor != null)
{
activeCommandEditor.DrawCommandInspectorGUI();
}
}
GUILayout.EndScrollView();
// Draw the resize bar after everything else has finished drawing
// This is mainly to avoid incorrect indenting.
Rect resizeRect = new Rect(0, flowchart.BlockViewHeight + topPanelHeight, EditorGUIUtility.currentViewWidth, 4f);
GUI.color = new Color(0.64f, 0.64f, 0.64f);
GUI.DrawTexture(resizeRect, EditorGUIUtility.whiteTexture);
resizeRect.height = 1;
GUI.color = new Color32(132, 132, 132, 255);
GUI.DrawTexture(resizeRect, EditorGUIUtility.whiteTexture);
resizeRect.y += 3;
GUI.DrawTexture(resizeRect, EditorGUIUtility.whiteTexture);
GUI.color = Color.white;
Repaint();
}
private void ResizeScrollView(Flowchart flowchart)
{
Rect cursorChangeRect = new Rect(0, flowchart.BlockViewHeight + 1 + topPanelHeight, EditorGUIUtility.currentViewWidth, 4f);
EditorGUIUtility.AddCursorRect(cursorChangeRect, MouseCursor.ResizeVertical);
if (cursorChangeRect.Contains(Event.current.mousePosition))
{
if (Event.current.type == EventType.MouseDown)
{
resize = true;
}
}
if (resize && Event.current.type == EventType.Repaint)
{
Undo.RecordObject(flowchart, "Resize view");
flowchart.BlockViewHeight = Event.current.mousePosition.y - topPanelHeight;
}
ClampBlockViewHeight(flowchart);
// Stop resizing if mouse is outside inspector window.
// This isn't standard Unity UI behavior but it is robust and safe.
if (resize && Event.current.type == EventType.MouseDrag)
{
Rect windowRect = new Rect(0, 0, EditorGUIUtility.currentViewWidth, windowHeight);
if (!windowRect.Contains(Event.current.mousePosition))
{
resize = false;
}
}
if (Event.current.type == EventType.MouseUp)
{
resize = false;
}
}
protected virtual void ClampBlockViewHeight(Flowchart flowchart)
{
// Screen.height seems to temporarily reset to 480 for a single frame whenever a command like
// Copy, Paste, etc. happens. Only clamp the block view height when one of these operations is not occuring.
if (Event.current.commandName != "")
{
clamp = false;
}
if (clamp)
{
// Make sure block view is always clamped to visible area
float height = flowchart.BlockViewHeight;
height = Mathf.Max(200, height);
height = Mathf.Min(windowHeight - 200,height);
flowchart.BlockViewHeight = height;
}
if (Event.current.type == EventType.Repaint)
{
clamp = true;
}
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using IntegrationTests.TestFixtures;
using MyCouch;
using MyCouch.Testing;
using MyCouch.Testing.Model;
using MyCouch.Testing.TestData;
using Xunit;
namespace IntegrationTests.CoreTests
{
public class MyCouchStoreQueryTests :
IntegrationTestsOf<MyCouchStore>,
IPreserveStatePerFixture,
IClassFixture<ViewsFixture>
{
protected Artist[] ArtistsById { get; set; }
public MyCouchStoreQueryTests(ViewsFixture data)
{
ArtistsById = data.Init(Environment);
SUT = new MyCouchStore(DbClient);
}
[MyFact(TestScenarios.MyCouchStore)]
public void GetHeaders_When_getting_three_headers_It_returns_the_three_requested_headers()
{
var artists = ArtistsById.Skip(2).Take(3).ToArray();
var ids = artists.Select(a => a.ArtistId).ToArray();
var headers = SUT.GetHeadersAsync(ids).Result;
headers.ToArray().Should().BeEquivalentTo(artists.Select(a => new DocumentHeader(a.ArtistId, a.ArtistRev)).ToArray());
}
[MyFact(TestScenarios.MyCouchStore)]
public void GetHeadersAync_When_getting_one_existing_and_one_non_existing_header_It_returns_only_the_existing_one()
{
var artists = ArtistsById.Skip(2).Take(1).ToArray();
var ids = artists.Select(a => a.ArtistId).ToList();
ids.Add("16dcd30f8ba04f7a8702e30e9503f53f");
var headers = SUT.GetHeadersAsync(ids.ToArray()).Result;
headers.ToArray().Should().BeEquivalentTo(artists.Select(a => new DocumentHeader(a.ArtistId, a.ArtistRev)).ToArray());
}
[MyFact(TestScenarios.MyCouchStore)]
public void GetByIds_for_json_When_ids_are_specified_Then_matching_docs_are_returned()
{
var artists = ArtistsById.Skip(2).Take(3).ToArray();
var ids = artists.Select(a => a.ArtistId).ToArray();
var docs = SUT.GetByIdsAsync(ids).Result;
docs.Select(d => DbClient.Entities.Serializer.Deserialize<Artist>(d)).ToArray().Should().BeEquivalentTo(artists);
}
[MyFact(TestScenarios.MyCouchStore)]
public void GetByIds_for_entity_When_ids_are_specified_Then_matching_entities_are_returned()
{
var artists = ArtistsById.Skip(2).Take(3).ToArray();
var ids = artists.Select(a => a.ArtistId).ToArray();
var docs = SUT.GetByIdsAsync<Artist>(ids)
.Result
.ToArray();
docs.Should().BeEquivalentTo(artists);
}
[MyFact(TestScenarios.MyCouchStore)]
public void GetValueByKeys_for_json_When_keys_are_specified_Then_matching_docs_are_returned()
{
var artists = ArtistsById.Skip(2).Take(3).ToArray();
var keys = artists.Select(a => a.Name).ToCouchKeys();
var values = SUT.GetValueByKeysAsync(ClientTestData.Views.ArtistsAlbumsViewId, keys)
.Result
.ToArray();
values.Should().BeEquivalentTo(artists.Select(a => DbClient.Serializer.Serialize(a.Albums)).ToArray());
}
[MyFact(TestScenarios.MyCouchStore)]
public void GetValueByKeys_for_entity_When_keys_are_specified_Then_matching_docs_are_returned()
{
var artists = ArtistsById.Skip(2).Take(3).ToArray();
var keys = artists.Select(a => a.Name).ToCouchKeys();
var values = SUT.GetValueByKeysAsync<Album[]>(ClientTestData.Views.ArtistsAlbumsViewId, keys)
.Result
.ToArray();
values.Should().BeEquivalentTo(artists.Select(a => a.Albums).ToArray());
}
[MyFact(TestScenarios.MyCouchStore)]
public void GetIncludedDocByKeys_for_json_When_Ids_are_specified_Then_matching_docs_are_returned()
{
var artists = ArtistsById.Skip(2).Take(3).ToArray();
var keys = artists.Select(a => a.ArtistId).ToCouchKeys();
var docs = SUT.GetIncludedDocByKeysAsync(SystemViewIdentity.AllDocs, keys).Result;
docs.Select(d => DbClient.Entities.Serializer.Deserialize<Artist>(d)).ToArray().Should().BeEquivalentTo(artists);
}
[MyFact(TestScenarios.MyCouchStore)]
public void GetIncludedDocByKeys_for_entity_When_Ids_are_specified_Then_matching_entities_are_returned()
{
var artists = ArtistsById.Skip(2).Take(3).ToArray();
var keys = artists.Select(a => a.ArtistId).ToCouchKeys();
var docs = SUT.GetIncludedDocByKeysAsync<Artist>(SystemViewIdentity.AllDocs, keys)
.Result
.ToArray();
docs.Should().BeEquivalentTo(artists);
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_no_key_with_sum_reduce_for_string_response_It_will_be_able_to_sum()
{
var expectedSum = ArtistsById.Sum(a => a.Albums.Count());
var query = new Query(ClientTestData.Views.ArtistsTotalNumOfAlbumsViewId).Configure(q => q.Reduce(true));
var r = SUT.QueryAsync(query)
.Result
.ToArray();
r.Length.Should().Be(1);
r.Single().Value.Should().Be(expectedSum.ToString(MyCouchRuntime.FormatingCulture.NumberFormat));
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_no_key_with_sum_reduce_for_dynamic_response_It_will_be_able_to_sum()
{
var expectedSum = ArtistsById.Sum(a => a.Albums.Count());
var query = new Query(ClientTestData.Views.ArtistsTotalNumOfAlbumsViewId).Configure(q => q.Reduce(true));
var r = SUT.QueryAsync<dynamic>(query)
.Result
.ToArray();
r.Length.Should().Be(1);
((long)r.Single().Value).Should().Be(expectedSum);
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_no_key_with_sum_reduce_for_typed_response_It_will_be_able_to_sum()
{
var expectedSum = ArtistsById.Sum(a => a.Albums.Count());
var query = new Query(ClientTestData.Views.ArtistsTotalNumOfAlbumsViewId).Configure(q => q.Reduce(true));
var r = SUT.QueryAsync<int>(query)
.Result
.ToArray();
r.Length.Should().Be(1);
r.Single().Value.Should().Be(expectedSum);
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_IncludeDocs_and_no_value_is_returned_for_string_response_Then_the_included_docs_are_extracted()
{
var query = new Query(ClientTestData.Views.ArtistsNameNoValueViewId).Configure(q => q.IncludeDocs(true));
var r = SUT.QueryAsync(query)
.Result
.ToArray();
r.Length.Should().Be(ArtistsById.Length);
r.Each((i, item) => ArtistsById[i].Should().BeEquivalentTo(DbClient.Entities.Serializer.Deserialize<Artist>(item.IncludedDoc)));
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_IncludeDocs_and_no_value_is_returned_for_entity_response_Then_the_included_docs_are_extracted()
{
var query = new Query(ClientTestData.Views.ArtistsNameNoValueViewId).Configure(q => q.IncludeDocs(true));
var r = SUT.QueryAsync<string, Artist>(query)
.Result
.ToArray();
r.Length.Should().Be(ArtistsById.Length);
r.Each((i, item) => ArtistsById[i].Should().BeEquivalentTo(item.IncludedDoc));
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_IncludeDocs_of_non_array_doc_and_null_value_is_returned_Then_the_neither_included_docs_nor_value_is_extracted()
{
var query = new Query(ClientTestData.Views.ArtistsNameNoValueViewId).Configure(q => q.IncludeDocs(true));
var r = SUT.QueryAsync<string[], string[]>(query)
.Result
.ToArray();
r.Length.Should().Be(ArtistsById.Length);
r.Each(item =>
{
item.Value.Should().BeNull();
item.IncludedDoc.Should().BeNull();
});
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_Skipping_2_of_10_using_json_Then_8_rows_are_returned()
{
const int skip = 2;
var albums = ArtistsById.Skip(skip).Select(a => DbClient.Serializer.Serialize(a.Albums)).ToArray();
var query = new Query(ClientTestData.Views.ArtistsAlbumsViewId).Configure(q => q.Skip(skip));
var values = SUT.QueryAsync(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(albums);
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_Skipping_2_of_10_using_json_array_Then_8_rows_are_returned()
{
const int skip = 2;
var albums = ArtistsById.Skip(skip).Select(a => a.Albums.Select(i => DbClient.Serializer.Serialize(i)).ToArray()).ToArray();
var query = new Query(ClientTestData.Views.ArtistsAlbumsViewId).Configure(q => q.Skip(skip));
var values = SUT.QueryAsync<string[]>(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(albums);
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_Skipping_2_of_10_using_entities_Then_8_rows_are_returned()
{
const int skip = 2;
var albums = ArtistsById.Skip(skip).Select(a => a.Albums).ToArray();
var query = new Query(ClientTestData.Views.ArtistsAlbumsViewId).Configure(q => q.Skip(skip));
var values = SUT.QueryAsync<Album[]>(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(albums);
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_Limit_to_2_using_json_Then_2_rows_are_returned()
{
const int limit = 2;
var albums = ArtistsById.Take(limit).Select(a => DbClient.Serializer.Serialize(a.Albums)).ToArray();
var query = new Query(ClientTestData.Views.ArtistsAlbumsViewId).Configure(q => q.Limit(limit));
var values = SUT.QueryAsync(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(albums);
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_Limit_to_2_using_json_array_Then_2_rows_are_returned()
{
const int limit = 2;
var albums = ArtistsById.Take(limit).Select(a => a.Albums.Select(i => DbClient.Serializer.Serialize(i)).ToArray()).ToArray();
var query = new Query(ClientTestData.Views.ArtistsAlbumsViewId).Configure(q => q.Limit(limit));
var values = SUT.QueryAsync<string[]>(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(albums);
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_Limit_to_2_using_entities_Then_2_rows_are_returned()
{
const int limit = 2;
var albums = ArtistsById.Take(limit).Select(a => a.Albums).ToArray();
var query = new Query(ClientTestData.Views.ArtistsAlbumsViewId).Configure(q => q.Limit(limit));
var values = SUT.QueryAsync<Album[]>(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(albums);
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_Key_is_specified_using_json_Then_the_matching_row_is_returned()
{
var artist = ArtistsById[2];
var query = new Query(ClientTestData.Views.ArtistsAlbumsViewId).Configure(q => q.Key(artist.Name));
var values = SUT.QueryAsync(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(new[] { DbClient.Serializer.Serialize(artist.Albums) });
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_Key_is_specified_using_json_array_Then_the_matching_row_is_returned()
{
var artist = ArtistsById[2];
var query = new Query(ClientTestData.Views.ArtistsAlbumsViewId).Configure(q => q.Key(artist.Name));
var values = SUT.QueryAsync<string[]>(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(new[] { artist.Albums.Select(i => DbClient.Serializer.Serialize(i)).ToArray() });
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_Key_is_specified_using_entities_Then_the_matching_row_is_returned()
{
var artist = ArtistsById[2];
var query = new Query(ClientTestData.Views.ArtistsAlbumsViewId).Configure(q => q.Key(artist.Name));
var values = SUT.QueryAsync<Album[]>(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(new[] { artist.Albums });
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_Keys_are_specified_using_json_Then_matching_rows_are_returned()
{
var artists = ArtistsById.Skip(2).Take(3).ToArray();
var keys = artists.Select(a => a.Name).ToArray();
var query = new Query(ClientTestData.Views.ArtistsAlbumsViewId).Configure(q => q.Keys(keys));
var values = SUT.QueryAsync(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(artists.Select(a => DbClient.Serializer.Serialize(a.Albums)).ToArray());
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_Keys_are_specified_using_json_array_Then_matching_rows_are_returned()
{
var artists = ArtistsById.Skip(2).Take(3).ToArray();
var keys = artists.Select(a => a.Name).ToArray();
var query = new Query(ClientTestData.Views.ArtistsAlbumsViewId).Configure(q => q.Keys(keys));
var values = SUT.QueryAsync<string[]>(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(artists.Select(a => a.Albums.Select(i => DbClient.Serializer.Serialize(i)).ToArray()).ToArray());
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_Keys_are_specified_using_entities_Then_matching_rows_are_returned()
{
var artists = ArtistsById.Skip(2).Take(3).ToArray();
var keys = artists.Select(a => a.Name).ToArray();
var query = new Query(ClientTestData.Views.ArtistsAlbumsViewId).Configure(q => q.Keys(keys));
var values = SUT.QueryAsync<Album[]>(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(artists.Select(a => a.Albums).ToArray());
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_StartKey_and_EndKey_are_specified_using_json_Then_matching_rows_are_returned()
{
var artists = ArtistsById.Skip(2).Take(5).ToArray();
var query = new Query(ClientTestData.Views.ArtistsAlbumsViewId).Configure(q => q
.StartKey(artists.First().Name)
.EndKey(artists.Last().Name));
var values = SUT.QueryAsync(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(artists.Select(a => DbClient.Serializer.Serialize(a.Albums)).ToArray());
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_StartKey_and_EndKey_are_specified_using_json_array_Then_matching_rows_are_returned()
{
var artists = ArtistsById.Skip(2).Take(5).ToArray();
var query = new Query(ClientTestData.Views.ArtistsAlbumsViewId).Configure(q => q
.StartKey(artists.First().Name)
.EndKey(artists.Last().Name));
var values = SUT.QueryAsync<string[]>(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(artists.Select(a => a.Albums.Select(i => DbClient.Serializer.Serialize(i)).ToArray()).ToArray());
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_StartKey_and_EndKey_are_specified_using_entities_Then_matching_rows_are_returned()
{
var artists = ArtistsById.Skip(2).Take(5).ToArray();
var query = new Query(ClientTestData.Views.ArtistsAlbumsViewId).Configure(q => q
.StartKey(artists.First().Name)
.EndKey(artists.Last().Name));
var values = SUT.QueryAsync<Album[]>(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(artists.Select(a => a.Albums).ToArray());
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_StartKey_and_EndKey_with_non_inclusive_end_are_specified_using_json_Then_matching_rows_are_returned()
{
var artists = ArtistsById.Skip(2).Take(5).ToArray();
var query = new Query(ClientTestData.Views.ArtistsAlbumsViewId).Configure(q => q
.StartKey(artists.First().Name)
.EndKey(artists.Last().Name)
.InclusiveEnd(false));
var values = SUT.QueryAsync(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(artists.Take(artists.Length - 1).Select(a => DbClient.Serializer.Serialize(a.Albums)).ToArray());
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_StartKey_and_EndKey_with_non_inclusive_end_are_specified_using_json_array_Then_matching_rows_are_returned()
{
var artists = ArtistsById.Skip(2).Take(5).ToArray();
var query = new Query(ClientTestData.Views.ArtistsAlbumsViewId).Configure(q => q
.StartKey(artists.First().Name)
.EndKey(artists.Last().Name)
.InclusiveEnd(false));
var values = SUT.QueryAsync<string[]>(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(artists.Take(artists.Length - 1).Select(a => a.Albums.Select(i => DbClient.Serializer.Serialize(i)).ToArray()).ToArray());
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_StartKey_and_EndKey_with_non_inclusive_end_are_specified_using_entities_Then_matching_rows_are_returned()
{
var artists = ArtistsById.Skip(2).Take(5).ToArray();
var query = new Query(ClientTestData.Views.ArtistsAlbumsViewId).Configure(q => q
.StartKey(artists.First().Name)
.EndKey(artists.Last().Name)
.InclusiveEnd(false));
var values = SUT.QueryAsync<Album[]>(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(artists.Take(artists.Length - 1).Select(a => a.Albums).ToArray());
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_skip_two_of_ten_It_should_return_the_other_eight()
{
const int skip = 2;
var artists = ArtistsById.Skip(skip).ToArray();
var query = new Query(ClientTestData.Views.ArtistsNameAsKeyAndDocAsValueId).Configure(q => q
.Skip(skip));
var values = SUT.QueryAsync<Artist>(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(artists);
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_limit_is_two_of_ten_It_should_return_the_two_first_artists()
{
const int limit = 2;
var artists = ArtistsById.Take(limit).ToArray();
var query = new Query(ClientTestData.Views.ArtistsNameAsKeyAndDocAsValueId).Configure(q => q
.Limit(limit));
var values = SUT.QueryAsync<Artist>(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(artists);
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_getting_all_artists_It_can_deserialize_artists_properly()
{
var query = new Query(ClientTestData.Views.ArtistsNameAsKeyAndDocAsValueId);
var values = SUT.QueryAsync<Artist>(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(ArtistsById);
}
[MyFact(TestScenarios.MyCouchStore)]
public void Query_When_Key_is_specified_using_custom_query_parameters_Then_the_matching_row_is_returned()
{
var artist = ArtistsById[2];
var query = new Query(ClientTestData.Views.ArtistsAlbumsViewId)
.Configure(q => q.CustomQueryParameters(new Dictionary<string, object>
{
["key"] = $"\"{artist.Name}\""
}));
var values = SUT.QueryAsync(query)
.Result
.OrderBy(r => r.Id)
.Select(r => r.Value)
.ToArray();
values.Should().BeEquivalentTo(new[] { DbClient.Serializer.Serialize(artist.Albums) });
}
}
}
| |
#region License
/*
* EndPointListener.cs
*
* This code is derived from EndPointListener.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2016 sta.blockhead
*
* 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 Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <[email protected]>
*/
#endregion
#region Contributors
/*
* Contributors:
* - Liryna <[email protected]>
* - Nicholas Devenish
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
namespace CustomWebSocketSharp.Net
{
internal sealed class EndPointListener
{
#region Private Fields
private List<HttpListenerPrefix> _all; // host == '+'
private static readonly string _defaultCertFolderPath;
private IPEndPoint _endpoint;
private Dictionary<HttpListenerPrefix, HttpListener> _prefixes;
private bool _secure;
private Socket _socket;
private ServerSslConfiguration _sslConfig;
private List<HttpListenerPrefix> _unhandled; // host == '*'
private Dictionary<HttpConnection, HttpConnection> _unregistered;
private object _unregisteredSync;
#endregion
#region Static Constructor
static EndPointListener ()
{
_defaultCertFolderPath =
Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);
}
#endregion
#region Internal Constructors
internal EndPointListener (
IPEndPoint endpoint,
bool secure,
string certificateFolderPath,
ServerSslConfiguration sslConfig,
bool reuseAddress
)
{
if (secure) {
var cert =
getCertificate (endpoint.Port, certificateFolderPath, sslConfig.ServerCertificate);
if (cert == null)
throw new ArgumentException ("No server certificate could be found.");
_secure = true;
_sslConfig =
new ServerSslConfiguration (
cert,
sslConfig.ClientCertificateRequired,
sslConfig.EnabledSslProtocols,
sslConfig.CheckCertificateRevocation
);
_sslConfig.ClientCertificateValidationCallback =
sslConfig.ClientCertificateValidationCallback;
}
_endpoint = endpoint;
_prefixes = new Dictionary<HttpListenerPrefix, HttpListener> ();
_unregistered = new Dictionary<HttpConnection, HttpConnection> ();
_unregisteredSync = ((ICollection) _unregistered).SyncRoot;
_socket =
new Socket (endpoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if (reuseAddress)
_socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_socket.Bind (endpoint);
_socket.Listen (500);
_socket.BeginAccept (onAccept, this);
}
#endregion
#region Public Properties
public IPAddress Address {
get {
return _endpoint.Address;
}
}
public bool IsSecure {
get {
return _secure;
}
}
public int Port {
get {
return _endpoint.Port;
}
}
public ServerSslConfiguration SslConfiguration {
get {
return _sslConfig;
}
}
#endregion
#region Private Methods
private static void addSpecial (List<HttpListenerPrefix> prefixes, HttpListenerPrefix prefix)
{
var path = prefix.Path;
foreach (var pref in prefixes) {
if (pref.Path == path)
throw new HttpListenerException (87, "The prefix is already in use.");
}
prefixes.Add (prefix);
}
private static RSACryptoServiceProvider createRSAFromFile (string filename)
{
byte[] pvk = null;
using (var fs = File.Open (filename, FileMode.Open, FileAccess.Read, FileShare.Read)) {
pvk = new byte[fs.Length];
fs.Read (pvk, 0, pvk.Length);
}
var rsa = new RSACryptoServiceProvider ();
rsa.ImportCspBlob (pvk);
return rsa;
}
private static X509Certificate2 getCertificate (
int port, string folderPath, X509Certificate2 defaultCertificate
)
{
if (folderPath == null || folderPath.Length == 0)
folderPath = _defaultCertFolderPath;
try {
var cer = Path.Combine (folderPath, String.Format ("{0}.cer", port));
var key = Path.Combine (folderPath, String.Format ("{0}.key", port));
if (File.Exists (cer) && File.Exists (key)) {
var cert = new X509Certificate2 (cer);
cert.PrivateKey = createRSAFromFile (key);
return cert;
}
}
catch {
}
return defaultCertificate;
}
private void leaveIfNoPrefix ()
{
if (_prefixes.Count > 0)
return;
var prefs = _unhandled;
if (prefs != null && prefs.Count > 0)
return;
prefs = _all;
if (prefs != null && prefs.Count > 0)
return;
EndPointManager.RemoveEndPoint (_endpoint);
}
private static void onAccept (IAsyncResult asyncResult)
{
var lsnr = (EndPointListener) asyncResult.AsyncState;
Socket sock = null;
try {
sock = lsnr._socket.EndAccept (asyncResult);
}
catch (SocketException) {
// TODO: Should log the error code when this class has a logging.
}
catch (ObjectDisposedException) {
return;
}
try {
lsnr._socket.BeginAccept (onAccept, lsnr);
}
catch {
if (sock != null)
sock.Close ();
return;
}
if (sock == null)
return;
processAccepted (sock, lsnr);
}
private static void processAccepted (Socket socket, EndPointListener listener)
{
HttpConnection conn = null;
try {
conn = new HttpConnection (socket, listener);
lock (listener._unregisteredSync)
listener._unregistered[conn] = conn;
conn.BeginReadRequest ();
}
catch {
if (conn != null) {
conn.Close (true);
return;
}
socket.Close ();
}
}
private static bool removeSpecial (List<HttpListenerPrefix> prefixes, HttpListenerPrefix prefix)
{
var path = prefix.Path;
var cnt = prefixes.Count;
for (var i = 0; i < cnt; i++) {
if (prefixes[i].Path == path) {
prefixes.RemoveAt (i);
return true;
}
}
return false;
}
private static HttpListener searchHttpListenerFromSpecial (
string path, List<HttpListenerPrefix> prefixes
)
{
if (prefixes == null)
return null;
HttpListener bestMatch = null;
var bestLen = -1;
foreach (var pref in prefixes) {
var prefPath = pref.Path;
var len = prefPath.Length;
if (len < bestLen)
continue;
if (path.StartsWith (prefPath)) {
bestLen = len;
bestMatch = pref.Listener;
}
}
return bestMatch;
}
#endregion
#region Internal Methods
internal static bool CertificateExists (int port, string folderPath)
{
if (folderPath == null || folderPath.Length == 0)
folderPath = _defaultCertFolderPath;
var cer = Path.Combine (folderPath, String.Format ("{0}.cer", port));
var key = Path.Combine (folderPath, String.Format ("{0}.key", port));
return File.Exists (cer) && File.Exists (key);
}
internal void RemoveConnection (HttpConnection connection)
{
lock (_unregisteredSync)
_unregistered.Remove (connection);
}
internal bool TrySearchHttpListener (Uri uri, out HttpListener listener)
{
listener = null;
if (uri == null)
return false;
var host = uri.Host;
var dns = Uri.CheckHostName (host) == UriHostNameType.Dns;
var port = uri.Port.ToString ();
var path = HttpUtility.UrlDecode (uri.AbsolutePath);
var pathSlash = path[path.Length - 1] != '/' ? path + "/" : path;
if (host != null && host.Length > 0) {
var bestLen = -1;
foreach (var pref in _prefixes.Keys) {
if (dns) {
var prefHost = pref.Host;
if (Uri.CheckHostName (prefHost) == UriHostNameType.Dns && prefHost != host)
continue;
}
if (pref.Port != port)
continue;
var prefPath = pref.Path;
var len = prefPath.Length;
if (len < bestLen)
continue;
if (path.StartsWith (prefPath) || pathSlash.StartsWith (prefPath)) {
bestLen = len;
listener = _prefixes[pref];
}
}
if (bestLen != -1)
return true;
}
var prefs = _unhandled;
listener = searchHttpListenerFromSpecial (path, prefs);
if (listener == null && pathSlash != path)
listener = searchHttpListenerFromSpecial (pathSlash, prefs);
if (listener != null)
return true;
prefs = _all;
listener = searchHttpListenerFromSpecial (path, prefs);
if (listener == null && pathSlash != path)
listener = searchHttpListenerFromSpecial (pathSlash, prefs);
return listener != null;
}
#endregion
#region Public Methods
public void AddPrefix (HttpListenerPrefix prefix, HttpListener listener)
{
List<HttpListenerPrefix> current, future;
if (prefix.Host == "*") {
do {
current = _unhandled;
future = current != null
? new List<HttpListenerPrefix> (current)
: new List<HttpListenerPrefix> ();
prefix.Listener = listener;
addSpecial (future, prefix);
}
while (Interlocked.CompareExchange (ref _unhandled, future, current) != current);
return;
}
if (prefix.Host == "+") {
do {
current = _all;
future = current != null
? new List<HttpListenerPrefix> (current)
: new List<HttpListenerPrefix> ();
prefix.Listener = listener;
addSpecial (future, prefix);
}
while (Interlocked.CompareExchange (ref _all, future, current) != current);
return;
}
Dictionary<HttpListenerPrefix, HttpListener> prefs, prefs2;
do {
prefs = _prefixes;
if (prefs.ContainsKey (prefix)) {
if (prefs[prefix] != listener) {
throw new HttpListenerException (
87, String.Format ("There's another listener for {0}.", prefix)
);
}
return;
}
prefs2 = new Dictionary<HttpListenerPrefix, HttpListener> (prefs);
prefs2[prefix] = listener;
}
while (Interlocked.CompareExchange (ref _prefixes, prefs2, prefs) != prefs);
}
public void Close ()
{
_socket.Close ();
HttpConnection[] conns = null;
lock (_unregisteredSync) {
if (_unregistered.Count == 0)
return;
var keys = _unregistered.Keys;
conns = new HttpConnection[keys.Count];
keys.CopyTo (conns, 0);
_unregistered.Clear ();
}
for (var i = conns.Length - 1; i >= 0; i--)
conns[i].Close (true);
}
public void RemovePrefix (HttpListenerPrefix prefix, HttpListener listener)
{
List<HttpListenerPrefix> current, future;
if (prefix.Host == "*") {
do {
current = _unhandled;
if (current == null)
break;
future = new List<HttpListenerPrefix> (current);
if (!removeSpecial (future, prefix))
break; // The prefix wasn't found.
}
while (Interlocked.CompareExchange (ref _unhandled, future, current) != current);
leaveIfNoPrefix ();
return;
}
if (prefix.Host == "+") {
do {
current = _all;
if (current == null)
break;
future = new List<HttpListenerPrefix> (current);
if (!removeSpecial (future, prefix))
break; // The prefix wasn't found.
}
while (Interlocked.CompareExchange (ref _all, future, current) != current);
leaveIfNoPrefix ();
return;
}
Dictionary<HttpListenerPrefix, HttpListener> prefs, prefs2;
do {
prefs = _prefixes;
if (!prefs.ContainsKey (prefix))
break;
prefs2 = new Dictionary<HttpListenerPrefix, HttpListener> (prefs);
prefs2.Remove (prefix);
}
while (Interlocked.CompareExchange (ref _prefixes, prefs2, prefs) != prefs);
leaveIfNoPrefix ();
}
#endregion
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using NUnit.Framework;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.PropertyEditors;
using Umbraco.Cms.Core.Serialization;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Services.Implement;
using Umbraco.Cms.Core.Strings;
using Umbraco.Cms.Infrastructure.Serialization;
using Umbraco.Cms.Tests.Common.Builders;
using Umbraco.Cms.Tests.Common.Builders.Extensions;
using Umbraco.Cms.Tests.UnitTests.TestHelpers;
using Umbraco.Extensions;
namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.Models
{
[TestFixture]
public class VariationTests
{
[Test]
public void ValidateVariationTests()
{
// All tests:
// 1. if exact is set to true: culture cannot be null when the ContentVariation.Culture flag is set
// 2. if wildcards is set to false: fail when "*" is passed in as either culture or segment.
// 3. ContentVariation flag is ignored when wildcards are used.
// 4. Empty string is considered the same as null
AssertForNovariation();
AssertForCultureVariation();
AssertForSegmentVariation();
AssertForCultureAndSegmentVariation();
}
private static void AssertForNovariation()
{
Assert4A(ContentVariation.Nothing, null, null, true);
Assert4A(ContentVariation.Nothing, null, string.Empty, true);
Assert4B(ContentVariation.Nothing, null, "*", true, false, false, true);
Assert4A(ContentVariation.Nothing, null, "segment", false);
Assert4A(ContentVariation.Nothing, string.Empty, null, true);
Assert4A(ContentVariation.Nothing, string.Empty, string.Empty, true);
Assert4B(ContentVariation.Nothing, string.Empty, "*", true, false, false, true);
Assert4A(ContentVariation.Nothing, string.Empty, "segment", false);
Assert4B(ContentVariation.Nothing, "*", null, true, false, false, true);
Assert4B(ContentVariation.Nothing, "*", string.Empty, true, false, false, true);
Assert4B(ContentVariation.Nothing, "*", "*", true, false, false, true);
Assert4A(ContentVariation.Nothing, "*", "segment", false);
Assert4A(ContentVariation.Nothing, "culture", null, false);
Assert4A(ContentVariation.Nothing, "culture", string.Empty, false);
Assert4A(ContentVariation.Nothing, "culture", "*", false);
Assert4A(ContentVariation.Nothing, "culture", "segment", false);
}
private static void AssertForCultureVariation()
{
Assert4B(ContentVariation.Culture, null, null, false, true, false, true);
Assert4B(ContentVariation.Culture, null, string.Empty, false, true, false, true);
Assert4B(ContentVariation.Culture, null, "*", false, false, false, true);
Assert4A(ContentVariation.Culture, null, "segment", false);
Assert4B(ContentVariation.Culture, string.Empty, null, false, true, false, true);
Assert4B(ContentVariation.Culture, string.Empty, string.Empty, false, true, false, true);
Assert4B(ContentVariation.Culture, string.Empty, "*", false, false, false, true);
Assert4A(ContentVariation.Culture, string.Empty, "segment", false);
Assert4B(ContentVariation.Culture, "*", null, true, false, false, true);
Assert4B(ContentVariation.Culture, "*", string.Empty, true, false, false, true);
Assert4B(ContentVariation.Culture, "*", "*", true, false, false, true);
Assert4A(ContentVariation.Culture, "*", "segment", false);
Assert4A(ContentVariation.Culture, "culture", null, true);
Assert4A(ContentVariation.Culture, "culture", string.Empty, true);
Assert4B(ContentVariation.Culture, "culture", "*", true, false, false, true);
Assert4A(ContentVariation.Culture, "culture", "segment", false);
}
private static void AssertForSegmentVariation()
{
Assert4B(ContentVariation.Segment, null, null, true, true, true, true);
Assert4B(ContentVariation.Segment, null, string.Empty, true, true, true, true);
Assert4B(ContentVariation.Segment, null, "*", true, false, false, true);
Assert4A(ContentVariation.Segment, null, "segment", true);
Assert4B(ContentVariation.Segment, string.Empty, null, true, true, true, true);
Assert4B(ContentVariation.Segment, string.Empty, string.Empty, true, true, true, true);
Assert4B(ContentVariation.Segment, string.Empty, "*", true, false, false, true);
Assert4A(ContentVariation.Segment, string.Empty, "segment", true);
Assert4B(ContentVariation.Segment, "*", null, true, false, false, true);
Assert4B(ContentVariation.Segment, "*", string.Empty, true, false, false, true);
Assert4B(ContentVariation.Segment, "*", "*", true, false, false, true);
Assert4B(ContentVariation.Segment, "*", "segment", true, false, false, true);
Assert4A(ContentVariation.Segment, "culture", null, false);
Assert4A(ContentVariation.Segment, "culture", string.Empty, false);
Assert4A(ContentVariation.Segment, "culture", "*", false);
Assert4A(ContentVariation.Segment, "culture", "segment", false);
}
private static void AssertForCultureAndSegmentVariation()
{
Assert4B(ContentVariation.CultureAndSegment, null, null, false, true, false, true);
Assert4B(ContentVariation.CultureAndSegment, null, string.Empty, false, true, false, true);
Assert4B(ContentVariation.CultureAndSegment, null, "*", false, false, false, true);
Assert4B(ContentVariation.CultureAndSegment, null, "segment", false, true, false, true);
Assert4B(ContentVariation.CultureAndSegment, string.Empty, null, false, true, false, true);
Assert4B(ContentVariation.CultureAndSegment, string.Empty, string.Empty, false, true, false, true);
Assert4B(ContentVariation.CultureAndSegment, string.Empty, "*", false, false, false, true);
Assert4B(ContentVariation.CultureAndSegment, string.Empty, "segment", false, true, false, true);
Assert4B(ContentVariation.CultureAndSegment, "*", null, true, false, false, true);
Assert4B(ContentVariation.CultureAndSegment, "*", string.Empty, true, false, false, true);
Assert4B(ContentVariation.CultureAndSegment, "*", "*", true, false, false, true);
Assert4B(ContentVariation.CultureAndSegment, "*", "segment", true, false, false, true);
Assert4B(ContentVariation.CultureAndSegment, "culture", null, true, true, true, true);
Assert4B(ContentVariation.CultureAndSegment, "culture", string.Empty, true, true, true, true);
Assert4B(ContentVariation.CultureAndSegment, "culture", "*", true, false, false, true);
Assert4B(ContentVariation.CultureAndSegment, "culture", "segment", true, true, true, true);
}
/// <summary>
/// Asserts the result of <see cref="ContentVariationExtensions.ValidateVariation"/>
/// </summary>
/// <param name="exactAndWildcards">Validate using Exact + Wildcards flags</param>
/// <param name="nonExactAndNoWildcards">Validate using non Exact + no Wildcard flags</param>
/// <param name="exactAndNoWildcards">Validate using Exact + no Wildcard flags</param>
/// <param name="nonExactAndWildcards">Validate using non Exact + Wildcard flags</param>
private static void Assert4B(
ContentVariation variation,
string culture,
string segment,
bool exactAndWildcards,
bool nonExactAndNoWildcards,
bool exactAndNoWildcards,
bool nonExactAndWildcards)
{
Assert.AreEqual(exactAndWildcards, variation.ValidateVariation(culture, segment, true, true, false));
Assert.AreEqual(nonExactAndNoWildcards, variation.ValidateVariation(culture, segment, false, false, false));
Assert.AreEqual(exactAndNoWildcards, variation.ValidateVariation(culture, segment, true, false, false));
Assert.AreEqual(nonExactAndWildcards, variation.ValidateVariation(culture, segment, false, true, false));
}
/// <summary>
/// Asserts the result of <see cref="ContentVariationExtensions.ValidateVariation(ContentVariation, string, string, bool, bool, bool)"/>
/// where expectedResult matches all combinations of Exact + Wildcard
/// </summary>
private static void Assert4A(ContentVariation variation, string culture, string segment, bool expectedResult) =>
Assert4B(variation, culture, segment, expectedResult, expectedResult, expectedResult, expectedResult);
[Test]
public void PropertyTests()
{
var propertyType = new PropertyType(TestHelper.ShortStringHelper, "editor", ValueStorageType.Nvarchar) { Alias = "prop" };
var prop = new Property(propertyType);
const string langFr = "fr-FR";
// can set value
// and get edited and published value
// because non-publishing
prop.SetValue("a");
Assert.AreEqual("a", prop.GetValue());
Assert.AreEqual("a", prop.GetValue(published: true));
// illegal, 'cos non-publishing
Assert.Throws<NotSupportedException>(() => prop.PublishValues());
// change
propertyType.SupportsPublishing = true;
// can get value
// and now published value is null
Assert.AreEqual("a", prop.GetValue());
Assert.IsNull(prop.GetValue(published: true));
// cannot set non-supported variation value
Assert.Throws<NotSupportedException>(() => prop.SetValue("x", langFr));
Assert.IsNull(prop.GetValue(langFr));
// can publish value
// and get edited and published values
prop.PublishValues();
Assert.AreEqual("a", prop.GetValue());
Assert.AreEqual("a", prop.GetValue(published: true));
// can set value
// and get edited and published values
prop.SetValue("b");
Assert.AreEqual("b", prop.GetValue());
Assert.AreEqual("a", prop.GetValue(published: true));
// can clear value
prop.UnpublishValues();
Assert.AreEqual("b", prop.GetValue());
Assert.IsNull(prop.GetValue(published: true));
// change - now we vary by culture
propertyType.Variations |= ContentVariation.Culture;
// can set value
// and get values
prop.SetValue("c", langFr);
Assert.IsNull(prop.GetValue()); // there is no invariant value anymore
Assert.IsNull(prop.GetValue(published: true));
Assert.AreEqual("c", prop.GetValue(langFr));
Assert.IsNull(prop.GetValue(langFr, published: true));
// can publish value
// and get edited and published values
prop.PublishValues(langFr);
Assert.IsNull(prop.GetValue());
Assert.IsNull(prop.GetValue(published: true));
Assert.AreEqual("c", prop.GetValue(langFr));
Assert.AreEqual("c", prop.GetValue(langFr, published: true));
// can clear all
prop.UnpublishValues("*");
Assert.IsNull(prop.GetValue());
Assert.IsNull(prop.GetValue(published: true));
Assert.AreEqual("c", prop.GetValue(langFr));
Assert.IsNull(prop.GetValue(langFr, published: true));
// can publish all
prop.PublishValues("*");
Assert.IsNull(prop.GetValue());
Assert.IsNull(prop.GetValue(published: true));
Assert.AreEqual("c", prop.GetValue(langFr));
Assert.AreEqual("c", prop.GetValue(langFr, published: true));
// same for culture
prop.UnpublishValues(langFr);
Assert.AreEqual("c", prop.GetValue(langFr));
Assert.IsNull(prop.GetValue(langFr, published: true));
prop.PublishValues(langFr);
Assert.AreEqual("c", prop.GetValue(langFr));
Assert.AreEqual("c", prop.GetValue(langFr, published: true));
prop.UnpublishValues(); // does not throw, internal, content item throws
Assert.IsNull(prop.GetValue());
Assert.IsNull(prop.GetValue(published: true));
prop.PublishValues(); // does not throw, internal, content item throws
Assert.IsNull(prop.GetValue());
Assert.IsNull(prop.GetValue(published: true));
}
[Test]
public void ContentNames()
{
IContentType contentType = new ContentTypeBuilder()
.WithAlias("contentType")
.Build();
Content content = CreateContent(contentType);
const string langFr = "fr-FR";
const string langUk = "en-UK";
// throws if the content type does not support the variation
Assert.Throws<NotSupportedException>(() => content.SetCultureName("name-fr", langFr));
// now it will work
contentType.Variations = ContentVariation.Culture;
// recreate content to re-capture content type variations
content = CreateContent(contentType);
// invariant name works
content.Name = "name";
Assert.AreEqual("name", content.GetCultureName(null));
content.SetCultureName("name2", null);
Assert.AreEqual("name2", content.Name);
Assert.AreEqual("name2", content.GetCultureName(null));
// variant names work
content.SetCultureName("name-fr", langFr);
content.SetCultureName("name-uk", langUk);
Assert.AreEqual("name-fr", content.GetCultureName(langFr));
Assert.AreEqual("name-uk", content.GetCultureName(langUk));
// variant dictionary of names work
Assert.AreEqual(2, content.CultureInfos.Count);
Assert.IsTrue(content.CultureInfos.ContainsKey(langFr));
Assert.AreEqual("name-fr", content.CultureInfos[langFr].Name);
Assert.IsTrue(content.CultureInfos.ContainsKey(langUk));
Assert.AreEqual("name-uk", content.CultureInfos[langUk].Name);
}
[Test]
public void ContentPublishValues()
{
const string langFr = "fr-FR";
PropertyType propertyType = new PropertyTypeBuilder()
.WithAlias("prop")
.Build();
IContentType contentType = new ContentTypeBuilder()
.WithAlias("contentType")
.Build();
contentType.AddPropertyType(propertyType);
Content content = CreateContent(contentType);
// can set value
// and get edited value, published is null
// because publishing
content.SetValue("prop", "a");
Assert.AreEqual("a", content.GetValue("prop"));
Assert.IsNull(content.GetValue("prop", published: true));
// cannot set non-supported variation value
Assert.Throws<NotSupportedException>(() => content.SetValue("prop", "x", langFr));
Assert.IsNull(content.GetValue("prop", langFr));
// can publish value
// and get edited and published values
Assert.IsTrue(content.PublishCulture(CultureImpact.All));
Assert.AreEqual("a", content.GetValue("prop"));
Assert.AreEqual("a", content.GetValue("prop", published: true));
// can set value
// and get edited and published values
content.SetValue("prop", "b");
Assert.AreEqual("b", content.GetValue("prop"));
Assert.AreEqual("a", content.GetValue("prop", published: true));
// can clear value
content.UnpublishCulture();
Assert.AreEqual("b", content.GetValue("prop"));
Assert.IsNull(content.GetValue("prop", published: true));
// change - now we vary by culture
contentType.Variations |= ContentVariation.Culture;
propertyType.Variations |= ContentVariation.Culture;
content.ChangeContentType(contentType);
// can set value
// and get values
content.SetValue("prop", "c", langFr);
Assert.IsNull(content.GetValue("prop")); // there is no invariant value anymore
Assert.IsNull(content.GetValue("prop", published: true));
Assert.AreEqual("c", content.GetValue("prop", langFr));
Assert.IsNull(content.GetValue("prop", langFr, published: true));
// can publish value
// and get edited and published values
Assert.IsFalse(content.PublishCulture(CultureImpact.Explicit(langFr, false))); // no name
content.SetCultureName("name-fr", langFr);
Assert.IsTrue(content.PublishCulture(CultureImpact.Explicit(langFr, false)));
Assert.IsNull(content.GetValue("prop"));
Assert.IsNull(content.GetValue("prop", published: true));
Assert.AreEqual("c", content.GetValue("prop", langFr));
Assert.AreEqual("c", content.GetValue("prop", langFr, published: true));
// can clear all
content.UnpublishCulture("*");
Assert.IsNull(content.GetValue("prop"));
Assert.IsNull(content.GetValue("prop", published: true));
Assert.AreEqual("c", content.GetValue("prop", langFr));
Assert.IsNull(content.GetValue("prop", langFr, published: true));
// can publish all
Assert.IsTrue(content.PublishCulture(CultureImpact.All));
Assert.IsNull(content.GetValue("prop"));
Assert.IsNull(content.GetValue("prop", published: true));
Assert.AreEqual("c", content.GetValue("prop", langFr));
Assert.AreEqual("c", content.GetValue("prop", langFr, published: true));
// same for culture
content.UnpublishCulture(langFr);
Assert.AreEqual("c", content.GetValue("prop", langFr));
Assert.IsNull(content.GetValue("prop", langFr, published: true));
Assert.IsTrue(content.PublishCulture(CultureImpact.Explicit(langFr, false)));
Assert.AreEqual("c", content.GetValue("prop", langFr));
Assert.AreEqual("c", content.GetValue("prop", langFr, published: true));
content.UnpublishCulture(); // clears invariant props if any
Assert.IsNull(content.GetValue("prop"));
Assert.IsNull(content.GetValue("prop", published: true));
Assert.IsTrue(content.PublishCulture(CultureImpact.All)); // publishes invariant props if any
Assert.IsNull(content.GetValue("prop"));
Assert.IsNull(content.GetValue("prop", published: true));
Content other = CreateContent(contentType, 2, "other");
Assert.Throws<NotSupportedException>(() => other.SetValue("prop", "o")); // don't even try
other.SetValue("prop", "o1", langFr);
// can copy other's edited value
content.CopyFrom(other);
Assert.IsNull(content.GetValue("prop"));
Assert.IsNull(content.GetValue("prop", published: true));
Assert.AreEqual("o1", content.GetValue("prop", langFr));
Assert.AreEqual("c", content.GetValue("prop", langFr, published: true));
// can copy self's published value
content.CopyFrom(content);
Assert.IsNull(content.GetValue("prop"));
Assert.IsNull(content.GetValue("prop", published: true));
Assert.AreEqual("c", content.GetValue("prop", langFr));
Assert.AreEqual("c", content.GetValue("prop", langFr, published: true));
}
[Test]
public void ContentPublishValuesWithMixedPropertyTypeVariations()
{
PropertyValidationService propertyValidationService = GetPropertyValidationService();
const string langFr = "fr-FR";
// content type varies by Culture
// prop1 varies by Culture
// prop2 is invariant
IContentType contentType = new ContentTypeBuilder()
.WithAlias("contentType")
.Build();
contentType.Variations |= ContentVariation.Culture;
PropertyType variantPropType = new PropertyTypeBuilder()
.WithAlias("prop1")
.WithVariations(ContentVariation.Culture)
.WithMandatory(true)
.Build();
PropertyType invariantPropType = new PropertyTypeBuilder()
.WithAlias("prop2")
.WithVariations(ContentVariation.Nothing)
.WithMandatory(true)
.Build();
contentType.AddPropertyType(variantPropType);
contentType.AddPropertyType(invariantPropType);
Content content = CreateContent(contentType);
content.SetCultureName("hello", langFr);
// for this test we'll make the french culture the default one - this is needed for publishing invariant property values
var langFrImpact = CultureImpact.Explicit(langFr, true);
Assert.IsTrue(content.PublishCulture(langFrImpact)); // succeeds because names are ok (not validating properties here)
Assert.IsFalse(propertyValidationService.IsPropertyDataValid(content, out _, langFrImpact)); // fails because prop1 is mandatory
content.SetValue("prop1", "a", langFr);
Assert.IsTrue(content.PublishCulture(langFrImpact)); // succeeds because names are ok (not validating properties here)
// Fails because prop2 is mandatory and invariant and the item isn't published.
// Invariant is validated against the default language except when there isn't a published version, in that case it's always validated.
Assert.IsFalse(propertyValidationService.IsPropertyDataValid(content, out _, langFrImpact));
content.SetValue("prop2", "x");
Assert.IsTrue(content.PublishCulture(langFrImpact)); // still ok...
Assert.IsTrue(propertyValidationService.IsPropertyDataValid(content, out _, langFrImpact)); // now it's ok
Assert.AreEqual("a", content.GetValue("prop1", langFr, published: true));
Assert.AreEqual("x", content.GetValue("prop2", published: true));
}
[Test]
public void ContentPublishVariations()
{
const string langFr = "fr-FR";
const string langUk = "en-UK";
const string langEs = "es-ES";
PropertyType propertyType = new PropertyTypeBuilder()
.WithAlias("prop")
.Build();
IContentType contentType = new ContentTypeBuilder()
.WithAlias("contentType")
.Build();
contentType.AddPropertyType(propertyType);
Content content = CreateContent(contentType);
// change - now we vary by culture
contentType.Variations |= ContentVariation.Culture;
propertyType.Variations |= ContentVariation.Culture;
content.ChangeContentType(contentType);
Assert.Throws<NotSupportedException>(() => content.SetValue("prop", "a")); // invariant = no
content.SetValue("prop", "a-fr", langFr);
content.SetValue("prop", "a-uk", langUk);
content.SetValue("prop", "a-es", langEs);
// cannot publish without a name
Assert.IsFalse(content.PublishCulture(CultureImpact.Explicit(langFr, false)));
// works with a name
// and then FR is available, and published
content.SetCultureName("name-fr", langFr);
Assert.IsTrue(content.PublishCulture(CultureImpact.Explicit(langFr, false)));
// now UK is available too
content.SetCultureName("name-uk", langUk);
// test available, published
Assert.IsTrue(content.IsCultureAvailable(langFr));
Assert.IsTrue(content.IsCulturePublished(langFr));
Assert.AreEqual("name-fr", content.GetPublishName(langFr));
Assert.AreNotEqual(DateTime.MinValue, content.GetPublishDate(langFr));
Assert.IsFalse(content.IsCultureEdited(langFr)); // once published, edited is *wrong* until saved
Assert.IsTrue(content.IsCultureAvailable(langUk));
Assert.IsFalse(content.IsCulturePublished(langUk));
Assert.IsNull(content.GetPublishName(langUk));
Assert.IsNull(content.GetPublishDate(langUk)); // not published
Assert.IsFalse(content.IsCultureAvailable(langEs));
Assert.IsFalse(content.IsCultureEdited(langEs)); // not avail, so... not edited
Assert.IsFalse(content.IsCulturePublished(langEs));
// not published!
Assert.IsNull(content.GetPublishName(langEs));
Assert.IsNull(content.GetPublishDate(langEs));
// cannot test IsCultureEdited here - as that requires the content service and repository
// see: ContentServiceTests.Can_SaveRead_Variations
}
[Test]
public void IsDirtyTests()
{
PropertyType propertyType = new PropertyTypeBuilder()
.WithAlias("prop")
.Build();
var prop = new Property(propertyType);
IContentType contentType = new ContentTypeBuilder()
.WithAlias("contentType")
.Build();
contentType.AddPropertyType(propertyType);
Content content = CreateContent(contentType);
prop.SetValue("a");
Assert.AreEqual("a", prop.GetValue());
Assert.IsNull(prop.GetValue(published: true));
Assert.IsTrue(prop.IsDirty());
content.SetValue("prop", "a");
Assert.AreEqual("a", content.GetValue("prop"));
Assert.IsNull(content.GetValue("prop", published: true));
Assert.IsTrue(content.IsDirty());
Assert.IsTrue(content.IsAnyUserPropertyDirty());
//// how can we tell which variation was dirty?
}
[Test]
public void ValidationTests()
{
PropertyType propertyType = new PropertyTypeBuilder()
.WithAlias("prop")
.WithSupportsPublishing(true)
.Build();
var prop = new Property(propertyType);
prop.SetValue("a");
Assert.AreEqual("a", prop.GetValue());
Assert.IsNull(prop.GetValue(published: true));
PropertyValidationService propertyValidationService = GetPropertyValidationService();
Assert.IsTrue(propertyValidationService.IsPropertyValid(prop));
propertyType.Mandatory = true;
Assert.IsTrue(propertyValidationService.IsPropertyValid(prop));
prop.SetValue(null);
Assert.IsFalse(propertyValidationService.IsPropertyValid(prop));
// can publish, even though invalid
prop.PublishValues();
}
private static Content CreateContent(IContentType contentType, int id = 1, string name = "content") =>
new ContentBuilder()
.WithId(id)
.WithVersionId(1)
.WithName(name)
.WithContentType(contentType)
.Build();
private static PropertyValidationService GetPropertyValidationService()
{
IIOHelper ioHelper = Mock.Of<IIOHelper>();
IDataTypeService dataTypeService = Mock.Of<IDataTypeService>();
ILocalizedTextService localizedTextService = Mock.Of<ILocalizedTextService>();
var attribute = new DataEditorAttribute("a", "a", "a");
IDataValueEditorFactory dataValueEditorFactory = Mock.Of<IDataValueEditorFactory>(x
=> x.Create<TextOnlyValueEditor>(It.IsAny<DataEditorAttribute>()) == new TextOnlyValueEditor(attribute, localizedTextService, Mock.Of<IShortStringHelper>(), new JsonNetSerializer(), Mock.Of<IIOHelper>()));
var textBoxEditor = new TextboxPropertyEditor(
dataValueEditorFactory,
ioHelper);
var serializer = new ConfigurationEditorJsonSerializer();
var mockDataTypeService = new Mock<IDataTypeService>();
Mock.Get(dataTypeService).Setup(x => x.GetDataType(It.Is<int>(y => y == Constants.DataTypes.Textbox)))
.Returns(new DataType(textBoxEditor, serializer));
var propertyEditorCollection = new PropertyEditorCollection(new DataEditorCollection(() => new[] { textBoxEditor }));
return new PropertyValidationService(
propertyEditorCollection,
dataTypeService,
localizedTextService,
new ValueEditorCache());
}
}
}
| |
// 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 ShiftLeftLogicalUInt3232()
{
var test = new ImmUnaryOpTest__ShiftLeftLogicalUInt3232();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__ShiftLeftLogicalUInt3232
{
private struct TestStruct
{
public Vector256<UInt32> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogicalUInt3232 testClass)
{
var result = Avx2.ShiftLeftLogical(_fld, 32);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data = new UInt32[Op1ElementCount];
private static Vector256<UInt32> _clsVar;
private Vector256<UInt32> _fld;
private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable;
static ImmUnaryOpTest__ShiftLeftLogicalUInt3232()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
}
public ImmUnaryOpTest__ShiftLeftLogicalUInt3232()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.ShiftLeftLogical(
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.ShiftLeftLogical(
Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.ShiftLeftLogical(
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.ShiftLeftLogical(
_clsVar,
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftLeftLogical(firstOp, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftLeftLogical(firstOp, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftLeftLogical(firstOp, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftLeftLogicalUInt3232();
var result = Avx2.ShiftLeftLogical(test._fld, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.ShiftLeftLogical(_fld, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.ShiftLeftLogical(test._fld, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt32> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (0 != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (0!= result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftLeftLogical)}<UInt32>(Vector256<UInt32><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using UOCApp.Helpers;
using UOCApp;
using UOCApp.Models;
using Xamarin.Forms;
namespace UOCApp
{
public partial class EntryPage : ContentPage
{
public ObstaclesPage obstaclesPage;
public EntryPage(string displayTime)
{
obstaclesPage = new ObstaclesPage();
InitializeComponent();
entry_Time.Text = displayTime;
}
private void NavHome(object sender, EventArgs args)
{
// Console.WriteLine("Clicked Nav Home");
Navigation.PopToRootAsync();
}
private void NavLeaderboard(object sender, EventArgs args)
{
// Console.WriteLine("Clicked Nav Leaderboard");
Navigation.PushAsync(new LeaderboardPage());
}
private void NavTimes(object sender, EventArgs args)
{
// Console.WriteLine("Clicked Nav Times");
Navigation.PushAsync(new TimesPage());
}
private void NavAdmin(object sender, EventArgs args)
{
//Console.WriteLine("Clicked Nav Admin");
Navigation.PushAsync(new AdminPage());
}
async void NavObstacle(object sender, EventArgs args)
{
//Console.WriteLine("Clicked Obstacles");
await Navigation.PushModalAsync(obstaclesPage);
}
private async void SaveResult(object sender, EventArgs args) //for debug
{
//Console.WriteLine("Clicked Save Result");
try
{
SharedResult sharedResult = new SharedResult(picker_Date.Date, ConvertTime(entry_Time.Text), false, false,
entry_Name.Text, Gender(), Grade(), entry_School.Text);
Result result = new Result();
result.result_id = null;
result.date = String.Format("{0:yyyy-MM-dd}", picker_Date.Date);
result.time = ConvertTime(entry_Time.Text);
result.shared = Convert.ToInt32(switch_Public.IsToggled);
result.student_name = entry_Name.Text;
result.student_gender = Gender();
result.student_grade = Grade();
var sure = await DisplayAlert("Confirm Save", "Please record accurate race times! \n \"Winners Don't Cheat, \n Champions Don't Lie!\"\n", "Save", "Back");
if (sure == true)
{
//selected obstacles can be obtained from obstaclesPage.obstacleList
// save to client database, unless in admin mode - TODO
var LocalID = App.databaseHelper.InsertResult(result, obstaclesPage.obstacleList);
if (LocalID >= 1) // verify local insertion success by primary key
{
if (switch_Public.IsToggled)
{ // did the user specify that they wish to post to the leaderboard?
if (!obstaclesPage.obstacleList.allComplete())//added dilibrate check to obstacle list due to known android bug
{
await DisplayAlert("Thank you!", "Your result has been saved", "OK");
await Navigation.PopToRootAsync(); // return to home once save complete
return;
}
if (await sharedResult.share((bool)switch_Official.IsToggled)) // post to server and return true if successful
{
await DisplayAlert("Thank you!", "Your result has been saved and shared with the leaderboard", "OK");
await Navigation.PopToRootAsync(); // return to home once save complete
return;
}
else
{
//Console.WriteLine ("Failed to share with leaderboard");
await DisplayAlert("Sorry", "Unable to connect to leaderboard. \n Check your internet connection.", "OK");
return;
}
}
await DisplayAlert("Thank you!", "Your result has been saved", "OK");
await Navigation.PopToRootAsync(); // return to home once save complete
return;
}
else
{
// fail to save locally
await DisplayAlert("Sorry", "Unable to save. \n Please try again", "OK");
return;
//Console.WriteLine ("Failed to save result");
}
}
else
{
//abort save, do nothing
return;
}
}
catch (ArgumentException e)
{ // fail to create a result instance, bad parameters
await DisplayAlert("Error", e.Message, "OK");
return;
//Console.WriteLine (e);
}
}
private String Gender()
{
// read the gender picker and assign values
var Gender = "";
var GenderIndex = picker_Gender.SelectedIndex;
switch (GenderIndex)
{
case 0:
Gender = "M";
break;
case 1:
Gender = "F";
break;
default:
// error behavior? no gender set, shouldn't be possible
Gender = null;
break;
}
return Gender;
}
private int Grade()
{
// read the grade picker and assign values
var Grade = 0;
var GradeIndex = picker_Grade.SelectedIndex;
switch (GradeIndex)
{
case 0:
Grade = 4;
break;
case 1:
Grade = 5;
break;
case 2:
Grade = 6;
break;
case 3:
Grade = 7;
break;
case 4: // GRADE_TEENAGER = -1
Grade = -1;
break;
case 5: // GRADE_ADULT = -2
Grade = -2;
break;
case 6: // GRADE_OLDADULT = -3
Grade = -3;
break;
default:
// error behavior? no grade set
break;
}
return Grade;
}
static decimal ConvertTime(string time)
{
try {
decimal result;
if (String.IsNullOrEmpty(time))
{
return 0;
}
if (time.Contains(':'))
{
//it's in mm:ss.iii format
int sepPos = time.IndexOf(':');
string minPart = time.Substring(0, sepPos);
string secPart = time.Substring(sepPos + 1);
result = (Convert.ToInt32(minPart) * 60) + Convert.ToDecimal(secPart);
}
else
{
//it's in ss.iii format so we can just convert it
result = Convert.ToDecimal(time);
}
return Decimal.Round(result, 3);
}
catch (FormatException e)
{
throw new ArgumentException("Invalid Time\n Minimum 30 seconds\n Please enter as Minutes:Seconds");
}
}
public void ShareButtonStatus()
{
if (obstaclesPage.obstacleList.allComplete())
{
switch_Public.IsEnabled = true;
label_obstacle.Opacity = 0;
}
else
{
switch_Public.IsToggled = false;
switch_Public.IsEnabled = false;
label_obstacle.Opacity = 1;
}
}
public void OfficialButtonStatus()
{
bool loggedIn = false;
if (Application.Current.Properties.ContainsKey("loggedin"))
{
loggedIn = Convert.ToBoolean(Application.Current.Properties["loggedin"]);
}
if (loggedIn)
{
switch_Official.IsEnabled = true;
switch_Official.Opacity = 1;
label_Official.Opacity = 1;
}
else
{
switch_Official.IsToggled = false;
switch_Official.IsEnabled = false;
switch_Official.Opacity = 0;
label_Official.Opacity = 0;
}
}
protected override void OnAppearing()
{
base.OnAppearing();
OfficialButtonStatus(); // update the offical button status dependant on if the user is logged in or not
ShareButtonStatus(); // update the share buttons status dependant on if all obstacles are complete
}
}
}
| |
using System;
using System.Collections;
using System.Text;
using System.Xml;
using System.Linq;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence.Caching;
using umbraco.BusinessLogic;
using Umbraco.Core.Services;
using umbraco.DataLayer;
using System.Collections.Generic;
using Umbraco.Core;
using PropertyType = umbraco.cms.businesslogic.propertytype.PropertyType;
namespace umbraco.cms.businesslogic.web
{
/// <summary>
/// Summary description for DocumentType.
/// </summary>
[Obsolete("Obsolete, Use Umbraco.Core.Models.ContentType", false)]
public class DocumentType : ContentType
{
#region Constructors
public DocumentType(int id) : base(id) { }
public DocumentType(Guid id) : base(id) { }
public DocumentType(int id, bool noSetup) : base(id, noSetup) { }
internal DocumentType(IContentType contentType)
: base(contentType)
{
SetupNode(contentType);
}
#endregion
#region Constants and Static members
public static Guid _objectType = new Guid(Constants.ObjectTypes.DocumentType);
new internal const string m_SQLOptimizedGetAll = @"
SELECT id, createDate, trashed, parentId, nodeObjectType, nodeUser, level, path, sortOrder, uniqueID, text,
allowAtRoot, isContainer, Alias,icon,thumbnail,description,
templateNodeId, IsDefault
FROM umbracoNode
INNER JOIN cmsContentType ON umbracoNode.id = cmsContentType.nodeId
LEFT OUTER JOIN cmsDocumentType ON cmsContentType.nodeId = cmsDocumentType.contentTypeNodeId
WHERE nodeObjectType = @nodeObjectType";
#endregion
#region Private Members
private ArrayList _templateIds = new ArrayList();
private int _defaultTemplate;
private bool _hasChildrenInitialized = false;
private bool _hasChildren;
private IContentType _contentType;
#endregion
#region Static Methods
/// <summary>
/// Generates the complete (simplified) XML DTD
/// </summary>
/// <returns>The DTD as a string</returns>
[Obsolete("Obsolete, Use Umbraco.Core.Services.ContentTypeService.GetDtd()", false)]
public static string GenerateDtd()
{
StringBuilder dtd = new StringBuilder();
// Renamed 'umbraco' to 'root' since the top level of the DOCTYPE should specify the name of the root node for it to be valid;
// there's no mention of 'umbraco' anywhere in the schema that this DOCTYPE governs
// (Alex N 20100212)
dtd.AppendLine("<!DOCTYPE root [ ");
dtd.AppendLine(GenerateXmlDocumentType());
dtd.AppendLine("]>");
return dtd.ToString();
}
[Obsolete("Obsolete, Use Umbraco.Core.Services.ContentTypeService.GetContentTypesDtd()", false)]
public static string GenerateXmlDocumentType()
{
StringBuilder dtd = new StringBuilder();
if (UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema)
{
dtd.AppendLine("<!ELEMENT node ANY> <!ATTLIST node id ID #REQUIRED> <!ELEMENT data ANY>");
}
else
{
// TEMPORARY: Added Try-Catch to this call since trying to generate a DTD against a corrupt db
// or a broken connection string is not handled yet
// (Alex N 20100212)
try
{
StringBuilder strictSchemaBuilder = new StringBuilder();
List<DocumentType> dts = GetAllAsList();
foreach (DocumentType dt in dts)
{
string safeAlias = helpers.Casing.SafeAlias(dt.Alias);
if (safeAlias != null)
{
strictSchemaBuilder.AppendLine(String.Format("<!ELEMENT {0} ANY>", safeAlias));
strictSchemaBuilder.AppendLine(String.Format("<!ATTLIST {0} id ID #REQUIRED>", safeAlias));
}
}
// Only commit the strong schema to the container if we didn't generate an error building it
dtd.Append(strictSchemaBuilder);
}
catch (Exception exception)
{
LogHelper.Error<DocumentType>("Exception while trying to build DTD for Xml schema; is Umbraco installed correctly and the connection string configured?", exception);
}
}
return dtd.ToString();
}
[Obsolete("Obsolete, Use Umbraco.Core.Services.ContentTypeService.GetContentType()", false)]
public new static DocumentType GetByAlias(string Alias)
{
try
{
var contentType = ApplicationContext.Current.Services.ContentTypeService.GetContentType(Alias);
return new DocumentType(contentType.Id);
}
catch
{
return null;
}
}
[Obsolete("Obsolete, Use Umbraco.Core.Models.ContentType and Umbraco.Core.Services.ContentTypeService.Save()", false)]
public static DocumentType MakeNew(User u, string Text)
{
var contentType = new Umbraco.Core.Models.ContentType(-1) { Name = Text, Alias = Text, CreatorId = u.Id, Thumbnail = "folder.png", Icon = "folder.gif" };
ApplicationContext.Current.Services.ContentTypeService.Save(contentType, u.Id);
var newDt = new DocumentType(contentType);
//event
NewEventArgs e = new NewEventArgs();
newDt.OnNew(e);
return newDt;
}
[Obsolete("Use GetAllAsList() method call instead", true)]
public new static DocumentType[] GetAll
{
get
{
return GetAllAsList().ToArray();
}
}
[Obsolete("Obsolete, Use Umbraco.Core.Services.ContentTypeService.GetAllContentTypes()", false)]
public static List<DocumentType> GetAllAsList()
{
var contentTypes = ApplicationContext.Current.Services.ContentTypeService.GetAllContentTypes();
var documentTypes = contentTypes.Select(x => new DocumentType(x));
return documentTypes.OrderBy(x => x.Text).ToList();
}
#endregion
#region Public Properties
[Obsolete("Obsolete, Use Umbraco.Core.Services.ContentTypeService.HasChildren()", false)]
public override bool HasChildren
{
get
{
if (_hasChildrenInitialized == false)
{
HasChildren = ApplicationContext.Current.Services.ContentTypeService.HasChildren(Id);
}
return _hasChildren;
}
set
{
_hasChildrenInitialized = true;
_hasChildren = value;
}
}
[Obsolete("Obsolete, Use SetDefaultTemplate() on Umbraco.Core.Models.ContentType", false)]
public int DefaultTemplate
{
get { return _defaultTemplate; }
set
{
RemoveDefaultTemplate();
_defaultTemplate = value;
if (_defaultTemplate != 0)
{
var template = ApplicationContext.Current.Services.FileService.GetTemplate(_defaultTemplate);
_contentType.SetDefaultTemplate(template);
}
}
}
/// <summary>
/// Gets/sets the allowed templates for this document type.
/// </summary>
[Obsolete("Obsolete, Use AllowedTemplates property on Umbraco.Core.Models.ContentType", false)]
public template.Template[] allowedTemplates
{
get
{
if (HasTemplate())
{
template.Template[] retval = new template.Template[_templateIds.Count];
for (int i = 0; i < _templateIds.Count; i++)
{
retval[i] = template.Template.GetTemplate((int)_templateIds[i]);
}
return retval;
}
return new template.Template[0];
}
set
{
clearTemplates();
var templates = new List<ITemplate>();
foreach (template.Template t in value)
{
var template = ApplicationContext.Current.Services.FileService.GetTemplate(t.Id);
templates.Add(template);
_templateIds.Add(t.Id);
}
_contentType.AllowedTemplates = templates;
}
}
public new string Path
{
get
{
List<int> path = new List<int>();
DocumentType working = this;
while (working != null)
{
path.Add(working.Id);
try
{
if (working.MasterContentType != 0)
{
working = new DocumentType(working.MasterContentType);
}
else
{
working = null;
}
}
catch (ArgumentException)
{
working = null;
}
}
path.Add(-1);
path.Reverse();
string sPath = string.Join(",", path.ConvertAll(item => item.ToString()).ToArray());
return sPath;
}
set
{
base.Path = value;
}
}
#endregion
#region Public Methods
#region Regenerate Xml Structures
/// <summary>
/// This will return all PUBLISHED content Ids that are of this content type or any descendant types as well.
/// </summary>
/// <returns></returns>
/// <remarks>
/// This will also work if we have multiple child content types (if one day we support that)
/// </remarks>
internal override IEnumerable<int> GetContentIdsForContentType()
{
var ids = new List<int>();
var currentContentTypeIds = new[] { this.Id };
while (currentContentTypeIds.Any())
{
var childContentTypeIds = new List<int>();
//loop through each content type id
foreach (var currentContentTypeId in currentContentTypeIds)
{
//get all the content item ids of the current content type
using (var dr = SqlHelper.ExecuteReader(@"SELECT DISTINCT cmsDocument.nodeId FROM cmsDocument
INNER JOIN cmsContent ON cmsContent.nodeId = cmsDocument.nodeId
INNER JOIN cmsContentType ON cmsContent.contentType = cmsContentType.nodeId
WHERE cmsContentType.nodeId = @contentTypeId AND cmsDocument.published = 1",
SqlHelper.CreateParameter("@contentTypeId", currentContentTypeId)))
{
while (dr.Read())
{
ids.Add(dr.GetInt("nodeId"));
}
dr.Close();
}
//lookup the child content types if there are any and add the ids to the content type ids array
using (var reader = SqlHelper.ExecuteReader("SELECT childContentTypeId FROM cmsContentType2ContentType WHERE parentContentTypeId=@contentTypeId",
SqlHelper.CreateParameter("@contentTypeId", currentContentTypeId)))
{
while (reader.Read())
{
childContentTypeIds.Add(reader.GetInt("childContentTypeId"));
}
}
}
currentContentTypeIds = childContentTypeIds.ToArray();
}
return ids;
}
/// <summary>
/// Rebuilds the xml structure for the content item by id
/// </summary>
/// <param name="contentId"></param>
/// <remarks>
/// This is not thread safe
/// </remarks>
internal override void RebuildXmlStructureForContentItem(int contentId)
{
var xd = new XmlDocument();
try
{
//create the document in optimized mode!
// (not sure why we wouldn't always do that ?!)
new Document(true, contentId).XmlGenerate(xd);
//The benchmark results that I found based contructing the Document object with 'true' for optimized
//mode, vs using the normal ctor. Clearly optimized mode is better!
/*
* The average page rendering time (after 10 iterations) for submitting /umbraco/dialogs/republish?xml=true when using
* optimized mode is
*
* 0.060400555555556
*
* The average page rendering time (after 10 iterations) for submitting /umbraco/dialogs/republish?xml=true when not
* using optimized mode is
*
* 0.107037777777778
*
* This means that by simply changing this to use optimized mode, it is a 45% improvement!
*
*/
}
catch (Exception ee)
{
LogHelper.Error<DocumentType>("Error generating xml", ee);
}
}
/// <summary>
/// Clears all xml structures in the cmsContentXml table for the current content type and any of it's descendant types
/// </summary>
/// <remarks>
/// This is not thread safe.
/// This will also work if we have multiple child content types (if one day we support that)
/// </remarks>
internal override void ClearXmlStructuresForContent()
{
var currentContentTypeIds = new[] {this.Id};
while (currentContentTypeIds.Any())
{
var childContentTypeIds = new List<int>();
//loop through each content type id
foreach (var currentContentTypeId in currentContentTypeIds)
{
//Remove all items from the cmsContentXml table that are of this current content type
SqlHelper.ExecuteNonQuery(@"DELETE FROM cmsContentXml WHERE nodeId IN
(SELECT DISTINCT cmsContent.nodeId FROM cmsContent
INNER JOIN cmsContentType ON cmsContent.contentType = cmsContentType.nodeId
WHERE cmsContentType.nodeId = @contentTypeId)",
SqlHelper.CreateParameter("@contentTypeId", currentContentTypeId));
//lookup the child content types if there are any and add the ids to the content type ids array
using (var reader = SqlHelper.ExecuteReader("SELECT childContentTypeId FROM cmsContentType2ContentType WHERE parentContentTypeId=@contentTypeId",
SqlHelper.CreateParameter("@contentTypeId", currentContentTypeId)))
{
while (reader.Read())
{
childContentTypeIds.Add(reader.GetInt("childContentTypeId"));
}
}
}
currentContentTypeIds = childContentTypeIds.ToArray();
}
}
#endregion
[Obsolete("Obsolete, Use RemoveTemplate() on Umbraco.Core.Models.ContentType", false)]
public void RemoveTemplate(int templateId)
{
// remove if default template
if (this.DefaultTemplate == templateId)
{
RemoveDefaultTemplate();
}
// remove from list of document type templates
if (_templateIds.Contains(templateId))
{
var template = _contentType.AllowedTemplates.FirstOrDefault(x => x.Id == templateId);
if (template != null)
_contentType.RemoveTemplate(template);
_templateIds.Remove(templateId);
}
}
/// <summary>
///
/// </summary>
/// <exception cref="ArgumentException">Throws an exception if trying to delete a document type that is assigned as a master document type</exception>
[Obsolete("Obsolete, Use Umbraco.Core.Services.ContentTypeService.Delete()", false)]
public override void delete()
{
DeleteEventArgs e = new DeleteEventArgs();
FireBeforeDelete(e);
if (e.Cancel == false)
{
// check that no document types uses me as a master
if (GetAllAsList().Any(dt => dt.MasterContentTypes.Contains(this.Id)))
{
throw new ArgumentException("Can't delete a Document Type used as a Master Content Type. Please remove all references first!");
}
ApplicationContext.Current.Services.ContentTypeService.Delete(_contentType);
clearTemplates();
FireAfterDelete(e);
}
}
public void clearTemplates()
{
_contentType.AllowedTemplates = new List<ITemplate>();
_templateIds.Clear();
}
public XmlElement ToXml(XmlDocument xd)
{
var exporter = new EntityXmlSerializer();
var xml = exporter.Serialize(ApplicationContext.Current.Services.DataTypeService, _contentType);
//convert the Linq to Xml structure to the old .net xml structure
var xNode = xml.GetXmlNode();
var doc = (XmlElement)xd.ImportNode(xNode, true);
return doc;
}
[Obsolete("Obsolete, Use SetDefaultTemplate(null) on Umbraco.Core.Models.ContentType", false)]
public void RemoveDefaultTemplate()
{
_defaultTemplate = 0;
_contentType.SetDefaultTemplate(null);
}
public bool HasTemplate()
{
return (_templateIds.Count > 0);
}
/// <summary>
/// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility
/// </summary>
[Obsolete("Obsolete, Use Umbraco.Core.Services.ContentTypeService.Save()", false)]
public override void Save()
{
var e = new SaveEventArgs();
FireBeforeSave(e);
if (!e.Cancel)
{
if (MasterContentType != 0)
_contentType.ParentId = MasterContentType;
foreach (var masterContentType in MasterContentTypes)
{
var contentType = ApplicationContext.Current.Services.ContentTypeService.GetContentType(masterContentType);
_contentType.AddContentType(contentType);
}
var current = User.GetCurrent();
int userId = current == null ? 0 : current.Id;
ApplicationContext.Current.Services.ContentTypeService.Save(_contentType, userId);
base.Save();
FireAfterSave(e);
}
}
#endregion
#region Protected Methods
[Obsolete("Depreated, No longer needed nor used")]
protected void PopulateDocumentTypeNodeFromReader(IRecordsReader dr)
{
if (!dr.IsNull("templateNodeId"))
{
_templateIds.Add(dr.GetInt("templateNodeId"));
if (!dr.IsNull("IsDefault"))
{
if (dr.GetBoolean("IsDefault"))
{
_defaultTemplate = dr.GetInt("templateNodeId");
}
}
}
}
protected override void setupNode()
{
var contentType = ApplicationContext.Current.Services.ContentTypeService.GetContentType(Id);
SetupNode(contentType);
}
#endregion
#region Private Methods
private void SetupNode(IContentType contentType)
{
_contentType = contentType;
foreach (var template in _contentType.AllowedTemplates.Where(t => t != null))
{
_templateIds.Add(template.Id);
}
if (_contentType.DefaultTemplate != null)
_defaultTemplate = _contentType.DefaultTemplate.Id;
base.PopulateContentTypeFromContentTypeBase(_contentType);
base.PopulateCMSNodeFromUmbracoEntity(_contentType, _objectType);
}
#endregion
#region Events
/// <summary>
/// The save event handler
/// </summary>
public delegate void SaveEventHandler(DocumentType sender, SaveEventArgs e);
/// <summary>
/// The New event handler
/// </summary>
public delegate void NewEventHandler(DocumentType sender, NewEventArgs e);
/// <summary>
/// The delete event handler
/// </summary>
public delegate void DeleteEventHandler(DocumentType sender, DeleteEventArgs e);
/// <summary>
/// Occurs when [before save].
/// </summary>
public static event SaveEventHandler BeforeSave;
/// <summary>
/// Raises the <see cref="E:BeforeSave"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireBeforeSave(SaveEventArgs e)
{
if (BeforeSave != null)
BeforeSave(this, e);
}
/// <summary>
/// Occurs when [after save].
/// </summary>
public static event SaveEventHandler AfterSave;
/// <summary>
/// Raises the <see cref="E:AfterSave"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireAfterSave(SaveEventArgs e)
{
if (AfterSave != null)
{
var updated = this._contentType == null
? new DocumentType(this.Id)
: new DocumentType(this._contentType);
AfterSave(updated, e);
}
}
/// <summary>
/// Occurs when [new].
/// </summary>
public static event NewEventHandler New;
/// <summary>
/// Raises the <see cref="E:New"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void OnNew(NewEventArgs e)
{
if (New != null)
New(this, e);
}
/// <summary>
/// Occurs when [before delete].
/// </summary>
public static event DeleteEventHandler BeforeDelete;
/// <summary>
/// Raises the <see cref="E:BeforeDelete"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireBeforeDelete(DeleteEventArgs e)
{
if (BeforeDelete != null)
BeforeDelete(this, e);
}
/// <summary>
/// Occurs when [after delete].
/// </summary>
public static event DeleteEventHandler AfterDelete;
/// <summary>
/// Raises the <see cref="E:AfterDelete"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireAfterDelete(DeleteEventArgs e)
{
if (AfterDelete != null)
AfterDelete(this, e);
}
#endregion
}
}
| |
// Copyright (c) Microsoft and contributors. 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol
{
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>
/// FileOperations operations.
/// </summary>
public partial interface IFileOperations
{
/// <summary>
/// Deletes the specified task file from the compute node where the
/// task ran.
/// </summary>
/// <param name='jobId'>
/// The id of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The id of the task whose file you want to delete.
/// </param>
/// <param name='fileName'>
/// The path to the task file that you want to delete.
/// </param>
/// <param name='recursive'>
/// Whether to delete children of a directory. If the fileName
/// parameter represents a directory instead of a file, you can set
/// Recursive to true to delete the directory and all of the files
/// and subdirectories in it. If Recursive is false then the
/// directory must be empty or deletion will fail.
/// </param>
/// <param name='fileDeleteFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<FileDeleteFromTaskHeaders>> DeleteFromTaskWithHttpMessagesAsync(string jobId, string taskId, string fileName, bool? recursive = default(bool?), FileDeleteFromTaskOptions fileDeleteFromTaskOptions = default(FileDeleteFromTaskOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the content of the specified task file.
/// </summary>
/// <param name='jobId'>
/// The id of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The id of the task whose file you want to retrieve.
/// </param>
/// <param name='fileName'>
/// The path to the task file that you want to get the content of.
/// </param>
/// <param name='fileGetFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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<System.IO.Stream,FileGetFromTaskHeaders>> GetFromTaskWithHttpMessagesAsync(string jobId, string taskId, string fileName, FileGetFromTaskOptions fileGetFromTaskOptions = default(FileGetFromTaskOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the properties of the specified task file.
/// </summary>
/// <param name='jobId'>
/// The id of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The id of the task whose file you want to get the properties of.
/// </param>
/// <param name='fileName'>
/// The path to the task file that you want to get the properties of.
/// </param>
/// <param name='fileGetNodeFilePropertiesFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<FileGetNodeFilePropertiesFromTaskHeaders>> GetNodeFilePropertiesFromTaskWithHttpMessagesAsync(string jobId, string taskId, string fileName, FileGetNodeFilePropertiesFromTaskOptions fileGetNodeFilePropertiesFromTaskOptions = default(FileGetNodeFilePropertiesFromTaskOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified task file from the compute node.
/// </summary>
/// <param name='poolId'>
/// The id of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The id of the compute node from which you want to delete the file.
/// </param>
/// <param name='fileName'>
/// The path to the file that you want to delete.
/// </param>
/// <param name='recursive'>
/// Whether to delete children of a directory. If the fileName
/// parameter represents a directory instead of a file, you can set
/// Recursive to true to delete the directory and all of the files
/// and subdirectories in it. If Recursive is false then the
/// directory must be empty or deletion will fail.
/// </param>
/// <param name='fileDeleteFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<FileDeleteFromComputeNodeHeaders>> DeleteFromComputeNodeWithHttpMessagesAsync(string poolId, string nodeId, string fileName, bool? recursive = default(bool?), FileDeleteFromComputeNodeOptions fileDeleteFromComputeNodeOptions = default(FileDeleteFromComputeNodeOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the content of the specified task file.
/// </summary>
/// <param name='poolId'>
/// The id of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The id of the compute node that contains the file.
/// </param>
/// <param name='fileName'>
/// The path to the task file that you want to get the content of.
/// </param>
/// <param name='fileGetFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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<System.IO.Stream,FileGetFromComputeNodeHeaders>> GetFromComputeNodeWithHttpMessagesAsync(string poolId, string nodeId, string fileName, FileGetFromComputeNodeOptions fileGetFromComputeNodeOptions = default(FileGetFromComputeNodeOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the properties of the specified compute node file.
/// </summary>
/// <param name='poolId'>
/// The id of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The id of the compute node that contains the file.
/// </param>
/// <param name='fileName'>
/// The path to the compute node file that you want to get the
/// properties of.
/// </param>
/// <param name='fileGetNodeFilePropertiesFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<FileGetNodeFilePropertiesFromComputeNodeHeaders>> GetNodeFilePropertiesFromComputeNodeWithHttpMessagesAsync(string poolId, string nodeId, string fileName, FileGetNodeFilePropertiesFromComputeNodeOptions fileGetNodeFilePropertiesFromComputeNodeOptions = default(FileGetNodeFilePropertiesFromComputeNodeOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the files in a task's directory on its compute node.
/// </summary>
/// <param name='jobId'>
/// The id of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The id of the task whose files you want to list.
/// </param>
/// <param name='recursive'>
/// Whether to list children of a directory.
/// </param>
/// <param name='fileListFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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<NodeFile>,FileListFromTaskHeaders>> ListFromTaskWithHttpMessagesAsync(string jobId, string taskId, bool? recursive = default(bool?), FileListFromTaskOptions fileListFromTaskOptions = default(FileListFromTaskOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all of the files in task directories on the specified
/// compute node.
/// </summary>
/// <param name='poolId'>
/// The id of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The id of the compute node whose files you want to list.
/// </param>
/// <param name='recursive'>
/// Whether to list children of a directory.
/// </param>
/// <param name='fileListFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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<NodeFile>,FileListFromComputeNodeHeaders>> ListFromComputeNodeWithHttpMessagesAsync(string poolId, string nodeId, bool? recursive = default(bool?), FileListFromComputeNodeOptions fileListFromComputeNodeOptions = default(FileListFromComputeNodeOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the files in a task's directory on its compute node.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='fileListFromTaskNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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<NodeFile>,FileListFromTaskHeaders>> ListFromTaskNextWithHttpMessagesAsync(string nextPageLink, FileListFromTaskNextOptions fileListFromTaskNextOptions = default(FileListFromTaskNextOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all of the files in task directories on the specified
/// compute node.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='fileListFromComputeNodeNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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<NodeFile>,FileListFromComputeNodeHeaders>> ListFromComputeNodeNextWithHttpMessagesAsync(string nextPageLink, FileListFromComputeNodeNextOptions fileListFromComputeNodeNextOptions = default(FileListFromComputeNodeNextOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Copyright 2003-2004 DigitalCraftsmen - http://www.digitalcraftsmen.com.br/
//
// 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.ManagementExtensions.Default.Strategy
{
using System;
using System.IO;
using System.Reflection;
using System.CodeDom;
using System.CodeDom.Compiler;
/// <summary>
/// Summary description for CodeGenerationInvokerStrategy.
/// </summary>
public sealed class CodeGenerationInvokerStrategy : InvokerStrategy
{
public CodeGenerationInvokerStrategy()
{
}
#region InvokerStrategy Members
public MDynamicSupport Create(Object instance)
{
ManagementInfo info = MInspector.BuildInfoFromStandardComponent(instance);
CodeGenerationDynamicSupport codeGen = new CodeGenerationDynamicSupport(
instance, info,
new MemberResolver(info, instance.GetType()));
return codeGen.GetImplementation();
}
#endregion
}
/// <summary>
///
/// </summary>
class CodeGenerationDynamicSupport
{
private Object instance;
private ManagementInfo info;
private MemberResolver resolver;
public CodeGenerationDynamicSupport(Object instance, ManagementInfo info, MemberResolver resolver)
{
this.info = info;
this.instance = instance;
this.resolver = resolver;
}
public MDynamicSupport GetImplementation()
{
// TODO: Adds a cache for generated assemblies...
CodeNamespace ns = BuildMDynamicSupportCodeDom();
Microsoft.CSharp.CSharpCodeProvider cp = new Microsoft.CSharp.CSharpCodeProvider();
cp.CreateGenerator().GenerateCodeFromNamespace( ns, Console.Out, null );
CodeCompileUnit unit = new CodeCompileUnit();
unit.Namespaces.Add( ns );
String[] assembliesName = GetRequiredAssemblies();
CompilerParameters parameters = new CompilerParameters(assembliesName);
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = true;
CompilerResults result =
cp.CreateCompiler().CompileAssemblyFromDom(parameters, unit);
if (result.Errors.HasErrors)
{
throw new CompilationException(result.Errors);
}
Type dynamicType =
result.CompiledAssembly.GetType(
"Castle.ManagementExtensions.Generated.DynamicImplementation", true, true);
Object inst = Activator.CreateInstance(
dynamicType,
new object[] { info, instance } );
return (MDynamicSupport) inst;
}
private String[] GetRequiredAssemblies()
{
return new String[] { Path.GetFileName( Assembly.GetExecutingAssembly().CodeBase ),
Path.GetFileName( instance.GetType().Assembly.CodeBase ) } ;
}
private CodeNamespace BuildMDynamicSupportCodeDom()
{
CodeNamespace ns = new CodeNamespace( "Castle.ManagementExtensions.Generated" );
ns.Imports.Add( new CodeNamespaceImport("Castle.ManagementExtensions") );
CodeTypeDeclaration typeDefinition = new CodeTypeDeclaration("DynamicImplementation");
ns.Types.Add(typeDefinition);
typeDefinition.IsClass = true;
typeDefinition.BaseTypes.Add( typeof(MDynamicSupport) );
BuildFields(typeDefinition);
BuildConstructor(typeDefinition);
BuildMethods(typeDefinition);
return ns;
}
private void BuildFields(CodeTypeDeclaration typeDefinition)
{
CodeMemberField fieldInfo = new CodeMemberField( typeof(ManagementInfo), "info" );
CodeMemberField fieldInstance = new CodeMemberField( instance.GetType(), "instance" );
typeDefinition.Members.Add(fieldInfo);
typeDefinition.Members.Add(fieldInstance);
}
private void BuildConstructor(CodeTypeDeclaration typeDefinition)
{
CodeConstructor constructor = new CodeConstructor();
constructor.Parameters.Add(
new CodeParameterDeclarationExpression(typeof(ManagementInfo), "info"));
constructor.Parameters.Add(
new CodeParameterDeclarationExpression(instance.GetType(), "instance"));
constructor.Statements.Add(
new CodeAssignStatement(
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(), "info"),
new CodeArgumentReferenceExpression("info")));
constructor.Statements.Add(
new CodeAssignStatement(
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(), "instance"),
new CodeArgumentReferenceExpression("instance")));
constructor.Attributes = MemberAttributes.Public;
typeDefinition.Members.Add( constructor );
}
private void BuildMethods(CodeTypeDeclaration typeDefinition)
{
BuildInvokeMethod(typeDefinition);
BuildInfoProperty(typeDefinition);
BuildGetAttributeMethod(typeDefinition);
BuildSetAttributeMethod(typeDefinition);
}
private void BuildInfoProperty(CodeTypeDeclaration typeDefinition)
{
CodeMemberProperty infoProperty = new CodeMemberProperty();
infoProperty.HasGet = true;
infoProperty.HasSet = false;
infoProperty.Type = new CodeTypeReference( typeof(ManagementInfo) );
infoProperty.Name = "Info";
infoProperty.Attributes = MemberAttributes.Public;
CodeMethodReturnStatement returnStmt = new CodeMethodReturnStatement();
returnStmt.Expression = new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(), "info");
infoProperty.GetStatements.Add(returnStmt);
typeDefinition.Members.Add(infoProperty);
}
private void BuildGetAttributeMethod(CodeTypeDeclaration typeDefinition)
{
CodeMemberMethod method = new CodeMemberMethod();
method.Attributes = MemberAttributes.Public;
method.Name = "GetAttributeValue";
method.ReturnType = new CodeTypeReference( typeof(Object) );
method.Parameters.Add(new CodeParameterDeclarationExpression(
typeof(String), "name" ));
CodeArgumentReferenceExpression nameArgument =
new CodeArgumentReferenceExpression("name");
CodeThisReferenceExpression thisRef =
new CodeThisReferenceExpression();
foreach(ManagementAttribute attribute in info.Attributes)
{
CodeConditionStatement stmt = new CodeConditionStatement();
stmt.Condition =
new CodeMethodInvokeExpression(nameArgument, "Equals",
new CodeSnippetExpression("\"" + attribute.Name + "\""));
PropertyInfo property = resolver.GetProperty(attribute.Name);
if (!property.CanRead)
{
// TODO: Adds throw
continue;
}
CodeMethodReturnStatement returnStmt = new CodeMethodReturnStatement();
returnStmt.Expression =
new CodePropertyReferenceExpression(
new CodeFieldReferenceExpression(
thisRef, "instance"), attribute.Name );
stmt.TrueStatements.Add( returnStmt );
method.Statements.Add(stmt);
}
{
CodeMethodReturnStatement returnStmt = new CodeMethodReturnStatement();
returnStmt.Expression = new CodeSnippetExpression("null");
method.Statements.Add( returnStmt );
}
typeDefinition.Members.Add( method );
}
private void BuildSetAttributeMethod(CodeTypeDeclaration typeDefinition)
{
CodeMemberMethod method = new CodeMemberMethod();
method.Attributes = MemberAttributes.Public;
method.Name = "SetAttributeValue";
method.Parameters.Add(new CodeParameterDeclarationExpression(
typeof(String), "name" ));
method.Parameters.Add(new CodeParameterDeclarationExpression(
typeof(Object), "value" ));
CodeArgumentReferenceExpression nameArgument =
new CodeArgumentReferenceExpression("name");
CodeArgumentReferenceExpression valueArgument =
new CodeArgumentReferenceExpression("value");
CodeThisReferenceExpression thisRef =
new CodeThisReferenceExpression();
foreach(ManagementAttribute attribute in info.Attributes)
{
CodeConditionStatement stmt = new CodeConditionStatement();
stmt.Condition =
new CodeMethodInvokeExpression(nameArgument, "Equals",
new CodeSnippetExpression("\"" + attribute.Name + "\""));
PropertyInfo property = resolver.GetProperty(attribute.Name);
if (!property.CanWrite)
{
// TODO: Adds throw
continue;
}
CodeAssignStatement assignStatement = new CodeAssignStatement();
assignStatement.Left =
new CodePropertyReferenceExpression(
new CodeFieldReferenceExpression(thisRef, "instance"), attribute.Name );
assignStatement.Right =
new CodeCastExpression( property.PropertyType,
new CodeArgumentReferenceExpression("value") );
stmt.TrueStatements.Add( assignStatement );
method.Statements.Add(stmt);
}
typeDefinition.Members.Add( method );
}
private void BuildInvokeMethod(CodeTypeDeclaration typeDefinition)
{
CodeMemberMethod method = new CodeMemberMethod();
method.Attributes = MemberAttributes.Public;
method.Name = "Invoke";
method.ReturnType = new CodeTypeReference( typeof(Object) );
method.Parameters.Add(new CodeParameterDeclarationExpression(
typeof(String), "action" ));
method.Parameters.Add(new CodeParameterDeclarationExpression(
typeof(Object[]), "args" ));
method.Parameters.Add(new CodeParameterDeclarationExpression(
typeof(Type[]), "sign" ));
// TODO: Statement to check if action is null
CodeArgumentReferenceExpression actionArgument =
new CodeArgumentReferenceExpression("action");
CodeThisReferenceExpression thisRef =
new CodeThisReferenceExpression();
foreach(MethodInfo methodInfo in resolver.Methods)
{
CodeConditionStatement stmt = new CodeConditionStatement();
stmt.Condition =
new CodeMethodInvokeExpression(actionArgument, "Equals",
new CodeSnippetExpression("\"" + methodInfo.Name + "\""));
CodeMethodInvokeExpression methodInv =
new CodeMethodInvokeExpression(
new CodeFieldReferenceExpression(thisRef, "instance"), methodInfo.Name);
int index = 0;
foreach(ParameterInfo parameter in methodInfo.GetParameters())
{
CodeVariableReferenceExpression varExp =
new CodeVariableReferenceExpression("args[" + index++ + "]");
CodeCastExpression castExp = new CodeCastExpression(
parameter.ParameterType,
varExp);
methodInv.Parameters.Add(castExp);
}
if (methodInfo.ReturnType != typeof(void))
{
CodeMethodReturnStatement retStmt = new CodeMethodReturnStatement(methodInv);
stmt.TrueStatements.Add(retStmt);
}
else
{
stmt.TrueStatements.Add(methodInv);
}
method.Statements.Add(stmt);
}
CodeMethodReturnStatement returnStmt = new CodeMethodReturnStatement();
returnStmt.Expression = new CodeSnippetExpression("null");
method.Statements.Add(returnStmt);
typeDefinition.Members.Add( method );
}
}
}
| |
using System;
using System.Linq;
using Microsoft.FSharp;
using Microsoft.FSharp.Core;
using Microsoft.FSharp.Collections;
class Maine
{
static int Main()
{
// Some typical code
{
Microsoft.FSharp.Core.FSharpOption<int> x = Microsoft.FSharp.Core.FSharpOption<int>.Some(3) ;
System.Console.WriteLine("{0}",x.Value);
Microsoft.FSharp.Collections.FSharpList<int> x2 =
Microsoft.FSharp.Collections.FSharpList<int>.Cons(3, Microsoft.FSharp.Collections.FSharpList<int>.Empty);
System.Console.WriteLine("{0}",x2.Head);
}
{
FSharpList<int> x = FSharpList<int>.Cons(3,(FSharpList<int>.Empty));
Console.WriteLine("x - IsCons = {0}", x != null);
Console.WriteLine("x - IsNil = {0}", x == null);
Console.WriteLine("x.Head = {0}", x.Head);
Console.WriteLine("x.Tail = {0}", x.Tail);
Console.WriteLine("x.Tail - IsNil = {0}", x.Tail);
switch (x.Tag)
{
case FSharpList<int>.Tags.Cons:
Console.WriteLine("Cons({0},{1})", x.Head, x.Tail);
break;
case FSharpList<int>.Tags.Empty:
Console.WriteLine("[]");
break;
}
}
{
FSharpList<int> x = FSharpList<int>.Cons(3, (FSharpList<int>.Empty));
foreach (int i in x) {
Console.WriteLine("i = {0}", i);
}
}
{
FSharpList<int> myList = ListModule.OfArray(new int[] { 4, 5, 6 });
ListModule.Iterate
(FuncConvert.ToFSharpFunc((Action<int>) delegate(int i)
{ Console.WriteLine("i = {0}", i);}),
myList);
// tests op_Implicit
ListModule.Iterate<int>
((Converter<int,Unit>) delegate(int i) { Console.WriteLine("i = {0} (2nd technique)", i); return null; },
myList);
// tests op_Implicit
FSharpList<string> myList2 =
ListModule.Map
(FuncConvert.ToFSharpFunc((Converter<int,string>) delegate(int i)
{ return i.ToString() + i.ToString(); }),
myList);
// tests op_Implicit
ListModule.Iterate
(FuncConvert.ToFSharpFunc((Action<string>) delegate(string s)
{ Console.WriteLine("i after duplication = {0}", s);}),
myList2);
// tests op_Implicit
myList2 =
ListModule.Map<int,string>
((Converter<int,string>) delegate(int i) { return i.ToString() + i.ToString(); },
myList);
ListModule.Iterate<string>
(FuncConvert.ToFSharpFunc((Action<string>) delegate(string s)
{ Console.WriteLine("i after duplication (2nd technique) = {0}", s);}),
myList2);
myList2 =
ListModule.Map<int,string>
(FuncConvert.ToFSharpFunc(delegate(int i) { return i.ToString() + i.ToString(); }),
myList);
myList2 =
ListModule.Map<int,string>
(FuncConvert.FromFunc((Func<int,string>) delegate(int i) { return i.ToString() + i.ToString(); }),
myList);
ListModule.Iterate<string>(FuncConvert.ToFSharpFunc<string>(s => { Console.WriteLine("s = {0}", s);}),myList2);
ListModule.Iterate<string>(FuncConvert.FromAction<string>(s => { Console.WriteLine("s = {0}", s);}),myList2);
ListModule.Iterate<string>(FuncConvert.FromFunc<string, Microsoft.FSharp.Core.Unit>(s => null),myList2);
myList2 = ListModule.Map<int,string>(FuncConvert.ToFSharpFunc<int,string>(i => i.ToString() + i.ToString()),myList);
myList2 = ListModule.Map<int,string>(FuncConvert.FromFunc<int,string>(i => i.ToString() + i.ToString()),myList);
myList2 = ListModule.MapIndexed<int,string>(FuncConvert.FromFunc<int,int,string>((i,j) => i.ToString() + j),myList);
var trans3 = FuncConvert.FromFunc<int,int,int,int>((i,j,k) => i + j + k);
var trans4 = FuncConvert.FromFunc<int,int,int,int,int>((i,j,k,l) => i + j + k + l);
var trans5 = FuncConvert.FromFunc<int,int,int,int,int,int>((i,j,k,l,m) => i + j + k + l + m);
var action3 = FuncConvert.FromAction<int,int,int>((i,j,k) => System.Console.WriteLine("action! {0}", i + j + k));
var action4 = FuncConvert.FromAction<int,int,int,int>((i,j,k,l) => System.Console.WriteLine("action! {0}", i + j + k + l));
var action5 = FuncConvert.FromAction<int,int,int,int,int>((i,j,k,l,m) => System.Console.WriteLine("action! {0}", i + j + k + l + m));
ListModule.Iterate<string>(FuncConvert.ToFSharpFunc<string>(s => { Console.WriteLine("i after duplication (2nd technique) = {0}", s);}),myList2);
ListModule.Iterate<string>(FuncConvert.FromAction<string>(s => { Console.WriteLine("i after duplication (2nd technique) = {0}", s);}),myList2);
}
// Construct a value of each type from the library
Lib.Recd1 r1 = new Lib.Recd1(3);
Lib.Recd2 r2 = new Lib.Recd2(3, "a");
Lib.RevRecd2 rr2 = new Lib.RevRecd2("a", 3);
Lib.Recd3<string> r3 = new Lib.Recd3<string>(4, "c", null);
r3.recd3field3 = r3;
Lib.One d10a = Lib.One.One;
Lib.Int d11a = Lib.Int.NewInt(3);
Lib.IntPair ip = Lib.IntPair.NewIntPair(3, 4);
Console.WriteLine("{0}", ip.Item1);
Console.WriteLine("{0}", ip.Item2);
Lib.IntPear ip2 = Lib.IntPear.NewIntPear(3,4);
Console.WriteLine("{0}", ip2.Fst);
Console.WriteLine("{0}", ip2.Snd);
Lib.Bool b = Lib.Bool.True;
Console.WriteLine("{0}", Lib.Bool.True);
Console.WriteLine("{0}", Lib.Bool.False);
//Console.WriteLine("{0}", Lib.Bool.IsTrue(b));
//Console.WriteLine("{0}", Lib.Bool.IsFalse(b));
switch (b.Tag)
{
case Lib.Bool.Tags.True:
Console.WriteLine("True");
break;
case Lib.Bool.Tags.False:
Console.WriteLine("False");
break;
}
Lib.OptionalInt oint = Lib.OptionalInt.NewSOME(3);
Console.WriteLine("oint - IsSOME = {0}", oint != null);
Console.WriteLine("oint - IsNONE = {0}", oint == null);
Console.WriteLine("{0}", (oint as Lib.OptionalInt.SOME).Item);
switch (oint.Tag)
{
case Lib.OptionalInt.Tags.SOME:
var c = oint as Lib.OptionalInt.SOME;
Console.WriteLine("SOME({0})", c.Item);
break;
case Lib.OptionalInt.Tags.NONE:
Console.WriteLine("NONE");
break;
}
Lib.IntOption iopt = Lib.IntOption.Nothing;
Console.WriteLine("iopt - IsSomething = {0}", iopt != null);
Console.WriteLine("iopt - IsNothing = {0}", iopt == null);
switch (iopt.Tag)
{
case Lib.IntOption.Tags.Something:
Console.WriteLine("Something({0})", (iopt as Lib.IntOption.Something).Item);
break;
case Lib.IntOption.Tags.Nothing:
Console.WriteLine("Nothing");
break;
}
Lib.GenericUnion<int, string> gu1 = Lib.GenericUnion<int, string>.Nothing;
Lib.GenericUnion<int, string> gu2 = Lib.GenericUnion<int, string>.NewSomething(3, "4");
Lib.GenericUnion<int, string> gu3 = Lib.GenericUnion<int, string>.NewSomethingElse(3);
Lib.GenericUnion<int, string> gu4 = Lib.GenericUnion<int, string>.NewSomethingElseAgain(4);
//Console.WriteLine("{0}", (gu1 as Lib.GenericUnion<int,string>.Cases.Nothing));
Console.WriteLine("{0}", (gu2 as Lib.GenericUnion<int,string>.Something).Item1);
Console.WriteLine("{0}", (gu3 as Lib.GenericUnion<int,string>.SomethingElse).Item);
Console.WriteLine("{0}", (gu4 as Lib.GenericUnion<int,string>.SomethingElseAgain).Item);
switch (gu1.Tag)
{
case Lib.GenericUnion<int, string>.Tags.Nothing:
Console.WriteLine("OK");
break;
case Lib.GenericUnion<int, string>.Tags.Something:
case Lib.GenericUnion<int, string>.Tags.SomethingElse:
case Lib.GenericUnion<int, string>.Tags.SomethingElseAgain:
Console.WriteLine("NOT OK");
throw (new System.Exception("ERROR - INCORRECT CASE TAG"));
}
switch (gu2.Tag)
{
case Lib.GenericUnion<int, string>.Tags.Something:
Console.WriteLine("OK");
break;
case Lib.GenericUnion<int, string>.Tags.Nothing:
case Lib.GenericUnion<int, string>.Tags.SomethingElse:
case Lib.GenericUnion<int, string>.Tags.SomethingElseAgain:
Console.WriteLine("NOT OK");
throw (new System.Exception("ERROR - INCORRECT CASE TAG"));
}
Lib.BigUnion bu1 = Lib.BigUnion.NewA1(3);
Lib.BigUnion bu2 = Lib.BigUnion.NewA2(3);
Lib.BigUnion bu3 = Lib.BigUnion.NewA3(3);
Lib.BigUnion bu4 = Lib.BigUnion.NewA4(3);
Lib.BigUnion bu5 = Lib.BigUnion.NewA5(3);
Lib.BigUnion bu6 = Lib.BigUnion.NewA6(3);
Lib.BigUnion bu7 = Lib.BigUnion.NewA7(3);
Lib.BigUnion bu8 = Lib.BigUnion.NewA8(3);
Lib.BigUnion bu9 = Lib.BigUnion.NewA9(3);
switch (bu1.Tag)
{
case Lib.BigUnion.Tags.A1:
Console.WriteLine("OK");
break;
case Lib.BigUnion.Tags.A2:
case Lib.BigUnion.Tags.A3:
case Lib.BigUnion.Tags.A4:
case Lib.BigUnion.Tags.A5:
case Lib.BigUnion.Tags.A6:
case Lib.BigUnion.Tags.A7:
case Lib.BigUnion.Tags.A8:
case Lib.BigUnion.Tags.A9:
Console.WriteLine("NOT OK");
throw (new System.Exception("ERROR - INCORRECT CASE TAG"));
}
Lib.BigEnum be1 = Lib.BigEnum.E1;
Lib.BigEnum be2 = Lib.BigEnum.E2;
Lib.BigEnum be3 = Lib.BigEnum.E3;
Lib.BigEnum be4 = Lib.BigEnum.E4;
Lib.BigEnum be5 = Lib.BigEnum.E5;
Lib.BigEnum be6 = Lib.BigEnum.E6;
Lib.BigEnum be7 = Lib.BigEnum.E7;
Lib.BigEnum be8 = Lib.BigEnum.E8;
Lib.BigEnum be9 = Lib.BigEnum.E9;
switch (be1.Tag)
{
case Lib.BigEnum.Tags.E1:
Console.WriteLine("OK");
break;
case Lib.BigEnum.Tags.E2:
case Lib.BigEnum.Tags.E3:
case Lib.BigEnum.Tags.E4:
case Lib.BigEnum.Tags.E5:
case Lib.BigEnum.Tags.E6:
case Lib.BigEnum.Tags.E7:
case Lib.BigEnum.Tags.E8:
case Lib.BigEnum.Tags.E9:
Console.WriteLine("NOT OK");
throw (new System.Exception("ERROR - INCORRECT CASE TAG"));
}
Lib.Index d211a = Lib.Index.NewIndex_A(3);
Lib.Bool d200b = Lib.Bool.False;
Lib.OptionalInt d210b = Lib.OptionalInt.NONE;
Lib.IntOption d201b = Lib.IntOption.NewSomething(3);
Lib.Index d211b = Lib.Index.NewIndex_B(4);
/*
type discr2_0_0 = True | False
type discr2_0_1 = Nothing | Something of int
type discr2_1_0 = SOME of int | NONE
type discr2_1_1 = Index_A of int | Index_B of int
type discr3_0_0_0 = Discr3_0_0_0_A | Discr3_0_0_0_B | Discr3_0_0_0_C
type discr3_0_1_0 = Discr3_0_1_0_A | Discr3_0_1_0_B of int | Discr3_0_0_0_C
type discr3_1_0_0 = Discr3_1_0_0_A of int | Discr3_1_0_0_B | Discr3_0_0_0_C
type discr3_1_1_0 = Discr3_1_1_0_A of int | Discr3_1_1_0_B of int | Discr3_0_0_0_C
type discr3_0_0_1 = Discr3_0_0_0_A | Discr3_0_0_0_B | Discr3_0_0_0_C of string
type discr3_0_1_1 = Discr3_0_1_0_A | Discr3_0_1_0_B of int | Discr3_0_0_0_C of string
type discr3_1_0_1 = Discr3_1_0_0_A of int | Discr3_1_0_0_B | Discr3_0_0_0_C of string
type discr3_1_1_1 = Discr3_1_1_0_A of int | Discr3_1_1_0_B of int | Discr3_0_0_0_C of string
*/
// Toplevel functions *
int f_1 = Lib.f_1(1);
int f_1_1 = Lib.f_1_1(1,2);
int f_1_1_1 = Lib.f_1_1_1(1,2,3);
int f_1_1_1_1 = Lib.f_1_1_1_1(1,2,3,4);
int f_1_1_1_1_1 = Lib.f_1_1_1_1_1(1,2,3,4,5);
#if DELEGATES
int f_1_effect_1 = Lib.f_1_effect_1(1)(2);
#else
int f_1_effect_1 = Lib.f_1_effect_1(1).Invoke(2);
#endif
//let f_2 x y = x+y
//let f_3 x y z = x+y+z
//let f_4 x1 x2 x3 x4 = x1+x2+x3+x4
//let f_5 x1 x2 x3 x4 x5 = x1+x2+x3+x4+x5
// Function returning a function
//let f_1_1 x = let x = ref 1 in fun y -> !x+y+1
// Tuple value
//let tup2 = (2,3)
//let tup3 = (2,3,4)
//let tup4 = (2,3,4,5)
System.Console.WriteLine("Test Passed.");
return 0;
}
}
| |
// <copyright file="VectorTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2013 Math.NET
//
// 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.
// </copyright>
using System;
using System.Collections;
using System.Collections.Generic;
using MathNet.Numerics.Distributions;
using MathNet.Numerics.LinearAlgebra;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Double
{
/// <summary>
/// Abstract class with the common set of vector tests.
/// </summary>
public abstract partial class VectorTests
{
/// <summary>
/// Test vector values.
/// </summary>
protected readonly double[] Data = { 1, 2, 3, 4, 5 };
/// <summary>
/// Can clone a vector.
/// </summary>
[Test]
public void CanCloneVector()
{
var vector = CreateVector(Data);
var clone = vector.Clone();
Assert.AreNotSame(vector, clone);
Assert.AreEqual(vector.Count, clone.Count);
CollectionAssert.AreEqual(vector, clone);
}
#if !PORTABLE
/// <summary>
/// Can clone a vector using <c>IClonable</c> interface method.
/// </summary>
[Test]
public void CanCloneVectorUsingICloneable()
{
var vector = CreateVector(Data);
var clone = (Vector<double>)((ICloneable)vector).Clone();
Assert.AreNotSame(vector, clone);
Assert.AreEqual(vector.Count, clone.Count);
CollectionAssert.AreEqual(vector, clone);
}
#endif
/// <summary>
/// Can copy part of a vector to another vector.
/// </summary>
[Test]
public void CanCopyPartialVectorToAnother()
{
var vector = CreateVector(Data);
var other = CreateVector(Data.Length);
vector.CopySubVectorTo(other, 2, 2, 2);
Assert.AreEqual(0.0, other[0]);
Assert.AreEqual(0.0, other[1]);
Assert.AreEqual(3.0, other[2]);
Assert.AreEqual(4.0, other[3]);
Assert.AreEqual(0.0, other[4]);
}
/// <summary>
/// Can copy part of a vector to the same vector.
/// </summary>
[Test]
public void CanCopyPartialVectorToSelf()
{
var vector = CreateVector(Data);
vector.CopySubVectorTo(vector, 0, 2, 2);
Assert.AreEqual(1.0, vector[0]);
Assert.AreEqual(2.0, vector[1]);
Assert.AreEqual(1.0, vector[2]);
Assert.AreEqual(2.0, vector[3]);
Assert.AreEqual(5.0, vector[4]);
}
/// <summary>
/// Can copy a vector to another vector.
/// </summary>
[Test]
public void CanCopyVectorToAnother()
{
var vector = CreateVector(Data);
var other = CreateVector(Data.Length);
vector.CopyTo(other);
CollectionAssert.AreEqual(vector, other);
}
/// <summary>
/// Can create a matrix using instance of a vector.
/// </summary>
[Test]
public void CanCreateMatrix()
{
var vector = CreateVector(Data);
var matrix = Matrix<double>.Build.SameAs(vector, 10, 10);
Assert.AreEqual(matrix.RowCount, 10);
Assert.AreEqual(matrix.ColumnCount, 10);
}
/// <summary>
/// Can create a vector using the instance of vector.
/// </summary>
[Test]
public void CanCreateVector()
{
var expected = CreateVector(5);
var actual = Vector<double>.Build.SameAs(expected, 5);
Assert.AreEqual(expected.Storage.IsDense, actual.Storage.IsDense, "vectors are same kind.");
}
/// <summary>
/// Can enumerate over a vector.
/// </summary>
[Test]
public void CanEnumerateOverVector()
{
var vector = CreateVector(Data);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i], vector[i]);
}
}
/// <summary>
/// Can enumerate over a vector using <c>IEnumerable</c> interface.
/// </summary>
[Test]
public void CanEnumerateOverVectorUsingIEnumerable()
{
var enumerable = (IEnumerable)CreateVector(Data);
var index = 0;
foreach (var element in enumerable)
{
Assert.AreEqual(Data[index++], (double)element);
}
}
/// <summary>
/// Can equate vectors.
/// </summary>
[Test]
public void CanEquateVectors()
{
var vector1 = CreateVector(Data);
var vector2 = CreateVector(Data);
var vector3 = CreateVector(4);
Assert.IsTrue(vector1.Equals(vector1));
Assert.IsTrue(vector1.Equals(vector2));
Assert.IsFalse(vector1.Equals(vector3));
Assert.IsFalse(vector1.Equals(null));
Assert.IsFalse(vector1.Equals(2));
}
/// <summary>
/// <c>CreateVector</c> throws <c>ArgumentOutOfRangeException</c> if size is not positive.
/// </summary>
[Test]
public void SizeIsNotPositiveThrowsArgumentOutOfRangeException()
{
Assert.That(() => CreateVector(-1), Throws.TypeOf<ArgumentOutOfRangeException>());
Assert.That(() => CreateVector(0), Throws.TypeOf<ArgumentOutOfRangeException>());
}
/// <summary>
/// Can equate vectors using Object.Equals.
/// </summary>
[Test]
public void CanEquateVectorsUsingObjectEquals()
{
var vector1 = CreateVector(Data);
var vector2 = CreateVector(Data);
Assert.IsTrue(vector1.Equals((object)vector2));
}
/// <summary>
/// Can get hash code of a vector.
/// </summary>
[Test]
public void CanGetHashCode()
{
var vector = CreateVector(new double[] { 1, 2, 3, 4 });
Assert.AreEqual(vector.GetHashCode(), vector.GetHashCode());
Assert.AreEqual(vector.GetHashCode(), CreateVector(new double[] { 1, 2, 3, 4 }).GetHashCode());
Assert.AreNotEqual(vector.GetHashCode(), CreateVector(new double[] { 1 }).GetHashCode());
}
/// <summary>
/// Can enumerate over a vector using indexed enumerator.
/// </summary>
[Test]
public void CanEnumerateOverVectorUsingIndexedEnumerator()
{
var vector = CreateVector(Data);
foreach (var pair in vector.EnumerateIndexed())
{
Assert.AreEqual(Data[pair.Item1], pair.Item2);
}
}
/// <summary>
/// Can enumerate over a vector using non-zero enumerator.
/// </summary>
[Test]
public void CanEnumerateOverVectorUsingNonZeroEnumerator()
{
var vector = CreateVector(Data);
foreach (var pair in vector.EnumerateIndexed(Zeros.AllowSkip))
{
Assert.AreEqual(Data[pair.Item1], pair.Item2);
Assert.AreNotEqual(0d, pair.Item2);
}
}
/// <summary>
/// Can convert a vector to array.
/// </summary>
[Test]
public void CanConvertVectorToArray()
{
var vector = CreateVector(Data);
var array = vector.ToArray();
CollectionAssert.AreEqual(array, vector);
}
/// <summary>
/// Can convert a vector to column matrix.
/// </summary>
[Test]
public void CanConvertVectorToColumnMatrix()
{
var vector = CreateVector(Data);
var matrix = vector.ToColumnMatrix();
Assert.AreEqual(vector.Count, matrix.RowCount);
Assert.AreEqual(1, matrix.ColumnCount);
for (var i = 0; i < vector.Count; i++)
{
Assert.AreEqual(vector[i], matrix[i, 0]);
}
}
/// <summary>
/// Can convert a vector to row matrix.
/// </summary>
[Test]
public void CanConvertVectorToRowMatrix()
{
var vector = CreateVector(Data);
var matrix = vector.ToRowMatrix();
Assert.AreEqual(vector.Count, matrix.ColumnCount);
Assert.AreEqual(1, matrix.RowCount);
for (var i = 0; i < vector.Count; i++)
{
Assert.AreEqual(vector[i], matrix[0, i]);
}
}
/// <summary>
/// Can set values in vector.
/// </summary>
[Test]
public void CanSetValues()
{
var vector = CreateVector(Data);
vector.SetValues(Data);
CollectionAssert.AreEqual(vector, Data);
}
/// <summary>
/// Can get subvector from a vector.
/// </summary>
/// <param name="index">The first element to begin copying from.</param>
/// <param name="length">The number of elements to copy.</param>
[TestCase(0, 5)]
[TestCase(2, 2)]
[TestCase(1, 4)]
public void CanGetSubVector(int index, int length)
{
var vector = CreateVector(Data);
var sub = vector.SubVector(index, length);
Assert.AreEqual(length, sub.Count);
for (var i = 0; i < length; i++)
{
Assert.AreEqual(vector[i + index], sub[i]);
}
}
/// <summary>
/// Getting subvector using wrong parameters throw an exception.
/// </summary>
/// <param name="index">The first element to begin copying from.</param>
/// <param name="length">The number of elements to copy.</param>
[TestCase(6, 10)]
[TestCase(1, -10)]
public void CanGetSubVectorWithWrongValuesShouldThrowException(int index, int length)
{
var vector = CreateVector(Data);
Assert.That(() => vector.SubVector(index, length), Throws.TypeOf<ArgumentOutOfRangeException>());
}
/// <summary>
/// Can find absolute minimum value index.
/// </summary>
[Test]
public void CanFindAbsoluteMinimumIndex()
{
var source = CreateVector(Data);
const int Expected = 0;
var actual = source.AbsoluteMinimumIndex();
Assert.AreEqual(Expected, actual);
}
/// <summary>
/// Can find absolute minimum value of a vector.
/// </summary>
[Test]
public void CanFindAbsoluteMinimum()
{
var source = CreateVector(Data);
const double Expected = 1;
var actual = source.AbsoluteMinimum();
Assert.AreEqual(Expected, actual);
}
/// <summary>
/// Can find absolute maximum value index.
/// </summary>
[Test]
public void CanFindAbsoluteMaximumIndex()
{
var source = CreateVector(Data);
const int Expected = 4;
var actual = source.AbsoluteMaximumIndex();
Assert.AreEqual(Expected, actual);
}
/// <summary>
/// Can find absolute maximum value of a vector.
/// </summary>
[Test]
public void CanFindAbsoluteMaximum()
{
var source = CreateVector(Data);
const double Expected = 5;
var actual = source.AbsoluteMaximum();
Assert.AreEqual(Expected, actual);
}
/// <summary>
/// Can find maximum value index.
/// </summary>
[Test]
public void CanFindMaximumIndex()
{
var vector = CreateVector(Data);
const int Expected = 4;
var actual = vector.MaximumIndex();
Assert.AreEqual(Expected, actual);
}
/// <summary>
/// Can find maximum value of a vector.
/// </summary>
[Test]
public void CanFindMaximum()
{
var vector = CreateVector(Data);
const double Expected = 5;
var actual = vector.Maximum();
Assert.AreEqual(Expected, actual);
}
/// <summary>
/// Can find minimum value index.
/// </summary>
[Test]
public void CanFindMinimumIndex()
{
var vector = CreateVector(Data);
const int Expected = 0;
var actual = vector.MinimumIndex();
Assert.AreEqual(Expected, actual);
}
/// <summary>
/// Can find minimum value of a vector.
/// </summary>
[Test]
public void CanFindMinimum()
{
var vector = CreateVector(Data);
const double Expected = 1;
var actual = vector.Minimum();
Assert.AreEqual(Expected, actual);
}
/// <summary>
/// Can compute the sum of a vector elements.
/// </summary>
[Test]
public void CanSum()
{
double[] testData = { -20, -10, 10, 20, 30 };
var vector = CreateVector(testData);
var actual = vector.Sum();
const double Expected = 30;
Assert.AreEqual(Expected, actual);
}
/// <summary>
/// Can compute the sum of the absolute value a vector elements.
/// </summary>
[Test]
public void CanSumMagnitudes()
{
double[] testData = { -20, -10, 10, 20, 30 };
var vector = CreateVector(testData);
var actual = vector.SumMagnitudes();
const double Expected = 90;
Assert.AreEqual(Expected, actual);
}
/// <summary>
/// Set values with <c>null</c> parameter throw exception.
/// </summary>
[Test]
public void SetValuesWithNullParameterThrowsArgumentException()
{
var vector = CreateVector(Data);
Assert.That(() => vector.SetValues(null), Throws.TypeOf<ArgumentNullException>());
}
/// <summary>
/// Set values with non-equal data length throw exception.
/// </summary>
[Test]
public void SetValuesWithNonEqualDataLengthThrowsArgumentException()
{
var vector = CreateVector(Data.Length + 2);
Assert.That(() => vector.SetValues(Data), Throws.TypeOf<ArgumentOutOfRangeException>());
}
/// <summary>
/// Generate a vector with number of elements less than zero throw an exception.
/// </summary>
[Test]
public void RandomWithNumberOfElementsLessThanZeroThrowsArgumentException()
{
Assert.That(() => Vector<double>.Build.Random(-2, new ContinuousUniform()), Throws.TypeOf<ArgumentOutOfRangeException>());
}
/// <summary>
/// Can clear a vector.
/// </summary>
[Test]
public void CanClearVector()
{
double[] testData = { -20, -10, 10, 20, 30 };
var vector = CreateVector(testData);
vector.Clear();
foreach (var element in vector)
{
Assert.AreEqual(0.0, element);
}
}
/// <summary>
/// Creates a new instance of the Vector class.
/// </summary>
/// <param name="size">The size of the <strong>Vector</strong> to construct.</param>
/// <returns>The new <c>Vector</c>.</returns>
protected abstract Vector<double> CreateVector(int size);
/// <summary>
/// Creates a new instance of the Vector class.
/// </summary>
/// <param name="data">The array to create this vector from.</param>
/// <returns>The new <c>Vector</c>.</returns>
protected abstract Vector<double> CreateVector(IList<double> data);
}
}
| |
// Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Threading;
using JetBrains.Annotations;
using NodaTime.Calendars;
using NodaTime.Properties;
using NodaTime.Text;
using NodaTime.Text.Patterns;
using NodaTime.TimeZones;
using NodaTime.Utility;
namespace NodaTime.Globalization
{
/// <summary>
/// A <see cref="IFormatProvider"/> for Noda Time types, initialised from a <see cref="CultureInfo"/>.
/// This provides a single place defining how NodaTime values are formatted and displayed, depending on the culture.
/// </summary>
/// <remarks>
/// Currently this is "shallow-immutable" - although none of these properties can be changed, the
/// CultureInfo itself may be mutable. In the future we will make this fully immutable.
/// </remarks>
/// <threadsafety>Instances which use read-only CultureInfo instances are immutable,
/// and may be used freely between threads. Instances with mutable cultures should not be shared between threads
/// without external synchronization.
/// See the thread safety section of the user guide for more information.</threadsafety>
internal sealed class NodaFormatInfo
{
// Names that we can use to check for broken Mono behaviour.
// The cloning is *also* to work around a Mono bug, where even read-only cultures can change...
// See http://bugzilla.xamarin.com/show_bug.cgi?id=3279
private static readonly string[] ShortInvariantMonthNames = (string[]) CultureInfo.InvariantCulture.DateTimeFormat.AbbreviatedMonthNames.Clone();
private static readonly string[] LongInvariantMonthNames = (string[]) CultureInfo.InvariantCulture.DateTimeFormat.MonthNames.Clone();
#region Patterns
private readonly object fieldLock = new object();
private FixedFormatInfoPatternParser<Duration> durationPatternParser;
private FixedFormatInfoPatternParser<Offset> offsetPatternParser;
private FixedFormatInfoPatternParser<Instant> instantPatternParser;
private FixedFormatInfoPatternParser<LocalTime> localTimePatternParser;
private FixedFormatInfoPatternParser<LocalDate> localDatePatternParser;
private FixedFormatInfoPatternParser<LocalDateTime> localDateTimePatternParser;
private FixedFormatInfoPatternParser<OffsetDateTime> offsetDateTimePatternParser;
private FixedFormatInfoPatternParser<ZonedDateTime> zonedDateTimePatternParser;
#endregion
/// <summary>
/// A NodaFormatInfo wrapping the invariant culture.
/// </summary>
// Note: this must occur below the pattern parsers, to make type initialization work...
public static readonly NodaFormatInfo InvariantInfo = new NodaFormatInfo(CultureInfo.InvariantCulture);
// Justification for max size: CultureInfo.GetCultures(CultureTypes.AllCultures) returns 378 cultures
// on Windows 8 in mid-2013. 500 should be ample, without being enormous.
private static readonly Cache<CultureInfo, NodaFormatInfo> Cache = new Cache<CultureInfo, NodaFormatInfo>
(500, culture => new NodaFormatInfo(culture), new ReferenceEqualityComparer<CultureInfo>());
#if PCL
private readonly string dateSeparator;
private readonly string timeSeparator;
#endif
private IList<string> longMonthNames;
private IList<string> longMonthGenitiveNames;
private IList<string> longDayNames;
private IList<string> shortMonthNames;
private IList<string> shortMonthGenitiveNames;
private IList<string> shortDayNames;
private readonly Dictionary<Era, EraDescription> eraDescriptions;
/// <summary>
/// Initializes a new instance of the <see cref="NodaFormatInfo" /> class.
/// </summary>
/// <param name="cultureInfo">The culture info to base this on.</param>
internal NodaFormatInfo([NotNull] CultureInfo cultureInfo)
{
Preconditions.CheckNotNull(cultureInfo, nameof(cultureInfo));
this.CultureInfo = cultureInfo;
eraDescriptions = new Dictionary<Era, EraDescription>();
#if PCL
// Horrible, but it does the job...
dateSeparator = DateTime.MinValue.ToString("%/", cultureInfo);
timeSeparator = DateTime.MinValue.ToString("%:", cultureInfo);
#endif
}
private void EnsureMonthsInitialized()
{
lock (fieldLock)
{
if (longMonthNames != null)
{
return;
}
// Turn month names into 1-based read-only lists
longMonthNames = ConvertMonthArray(CultureInfo.DateTimeFormat.MonthNames);
shortMonthNames = ConvertMonthArray(CultureInfo.DateTimeFormat.AbbreviatedMonthNames);
longMonthGenitiveNames = ConvertGenitiveMonthArray(longMonthNames, CultureInfo.DateTimeFormat.MonthGenitiveNames, LongInvariantMonthNames);
shortMonthGenitiveNames = ConvertGenitiveMonthArray(shortMonthNames, CultureInfo.DateTimeFormat.AbbreviatedMonthGenitiveNames, ShortInvariantMonthNames);
}
}
/// <summary>
/// The BCL returns arrays of month names starting at 0; we want a read-only list starting at 1 (with 0 as null).
/// </summary>
private static IList<string> ConvertMonthArray(string[] monthNames)
{
List<string> list = new List<string>(monthNames);
list.Insert(0, null);
return new ReadOnlyCollection<string>(list);
}
private void EnsureDaysInitialized()
{
lock (fieldLock)
{
if (longDayNames != null)
{
return;
}
longDayNames = ConvertDayArray(CultureInfo.DateTimeFormat.DayNames);
shortDayNames = ConvertDayArray(CultureInfo.DateTimeFormat.AbbreviatedDayNames);
}
}
/// <summary>
/// The BCL returns arrays of week names starting at 0 as Sunday; we want a read-only list starting at 1 (with 0 as null)
/// and with 7 as Sunday.
/// </summary>
private static IList<string> ConvertDayArray(string[] dayNames)
{
List<string> list = new List<string>(dayNames);
list.Add(dayNames[0]);
list[0] = null;
return new ReadOnlyCollection<string>(list);
}
/// <summary>
/// Checks whether any of the genitive names differ from the non-genitive names, and returns
/// either a reference to the non-genitive names or a converted list as per ConvertMonthArray.
/// </summary>
/// <remarks>
/// <para>
/// Mono uses the invariant month names for the genitive month names by default, so we'll assume that
/// if we see an invariant name, that *isn't* deliberately a genitive month name. A non-invariant culture
/// which decided to have genitive month names exactly matching the invariant ones would be distinctly odd.
/// See http://bugzilla.xamarin.com/show_bug.cgi?id=3278 for more details and progress.
/// </para>
/// <para>
/// Mono 3.0.6 has an exciting and different bug, where all the abbreviated genitive month names are just numbers ("1" etc).
/// So again, if we detect that, we'll go back to the non-genitive version.
/// See http://bugzilla.xamarin.com/show_bug.cgi?id=11361 for more details and progress.
/// </para>
/// </remarks>
private IList<string> ConvertGenitiveMonthArray(IList<string> nonGenitiveNames, string[] bclNames, string[] invariantNames)
{
int ignored;
if (int.TryParse(bclNames[0], out ignored))
{
return nonGenitiveNames;
}
for (int i = 0; i < bclNames.Length; i++)
{
if (bclNames[i] != nonGenitiveNames[i + 1] && bclNames[i] != invariantNames[i])
{
return ConvertMonthArray(bclNames);
}
}
return nonGenitiveNames;
}
/// <summary>
/// Gets the culture info associated with this format provider.
/// </summary>
public CultureInfo CultureInfo { get; }
/// <summary>
/// Gets the text comparison information associated with this format provider.
/// </summary>
public CompareInfo CompareInfo => CultureInfo.CompareInfo;
internal FixedFormatInfoPatternParser<Duration> DurationPatternParser => EnsureFixedFormatInitialized(ref durationPatternParser, () => new DurationPatternParser());
internal FixedFormatInfoPatternParser<Offset> OffsetPatternParser => EnsureFixedFormatInitialized(ref offsetPatternParser, () => new OffsetPatternParser());
internal FixedFormatInfoPatternParser<Instant> InstantPatternParser => EnsureFixedFormatInitialized(ref instantPatternParser, () => new InstantPatternParser());
internal FixedFormatInfoPatternParser<LocalTime> LocalTimePatternParser => EnsureFixedFormatInitialized(ref localTimePatternParser, () => new LocalTimePatternParser(LocalTime.Midnight));
internal FixedFormatInfoPatternParser<LocalDate> LocalDatePatternParser => EnsureFixedFormatInitialized(ref localDatePatternParser, () => new LocalDatePatternParser(LocalDatePattern.DefaultTemplateValue));
internal FixedFormatInfoPatternParser<LocalDateTime> LocalDateTimePatternParser => EnsureFixedFormatInitialized(ref localDateTimePatternParser, () => new LocalDateTimePatternParser(LocalDateTimePattern.DefaultTemplateValue));
internal FixedFormatInfoPatternParser<OffsetDateTime> OffsetDateTimePatternParser => EnsureFixedFormatInitialized(ref offsetDateTimePatternParser, () => new OffsetDateTimePatternParser(OffsetDateTimePattern.DefaultTemplateValue));
internal FixedFormatInfoPatternParser<ZonedDateTime> ZonedDateTimePatternParser => EnsureFixedFormatInitialized(ref zonedDateTimePatternParser, () => new ZonedDateTimePatternParser(ZonedDateTimePattern.DefaultTemplateValue, Resolvers.StrictResolver, null));
private FixedFormatInfoPatternParser<T> EnsureFixedFormatInitialized<T>(ref FixedFormatInfoPatternParser<T> field,
Func<IPatternParser<T>> patternParserFactory)
{
lock (fieldLock)
{
if (field == null)
{
field = new FixedFormatInfoPatternParser<T>(patternParserFactory(), this);
}
return field;
}
}
/// <summary>
/// Returns a read-only list of the names of the months for the default calendar for this culture.
/// See the usage guide for caveats around the use of these names for other calendars.
/// Element 0 of the list is null, to allow a more natural mapping from (say) 1 to the string "January".
/// </summary>
public IList<string> LongMonthNames { get { EnsureMonthsInitialized(); return longMonthNames; } }
/// <summary>
/// Returns a read-only list of the abbreviated names of the months for the default calendar for this culture.
/// See the usage guide for caveats around the use of these names for other calendars.
/// Element 0 of the list is null, to allow a more natural mapping from (say) 1 to the string "Jan".
/// </summary>
public IList<string> ShortMonthNames { get { EnsureMonthsInitialized(); return shortMonthNames; } }
/// <summary>
/// Returns a read-only list of the names of the months for the default calendar for this culture.
/// See the usage guide for caveats around the use of these names for other calendars.
/// Element 0 of the list is null, to allow a more natural mapping from (say) 1 to the string "January".
/// The genitive form is used for month text where the day of month also appears in the pattern.
/// If the culture does not use genitive month names, this property will return the same reference as
/// <see cref="LongMonthNames"/>.
/// </summary>
public IList<string> LongMonthGenitiveNames { get { EnsureMonthsInitialized(); return longMonthGenitiveNames; } }
/// <summary>
/// Returns a read-only list of the abbreviated names of the months for the default calendar for this culture.
/// See the usage guide for caveats around the use of these names for other calendars.
/// Element 0 of the list is null, to allow a more natural mapping from (say) 1 to the string "Jan".
/// The genitive form is used for month text where the day also appears in the pattern.
/// If the culture does not use genitive month names, this property will return the same reference as
/// <see cref="ShortMonthNames"/>.
/// </summary>
public IList<string> ShortMonthGenitiveNames { get { EnsureMonthsInitialized(); return shortMonthGenitiveNames; } }
/// <summary>
/// Returns a read-only list of the names of the days of the week for the default calendar for this culture.
/// See the usage guide for caveats around the use of these names for other calendars.
/// Element 0 of the list is null, and the other elements correspond with the index values returned from
/// <see cref="LocalDateTime.DayOfWeek"/> and similar properties.
/// </summary>
public IList<string> LongDayNames { get { EnsureDaysInitialized(); return longDayNames; } }
/// <summary>
/// Returns a read-only list of the abbreviated names of the days of the week for the default calendar for this culture.
/// See the usage guide for caveats around the use of these names for other calendars.
/// Element 0 of the list is null, and the other elements correspond with the index values returned from
/// <see cref="LocalDateTime.DayOfWeek"/> and similar properties.
/// </summary>
public IList<string> ShortDayNames { get { EnsureDaysInitialized(); return shortDayNames; } }
/// <summary>
/// Gets the number format associated with this formatting information.
/// </summary>
public NumberFormatInfo NumberFormat => CultureInfo.NumberFormat;
/// <summary>
/// Gets the BCL date time format associated with this formatting information.
/// </summary>
public DateTimeFormatInfo DateTimeFormat => CultureInfo.DateTimeFormat;
/// <summary>
/// Gets the positive sign.
/// </summary>
public string PositiveSign => NumberFormat.PositiveSign;
/// <summary>
/// Gets the negative sign.
/// </summary>
public string NegativeSign => NumberFormat.NegativeSign;
#if PCL
/// <summary>
/// Gets the time separator.
/// </summary>
public string TimeSeparator => timeSeparator;
/// <summary>
/// Gets the date separator.
/// </summary>
public string DateSeparator => dateSeparator;
#else
/// <summary>
/// Gets the time separator.
/// </summary>
public string TimeSeparator => DateTimeFormat.TimeSeparator;
/// <summary>
/// Gets the date separator.
/// </summary>
public string DateSeparator => DateTimeFormat.DateSeparator;
#endif
/// <summary>
/// Gets the AM designator.
/// </summary>
public string AMDesignator => DateTimeFormat.AMDesignator;
/// <summary>
/// Gets the PM designator.
/// </summary>
public string PMDesignator => DateTimeFormat.PMDesignator;
/// <summary>
/// Returns the names for the given era in this culture.
/// </summary>
/// <param name="era">The era to find the names of.</param>
/// <returns>A read-only list of names for the given era, or an empty list if
/// the era is not known in this culture.</returns>
public IList<string> GetEraNames([NotNull] Era era)
{
Preconditions.CheckNotNull(era, nameof(era));
return GetEraDescription(era).AllNames;
}
/// <summary>
/// Returns the primary name for the given era in this culture.
/// </summary>
/// <param name="era">The era to find the primary name of.</param>
/// <returns>The primary name for the given era, or an empty string if the era name is not known.</returns>
public string GetEraPrimaryName([NotNull] Era era)
{
Preconditions.CheckNotNull(era, nameof(era));
return GetEraDescription(era).PrimaryName;
}
private EraDescription GetEraDescription(Era era)
{
lock (eraDescriptions)
{
EraDescription ret;
if (!eraDescriptions.TryGetValue(era, out ret))
{
ret = EraDescription.ForEra(era, CultureInfo);
eraDescriptions[era] = ret;
}
return ret;
}
}
/// <summary>
/// Gets the <see cref="NodaFormatInfo" /> object for the current thread.
/// </summary>
public static NodaFormatInfo CurrentInfo => GetInstance(Thread.CurrentThread.CurrentCulture);
/// <summary>
/// Gets the <see cref="Offset" /> "L" pattern.
/// </summary>
public string OffsetPatternLong => PatternResources.ResourceManager.GetString("OffsetPatternLong", CultureInfo);
/// <summary>
/// Gets the <see cref="Offset" /> "M" pattern.
/// </summary>
public string OffsetPatternMedium => PatternResources.ResourceManager.GetString("OffsetPatternMedium", CultureInfo);
/// <summary>
/// Gets the <see cref="Offset" /> "S" pattern.
/// </summary>
public string OffsetPatternShort => PatternResources.ResourceManager.GetString("OffsetPatternShort", CultureInfo);
/// <summary>
/// Clears the cache. Only used for test purposes.
/// </summary>
internal static void ClearCache() => Cache.Clear();
/// <summary>
/// Gets the <see cref="NodaFormatInfo" /> for the given <see cref="CultureInfo" />.
/// </summary>
/// <remarks>
/// This method maintains a cache of results for read-only cultures.
/// </remarks>
/// <param name="cultureInfo">The culture info.</param>
/// <returns>The <see cref="NodaFormatInfo" />. Will never be null.</returns>
internal static NodaFormatInfo GetFormatInfo([NotNull] CultureInfo cultureInfo)
{
Preconditions.CheckNotNull(cultureInfo, nameof(cultureInfo));
if (cultureInfo == CultureInfo.InvariantCulture)
{
return InvariantInfo;
}
// Never cache (or consult the cache) for non-read-only cultures.
if (!cultureInfo.IsReadOnly)
{
return new NodaFormatInfo(cultureInfo);
}
return Cache.GetOrAdd(cultureInfo);
}
/// <summary>
/// Gets the <see cref="NodaFormatInfo" /> for the given <see cref="IFormatProvider" />. If the
/// format provider is null or if it does not provide a <see cref="NodaFormatInfo" />
/// object then the format object for the current thread is returned.
/// </summary>
/// <param name="provider">The <see cref="IFormatProvider" />.</param>
/// <returns>The <see cref="NodaFormatInfo" />. Will never be null.</returns>
public static NodaFormatInfo GetInstance(IFormatProvider provider)
{
if (provider != null)
{
var cultureInfo = provider as CultureInfo;
if (cultureInfo != null)
{
return GetFormatInfo(cultureInfo);
}
}
return GetInstance(CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
public override string ToString() => "NodaFormatInfo[" + CultureInfo.Name + "]";
/// <summary>
/// The description for an era: the primary name and all possible names.
/// </summary>
private class EraDescription
{
internal string PrimaryName { get; }
internal ReadOnlyCollection<string> AllNames { get; }
private EraDescription(string primaryName, ReadOnlyCollection<string> allNames)
{
this.PrimaryName = primaryName;
this.AllNames = allNames;
}
internal static EraDescription ForEra(Era era, CultureInfo cultureInfo)
{
string pipeDelimited = PatternResources.ResourceManager.GetString(era.ResourceIdentifier, cultureInfo);
string primaryName;
string[] allNames;
if (pipeDelimited == null)
{
allNames = new string[0];
primaryName = "";
}
else
{
allNames = pipeDelimited.Split('|');
primaryName = allNames[0];
// Order by length, descending to avoid early out (e.g. parsing BCE as BC and then having a spare E)
Array.Sort(allNames, (x, y) => y.Length.CompareTo(x.Length));
}
return new EraDescription(primaryName, new ReadOnlyCollection<string>(allNames));
}
}
}
}
| |
/**
* StoryGraph.cs
* Author: Gabriel Parrott
*/
using System.Collections.Generic;
using UnityEngine;
public class StoryGraph<NodeType>
{
private List<int[]> _adjacencyLists = new List<int[]>();
private NodeType[] _data = new NodeType[Size];
private NodeType _current;
public int DataIndex { get; private set; }
public const int Size = 12;
public StoryGraph()
{
SetupGraph();
}
public NodeType GetCurrent()
{
return _current;
}
public int GetIndex(NodeType node)
{
int i = 0;
foreach (var n in _data)
{
if (n.Equals(node))
{
return i;
}
i += 1;
}
return -1;
}
public void SetCurrent(NodeType next)
{
_current = next;
int i = 0;
foreach (var node in _data)
{
if (_data.Equals(next))
{
DataIndex = i;
break;
}
i += 1;
}
}
public void SetCurrent(int index)
{
_current = _data[index];
DataIndex = index;
}
public bool AddVertexData(NodeType data, int index)
{
if (index < 0 || index >= 12)
{
Debug.Log("StoryGraph warning: Calling AddVertexData() with invalid index. This script will break and this function will return false");
return false;
}
_data[index] = data;
return true;
}
public List<NodeType> Choices(int index)
{
if (index < 0 || index >= 12)
{
Debug.Log("StoryGraph warning: Calling Choices() with invalid index. This script will break and this function will return null");
return null;
}
var r = new List<NodeType>();
if (_adjacencyLists[index] == null)
{
return null;
}
foreach (var i in _adjacencyLists[index])
{
r.Add(_data[AsIndex(i)]);
}
return r;
}
public List<NodeType> Choices()
{
return Choices(CurrentIndex());
}
public int CurrentIndex()
{
for (int i = 0; i < _data.Length; i += 1)
{
if (_data[i].Equals(_current))
{
return i;
}
}
Debug.Log("StoryGraph Warning: In CurrentIndex(), could not find the index of the current node. Be careful");
return -1;
}
public bool IsTerminal(int index)
{
if (index < 0 || index >= _adjacencyLists.Count)
{
Debug.Log("StoryGraph Warning: Calling IsTerminal() with invalid index parameter. This script will break");
return false;
}
return _adjacencyLists[index] == null;
}
private int AsIndex(int i)
{
return i - 1;
}
// setup the adjacency lists
private void SetupGraph()
{
// 1 connects to 3 and 6
_adjacencyLists.Add(new int[2]);
// 2 connects to 4 and 9
_adjacencyLists.Add(new int[2]);
// 3 connects to 5
_adjacencyLists.Add(new int[1]);
// 4 connects to 5 and 7
_adjacencyLists.Add(new int[2]);
// 5 connects to 6 and 7
_adjacencyLists.Add(new int[2]);
// 6 connects to 8 and 11
_adjacencyLists.Add(new int[2]);
// 7 is a terminal node
_adjacencyLists.Add(new int[2]);
// 8 connects to 10 and 12
_adjacencyLists.Add(new int[2]);
// 9 is a terminal node
_adjacencyLists.Add(new int[2]);
// 10 is a terminal node
_adjacencyLists.Add(new int[2]);
// 11 connects to 2
_adjacencyLists.Add(new int[1]);
// 12 connects to 1
_adjacencyLists.Add(new int[1]);
_adjacencyLists[0][0] = 3;
_adjacencyLists[0][1] = 6;
_adjacencyLists[1][0] = 4;
_adjacencyLists[1][1] = 9;
_adjacencyLists[2][0] = 5;
_adjacencyLists[3][0] = 5;
_adjacencyLists[3][1] = 7;
_adjacencyLists[4][0] = 6;
_adjacencyLists[4][1] = 7;
_adjacencyLists[5][0] = 8;
_adjacencyLists[5][1] = 11;
_adjacencyLists[6][0] = 1;
_adjacencyLists[6][1] = 2;
_adjacencyLists[7][0] = 10;
_adjacencyLists[7][1] = 12;
_adjacencyLists[8][0] = 2;
_adjacencyLists[8][1] = 3;
_adjacencyLists[9][0] = 5;
_adjacencyLists[9][1] = 7;
_adjacencyLists[10][0] = 2;
_adjacencyLists[11][0] = 1;
}
}
| |
// Graph Engine
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using Trinity;
using Trinity.Network;
using Trinity.Network.Sockets;
using Trinity.Diagnostics;
using Trinity.Network.Http;
using Trinity.Storage;
using System.Runtime.CompilerServices;
using System.Globalization;
using Trinity.Network.Messaging;
using System.Diagnostics;
namespace Trinity.Network
{
/// <summary>
/// Represents a Trinity instance that can be started and perform two-way communication with other instances.
/// </summary>
public abstract class CommunicationInstance : CommunicationProtocolGroup
{
#region Fields
private TrinityHttpServer m_HttpServer = null;
private Dictionary<string, CommunicationModule> m_CommunicationModules = new Dictionary<string, CommunicationModule>();
private ushort m_SynReqIdOffset;
private ushort m_SynReqRspIdOffset;
private ushort m_AsynReqIdOffset;
private ushort m_AsynReqRspIdOffset;
private MemoryCloud memory_cloud;
private bool m_started = false;
// XXX ThreadStatic does not work well with async/await. Find a solution.
[ThreadStatic]
private static HttpListenerContext s_current_http_ctx = null;
#endregion
/// <summary>
/// Get a reference to the MemoryCloud that the current communication instance is connected to.
/// </summary>
public MemoryCloud CloudStorage
{
get
{
return memory_cloud;
}
}
/// <summary>
/// Register user-defined message handlers.
/// </summary>
protected override void RegisterMessageHandler()
{
/* Stock instance does not have additional handlers. */
}
internal sealed override CommunicationInstance GetCommunicationInstance()
{
return this;
}
internal HttpListenerContext _GetCurrentHttpListenerContext_impl()
{
if (s_current_http_ctx == null)
{
throw new InvalidOperationException("Could not get the current HttpListenerContext. It is likely that the method is called from outside an Http handler.");
}
return s_current_http_ctx;
}
private void _InitializeModules()
{
HashSet<Type> cur_types = new HashSet<Type>();
HashSet<Type> add_types = new HashSet<Type>(GetRegisteredCommunicationModuleTypes());
Type[] ctor_ptypes = new Type[] { };
object[] ctor_params = new object[] { };
ICommunicationSchema schema = this.GetCommunicationSchema();
this.SynReqIdOffset = (ushort)schema.SynReqProtocolDescriptors.Count();
this.SynReqRspIdOffset = (ushort)schema.SynReqRspProtocolDescriptors.Count();
this.AsynReqIdOffset = (ushort)schema.AsynReqProtocolDescriptors.Count();
this.AsynReqRspIdOffset = (ushort)schema.AsynReqRspProtocolDescriptors.Count();
/* TODO check circular dependency */
while (add_types.Count != 0)
{
var added_modules = add_types
.Select(type => type.GetConstructor(ctor_ptypes).Invoke(ctor_params) as CommunicationModule)
.ToList();
foreach (var t in add_types) { cur_types.Add(t); }
add_types.Clear();
foreach (var m in added_modules)
{
/* Register and initialize the module */
m_CommunicationModules[m.GetModuleName()] = m;
m.Initialize(this);
foreach (var t in m.GetRegisteredCommunicationModuleTypes())
{
if (!cur_types.Contains(t))
add_types.Add(t);
}
}
}
}
#region Http
/// <summary>
/// The handler that processes requests on the root endpoint.
/// The default handler responds with a list of available endpoints.
/// This method can be overridden for custom behaviors.
/// </summary>
/// <param name="ctx">The context object.</param>
protected override void RootHttpHandler(HttpListenerContext ctx)
{
CommonHttpHandlers.ListAvailableEndpoints(ctx, new List<string> { }, this.GetType());
}
/// <summary>
/// Dispatches an http request to a handler. The default dispatcher routes all requests to the root handler.
/// This method can be overridden for custom dispatching logic.
/// </summary>
/// <remarks>
/// This method will be overridden by TSL-generated stub classes.
/// </remarks>
/// <param name="ctx">The context object.</param>
/// <param name="handlerName">The name of the handler.</param>
/// <param name="url"></param>
protected override void DispatchHttpRequest(HttpListenerContext ctx, string handlerName, string url)
{
RootHttpHandler(ctx);
}
private void StartHttpServer()
{
try
{
int http_port = TrinityConfig.HttpPort;
if (http_port <= UInt16.MinValue || http_port > UInt16.MaxValue) { return; }
List<string> endpoints = new List<string> { string.Format(CultureInfo.InvariantCulture, "http://+:{0}/", http_port) };
m_HttpServer = new TrinityHttpServer(_HttpHandler, endpoints);
if (RunningMode == Trinity.RunningMode.Server)
m_HttpServer.SetInstanceList(TrinityConfig.Servers);
else if (RunningMode == Trinity.RunningMode.Proxy)
m_HttpServer.SetInstanceList(TrinityConfig.Proxies);
m_HttpServer.Listen();
Log.WriteLine(LogLevel.Info, "HTTP server listening on port {0}", http_port);
}
catch
{
Log.WriteLine(LogLevel.Error, "Failed to start HTTP server. HTTP endpoints are disabled.");
}
}
private void StopHttpServer()
{
if (m_HttpServer == null) return;
try
{
m_HttpServer.Dispose();
m_HttpServer = null;
Log.WriteLine(LogLevel.Info, "HTTP server stopped");
}
catch
{
Log.WriteLine(LogLevel.Error, "Failed to stop HTTP server.");
}
}
/// <summary>
/// The primary http handler that routes the request to the proper handler.
/// </summary>
private void _HttpHandler(HttpListenerContext context)
{
// Record the context into the thread-static storage
s_current_http_ctx = context;
// The raw url will be starting with "/", trimming all authority part.
var url = Uri.UnescapeDataString(context.Request.RawUrl);
var separator_idx = url.IndexOf('/', 1);
// If url is "" or "/", or "/{Service_Name}/ cannot be determined (lacking the second separator),
// it means that the request is pointing to the root endpoint.
if (url.Length < 2 || url[1] == '?' || separator_idx == -1)
{
RootHttpHandler(context);
goto cleanup;
}
var endpoint_name = url.Substring(1, separator_idx - 1);
// This request might be of the form "/{instance_id}/..."
uint instance_id;
if (UInt32.TryParse(endpoint_name, out instance_id))
{
// In this case, we relay this message to the desired instance.
m_HttpServer.RelayRequest((int)instance_id, context);
goto cleanup;
}
// This request might be of the form "/{module_name}/..."
CommunicationModule module = null;
if (m_CommunicationModules.TryGetValue(endpoint_name, out module))
{
/* Swallow the module_name part and reset the variables as if we're working on the root. */
url = url.Substring(separator_idx);
separator_idx = url.IndexOf('/', 1);
if (url.Length < 2 || url[1] == '?' || separator_idx == -1)
{
module.GetRootHttpHandler()(context);
}
else
{
endpoint_name = url.Substring(1, separator_idx - 1);
module.GetHttpRequestDispatcher()(context, endpoint_name, url.Substring(separator_idx + 1));
}
goto cleanup;
}
// Otherwise, this request should be dispatched by
DispatchHttpRequest(context, endpoint_name, url.Substring(separator_idx + 1));
cleanup:
// Erase the context as it is not being processed anymore.
s_current_http_ctx = null;
}
#endregion
internal abstract RunningMode RunningMode { get; }
#region private instance information
private IList<AvailabilityGroup> _InstanceList
{
get
{
switch (this.RunningMode)
{
case RunningMode.Server:
return TrinityConfig.Servers;
case RunningMode.Proxy:
return TrinityConfig.Proxies;
default:
throw new ArgumentOutOfRangeException();
}
}
}
#endregion
private bool HasHttpEndpoints()
{
return
(this.GetCommunicationSchema().HttpEndpointNames.Count() != 0) ||
(this.m_CommunicationModules.Values.Any(m => m.GetCommunicationSchema().HttpEndpointNames.Count() != 0));
}
/// <summary>
/// Starts a Trinity instance.
/// </summary>
[MethodImpl(MethodImplOptions.Synchronized)]
public void Start()
{
if (m_started) return;
try
{
Log.WriteLine(LogLevel.Debug, "Starting communication instance.");
var _config = TrinityConfig.CurrentClusterConfig;
_config.RunningMode = this.RunningMode;
Global.CommunicationInstance = this;
if (_InstanceList.Count == 0)
{
Log.WriteLine(LogLevel.Warning, "No distributed instances configured. Turning on local test mode.");
TrinityConfig.LocalTest = true;
}
// Initialize message handlers
MessageHandlers.Initialize();
RegisterMessageHandler();
// Initialize message passing networking
NativeNetwork.StartTrinityServer((UInt16)_config.ListeningPort);
Log.WriteLine("My IPEndPoint: " + _config.MyBoundIP + ":" + _config.ListeningPort);
// Initialize cloud storage
memory_cloud = Global.CloudStorage;
// Initialize the modules
_InitializeModules();
if (HasHttpEndpoints())
StartHttpServer();
Console.WriteLine("Working Directory: {0}", Global.MyAssemblyPath);
Console.WriteLine(_config.OutputCurrentConfig());
Console.WriteLine(TrinityConfig.OutputCurrentConfig());
m_started = true;
Log.WriteLine("{0} {1} is successfully started.", RunningMode, _config.MyInstanceId);
_RaiseStartedEvents();
}
catch (Exception ex)
{
Log.WriteLine(LogLevel.Error, "CommunicationInstance: " + ex.ToString());
}
}
/// <summary>
/// Stops a Trinity instance.
/// </summary>
[MethodImpl(MethodImplOptions.Synchronized)]
public void Stop()
{
if (!m_started) return;
try
{
Log.WriteLine(LogLevel.Debug, "Stopping communication instance.");
// TODO notify the modules
if (HasHttpEndpoints())
StopHttpServer();
// Unregister cloud storage
memory_cloud = null;
// Shutdown message passing networking
NativeNetwork.StopTrinityServer();
// Unregister communication instance
Global.CommunicationInstance = null;
var _config = TrinityConfig.CurrentClusterConfig;
m_started = false;
Log.WriteLine("{0} {1} is successfully stopped.", RunningMode, _config.MyInstanceId);
}
catch (Exception ex)
{
Log.WriteLine(LogLevel.Error, "CommunicationInstance: " + ex.ToString());
}
}
private void _RaiseStartedEvents()
{
this._RaiseStartedEvent();
foreach (var module in m_CommunicationModules.Values)
module._RaiseStartedEvent();
}
internal T _GetCommunicationModule_impl<T>() where T : CommunicationModule
{
return m_CommunicationModules.FirstOrDefault(_ => _.Value is T).Value as T;
}
internal CommunicationModule _GetCommunicationModuleByName(string moduleName)
{
CommunicationModule module = null;
m_CommunicationModules.TryGetValue(moduleName, out module);
return module;
}
#region Message id offsets
internal ushort SynReqIdOffset
{
get { return m_SynReqIdOffset; }
set { m_SynReqIdOffset = value; }
}
internal ushort SynReqRspIdOffset
{
get { return m_SynReqRspIdOffset; }
set { m_SynReqRspIdOffset = value; }
}
internal ushort AsynReqIdOffset
{
get { return m_AsynReqIdOffset; }
set { m_AsynReqIdOffset = value; }
}
internal ushort AsynReqRspIdOffset
{
get { return m_AsynReqRspIdOffset; }
set { m_AsynReqRspIdOffset = value; }
}
#endregion
/// <summary>
/// Sets the authentication schemes of the Http endpoints.
/// </summary>
/// <param name="auth_schemes">A value of <see cref="System.Net.AuthenticationSchemes"/>, specifying acceptable authentication schemes.</param>
internal void SetHttpAuthenticationSchemes(AuthenticationSchemes auth_schemes)
{
this.m_HttpServer.SetAuthenticationSchemes(auth_schemes);
}
/// <summary>
/// Occurs when an exception is not caught by a message handler.
/// </summary>
public event MessagingUnhandledExceptionEventHandler UnhandledException;
/// <summary>
/// It is guaranteed that this method does not throw exceptions.
/// When no event handlers subscribes to UnhandledException of the current running communication instance (if there is one),
/// then the default exception logging routine will be called.
/// </summary>
internal static unsafe void _RaiseUnhandledExceptionEvents(object reqArgs, MessagingUnhandledExceptionEventArgs e)
{
try
{
CommunicationInstance comm_instance = Global.CommunicationInstance;
MessagingUnhandledExceptionEventHandler exception_event_handler = null;
if (comm_instance != null) { exception_event_handler = comm_instance.UnhandledException; }
if (exception_event_handler != null)
{
exception_event_handler(reqArgs, e);
}
else
{
_LogMessageReqArgsAndException(reqArgs, e);
}
}
catch (Exception exception)
{
//The unhandled exception event handler throws exception.
//We first log the original exception down, and then explain
//how the exception handler failed.
_LogMessageReqArgsAndException(reqArgs, e);
Log.WriteLine(LogLevel.Error, "Exceptions are caught in the UnhandledException event handler.");
Log.WriteLine(LogLevel.Error, exception.Message);
Log.WriteLine(LogLevel.Error, exception.StackTrace);
}
}
private static unsafe void _LogMessageReqArgsAndException(object reqArgs, MessagingUnhandledExceptionEventArgs e)
{
Debug.Assert(reqArgs != null);
Debug.Assert(e != null && e.ExceptionObject != null && e.Buffer != null);
string message_type = "unknown message";
if (reqArgs is AsynReqArgs) { message_type = "asynchronous message"; }
if (reqArgs is SynReqArgs) { message_type = "synchronous message"; }
if (reqArgs is SynReqRspArgs) { message_type = "synchronous message (with RSP request)"; }
Log.WriteLine(LogLevel.Error, "Exceptions are caught in the handler of {0}, message sn: {1}", message_type, e.Buffer[TrinityProtocol.MsgIdOffset]);
Log.WriteLine(LogLevel.Error, e.ExceptionObject.Message);
Log.WriteLine(LogLevel.Error, e.ExceptionObject.StackTrace);
Log.WriteLine(LogLevel.Error, "Message buffer length: {0}", e.Size);
Log.WriteLine(LogLevel.Error, "Hexadecimal dump of the message buffer (first 128 bytes):");
Log.WriteLine(LogLevel.Error);
Log.WriteLine(LogLevel.Error, HexDump.ToString(e.Buffer, e.Size + TrinityProtocol.TrinityMsgHeader, 128));
Log.WriteLine(LogLevel.Error);
Log.Flush();
}
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Compute.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedInterconnectsClientTest
{
[xunit::FactAttribute]
public void GetRequestObject()
{
moq::Mock<Interconnects.InterconnectsClient> mockGrpcClient = new moq::Mock<Interconnects.InterconnectsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInterconnectRequest request = new GetInterconnectRequest
{
Interconnect = "interconnect253e8bf5",
Project = "projectaa6ff846",
};
Interconnect expectedResponse = new Interconnect
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CustomerName = "customer_name2ace137a",
NocContactEmail = "noc_contact_email1d95c1b6",
CreationTimestamp = "creation_timestamp235e59a1",
RequestedLinkCount = 2020560861,
State = Interconnect.Types.State.UndefinedState,
CircuitInfos =
{
new InterconnectCircuitInfo(),
},
OperationalStatus = Interconnect.Types.OperationalStatus.UndefinedOperationalStatus,
PeerIpAddress = "peer_ip_address07617b81",
ExpectedOutages =
{
new InterconnectOutageNotification(),
},
Location = "locatione09d18d5",
ProvisionedLinkCount = 1441690745,
Description = "description2cf9da67",
InterconnectAttachments =
{
"interconnect_attachmentsdc10a889",
},
GoogleIpAddress = "google_ip_address246d4427",
AdminEnabled = true,
SelfLink = "self_link7e87f12d",
SatisfiesPzs = false,
InterconnectType = Interconnect.Types.InterconnectType.Partner,
LinkType = Interconnect.Types.LinkType.UndefinedLinkType,
GoogleReferenceId = "google_reference_id815b6ab4",
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InterconnectsClient client = new InterconnectsClientImpl(mockGrpcClient.Object, null);
Interconnect response = client.Get(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRequestObjectAsync()
{
moq::Mock<Interconnects.InterconnectsClient> mockGrpcClient = new moq::Mock<Interconnects.InterconnectsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInterconnectRequest request = new GetInterconnectRequest
{
Interconnect = "interconnect253e8bf5",
Project = "projectaa6ff846",
};
Interconnect expectedResponse = new Interconnect
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CustomerName = "customer_name2ace137a",
NocContactEmail = "noc_contact_email1d95c1b6",
CreationTimestamp = "creation_timestamp235e59a1",
RequestedLinkCount = 2020560861,
State = Interconnect.Types.State.UndefinedState,
CircuitInfos =
{
new InterconnectCircuitInfo(),
},
OperationalStatus = Interconnect.Types.OperationalStatus.UndefinedOperationalStatus,
PeerIpAddress = "peer_ip_address07617b81",
ExpectedOutages =
{
new InterconnectOutageNotification(),
},
Location = "locatione09d18d5",
ProvisionedLinkCount = 1441690745,
Description = "description2cf9da67",
InterconnectAttachments =
{
"interconnect_attachmentsdc10a889",
},
GoogleIpAddress = "google_ip_address246d4427",
AdminEnabled = true,
SelfLink = "self_link7e87f12d",
SatisfiesPzs = false,
InterconnectType = Interconnect.Types.InterconnectType.Partner,
LinkType = Interconnect.Types.LinkType.UndefinedLinkType,
GoogleReferenceId = "google_reference_id815b6ab4",
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Interconnect>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InterconnectsClient client = new InterconnectsClientImpl(mockGrpcClient.Object, null);
Interconnect responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Interconnect responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Get()
{
moq::Mock<Interconnects.InterconnectsClient> mockGrpcClient = new moq::Mock<Interconnects.InterconnectsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInterconnectRequest request = new GetInterconnectRequest
{
Interconnect = "interconnect253e8bf5",
Project = "projectaa6ff846",
};
Interconnect expectedResponse = new Interconnect
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CustomerName = "customer_name2ace137a",
NocContactEmail = "noc_contact_email1d95c1b6",
CreationTimestamp = "creation_timestamp235e59a1",
RequestedLinkCount = 2020560861,
State = Interconnect.Types.State.UndefinedState,
CircuitInfos =
{
new InterconnectCircuitInfo(),
},
OperationalStatus = Interconnect.Types.OperationalStatus.UndefinedOperationalStatus,
PeerIpAddress = "peer_ip_address07617b81",
ExpectedOutages =
{
new InterconnectOutageNotification(),
},
Location = "locatione09d18d5",
ProvisionedLinkCount = 1441690745,
Description = "description2cf9da67",
InterconnectAttachments =
{
"interconnect_attachmentsdc10a889",
},
GoogleIpAddress = "google_ip_address246d4427",
AdminEnabled = true,
SelfLink = "self_link7e87f12d",
SatisfiesPzs = false,
InterconnectType = Interconnect.Types.InterconnectType.Partner,
LinkType = Interconnect.Types.LinkType.UndefinedLinkType,
GoogleReferenceId = "google_reference_id815b6ab4",
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InterconnectsClient client = new InterconnectsClientImpl(mockGrpcClient.Object, null);
Interconnect response = client.Get(request.Project, request.Interconnect);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAsync()
{
moq::Mock<Interconnects.InterconnectsClient> mockGrpcClient = new moq::Mock<Interconnects.InterconnectsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInterconnectRequest request = new GetInterconnectRequest
{
Interconnect = "interconnect253e8bf5",
Project = "projectaa6ff846",
};
Interconnect expectedResponse = new Interconnect
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CustomerName = "customer_name2ace137a",
NocContactEmail = "noc_contact_email1d95c1b6",
CreationTimestamp = "creation_timestamp235e59a1",
RequestedLinkCount = 2020560861,
State = Interconnect.Types.State.UndefinedState,
CircuitInfos =
{
new InterconnectCircuitInfo(),
},
OperationalStatus = Interconnect.Types.OperationalStatus.UndefinedOperationalStatus,
PeerIpAddress = "peer_ip_address07617b81",
ExpectedOutages =
{
new InterconnectOutageNotification(),
},
Location = "locatione09d18d5",
ProvisionedLinkCount = 1441690745,
Description = "description2cf9da67",
InterconnectAttachments =
{
"interconnect_attachmentsdc10a889",
},
GoogleIpAddress = "google_ip_address246d4427",
AdminEnabled = true,
SelfLink = "self_link7e87f12d",
SatisfiesPzs = false,
InterconnectType = Interconnect.Types.InterconnectType.Partner,
LinkType = Interconnect.Types.LinkType.UndefinedLinkType,
GoogleReferenceId = "google_reference_id815b6ab4",
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Interconnect>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InterconnectsClient client = new InterconnectsClientImpl(mockGrpcClient.Object, null);
Interconnect responseCallSettings = await client.GetAsync(request.Project, request.Interconnect, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Interconnect responseCancellationToken = await client.GetAsync(request.Project, request.Interconnect, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetDiagnosticsRequestObject()
{
moq::Mock<Interconnects.InterconnectsClient> mockGrpcClient = new moq::Mock<Interconnects.InterconnectsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetDiagnosticsInterconnectRequest request = new GetDiagnosticsInterconnectRequest
{
Interconnect = "interconnect253e8bf5",
Project = "projectaa6ff846",
};
InterconnectsGetDiagnosticsResponse expectedResponse = new InterconnectsGetDiagnosticsResponse
{
Result = new InterconnectDiagnostics(),
};
mockGrpcClient.Setup(x => x.GetDiagnostics(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InterconnectsClient client = new InterconnectsClientImpl(mockGrpcClient.Object, null);
InterconnectsGetDiagnosticsResponse response = client.GetDiagnostics(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetDiagnosticsRequestObjectAsync()
{
moq::Mock<Interconnects.InterconnectsClient> mockGrpcClient = new moq::Mock<Interconnects.InterconnectsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetDiagnosticsInterconnectRequest request = new GetDiagnosticsInterconnectRequest
{
Interconnect = "interconnect253e8bf5",
Project = "projectaa6ff846",
};
InterconnectsGetDiagnosticsResponse expectedResponse = new InterconnectsGetDiagnosticsResponse
{
Result = new InterconnectDiagnostics(),
};
mockGrpcClient.Setup(x => x.GetDiagnosticsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InterconnectsGetDiagnosticsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InterconnectsClient client = new InterconnectsClientImpl(mockGrpcClient.Object, null);
InterconnectsGetDiagnosticsResponse responseCallSettings = await client.GetDiagnosticsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
InterconnectsGetDiagnosticsResponse responseCancellationToken = await client.GetDiagnosticsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetDiagnostics()
{
moq::Mock<Interconnects.InterconnectsClient> mockGrpcClient = new moq::Mock<Interconnects.InterconnectsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetDiagnosticsInterconnectRequest request = new GetDiagnosticsInterconnectRequest
{
Interconnect = "interconnect253e8bf5",
Project = "projectaa6ff846",
};
InterconnectsGetDiagnosticsResponse expectedResponse = new InterconnectsGetDiagnosticsResponse
{
Result = new InterconnectDiagnostics(),
};
mockGrpcClient.Setup(x => x.GetDiagnostics(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InterconnectsClient client = new InterconnectsClientImpl(mockGrpcClient.Object, null);
InterconnectsGetDiagnosticsResponse response = client.GetDiagnostics(request.Project, request.Interconnect);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetDiagnosticsAsync()
{
moq::Mock<Interconnects.InterconnectsClient> mockGrpcClient = new moq::Mock<Interconnects.InterconnectsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetDiagnosticsInterconnectRequest request = new GetDiagnosticsInterconnectRequest
{
Interconnect = "interconnect253e8bf5",
Project = "projectaa6ff846",
};
InterconnectsGetDiagnosticsResponse expectedResponse = new InterconnectsGetDiagnosticsResponse
{
Result = new InterconnectDiagnostics(),
};
mockGrpcClient.Setup(x => x.GetDiagnosticsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InterconnectsGetDiagnosticsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InterconnectsClient client = new InterconnectsClientImpl(mockGrpcClient.Object, null);
InterconnectsGetDiagnosticsResponse responseCallSettings = await client.GetDiagnosticsAsync(request.Project, request.Interconnect, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
InterconnectsGetDiagnosticsResponse responseCancellationToken = await client.GetDiagnosticsAsync(request.Project, request.Interconnect, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
(>= (f187 (var x3)) (var x3))
(>= (f188 (var x2)) (var x2))
(>=
(f189 (var x3))
(f187 (var x3)))
(>=
(f190 (var x2) (var x3))
(+
(f15
(f188 (var x2))
(f191)
(f192 (var x2) (var x3)))
(f189 (var x3))))
(>= (f191) 0)
(>=
(f192 (var x2) (var x3))
(f190 (var x2) (var x3)))
(>=
(f193 (var x2) (var x3))
(+
(f14 (f188 (var x2)) (f191))
(f192 (var x2) (var x3))))
(>=
(f11 (var x2))
(f13 (f188 (var x2)) (f191)))
(>=
(+ (f12 (var x2)) (var x3))
(+ (f193 (var x2) (var x3)) 1))
(>= (f194 (var x8)) (var x8))
(>=
(f195 (var x8))
(f194 (var x8)))
(>= (f196 (var x10)) (var x10))
(>=
(f197 (var x8))
(f195 (var x8)))
(>= (f198 (var x83)) (var x83))
(>= (f199 (var x84)) (var x84))
(>=
(f1 (var x83) (f200 (var x10)))
(f13
(f196 (var x10))
(f198 (var x83))))
(>=
(+
(f2 (var x83) (f200 (var x10)))
(var x84))
(+
(f14
(f196 (var x10))
(f198 (var x83)))
(f199 (var x84))))
(>=
(f201
(var x8)
(var x10)
(var x83)
(var x84))
(+
(f15
(f196 (var x10))
(f198 (var x83))
(f199 (var x84)))
(f197 (var x8))))
(>=
(f202
(var x6)
(var x7)
(var x8)
(var x10)
(var x83)
(var x84)
(var x124)
(var x125))
(+
(f8
(f200 (var x10))
(f203)
(f204 (var x6))
(f205 (var x7))
(f206
(var x6)
(var x7)
(var x8)
(var x10)
(var x83)
(var x84)
(var x124)
(var x125)))
(f201
(var x8)
(var x10)
(var x83)
(var x84))))
(>=
(f207
(var x6)
(var x7)
(var x8)
(var x10)
(var x83)
(var x84)
(var x124)
(var x125))
(f202
(var x6)
(var x7)
(var x8)
(var x10)
(var x83)
(var x84)
(var x124)
(var x125)))
(>=
(f208 (var x124))
(var x124))
(>=
(f209 (var x125))
(var x125))
(>=
(f3
(f200 (var x10))
(var x124)
(f203))
(+ (f208 (var x124)) 1))
(>=
(+
(f4
(f200 (var x10))
(var x124)
(f203))
(var x125))
(f209 (var x125)))
(>=
(f206
(var x6)
(var x7)
(var x8)
(var x10)
(var x83)
(var x84)
(var x124)
(var x125))
(f207
(var x6)
(var x7)
(var x8)
(var x10)
(var x83)
(var x84)
(var x124)
(var x125)))
(>=
(f210
(var x6)
(var x7)
(var x8)
(var x10)
(var x83)
(var x84)
(var x124)
(var x125))
(+
(f7
(f200 (var x10))
(f203)
(f204 (var x6))
(f205 (var x7)))
(f206
(var x6)
(var x7)
(var x8)
(var x10)
(var x83)
(var x84)
(var x124)
(var x125))))
(>= (f204 (var x6)) (var x6))
(>= (f205 (var x7)) (var x7))
(>=
(f13 (+ (var x10) 1) (var x6))
(f5
(f200 (var x10))
(f203)
(f204 (var x6))))
(>=
(+
(f14 (+ (var x10) 1) (var x6))
(var x7))
(+
(f6
(f200 (var x10))
(f203)
(f204 (var x6)))
(f205 (var x7))))
(>=
(+
(f15
(+ (var x10) 1)
(var x6)
(var x7))
(var x8))
(+
(f210
(var x6)
(var x7)
(var x8)
(var x10)
(var x83)
(var x84)
(var x124)
(var x125))
1))
(>= (f211 (var x15)) (var x15))
(>=
(f212 (var x15))
(f211 (var x15)))
(>= (f213 (var x13)) (var x13))
(>= (f214 (var x14)) (var x14))
(>=
(f13 0 (var x13))
(f9 (f213 (var x13))))
(>=
(+ (f14 0 (var x13)) (var x14))
(+
(f10 (f213 (var x13)))
(f214 (var x14))))
(>=
(+
(f15 0 (var x13) (var x14))
(var x15))
(+ (f212 (var x15)) 1))
(>= (f215 (var x19)) (var x19))
(>= (f9 (var x18)) (var x18))
(>=
(+ (f10 (var x18)) (var x19))
(+ (f215 (var x19)) 1))
(>= (f216 (var x23)) (var x23))
(>= (f217 (var x24)) (var x24))
(>=
(f218
(var x21)
(var x22)
(var x23))
(f3
(var x21)
(f216 (var x23))
(var x22)))
(>=
(f219
(var x21)
(var x22)
(var x23)
(var x24))
(+
(f4
(var x21)
(f216 (var x23))
(var x22))
(f217 (var x24))))
(>=
(f220
(var x21)
(var x22)
(var x23)
(var x24))
(+
(f2
(f218
(var x21)
(var x22)
(var x23))
(var x21))
(f219
(var x21)
(var x22)
(var x23)
(var x24))))
(>=
(f5
(var x21)
(var x22)
(var x23))
(f1
(f218
(var x21)
(var x22)
(var x23))
(var x21)))
(>=
(+
(f6
(var x21)
(var x22)
(var x23))
(var x24))
(+
(f220
(var x21)
(var x22)
(var x23)
(var x24))
1))
| |
// Copyright (c) 2015, Outercurve Foundation.
// 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 the Outercurve Foundation 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 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.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using Microsoft.Web.Services3;
using WebsitePanel.Providers;
using WebsitePanel.Providers.OS;
using WebsitePanel.Providers.SharePoint;
using WebsitePanel.Server.Utils;
namespace WebsitePanel.Server
{
/// <summary>
/// Summary description for SharePointServer
/// </summary>
[WebService(Namespace = "http://smbsaas/websitepanel/server/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Policy("ServerPolicy")]
[ToolboxItem(false)]
public class SharePointServer : HostingServiceProviderWebService
{
private ISharePointServer SPS
{
get { return (ISharePointServer)Provider; }
}
#region Sites
[WebMethod, SoapHeader("settings")]
public void ExtendVirtualServer(SharePointSite site)
{
try
{
Log.WriteStart("'{0}' ExtendVirtualServer", ProviderSettings.ProviderName);
SPS.ExtendVirtualServer(site);
Log.WriteEnd("'{0}' ExtendVirtualServer", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("Can't ExtendVirtualServer '{0}' provider", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void UnextendVirtualServer(string url, bool deleteContent)
{
try
{
Log.WriteStart("'{0}' GetProviderProperties", ProviderSettings.ProviderName);
SPS.UnextendVirtualServer(url, deleteContent);
Log.WriteEnd("'{0}' GetProviderProperties", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("Can't GetProviderProperties '{0}' provider", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region Backup/Restore
[WebMethod, SoapHeader("settings")]
public string BackupVirtualServer(string url, string fileName, bool zipBackup)
{
try
{
Log.WriteStart("'{0}' BackupVirtualServer", ProviderSettings.ProviderName);
string result = SPS.BackupVirtualServer(url, fileName, zipBackup);
Log.WriteEnd("'{0}' BackupVirtualServer", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("Can't BackupVirtualServer '{0}' provider", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void RestoreVirtualServer(string url, string fileName)
{
try
{
Log.WriteStart("'{0}' RestoreVirtualServer", ProviderSettings.ProviderName);
SPS.RestoreVirtualServer(url, fileName);
Log.WriteEnd("'{0}' RestoreVirtualServer", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("Can't RestoreVirtualServer '{0}' provider", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public byte[] GetTempFileBinaryChunk(string path, int offset, int length)
{
try
{
Log.WriteStart("'{0}' GetTempFileBinaryChunk", ProviderSettings.ProviderName);
byte[] result = SPS.GetTempFileBinaryChunk(path, offset, length);
Log.WriteEnd("'{0}' GetTempFileBinaryChunk", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("Can't GetTempFileBinaryChunk '{0}' provider", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public string AppendTempFileBinaryChunk(string fileName, string path, byte[] chunk)
{
try
{
Log.WriteStart("'{0}' AppendTempFileBinaryChunk", ProviderSettings.ProviderName);
string result = SPS.AppendTempFileBinaryChunk(fileName, path, chunk);
Log.WriteEnd("'{0}' AppendTempFileBinaryChunk", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("Can't AppendTempFileBinaryChunk '{0}' provider", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region Web Parts
[WebMethod, SoapHeader("settings")]
public string[] GetInstalledWebParts(string url)
{
try
{
Log.WriteStart("'{0}' GetInstalledWebParts", ProviderSettings.ProviderName);
string[] result = SPS.GetInstalledWebParts(url);
Log.WriteEnd("'{0}' GetInstalledWebParts", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("Can't GetInstalledWebParts '{0}' provider", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void InstallWebPartsPackage(string url, string packageName)
{
try
{
Log.WriteStart("'{0}' InstallWebPartsPackage", ProviderSettings.ProviderName);
SPS.InstallWebPartsPackage(url, packageName);
Log.WriteEnd("'{0}' InstallWebPartsPackage", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("Can't InstallWebPartsPackage '{0}' provider", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void DeleteWebPartsPackage(string url, string packageName)
{
try
{
Log.WriteStart("'{0}' DeleteWebPartsPackage", ProviderSettings.ProviderName);
SPS.DeleteWebPartsPackage(url, packageName);
Log.WriteEnd("'{0}' DeleteWebPartsPackage", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("Can't DeleteWebPartsPackage '{0}' provider", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region Users
[WebMethod, SoapHeader("settings")]
public bool UserExists(string username)
{
try
{
Log.WriteStart("'{0}' UserExists", ProviderSettings.ProviderName);
bool result = SPS.UserExists(username);
Log.WriteEnd("'{0}' UserExists", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' UserExists", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public string[] GetUsers()
{
try
{
Log.WriteStart("'{0}' GetUsers", ProviderSettings.ProviderName);
string[] result = SPS.GetUsers();
Log.WriteEnd("'{0}' GetUsers", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetUsers", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public SystemUser GetUser(string username)
{
try
{
Log.WriteStart("'{0}' GetUser", ProviderSettings.ProviderName);
SystemUser result = SPS.GetUser(username);
Log.WriteEnd("'{0}' GetUser", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetUser", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void CreateUser(SystemUser user)
{
try
{
Log.WriteStart("'{0}' CreateUser", ProviderSettings.ProviderName);
SPS.CreateUser(user);
Log.WriteEnd("'{0}' CreateUser", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' CreateUser", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void UpdateUser(SystemUser user)
{
try
{
Log.WriteStart("'{0}' UpdateUser", ProviderSettings.ProviderName);
SPS.UpdateUser(user);
Log.WriteEnd("'{0}' UpdateUser", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' UpdateUser", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void ChangeUserPassword(string username, string password)
{
try
{
Log.WriteStart("'{0}' ChangeUserPassword", ProviderSettings.ProviderName);
SPS.ChangeUserPassword(username, password);
Log.WriteEnd("'{0}' ChangeUserPassword", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' ChangeUserPassword", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void DeleteUser(string username)
{
try
{
Log.WriteStart("'{0}' DeleteUser", ProviderSettings.ProviderName);
SPS.DeleteUser(username);
Log.WriteEnd("'{0}' DeleteUser", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' DeleteUser", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region Groups
[WebMethod, SoapHeader("settings")]
public bool GroupExists(string groupName)
{
try
{
Log.WriteStart("'{0}' GroupExists", ProviderSettings.ProviderName);
bool result = SPS.GroupExists(groupName);
Log.WriteEnd("'{0}' GroupExists", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GroupExists", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public string[] GetGroups()
{
try
{
Log.WriteStart("'{0}' GetGroups", ProviderSettings.ProviderName);
string[] result = SPS.GetGroups();
Log.WriteEnd("'{0}' GetGroups", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetGroups", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public SystemGroup GetGroup(string groupName)
{
try
{
Log.WriteStart("'{0}' GetGroup", ProviderSettings.ProviderName);
SystemGroup result = SPS.GetGroup(groupName);
Log.WriteEnd("'{0}' GetGroup", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetGroup", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void CreateGroup(SystemGroup group)
{
try
{
Log.WriteStart("'{0}' CreateGroup", ProviderSettings.ProviderName);
SPS.CreateGroup(group);
Log.WriteEnd("'{0}' CreateGroup", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' CreateGroup", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void UpdateGroup(SystemGroup group)
{
try
{
Log.WriteStart("'{0}' UpdateGroup", ProviderSettings.ProviderName);
SPS.UpdateGroup(group);
Log.WriteEnd("'{0}' UpdateGroup", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' UpdateGroup", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void DeleteGroup(string groupName)
{
try
{
Log.WriteStart("'{0}' DeleteGroup", ProviderSettings.ProviderName);
SPS.DeleteGroup(groupName);
Log.WriteEnd("'{0}' DeleteGroup", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' DeleteGroup", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
}
}
| |
using System;
using System.Text;
using System.Collections;
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
public static class ArrayExtensions {
public static bool Contains<T>(this T[] array, T element) {
for (int i = 0; i < array.Length; i++) {
if (array[i].Equals(element))
return true;
}
return false;
}
/// <summary>
/// Adds a blank space in an array at and index, moving every element after the index to make room for the space.
/// </summary>
/// <typeparam name="T">Type of the array</typeparam>
/// <param name="array">The array to add a blank space to</param>
/// <param name="position">The position of the space</param>
/// <returns>A copy of the old array, with an extra, open index in the given space</returns>
public static T[] AddSpaceInArray<T>(this T[] array, int position) {
int newLength = array.Length + 1;
T[] newArray = new T[newLength];
for (int i = 0; i < array.Length; i++) {
int otherArrayIndex = i;
if (i >= position) {
otherArrayIndex++;
}
newArray[otherArrayIndex] = array[i];
}
return newArray;
}
public static T[] AppendToArray<T>(this T[] array, T element) {
int newIndex = array.Length;
array = array.AddSpaceInArray(newIndex);
array[newIndex] = element;
return array;
}
/// <summary>
/// Removes an element from an array at the given index. Shrinks the array, moving all of the subsequent elements back
/// one space.
///
/// Can give a negative index. In that case, removes from the end, so removeFromArray(-1) means "remove last element"
/// </summary>
/// <typeparam name="T">Type of the array</typeparam>
/// <param name="array">Array to remove the element from</param>
/// <param name="index">Index to remove the element at</param>
/// <returns>A copy of the old array, with the index removed</returns>
public static T[] RemoveFromArray<T>(this T[] array, int index) {
int newLength = array.Length - 1;
T[] newArray = new T[newLength];
if (index < 0)
index = array.Length + index;
for (int i = 0; i < newLength; i++) {
int otherArrayIndex = i;
if (i >= index) {
otherArrayIndex++;
}
newArray[i] = array[otherArrayIndex];
}
return newArray;
}
public static void Swap<T>(this T[] array, int idx1, int idx2) {
T temp = array[idx1];
array[idx1] = array[idx2];
array[idx2] = temp;
}
/// <summary>
/// Finds the index of an element in an array. Looks for Equal objects,
/// which is reference equality if Equals hasn't been overridden.
/// </summary>
/// <typeparam name="T">Type of the array and element</typeparam>
/// <param name="array">Array to look in.</param>
/// <param name="element">The element to look for</param>
/// <returns>First index of element in arr. -1 if not found</returns>
public static int IndexOf<T>(this T[] array, T element) {
for (int i = 0; i < array.Length; i++) {
if (array[i].Equals(element))
return i;
}
return -1;
}
public static T[] Concatenate<T>(this T[] array, T[] otherArray) {
T[] newArr = new T[array.Length + otherArray.Length];
array.CopyTo(newArr, 0);
otherArray.CopyTo(newArr, array.Length);
return newArr;
}
/// <summary>
/// Fills an array with an element
///
/// If the element is a pointer, the array will be filled with that pointer, so you probably don't want to do
/// this with string arrays and such.
/// </summary>
public static void Populate<T>(this T[] array, T element) {
for (int i = 0; i < array.Length; i++) {
array[i] = element;
}
}
/// <summary>
/// Fills an array with the elements supplied by a function that takes the index of the array and returns the type.
///
/// To fill an int-array with it's indices (such that array[i] == i), do:
/// array.Populate(x => x);
///
/// To reverse oldArray into newArray, do:
/// newArray.Populate(x => oldArray.Length - x - 1);
///
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="array"></param>
/// <param name="populateFunc"></param>
public static void PopulateByIndexFunc<T>(this T[] array, Func<int, T> populateFunc) {
for (int i = 0; i < array.Length; i++) {
array[i] = populateFunc(i);
}
}
public static void Each<T>(this IEnumerable<T> array, Action<T> function) {
foreach (var element in array) {
function(element);
}
}
/// <summary>
/// Returns a pretty string representation of an Array. Or anything else that's IEnumerable. Like a list or whatever.
///
/// Does basic [element,element] formatting, and also does recursive calls to inner lists. You can also give it a functon to
/// do even prettier printing, usefull to get IE. a GameObject's name instead of "name (UnityEngine.GameObject)". If the function
/// isn't supplied, toString is used.
///
/// Also turns null into "null" instead of ""
///
/// Will cause a stack overflow if you put list A in list B and list B in list A, but you wouldn't do that, would you?
/// </summary>
/// <param name="array">Some array</param>
/// <param name="newLines">Set to true if the elements should be separated with a newline</param>
/// <param name="printFunc">An optional function that you can use in place of ToString</param>
/// <typeparam name="T">The type of the array</typeparam>
/// <returns>a pretty printing of the array</returns>
public static string PrettyPrint<T>(this IEnumerable<T> array, bool newLines = false, System.Func<T, string> printFunc = null) {
if (array == null)
return "null"; //won't this cause a nullpointer instead of calling this method?
StringBuilder builder = new StringBuilder();
builder.Append("[");
bool added = false;
foreach (T t in array) {
added = true;
if (t == null)
builder.Append("null");
else if (t is IEnumerable<T>)
builder.Append(((IEnumerable<T>) t).PrettyPrint());
else {
if (printFunc == null)
builder.Append(t.ToString());
else
builder.Append(printFunc(t));
}
builder.Append(newLines ? "\n " : ", ");
}
if (added) //removes the trailing ", "
builder.Remove(builder.Length - 2, 2);
builder.Append("]");
return builder.ToString();
}
public static string Join<T>(this IEnumerable<T> array, string join) {
if (array == null)
return null;
StringBuilder builder = new StringBuilder();
foreach (T t in array) {
if (t == null)
builder.Append("null");
else if (t is IEnumerable<T>)
builder.Append(((IEnumerable<T>) t).Join(join));
else
builder.Append(t.ToString());
builder.Append(join);
}
builder.Remove(builder.Length - join.Length, join.Length);
return builder.ToString();
}
public static T[] CopyArray<T>(this T[] array) {
T[] newArray = new T[array.Length];
for (int i = 0; i < array.Length; i++) {
newArray[i] = array[i];
}
return newArray;
}
public static T[,] CopyArray<T>(this T[,] array) {
T[,] newArray = new T[array.GetLength(0), array.GetLength(1)];
for (int i = 0; i < array.GetLength(0); i++) {
for (int j = 0; j < array.GetLength(1); j++) {
newArray[i, j] = array[i, j];
}
}
return newArray;
}
public static T[] CopyRow<T>(this T[,] array, int row) {
T[] rowArray = new T[array.GetLength(0)];
for (int i = 0; i < array.GetLength(0); i++) {
rowArray[i] = array[i, row];
}
return rowArray;
}
public static T[] CopyColumn<T>(this T[,] array, int column) {
T[] rowArray = new T[array.GetLength(1)];
for (int i = 0; i < array.GetLength(1); i++) {
rowArray[i] = array[column, i];
}
return rowArray;
}
/// <summary>
/// Given a two-dimensional array, creates a spiraling iterator.
///
/// The iterator returns the elements starting at the given x- and y-coordinates, and "spirals", starting to the right.
/// The spiral goes through all of the elements, skipping over points "outside" the spiral
///
/// If XY is the starting point, the order looks like this:
///
/// [06][07][08][09] [xy][01][04][09] [12][13][14][15]
/// [05][xy][01][10] [03][02][05][10] [11][06][07][08]
/// [04][03][02][11] [08][07][06][11] [10][05][xy][01]
/// [15][14][13][12] [15][14][13][12] [09][04][03][02]
///
/// Note that the algorithm allows you to start outside the array. It still "checks" the empty outside spiral points, which means that
/// doing that will take a long time
public static IEnumerable<T> GetSpiralIterator<T>(this T[,] squareArr, int startX, int startY) {
return GetSpiralIterator<T, T>(squareArr, startX, startY, (arr, x, y) => arr[x, y]);
}
/// <summary>
/// See the version without the return function.
///
/// This method does not return the element at the spiral index, but rather the return function of a function that takes the array and the
/// spiral indices.
/// </summary>
public static IEnumerable<V> GetSpiralIterator<T, V>(this T[,] squareArr, int startX, int startY, Func<T[,], int, int, V> returnFunc) {
int numToLookAt = squareArr.GetLength(0) * squareArr.GetLength(1);
int numLookedAt = 0;
int currentX = startX;
int currentY = startY;
int xDir = 1;
int yDir = 1;
int xTarget = startX + 1;
int yTarget = startY + 1;
bool movingX = true;
while (numLookedAt < numToLookAt) {
if (currentX >= 0 && currentX < squareArr.GetLength(0) && currentY >= 0 && currentY < squareArr.GetLength(1)) {
yield return returnFunc(squareArr, currentX, currentY);
numLookedAt++;
}
if (movingX) {
currentX += xDir;
if (currentX == xTarget) {
movingX = false;
}
}
else {
currentY += yDir;
if (currentY == yTarget) {
movingX = true;
if (xDir > 0) {
xTarget = startX - (xTarget - startX);
yTarget = startY - (yTarget - startY);
}
else {
xTarget = startX + (startX - xTarget) + 1;
yTarget = startY + (startY - yTarget) + 1;
}
xDir *= -1;
yDir *= -1;
}
}
}
}
public static T[] Shuffled<T>(this T[] array) {
T[] copy = array.CopyArray();
// Knuth shuffle algorithm
for (int t = 0; t < copy.Length; t++) {
T tmp = copy[t];
int r = UnityEngine.Random.Range(t, copy.Length);
copy[t] = copy[r];
copy[r] = tmp;
}
return copy;
}
public static T GetRandom<T>(this T[] array) {
if (array.Length == 0)
return default(T);
return array[UnityEngine.Random.Range(0, array.Length)];
}
public static T GetRandom<T>(this List<T> array) {
if (array.Count == 0)
return default(T);
return array[UnityEngine.Random.Range(0, array.Count)];
}
}
| |
/**
* $Id: IrcConnection.cs 77 2004-09-19 13:31:53Z meebey $
* $URL: svn://svn.qnetp.net/smartirc/SmartIrc4net/tags/0.2.0/src/IrcConnection.cs $
* $Rev: 77 $
* $Author: meebey $
* $Date: 2004-09-19 15:31:53 +0200 (Sun, 19 Sep 2004) $
*
* Copyright (c) 2003-2004 Mirco 'meebey' Bauer <[email protected]> <http://www.meebey.net>
*
* Full LGPL License: <http://www.gnu.org/licenses/lgpl.txt>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Threading;
using System.Reflection;
using Meebey.SmartIrc4net.Delegates;
namespace Meebey.SmartIrc4net
{
/// <summary>
///
/// </summary>
public class IrcConnection
{
private string _Version;
private string _VersionString;
private string[] _AddressList = {"localhost"};
private int _CurrentAddress = 0;
private int _Port = 6667;
private StreamReader _Reader;
private StreamWriter _Writer;
private ReadThread _ReadThread;
private WriteThread _WriteThread;
private IrcTcpClient _TcpClient;
private Hashtable _SendBuffer = Hashtable.Synchronized(new Hashtable());
private int _SendDelay = 200;
private bool _Registered = false;
private bool _Connected = false;
private int _ConnectTries = 0;
private bool _AutoRetry = false;
private bool _AutoReconnect = false;
private bool _ConnectionError = false;
private Encoding _Encoding = Encoding.GetEncoding("ISO-8859-15");
//private Encoding _Encoding = Encoding.GetEncoding(1252);
//private Encoding _Encoding = Encoding.UTF8;
public event ReadLineEventHandler OnReadLine;
public event WriteLineEventHandler OnWriteLine;
public event SimpleEventHandler OnConnect;
public event SimpleEventHandler OnConnected;
public event SimpleEventHandler OnDisconnect;
public event SimpleEventHandler OnDisconnected;
protected bool ConnectionError
{
get {
lock (this) {
return _ConnectionError;
}
}
set {
lock (this) {
_ConnectionError = value;
}
}
}
public string Address
{
get {
return _AddressList[_CurrentAddress];
}
}
public string[] AddressList
{
get {
return _AddressList;
}
}
public int Port
{
get {
return _Port;
}
}
public bool AutoReconnect
{
get {
return _AutoReconnect;
}
set {
#if LOG4NET
if (value == true) {
Logger.Connection.Info("AutoReconnect enabled");
} else {
Logger.Connection.Info("AutoReconnect disabled");
}
#endif
_AutoReconnect = value;
}
}
public bool AutoRetry
{
get {
return _AutoRetry;
}
set {
#if LOG4NET
if (value == true) {
Logger.Connection.Info("AutoRetry enabled");
} else {
Logger.Connection.Info("AutoRetry disabled");
}
#endif
_AutoRetry = value;
}
}
public int SendDelay
{
get {
return _SendDelay;
}
set {
_SendDelay = value;
}
}
public bool Registered
{
get {
return _Registered;
}
}
public bool Connected
{
get {
return _Connected;
}
}
public string Version
{
get {
return _Version;
}
}
public string VersionString
{
get {
return _VersionString;
}
}
public Encoding Encoding
{
get {
return _Encoding;
}
set {
_Encoding = value;
}
}
public IrcConnection()
{
#if LOG4NET
Logger.Init();
#endif
_SendBuffer[Priority.High] = Queue.Synchronized(new Queue());
_SendBuffer[Priority.AboveMedium] = Queue.Synchronized(new Queue());
_SendBuffer[Priority.Medium] = Queue.Synchronized(new Queue());
_SendBuffer[Priority.BelowMedium] = Queue.Synchronized(new Queue());
_SendBuffer[Priority.Low] = Queue.Synchronized(new Queue());
OnReadLine += new ReadLineEventHandler(_SimpleParser);
_ReadThread = new ReadThread(this);
_WriteThread = new WriteThread(this);
Assembly assembly = Assembly.GetAssembly(this.GetType());
AssemblyName assembly_name = assembly.GetName(false);
AssemblyProductAttribute pr = (AssemblyProductAttribute)assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false)[0];
_Version = assembly_name.Version.ToString();
_VersionString = pr.Product+" "+_Version;
}
public bool Connect(string[] addresslist, int port)
{
if (_Connected != false) {
throw new Exception("already connected");
}
#if LOG4NET
Logger.Connection.Info("connecting...");
#endif
_ConnectTries++;
_AddressList = (string[])addresslist.Clone();
_Port = port;
if (OnConnect != null) {
OnConnect();
}
try {
System.Net.IPAddress ip = System.Net.Dns.Resolve(Address).AddressList[0];
_TcpClient = new IrcTcpClient();
_TcpClient.Connect(ip, port);
if (OnConnected != null) {
OnConnected();
}
_Reader = new StreamReader(_TcpClient.GetStream(), Encoding);
_Writer = new StreamWriter(_TcpClient.GetStream(), Encoding);
// Connection was succeful, reseting the connect counter
_ConnectTries = 0;
// updating the connection id, so connecting is possible again
lock(this) {
ConnectionError = false;
}
_Connected = true;
#if LOG4NET
Logger.Connection.Info("connected");
#endif
// lets power up our threads
_ReadThread.Start();
_WriteThread.Start();
return true;
} catch (Exception e) {
if (_Reader != null) {
_Reader.Close();
}
if (_Writer != null) {
_Writer.Close();
}
if (_TcpClient != null) {
_TcpClient.Close();
}
_Connected = false;
ConnectionError = true;
#if LOG4NET
Logger.Connection.Info("connection failed: "+e.Message);
#endif
if (_AutoRetry == true &&
_ConnectTries <= 3) {
_NextAddress();
if (Reconnect(false)) {
return true;
}
}
return false;
}
}
public bool Connect(string address, int port)
{
return Connect(new string[] {address}, port);
}
// login parameter only for IrcClient needed
public virtual bool Reconnect(bool login)
{
#if LOG4NET
Logger.Connection.Info("reconnecting...");
#endif
Disconnect();
return Connect(_AddressList, _Port);
}
public bool Reconnect()
{
return Reconnect(true);
}
public bool Disconnect()
{
if (Connected == true) {
#if LOG4NET
Logger.Connection.Info("disconnecting...");
#endif
if (OnDisconnect != null) {
OnDisconnect();
}
_ReadThread.Stop();
_WriteThread.Stop();
_TcpClient.Close();
_Connected = false;
_Registered = false;
if (OnDisconnected != null) {
OnDisconnected();
}
#if LOG4NET
Logger.Connection.Info("disconnected");
#endif
return true;
} else {
return false;
}
}
public void Listen(bool blocking)
{
if (blocking) {
while(Connected == true) {
ReadLine(true);
if (ConnectionError == true) {
if (AutoReconnect == true) {
Reconnect();
} else {
Disconnect();
}
}
}
} else {
while (ReadLine(false) != String.Empty) {
// loop as long as we receive messages
}
}
}
public void Listen()
{
Listen(true);
}
public void ListenOnce(bool blocking)
{
ReadLine(blocking);
}
public void ListenOnce()
{
ListenOnce(true);
}
public string ReadLine(bool blocking)
{
string data = "";
bool received = false;
if (blocking) {
// block till the queue has data
while ((Connected == true) &&
(_ReadThread.Queue.Count == 0)) {
Thread.Sleep(10);
}
}
if ((Connected == true) &&
(_ReadThread.Queue.Count > 0)) {
data = (string)(_ReadThread.Queue.Dequeue());
}
if (data != "" && data != null) {
#if LOG4NET
Logger.Queue.Debug("read: \""+data+"\"");
#endif
if (OnReadLine != null) {
OnReadLine(data);
}
}
return data;
}
public void WriteLine(string data, Priority priority)
{
if (priority == Priority.Critical) {
_WriteLine(data);
} else {
((Queue)_SendBuffer[priority]).Enqueue(data);
}
}
public void WriteLine(string data)
{
WriteLine(data, Priority.Medium);
}
private bool _WriteLine(string data)
{
if (Connected == true) {
try {
_Writer.Write(data+"\r\n");
_Writer.Flush();
} catch (IOException) {
#if LOG4NET
Logger.Socket.Warn("sending data failed, connection lost");
#endif
ConnectionError = true;
return false;
}
#if LOG4NET
Logger.Socket.Debug("sent: \""+data+"\"");
#endif
if (OnWriteLine != null) {
OnWriteLine(data);
}
return true;
}
return false;
}
private void _NextAddress()
{
_CurrentAddress++;
if (_CurrentAddress < _AddressList.Length) {
// nothing
} else {
_CurrentAddress = 0;
}
#if LOG4NET
Logger.Connection.Info("set server to: "+Address);
#endif
}
private void _SimpleParser(string rawline)
{
string messagecode = "";
string[] rawlineex = rawline.Split(new Char[] {' '});
if (rawline.Substring(0, 1) == ":") {
messagecode = rawlineex[1];
try {
ReplyCode replycode = (ReplyCode)int.Parse(messagecode);
switch(replycode) {
case ReplyCode.RPL_WELCOME:
_Registered = true;
#if LOG4NET
Logger.Connection.Info("logged in");
#endif
break;
}
} catch (FormatException) {
// nothing
}
} else {
messagecode = rawlineex[0];
switch(messagecode) {
case "ERROR":
ConnectionError = true;
break;
}
}
}
private class ReadThread
{
private IrcConnection _Connection;
private Thread _Thread;
// syncronized queue (thread safe)
private Queue _Queue = Queue.Synchronized(new Queue());
public Queue Queue
{
get {
return _Queue;
}
}
public ReadThread(IrcConnection connection)
{
_Connection = connection;
}
public void Start()
{
_Thread = new Thread(new ThreadStart(_Worker));
_Thread.Name = "ReadThread ("+_Connection.Address+":"+_Connection.Port+")";
_Thread.IsBackground = true;
_Thread.Start();
}
public void Stop()
{
_Thread.Abort();
_Connection._Reader.Close();
}
private void _Worker()
{
#if LOG4NET
Logger.Socket.Debug("ReadThread started");
#endif
try {
string data = "";
try {
while ((_Connection.Connected == true) &&
((data = _Connection._Reader.ReadLine()) != null)) {
_Queue.Enqueue(data);
#if LOG4NET
Logger.Socket.Debug("received: \""+data+"\"");
#endif
}
} catch (IOException e) {
#if LOG4NET
Logger.Socket.Warn("IOException: "+e.Message);
#endif
}
#if LOG4NET
Logger.Socket.Warn("connection lost");
#endif
_Connection.ConnectionError = true;
} catch (ThreadAbortException) {
Thread.ResetAbort();
#if LOG4NET
Logger.Socket.Debug("ReadThread aborted");
#endif
}
}
}
private class WriteThread
{
private IrcConnection _Connection;
private Thread _Thread;
private int _HighCount = 0;
private int _AboveMediumCount = 0;
private int _MediumCount = 0;
private int _BelowMediumCount = 0;
private int _LowCount = 0;
private int _AboveMediumSentCount = 0;
private int _MediumSentCount = 0;
private int _BelowMediumSentCount = 0;
private int _AboveMediumThresholdCount = 4;
private int _MediumThresholdCount = 2;
private int _BelowMediumThresholdCount = 1;
private int _BurstCount = 0;
public WriteThread(IrcConnection connection)
{
_Connection = connection;
}
public void Start()
{
_Thread = new Thread(new ThreadStart(_Worker));
_Thread.Name = "WriteThread ("+_Connection.Address+":"+_Connection.Port+")";
_Thread.IsBackground = true;
_Thread.Start();
}
public void Stop()
{
_Thread.Abort();
_Connection._Writer.Close();
}
private void _Worker()
{
#if LOG4NET
Logger.Socket.Debug("WriteThread started");
#endif
try {
while (_Connection.Connected == true) {
_CheckBuffer();
Thread.Sleep(_Connection._SendDelay);
}
#if LOG4NET
Logger.Socket.Warn("connection lost");
#endif
_Connection.ConnectionError = true;
} catch (ThreadAbortException) {
Thread.ResetAbort();
#if LOG4NET
Logger.Socket.Debug("WriteThread aborted");
#endif
}
}
// WARNING: complex scheduler, don't even think about changing it!
private void _CheckBuffer()
{
// only send data if we are succefully registered on the IRC network
if (!_Connection._Registered) {
return;
}
_HighCount = ((Queue)_Connection._SendBuffer[Priority.High]).Count;
_AboveMediumCount = ((Queue)_Connection._SendBuffer[Priority.AboveMedium]).Count;
_MediumCount = ((Queue)_Connection._SendBuffer[Priority.Medium]).Count;
_BelowMediumCount = ((Queue)_Connection._SendBuffer[Priority.BelowMedium]).Count;
_LowCount = ((Queue)_Connection._SendBuffer[Priority.Low]).Count;
if ((_CheckHighBuffer() == true) &&
(_CheckAboveMediumBuffer() == true) &&
(_CheckMediumBuffer() == true) &&
(_CheckBelowMediumBuffer() == true) &&
(_CheckLowBuffer() == true)) {
// everything is sent, resetting all counters
_AboveMediumSentCount = 0;
_MediumSentCount = 0;
_BelowMediumSentCount = 0;
_BurstCount = 0;
}
if (_BurstCount < 3) {
_BurstCount++;
//_CheckBuffer();
}
}
private bool _CheckHighBuffer()
{
if (_HighCount > 0) {
string data = (string)((Queue)_Connection._SendBuffer[Priority.High]).Dequeue();
if (_Connection._WriteLine(data) == false) {
// putting the message back into the queue if sending was not successful
((Queue)_Connection._SendBuffer[Priority.High]).Enqueue(data);
}
if (_HighCount > 1) {
// there is more data to send
return false;
}
}
return true;
}
private bool _CheckAboveMediumBuffer()
{
if ((_AboveMediumCount > 0) &&
(_AboveMediumSentCount < _AboveMediumThresholdCount)) {
string data = (string)((Queue)_Connection._SendBuffer[Priority.AboveMedium]).Dequeue();
if (_Connection._WriteLine(data) == false) {
((Queue)_Connection._SendBuffer[Priority.AboveMedium]).Enqueue(data);
}
_AboveMediumSentCount++;
if (_AboveMediumSentCount < _AboveMediumThresholdCount) {
return false;
}
}
return true;
}
private bool _CheckMediumBuffer()
{
if ((_MediumCount > 0) &&
(_MediumSentCount < _MediumThresholdCount)) {
string data = (string)((Queue)_Connection._SendBuffer[Priority.Medium]).Dequeue();
if (_Connection._WriteLine(data) == false) {
((Queue)_Connection._SendBuffer[Priority.Medium]).Enqueue(data);
}
_MediumSentCount++;
if (_MediumSentCount < _MediumThresholdCount) {
return false;
}
}
return true;
}
private bool _CheckBelowMediumBuffer()
{
if ((_BelowMediumCount > 0) &&
(_BelowMediumSentCount < _BelowMediumThresholdCount)) {
string data = (string)((Queue)_Connection._SendBuffer[Priority.BelowMedium]).Dequeue();
if (_Connection._WriteLine(data) == false) {
((Queue)_Connection._SendBuffer[Priority.BelowMedium]).Enqueue(data);
}
_BelowMediumSentCount++;
if (_BelowMediumSentCount < _BelowMediumThresholdCount) {
return false;
}
}
return true;
}
private bool _CheckLowBuffer()
{
if (_LowCount > 0) {
if ((_HighCount > 0) ||
(_AboveMediumCount > 0) ||
(_MediumCount > 0) ||
(_BelowMediumCount > 0)) {
return true;
}
string data = (string)((Queue)_Connection._SendBuffer[Priority.Low]).Dequeue();
if (_Connection._WriteLine(data) == false) {
((Queue)_Connection._SendBuffer[Priority.Low]).Enqueue(data);
}
if (_LowCount > 1) {
return false;
}
}
return true;
}
// END OF WARNING, below this you can read/change again ;)
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Net;
using System.Linq;
using Microsoft.Azure;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Azure.Test;
using Microsoft.Rest.TransientFaultHandling;
using Xunit;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Newtonsoft.Json.Linq;
using Microsoft.Rest.Azure.OData;
namespace ResourceGroups.Tests
{
public class LiveResourceTests : TestBase
{
const string WebResourceProviderVersion = "2016-08-01";
const string SendGridResourceProviderVersion = "2015-01-01";
string ResourceGroupLocation
{
get { return "South Central US"; }
}
public static ResourceIdentity CreateResourceIdentity(GenericResource resource)
{
string[] parts = resource.Type.Split('/');
return new ResourceIdentity { ResourceType = parts[1], ResourceProviderNamespace = parts[0], ResourceName = resource.Name, ResourceProviderApiVersion = WebResourceProviderVersion };
}
public ResourceManagementClient GetResourceManagementClient(MockContext context, RecordedDelegatingHandler handler)
{
handler.IsPassThrough = true;
return this.GetResourceManagementClientWithHandler(context, handler);
}
public string GetWebsiteLocation(ResourceManagementClient client)
{
return "WestUS";
}
public string GetMySqlLocation(ResourceManagementClient client)
{
return ResourcesManagementTestUtilities.GetResourceLocation(client, "SuccessBricks.ClearDB/databases");
}
[Fact]
public void CleanupAllResources()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
var client = GetResourceManagementClient(context, handler);
client.SetRetryPolicy(new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(1));
var groups = client.ResourceGroups.List();
foreach (var group in groups)
{
var resources = client.Resources.ListByResourceGroup(group.Name, new ODataQuery<GenericResourceFilter>(r => r.ResourceType == "Microsoft.Web/sites"));
foreach (var resource in resources)
{
client.Resources.Delete(group.Name,
CreateResourceIdentity(resource).ResourceProviderNamespace,
string.Empty,
CreateResourceIdentity(resource).ResourceType,
resource.Name,
CreateResourceIdentity(resource).ResourceProviderApiVersion);
}
client.ResourceGroups.BeginDelete(group.Name);
}
}
}
[Fact]
public void CreateResourceWithPlan()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
string groupName = TestUtilities.GenerateName("csmrg");
string resourceName = TestUtilities.GenerateName("csmr");
string password = TestUtilities.GenerateName("p@ss");
var client = GetResourceManagementClient(context, handler);
string mySqlLocation = "centralus";
var groupIdentity = new ResourceIdentity
{
ResourceName = resourceName,
ResourceProviderNamespace = "Sendgrid.Email",
ResourceType = "accounts",
ResourceProviderApiVersion = SendGridResourceProviderVersion
};
client.SetRetryPolicy(new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(1));
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "centralus" });
var createOrUpdateResult = client.Resources.CreateOrUpdate(groupName, groupIdentity.ResourceProviderNamespace, "", groupIdentity.ResourceType,
groupIdentity.ResourceName, groupIdentity.ResourceProviderApiVersion,
new GenericResource
{
Location = mySqlLocation,
Plan = new Plan {Name = "free", Publisher= "Sendgrid",Product= "sendgrid_azure",PromotionCode="" },
Tags = new Dictionary<string, string> { { "provision_source", "RMS" } },
Properties = JObject.Parse("{'password':'" + password + "','acceptMarketingEmails':false,'email':'[email protected]'}"),
}
);
Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(mySqlLocation, createOrUpdateResult.Location),
string.Format("Resource location for resource '{0}' does not match expected location '{1}'", createOrUpdateResult.Location, mySqlLocation));
Assert.NotNull(createOrUpdateResult.Plan);
Assert.Equal("free", createOrUpdateResult.Plan.Name);
var getResult = client.Resources.Get(groupName, groupIdentity.ResourceProviderNamespace,
"", groupIdentity.ResourceType, groupIdentity.ResourceName, groupIdentity.ResourceProviderApiVersion);
Assert.Equal(resourceName, getResult.Name);
Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(mySqlLocation, getResult.Location),
string.Format("Resource location for resource '{0}' does not match expected location '{1}'", getResult.Location, mySqlLocation));
Assert.NotNull(getResult.Plan);
Assert.Equal("free", getResult.Plan.Name);
}
}
[Fact]
public void CreatedResourceIsAvailableInList()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
string groupName = TestUtilities.GenerateName("csmrg");
string resourceName = TestUtilities.GenerateName("csmr");
var client = GetResourceManagementClient(context, handler);
string websiteLocation = GetWebsiteLocation(client);
client.SetRetryPolicy(new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(1));
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = this.ResourceGroupLocation });
var createOrUpdateResult = client.Resources.CreateOrUpdate(groupName, "Microsoft.Web", "", "sites",resourceName, WebResourceProviderVersion,
new GenericResource
{
Location = websiteLocation,
Properties = JObject.Parse("{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}"),
}
);
Assert.NotNull(createOrUpdateResult.Id);
Assert.Equal(resourceName, createOrUpdateResult.Name);
Assert.Equal("Microsoft.Web/sites", createOrUpdateResult.Type);
Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(websiteLocation, createOrUpdateResult.Location),
string.Format("Resource location for website '{0}' does not match expected location '{1}'", createOrUpdateResult.Location, websiteLocation));
var listResult = client.Resources.ListByResourceGroup(groupName);
Assert.Equal(1, listResult.Count());
Assert.Equal(resourceName, listResult.First().Name);
Assert.Equal("Microsoft.Web/sites", listResult.First().Type);
Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(websiteLocation, listResult.First().Location),
string.Format("Resource list location for website '{0}' does not match expected location '{1}'", listResult.First().Location, websiteLocation));
listResult = client.Resources.ListByResourceGroup(groupName, new ODataQuery<GenericResourceFilter> { Top = 10 });
Assert.Equal(1, listResult.Count());
Assert.Equal(resourceName, listResult.First().Name);
Assert.Equal("Microsoft.Web/sites", listResult.First().Type);
Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(websiteLocation, listResult.First().Location),
string.Format("Resource list location for website '{0}' does not match expected location '{1}'", listResult.First().Location, websiteLocation));
}
}
[Fact]
public void CreatedResourceIsAvailableInListFilteredByTagName()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
string groupName = TestUtilities.GenerateName("csmrg");
string resourceName = TestUtilities.GenerateName("csmr");
string resourceNameNoTags = TestUtilities.GenerateName("csmr");
string tagName = TestUtilities.GenerateName("csmtn");
var client = GetResourceManagementClient(context, handler);
string websiteLocation = GetWebsiteLocation(client);
client.SetRetryPolicy(new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(1));
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = this.ResourceGroupLocation });
client.Resources.CreateOrUpdate(
groupName,
"Microsoft.Web",
string.Empty,
"sites",
resourceName,
WebResourceProviderVersion,
new GenericResource
{
Tags = new Dictionary<string, string> { { tagName, "" } },
Location = websiteLocation,
Properties = JObject.Parse("{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}")
});
client.Resources.CreateOrUpdate(
groupName,
"Microsoft.Web",
string.Empty,
"sites",
resourceNameNoTags,
WebResourceProviderVersion,
new GenericResource
{
Location = websiteLocation,
Properties = JObject.Parse("{'name':'" + resourceNameNoTags + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}")
});
var listResult = client.Resources.ListByResourceGroup(groupName, new ODataQuery<GenericResourceFilter>(r => r.Tagname == tagName));
Assert.Equal(1, listResult.Count());
Assert.Equal(resourceName, listResult.First().Name);
var getResult = client.Resources.Get(
groupName,
"Microsoft.Web",
string.Empty,
"sites",
resourceName,
WebResourceProviderVersion);
Assert.Equal(resourceName, getResult.Name);
Assert.True(getResult.Tags.Keys.Contains(tagName));
}
}
[Fact]
public void CreatedResourceIsAvailableInListFilteredByTagNameAndValue()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
string groupName = TestUtilities.GenerateName("csmrg");
string resourceName = TestUtilities.GenerateName("csmr");
string resourceNameNoTags = TestUtilities.GenerateName("csmr");
string tagName = TestUtilities.GenerateName("csmtn");
string tagValue = TestUtilities.GenerateName("csmtv");
var client = GetResourceManagementClient(context, handler);
string websiteLocation = GetWebsiteLocation(client);
client.SetRetryPolicy(new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(1));
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = this.ResourceGroupLocation });
client.Resources.CreateOrUpdate(
groupName,
"Microsoft.Web",
"",
"sites",
resourceName,
WebResourceProviderVersion,
new GenericResource
{
Tags = new Dictionary<string, string> { { tagName, tagValue } },
Location = websiteLocation,
Properties = JObject.Parse("{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}")
}
);
client.Resources.CreateOrUpdate(
groupName,
"Microsoft.Web",
"",
"sites",
resourceNameNoTags,
WebResourceProviderVersion,
new GenericResource
{
Location = websiteLocation,
Properties = JObject.Parse("{'name':'" + resourceNameNoTags + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}")
}
);
var listResult = client.Resources.ListByResourceGroup(groupName,
new ODataQuery<GenericResourceFilter>(r => r.Tagname == tagName && r.Tagvalue == tagValue));
Assert.Equal(1, listResult.Count());
Assert.Equal(resourceName, listResult.First().Name);
var getResult = client.Resources.Get(
groupName,
"Microsoft.Web",
"",
"sites",
resourceName,
WebResourceProviderVersion);
Assert.Equal(resourceName, getResult.Name);
Assert.True(getResult.Tags.Keys.Contains(tagName));
}
}
[Fact]
public void CreatedAndDeleteResource()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
string groupName = TestUtilities.GenerateName("csmrg");
string resourceName = TestUtilities.GenerateName("csmr");
var client = GetResourceManagementClient(context, handler);
client.SetRetryPolicy(new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(1));
string location = this.GetWebsiteLocation(client);
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = location });
var createOrUpdateResult = client.Resources.CreateOrUpdate(
groupName,
"Microsoft.Web",
"",
"sites",
resourceName,
WebResourceProviderVersion,
new GenericResource
{
Location = location,
Properties = JObject.Parse("{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}")
}
);
var listResult = client.Resources.ListByResourceGroup(groupName);
Assert.Equal(resourceName, listResult.First().Name);
client.Resources.Delete(
groupName,
"Microsoft.Web",
"",
"sites",
resourceName,
WebResourceProviderVersion);
}
}
[Fact]
public void CreatedAndDeleteResourceById()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
string subscriptionId = "fb3a3d6b-44c8-44f5-88c9-b20917c9b96b";
string groupName = TestUtilities.GenerateName("csmrg");
string resourceName = TestUtilities.GenerateName("csmr");
var client = GetResourceManagementClient(context, handler);
client.SetRetryPolicy(new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(1));
string location = this.GetWebsiteLocation(client);
string resourceId = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Web/sites/{2}", subscriptionId, groupName, resourceName);
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = location });
var createOrUpdateResult = client.Resources.CreateOrUpdateById(
resourceId,
WebResourceProviderVersion,
new GenericResource
{
Location = location,
Properties = JObject.Parse("{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}")
}
);
var listResult = client.Resources.ListByResourceGroup(groupName);
Assert.Equal(resourceName, listResult.First().Name);
client.Resources.DeleteById(
resourceId,
WebResourceProviderVersion);
}
}
[Fact]
public void CreatedAndListResource()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
string groupName = TestUtilities.GenerateName("csmrg");
string resourceName = TestUtilities.GenerateName("csmr");
var client = GetResourceManagementClient(context, handler);
string location = this.GetWebsiteLocation(client);
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = location });
var createOrUpdateResult = client.Resources.CreateOrUpdate(
groupName,
"Microsoft.Web",
"",
"sites",
resourceName,
WebResourceProviderVersion,
new GenericResource
{
Location = location,
Tags = new Dictionary<string, string>() { { "department", "finance" }, { "tagname", "tagvalue" } },
Properties = JObject.Parse("{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}")
}
);
var listResult = client.Resources.List(new ODataQuery<GenericResourceFilter>(r => r.ResourceType == "Microsoft.Web/sites"));
Assert.NotEmpty(listResult);
Assert.Equal(2, listResult.First().Tags.Count);
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.SS.Util
{
using System;
using System.Text;
using System.Text.RegularExpressions;
using NPOI.SS.Formula;
using NPOI.SS.UserModel;
using System.Globalization;
public enum NameType:int
{
/// <summary>
/// Allow accessing the Initial value.
/// </summary>
None = 0,
Cell = 1,
NamedRange = 2,
Column = 3,
Row = 4,
BadCellOrNamedRange = -1
}
/**
*
* @author Avik Sengupta
* @author Dennis doubleday (patch to seperateRowColumns())
*/
public class CellReference
{
/** The character ($) that signifies a row or column value is absolute instead of relative */
private const char ABSOLUTE_REFERENCE_MARKER = '$';
/** The character (!) that Separates sheet names from cell references */
private const char SHEET_NAME_DELIMITER = '!';
/** The character (') used to quote sheet names when they contain special characters */
private const char SPECIAL_NAME_DELIMITER = '\'';
/**
* Matches a run of one or more letters followed by a run of one or more digits.
* The run of letters is group 1 and the run of digits is group 2.
* Each group may optionally be prefixed with a single '$'.
*/
private const string CELL_REF_PATTERN = @"^\$?([A-Za-z]+)\$?([0-9]+)";
/**
* Matches a run of one or more letters. The run of letters is group 1.
* The text may optionally be prefixed with a single '$'.
*/
private const string COLUMN_REF_PATTERN = @"^\$?([A-Za-z]+)$";
/**
* Matches a run of one or more digits. The run of digits is group 1.
* The text may optionally be prefixed with a single '$'.
*/
private const string ROW_REF_PATTERN = @"^\$?([0-9]+)$";
/**
* Named range names must start with a letter or underscore. Subsequent characters may include
* digits or dot. (They can even end in dot).
*/
private const string NAMED_RANGE_NAME_PATTERN = "^[_A-Za-z][_.A-Za-z0-9]*$";
//private static string BIFF8_LAST_COLUMN = "IV";
//private static int BIFF8_LAST_COLUMN_TEXT_LEN = BIFF8_LAST_COLUMN.Length;
//private static string BIFF8_LAST_ROW = (0x10000).ToString();
//private static int BIFF8_LAST_ROW_TEXT_LEN = BIFF8_LAST_ROW.Length;
private int _rowIndex;
private int _colIndex;
private String _sheetName;
private bool _isRowAbs;
private bool _isColAbs;
/**
* Create an cell ref from a string representation. Sheet names containing special characters should be
* delimited and escaped as per normal syntax rules for formulas.
*/
public CellReference(String cellRef)
{
if (cellRef.EndsWith("#REF!", StringComparison.CurrentCulture))
{
throw new ArgumentException("Cell reference invalid: " + cellRef);
}
String[] parts = SeparateRefParts(cellRef);
_sheetName = parts[0];
String colRef = parts[1];
//if (colRef.Length < 1)
//{
// throw new ArgumentException("Invalid Formula cell reference: '" + cellRef + "'");
//}
_isColAbs = (colRef.Length > 0) && colRef[0] == '$';
//_isColAbs = colRef[0] == '$';
if (_isColAbs)
{
colRef = colRef.Substring(1);
}
if (colRef.Length == 0)
{
_colIndex = -1;
}
else
{
_colIndex = ConvertColStringToIndex(colRef);
}
String rowRef = parts[2];
//if (rowRef.Length < 1)
//{
// throw new ArgumentException("Invalid Formula cell reference: '" + cellRef + "'");
//}
//_isRowAbs = rowRef[0] == '$';
_isRowAbs = (rowRef.Length > 0) && rowRef[0] == '$';
if (_isRowAbs)
{
rowRef = rowRef.Substring(1);
}
if (rowRef.Length == 0)
{
_rowIndex = -1;
}
else
{
_rowIndex = int.Parse(rowRef, CultureInfo.InvariantCulture) - 1; // -1 to convert 1-based to zero-based
}
}
public CellReference(ICell cell):this(cell.RowIndex, cell.ColumnIndex, false, false)
{
}
public CellReference(int pRow, int pCol)
: this(pRow, pCol, false, false)
{
}
public CellReference(int pRow, short pCol)
: this(pRow, pCol & 0xFFFF, false, false)
{
}
public CellReference(int pRow, int pCol, bool pAbsRow, bool pAbsCol)
: this(null, pRow, pCol, pAbsRow, pAbsCol)
{
}
public CellReference(String pSheetName, int pRow, int pCol, bool pAbsRow, bool pAbsCol)
{
// TODO - "-1" is a special value being temporarily used for whole row and whole column area references.
// so these Checks are currently N.Q.R.
if (pRow < -1)
{
throw new ArgumentException("row index may not be negative, but had " + pRow);
}
if (pCol < -1)
{
throw new ArgumentException("column index may not be negative, but had " + pCol);
}
_sheetName = pSheetName;
_rowIndex = pRow;
_colIndex = pCol;
_isRowAbs = pAbsRow;
_isColAbs = pAbsCol;
}
public int Row
{
get { return _rowIndex; }
}
public short Col
{
get
{
return (short)_colIndex;
}
}
public bool IsRowAbsolute
{
get { return _isRowAbs; }
}
public bool IsColAbsolute
{
get { return _isColAbs; }
}
/**
* @return possibly <c>null</c> if this is a 2D reference. Special characters are not
* escaped or delimited
*/
public String SheetName
{
get { return _sheetName; }
}
/**
* takes in a column reference portion of a CellRef and converts it from
* ALPHA-26 number format to 0-based base 10.
* 'A' -> 0
* 'Z' -> 25
* 'AA' -> 26
* 'IV' -> 255
* @return zero based column index
*/
public static int ConvertColStringToIndex(String ref1)
{
int retval = 0;
char[] refs = ref1.ToUpper().ToCharArray();
for (int k = 0; k < refs.Length; k++)
{
char thechar = refs[k];
if (thechar == ABSOLUTE_REFERENCE_MARKER)
{
if (k != 0)
{
throw new ArgumentException("Bad col ref format '" + ref1 + "'");
}
continue;
}
// Character is uppercase letter, find relative value to A
retval = (retval * 26) + (thechar - 'A' + 1);
}
return retval - 1;
}
public static bool IsPartAbsolute(String part)
{
return part[0] == ABSOLUTE_REFERENCE_MARKER;
}
public static NameType ClassifyCellReference(String str, SpreadsheetVersion ssVersion)
{
int len = str.Length;
if (len < 1)
{
throw new ArgumentException("Empty string not allowed");
}
char firstChar = str[0];
switch (firstChar)
{
case ABSOLUTE_REFERENCE_MARKER:
case '.':
case '_':
break;
default:
if (!Char.IsLetter(firstChar) && !Char.IsDigit(firstChar))
{
throw new ArgumentException("Invalid first char (" + firstChar
+ ") of cell reference or named range. Letter expected");
}
break;
}
if (!Char.IsDigit(str[len - 1]))
{
// no digits at end of str
return ValidateNamedRangeName(str, ssVersion);
}
Regex cellRefPatternMatcher = new Regex(CELL_REF_PATTERN);
if (!cellRefPatternMatcher.IsMatch(str))
{
return ValidateNamedRangeName(str, ssVersion);
}
MatchCollection matches = cellRefPatternMatcher.Matches(str);
string lettersGroup = matches[0].Groups[1].Value;
string digitsGroup = matches[0].Groups[2].Value;
if (CellReferenceIsWithinRange(lettersGroup, digitsGroup, ssVersion))
{
// valid cell reference
return NameType.Cell;
}
// If str looks like a cell reference, but is out of (row/col) range, it is a valid
// named range name
// This behaviour is a little weird. For example, "IW123" is a valid named range name
// because the column "IW" is beyond the maximum "IV". Note - this behaviour is version
// dependent. In BIFF12, "IW123" is not a valid named range name, but in BIFF8 it is.
if (str.IndexOf(ABSOLUTE_REFERENCE_MARKER) >= 0)
{
// Of course, named range names cannot have '$'
return NameType.BadCellOrNamedRange;
}
return NameType.NamedRange;
}
private static NameType ValidateNamedRangeName(String str, SpreadsheetVersion ssVersion)
{
Regex colMatcher = new Regex(COLUMN_REF_PATTERN);
if (colMatcher.IsMatch(str))
{
Group colStr = colMatcher.Matches(str)[0].Groups[1];
if (IsColumnWithnRange(colStr.Value, ssVersion))
{
return NameType.Column;
}
}
Regex rowMatcher = new Regex(ROW_REF_PATTERN);
if (rowMatcher.IsMatch(str))
{
Group rowStr = rowMatcher.Matches(str)[0].Groups[1];
if (IsRowWithnRange(rowStr.Value, ssVersion))
{
return NameType.Row;
}
}
if (!Regex.IsMatch(str, NAMED_RANGE_NAME_PATTERN))
{
return NameType.BadCellOrNamedRange;
}
return NameType.NamedRange;
}
/**
* Takes in a 0-based base-10 column and returns a ALPHA-26
* representation.
* eg column #3 -> D
*/
public static String ConvertNumToColString(int col)
{
// Excel counts column A as the 1st column, we
// treat it as the 0th one
int excelColNum = col + 1;
StringBuilder colRef = new StringBuilder(2);
int colRemain = excelColNum;
while (colRemain > 0)
{
int thisPart = colRemain % 26;
if (thisPart == 0) { thisPart = 26; }
colRemain = (colRemain - thisPart) / 26;
// The letter A is at 65
char colChar = (char)(thisPart + 64);
colRef.Insert(0, colChar);
}
return colRef.ToString();
}
/**
* Separates the row from the columns and returns an array of three Strings. The first element
* is the sheet name. Only the first element may be null. The second element in is the column
* name still in ALPHA-26 number format. The third element is the row.
*/
private static String[] SeparateRefParts(String reference)
{
int plingPos = reference.LastIndexOf(SHEET_NAME_DELIMITER);
String sheetName = ParseSheetName(reference, plingPos);
int start = plingPos + 1;
int Length = reference.Length;
int loc = start;
// skip initial dollars
if (reference[loc] == ABSOLUTE_REFERENCE_MARKER)
{
loc++;
}
// step over column name chars Until first digit (or dollars) for row number.
for (; loc < Length; loc++)
{
char ch = reference[loc];
if (Char.IsDigit(ch) || ch == ABSOLUTE_REFERENCE_MARKER)
{
break;
}
}
return new String[] {
sheetName,
reference.Substring(start,loc-start),
reference.Substring(loc),
};
}
private static String ParseSheetName(String reference, int indexOfSheetNameDelimiter)
{
if (indexOfSheetNameDelimiter < 0)
{
return null;
}
bool IsQuoted = reference[0] == SPECIAL_NAME_DELIMITER;
if (!IsQuoted)
{
return reference.Substring(0, indexOfSheetNameDelimiter);
}
int lastQuotePos = indexOfSheetNameDelimiter - 1;
if (reference[lastQuotePos] != SPECIAL_NAME_DELIMITER)
{
throw new Exception("Mismatched quotes: (" + reference + ")");
}
// TODO - refactor cell reference parsing logic to one place.
// Current known incarnations:
// FormulaParser.Name
// CellReference.ParseSheetName() (here)
// AreaReference.SeparateAreaRefs()
// SheetNameFormatter.format() (inverse)
StringBuilder sb = new StringBuilder(indexOfSheetNameDelimiter);
for (int i = 1; i < lastQuotePos; i++)
{ // Note boundaries - skip outer quotes
char ch = reference[i];
if (ch != SPECIAL_NAME_DELIMITER)
{
sb.Append(ch);
continue;
}
if (i < lastQuotePos)
{
if (reference[i + 1] == SPECIAL_NAME_DELIMITER)
{
// two consecutive quotes is the escape sequence for a single one
i++; // skip this and keep parsing the special name
sb.Append(ch);
continue;
}
}
throw new Exception("Bad sheet name quote escaping: (" + reference + ")");
}
return sb.ToString();
}
/**
* Example return values:
* <table border="0" cellpAdding="1" cellspacing="0" summary="Example return values">
* <tr><th align='left'>Result</th><th align='left'>Comment</th></tr>
* <tr><td>A1</td><td>Cell reference without sheet</td></tr>
* <tr><td>Sheet1!A1</td><td>Standard sheet name</td></tr>
* <tr><td>'O''Brien''s Sales'!A1'</td><td>Sheet name with special characters</td></tr>
* </table>
* @return the text representation of this cell reference as it would appear in a formula.
*/
public String FormatAsString()
{
StringBuilder sb = new StringBuilder(32);
if (_sheetName != null)
{
SheetNameFormatter.AppendFormat(sb, _sheetName);
sb.Append(SHEET_NAME_DELIMITER);
}
AppendCellReference(sb);
return sb.ToString();
}
public override String ToString()
{
StringBuilder sb = new StringBuilder(64);
sb.Append(this.GetType().Name).Append(" [");
sb.Append(FormatAsString());
sb.Append("]");
return sb.ToString();
}
/**
* Returns the three parts of the cell reference, the
* Sheet name (or null if none supplied), the 1 based
* row number, and the A based column letter.
* This will not include any markers for absolute
* references, so use {@link #formatAsString()}
* to properly turn references into strings.
*/
public String[] CellRefParts
{
get
{
return new String[] {
_sheetName,
(_rowIndex+1).ToString(CultureInfo.InvariantCulture),
ConvertNumToColString(_colIndex)
};
}
}
/**
* Appends cell reference with '$' markers for absolute values as required.
* Sheet name is not included.
*/
/* package */
public void AppendCellReference(StringBuilder sb)
{
if (_colIndex != -1)
{
if (_isColAbs)
{
sb.Append(ABSOLUTE_REFERENCE_MARKER);
}
sb.Append(ConvertNumToColString(_colIndex));
}
if (_rowIndex != -1)
{
if (_isRowAbs)
{
sb.Append(ABSOLUTE_REFERENCE_MARKER);
}
sb.Append(_rowIndex + 1);
}
}
/**
* Used to decide whether a name of the form "[A-Z]*[0-9]*" that appears in a formula can be
* interpreted as a cell reference. Names of that form can be also used for sheets and/or
* named ranges, and in those circumstances, the question of whether the potential cell
* reference is valid (in range) becomes important.
* <p/>
* Note - that the maximum sheet size varies across Excel versions:
* <p/>
* <blockquote><table border="0" cellpadding="1" cellspacing="0"
* summary="Notable cases.">
* <tr><th>Version </th><th>File Format </th>
* <th>Last Column </th><th>Last Row</th></tr>
* <tr><td>97-2003</td><td>BIFF8</td><td>"IV" (2^8)</td><td>65536 (2^14)</td></tr>
* <tr><td>2007</td><td>BIFF12</td><td>"XFD" (2^14)</td><td>1048576 (2^20)</td></tr>
* </table></blockquote>
* POI currently targets BIFF8 (Excel 97-2003), so the following behaviour can be observed for
* this method:
* <blockquote><table border="0" cellpadding="1" cellspacing="0"
* summary="Notable cases.">
* <tr><th>Input </th>
* <th>Result </th></tr>
* <tr><td>"A", "1"</td><td>true</td></tr>
* <tr><td>"a", "111"</td><td>true</td></tr>
* <tr><td>"A", "65536"</td><td>true</td></tr>
* <tr><td>"A", "65537"</td><td>false</td></tr>
* <tr><td>"iv", "1"</td><td>true</td></tr>
* <tr><td>"IW", "1"</td><td>false</td></tr>
* <tr><td>"AAA", "1"</td><td>false</td></tr>
* <tr><td>"a", "111"</td><td>true</td></tr>
* <tr><td>"Sheet", "1"</td><td>false</td></tr>
* </table></blockquote>
*
* @param colStr a string of only letter characters
* @param rowStr a string of only digit characters
* @return <c>true</c> if the row and col parameters are within range of a BIFF8 spreadsheet.
*/
public static bool CellReferenceIsWithinRange(String colStr, String rowStr, SpreadsheetVersion ssVersion)
{
if (!IsColumnWithnRange(colStr, ssVersion))
{
return false;
}
return IsRowWithnRange(rowStr, ssVersion);
}
public static bool IsRowWithnRange(String rowStr, SpreadsheetVersion ssVersion)
{
int rowNum = Int32.Parse(rowStr, CultureInfo.InvariantCulture);
if (rowNum < 0)
{
throw new InvalidOperationException("Invalid rowStr '" + rowStr + "'.");
}
if (rowNum == 0)
{
// execution Gets here because caller does first pass of discriminating
// potential cell references using a simplistic regex pattern.
return false;
}
return rowNum <= ssVersion.MaxRows;
}
public static bool IsColumnWithnRange(String colStr, SpreadsheetVersion ssVersion)
{
String lastCol = ssVersion.LastColumnName;
int lastColLength = lastCol.Length;
int numberOfLetters = colStr.Length;
if (numberOfLetters > lastColLength)
{
// "Sheet1" case etc
return false; // that was easy
}
if (numberOfLetters == lastColLength)
{
//if (colStr.ToUpper().CompareTo(lastCol) > 0)
if (string.Compare(colStr.ToUpper(), lastCol, StringComparison.Ordinal) > 0)
{
return false;
}
}
else
{
// apparent column name has less chars than max
// no need to check range
}
return true;
}
public override bool Equals(Object o)
{
if (object.ReferenceEquals(this, o))
return true;
if (!(o is CellReference))
{
return false;
}
CellReference cr = (CellReference)o;
return _rowIndex == cr._rowIndex
&& _colIndex == cr._colIndex
&& _isRowAbs == cr._isRowAbs
&& _isColAbs == cr._isColAbs;
}
public override int GetHashCode ()
{
int result = 17;
result = 31 * result + _rowIndex;
result = 31 * result + _colIndex;
result = 31 * result + (_isRowAbs ? 1 : 0);
result = 31 * result + (_isColAbs ? 1 : 0);
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;
namespace LumiSoft.Net.AUTH
{
/// <summary>
/// HTTP digest authentication nonce manager.
/// </summary>
public class Auth_HttpDigest_NonceManager : IDisposable
{
#region class NonceEntry
/// <summary>
/// This class represents nonce entry in active nonces collection.
/// </summary>
private class NonceEntry
{
private string m_Nonce = "";
private DateTime m_CreateTime;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="nonce"></param>
public NonceEntry(string nonce)
{
m_Nonce = nonce;
m_CreateTime = DateTime.Now;
}
#region Properties Implementation
/// <summary>
/// Gets nonce value.
/// </summary>
public string Nonce
{
get{ return m_Nonce; }
}
/// <summary>
/// Gets time when this nonce entry was created.
/// </summary>
public DateTime CreateTime
{
get{ return m_CreateTime; }
}
#endregion
}
#endregion
private List<NonceEntry> m_pNonces = null;
private int m_ExpireTime = 30;
private Timer m_pTimer = null;
/// <summary>
/// Default constructor.
/// </summary>
public Auth_HttpDigest_NonceManager()
{
m_pNonces = new List<NonceEntry>();
m_pTimer = new Timer(15000);
m_pTimer.Elapsed += new ElapsedEventHandler(m_pTimer_Elapsed);
m_pTimer.Enabled = true;
}
#region method Dispose
/// <summary>
/// Cleans up nay resource being used.
/// </summary>
public void Dispose()
{
if(m_pNonces == null){
m_pNonces.Clear();
m_pNonces = null;
}
if(m_pTimer != null){
m_pTimer.Dispose();
m_pTimer = null;
}
}
#endregion
#region method m_pTimer_Elapsed
private void m_pTimer_Elapsed(object sender,ElapsedEventArgs e)
{
RemoveExpiredNonces();
}
#endregion
#region mehtod CreateNonce
/// <summary>
/// Creates new nonce and adds it to active nonces collection.
/// </summary>
/// <returns>Returns new created nonce.</returns>
public string CreateNonce()
{
string nonce = Guid.NewGuid().ToString().Replace("-","");
m_pNonces.Add(new NonceEntry(nonce));
return nonce;
}
#endregion
#region method NonceExists
/// <summary>
/// Checks if specified nonce exists in active nonces collection.
/// </summary>
/// <param name="nonce">Nonce to check.</param>
/// <returns>Returns true if nonce exists in active nonces collection, otherwise returns false.</returns>
public bool NonceExists(string nonce)
{
lock(m_pNonces){
foreach(NonceEntry e in m_pNonces){
if(e.Nonce == nonce){
return true;
}
}
}
return false;
}
#endregion
#region method RemoveNonce
/// <summary>
/// Removes specified nonce from active nonces collection.
/// </summary>
/// <param name="nonce">Nonce to remove.</param>
public void RemoveNonce(string nonce)
{
lock(m_pNonces){
for(int i=0;i<m_pNonces.Count;i++){
if(m_pNonces[i].Nonce == nonce){
m_pNonces.RemoveAt(i);
i--;
}
}
}
}
#endregion
#region method RemoveExpiredNonces
/// <summary>
/// Removes not used nonces what has expired.
/// </summary>
private void RemoveExpiredNonces()
{
lock(m_pNonces){
for(int i=0;i<m_pNonces.Count;i++){
// Nonce expired, remove it.
if(m_pNonces[i].CreateTime.AddSeconds(m_ExpireTime) > DateTime.Now){
m_pNonces.RemoveAt(i);
i--;
}
}
}
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets or sets nonce expire time in seconds.
/// </summary>
public int ExpireTime
{
get{ return m_ExpireTime; }
set{
if(value < 5){
throw new ArgumentException("Property ExpireTime value must be >= 5 !");
}
m_ExpireTime = value;
}
}
#endregion
}
}
| |
/// Copyright (C) 2012-2014 Soomla Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
using UnityEngine;
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
namespace Soomla.Store {
/// <summary>
/// This class provides functions for event handling.
/// </summary>
public class StoreEvents : MonoBehaviour {
private const string TAG = "SOOMLA StoreEvents";
private static StoreEvents instance = null;
/// <summary>
/// Initializes game state before the game starts.
/// </summary>
void Awake(){
if(instance == null){ // making sure we only initialize one instance.
instance = this;
GameObject.DontDestroyOnLoad(this.gameObject);
Initialize();
} else { // Destroying unused instances.
GameObject.Destroy(this.gameObject);
}
}
public static void Initialize() {
SoomlaUtils.LogDebug (TAG, "Initializing StoreEvents ...");
#if UNITY_ANDROID && !UNITY_EDITOR
AndroidJNI.PushLocalFrame(100);
//init EventHandler
using(AndroidJavaClass jniEventHandler = new AndroidJavaClass("com.soomla.unity.StoreEventHandler")) {
jniEventHandler.CallStatic("initialize");
}
AndroidJNI.PopLocalFrame(IntPtr.Zero);
#elif UNITY_IOS && !UNITY_EDITOR
// On iOS, this is initialized inside the bridge library when we call "soomlaStore_Init" in SoomlaStoreIOS
#endif
}
/// <summary>
/// Handles an <c>onBillingSupported</c> event, which is fired when SOOMLA knows that billing IS
/// supported on the device.
/// </summary>
/// <param name="message">Not used here.</param>
public void onBillingSupported(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onBillingSupported");
StoreEvents.OnBillingSupported();
}
/// <summary>
/// Handles an <c>onBillingNotSupported</c> event, which is fired when SOOMLA knows that billing is NOT
/// supported on the device.
/// </summary>
/// <param name="message">Not used here.</param>
public void onBillingNotSupported(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onBillingNotSupported");
StoreEvents.OnBillingNotSupported();
}
/// <summary>
/// Handles an <c>onCurrencyBalanceChanged</c> event, which is fired when the balance of a specific
/// <c>VirtualCurrency</c> has changed.
/// </summary>
/// <param name="message">Message that contains information about the currency whose balance has
/// changed.</param>
public void onCurrencyBalanceChanged(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onCurrencyBalanceChanged:" + message);
string[] vars = Regex.Split(message, "#SOOM#");
VirtualCurrency vc = (VirtualCurrency)StoreInfo.GetItemByItemId(vars[0]);
int balance = int.Parse(vars[1]);
int amountAdded = int.Parse(vars[2]);
StoreEvents.OnCurrencyBalanceChanged(vc, balance, amountAdded);
}
/// <summary>
/// Handles an <c>onGoodBalanceChanged</c> event, which is fired when the balance of a specific
/// <c>VirtualGood</c> has changed.
/// </summary>
/// <param name="message">Message that contains information about the good whose balance has
/// changed.</param>
public void onGoodBalanceChanged(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGoodBalanceChanged:" + message);
string[] vars = Regex.Split(message, "#SOOM#");
VirtualGood vg = (VirtualGood)StoreInfo.GetItemByItemId(vars[0]);
int balance = int.Parse(vars[1]);
int amountAdded = int.Parse(vars[2]);
StoreEvents.OnGoodBalanceChanged(vg, balance, amountAdded);
}
/// <summary>
/// Handles an <c>onGoodEquipped</c> event, which is fired when a specific <c>EquippableVG</c> has been
/// equipped.
/// </summary>
/// <param name="message">Message that contains information about the <c>EquippableVG</c>.</param>
public void onGoodEquipped(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onVirtualGoodEquipped:" + message);
EquippableVG vg = (EquippableVG)StoreInfo.GetItemByItemId(message);
StoreEvents.OnGoodEquipped(vg);
}
/// <summary>
/// Handles an <c>onGoodUnequipped</c> event, which is fired when a specific <c>EquippableVG</c>
/// has been unequipped.
/// </summary>
/// <param name="message">Message that contains information about the <c>EquippableVG</c>.</param>
public void onGoodUnequipped(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onVirtualGoodUnEquipped:" + message);
EquippableVG vg = (EquippableVG)StoreInfo.GetItemByItemId(message);
StoreEvents.OnGoodUnEquipped(vg);
}
/// <summary>
/// Handles an <c>onGoodUpgrade</c> event, which is fired when a specific <c>UpgradeVG</c> has
/// been upgraded/downgraded.
/// </summary>
/// <param name="message">Message that contains information about the good that has been
/// upgraded/downgraded.</param>
public void onGoodUpgrade(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGoodUpgrade:" + message);
string[] vars = Regex.Split(message, "#SOOM#");
VirtualGood vg = (VirtualGood)StoreInfo.GetItemByItemId(vars[0]);
UpgradeVG vgu = null;
if (vars.Length > 1) {
vgu = (UpgradeVG)StoreInfo.GetItemByItemId(vars[1]);
}
StoreEvents.OnGoodUpgrade(vg, vgu);
}
/// <summary>
/// Handles an <c>onItemPurchased</c> event, which is fired when a specific
/// <c>PurchasableVirtualItem</c> has been purchased.
/// </summary>
/// <param name="message">Message that contains information about the good that has been purchased.</param>
public void onItemPurchased(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onItemPurchased:" + message);
string[] vars = Regex.Split(message, "#SOOM#");
PurchasableVirtualItem pvi = (PurchasableVirtualItem)StoreInfo.GetItemByItemId(vars[0]);
string payload = "";
if (vars.Length > 1) {
payload = vars[1];
}
StoreEvents.OnItemPurchased(pvi, payload);
}
/// <summary>
/// Handles the <c>onItemPurchaseStarted</c> event, which is fired when a specific
/// <c>PurchasableVirtualItem</c> purchase process has started.
/// </summary>
/// <param name="message">Message that contains information about the item being purchased.</param>
public void onItemPurchaseStarted(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onItemPurchaseStarted:" + message);
PurchasableVirtualItem pvi = (PurchasableVirtualItem)StoreInfo.GetItemByItemId(message);
StoreEvents.OnItemPurchaseStarted(pvi);
}
/// <summary>
/// Handles the <c>onMarketPurchaseCancelled</c> event, which is fired when a Market purchase was cancelled
/// by the user.
/// </summary>
/// <param name="message">Message that contains information about the market purchase that is being
/// cancelled.</param>
public void onMarketPurchaseCancelled(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onMarketPurchaseCancelled: " + message);
PurchasableVirtualItem pvi = (PurchasableVirtualItem)StoreInfo.GetItemByItemId(message);
StoreEvents.OnMarketPurchaseCancelled(pvi);
}
/// <summary>
/// Handles the <c>onMarketPurchase</c> event, which is fired when a Market purchase has occurred.
/// </summary>
/// <param name="message">Message that contains information about the market purchase.</param>
public void onMarketPurchase(string message) {
Debug.Log ("SOOMLA/UNITY onMarketPurchase:" + message);
string[] vars = Regex.Split(message, "#SOOM#");
PurchasableVirtualItem pvi = (PurchasableVirtualItem)StoreInfo.GetItemByItemId(vars[0]);
string payload = "";
string purchaseToken = "";
if (vars.Length > 1) {
payload = vars[1];
}
if (vars.Length > 2) {
purchaseToken = vars[2];
}
StoreEvents.OnMarketPurchase(pvi, purchaseToken, payload);
}
/// <summary>
/// Handles the <c>onMarketPurchaseStarted</c> event, which is fired when a Market purchase has started.
/// </summary>
/// <param name="message">Message that contains information about the maret purchase that is being
/// started.</param>
public void onMarketPurchaseStarted(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onMarketPurchaseStarted: " + message);
PurchasableVirtualItem pvi = (PurchasableVirtualItem)StoreInfo.GetItemByItemId(message);
StoreEvents.OnMarketPurchaseStarted(pvi);
}
/// <summary>
/// Handles the <c>onMarketRefund</c> event, which is fired when a Market refund has been issued.
/// </summary>
/// <param name="message">Message that contains information about the market refund that has occurred.</param>
public void onMarketRefund(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onMarketRefund:" + message);
PurchasableVirtualItem pvi = (PurchasableVirtualItem)StoreInfo.GetItemByItemId(message);
StoreEvents.OnMarketPurchaseStarted(pvi);
}
/// <summary>
/// Handles the <c>onRestoreTransactionsFinished</c> event, which is fired when the restore transactions
/// process has finished.
/// </summary>
/// <param name="message">Message that contains information about the <c>restoreTransactions</c> process that
/// has finished.</param>
public void onRestoreTransactionsFinished(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onRestoreTransactionsFinished:" + message);
bool success = Convert.ToBoolean(int.Parse(message));
StoreEvents.OnRestoreTransactionsFinished(success);
}
/// <summary>
/// Handles the <c>onRestoreTransactionsStarted</c> event, which is fired when the restore transactions
/// process has started.
/// </summary>
/// <param name="message">Message that contains information about the <c>restoreTransactions</c> process that
/// has started.</param>
public void onRestoreTransactionsStarted(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onRestoreTransactionsStarted");
StoreEvents.OnRestoreTransactionsStarted();
}
/// <summary>
/// Handles the <c>onMarketItemsRefreshStarted</c> event, which is fired when items associated with market
/// refresh process has started.
/// </summary>
/// <param name="message">Message that contains information about the <c>market refresh</c> process that
/// has started.</param>
public void onMarketItemsRefreshStarted(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onMarketItemsRefreshStarted");
StoreEvents.OnMarketItemsRefreshStarted();
}
/// <summary>
/// Handles the <c>onMarketItemsRefreshFinished</c> event, which is fired when items associated with market are
/// refreshed (prices, titles ...).
/// </summary>
/// <param name="message">Message that contains information about the process that is occurring.</param>
public void onMarketItemsRefreshFinished(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onMarketItemsRefreshFinished: " + message);
string[] marketItemsChanges = Regex.Split(message, "#SOOM#");
List<MarketItem> marketItems = new List<MarketItem>();
foreach (string mic in marketItemsChanges) {
if (string.IsNullOrEmpty(mic.Trim())) {
continue;
}
JSONObject micJSON = new JSONObject(mic);
string productId = micJSON["productId"].str;
string marketPrice = micJSON["market_price"].str;
string marketTitle = micJSON["market_title"].str;
string marketDescription = micJSON["market_desc"].str;
try {
PurchasableVirtualItem pvi = StoreInfo.GetPurchasableItemWithProductId(productId);
MarketItem mi = ((PurchaseWithMarket)pvi.PurchaseType).MarketItem;
mi.MarketPrice = marketPrice;
mi.MarketTitle = marketTitle;
mi.MarketDescription = marketDescription;
pvi.save();
marketItems.Add(mi);
} catch (VirtualItemNotFoundException ex){
SoomlaUtils.LogDebug(TAG, ex.Message);
}
}
StoreEvents.OnMarketItemsRefreshFinished(marketItems);
}
/// <summary>
/// Handles the <c>onItemPurchaseStarted</c> event, which is fired when an unexpected/unrecognized error
/// occurs in store.
/// </summary>
/// <param name="message">Message that contains information about the error.</param>
public void onUnexpectedErrorInStore(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onUnexpectedErrorInStore");
StoreEvents.OnUnexpectedErrorInStore(message);
}
/// <summary>
/// Handles the <c>onSoomlaStoreInitialized</c> event, which is fired when <c>SoomlaStore</c>
/// is initialized.
/// </summary>
/// <param name="message">Not used here.</param>
public void onSoomlaStoreInitialized(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onSoomlaStoreInitialized");
StoreEvents.OnSoomlaStoreInitialized();
}
#if UNITY_ANDROID && !UNITY_EDITOR
public void onIabServiceStarted(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onIabServiceStarted");
StoreEvents.OnIabServiceStarted();
}
public void onIabServiceStopped(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onIabServiceStopped");
StoreEvents.OnIabServiceStopped();
}
#endif
public delegate void Action();
public static Action OnBillingNotSupported = delegate {};
public static Action OnBillingSupported = delegate {};
public static Action<VirtualCurrency, int, int> OnCurrencyBalanceChanged = delegate {};
public static Action<VirtualGood, int, int> OnGoodBalanceChanged = delegate {};
public static Action<EquippableVG> OnGoodEquipped = delegate {};
public static Action<EquippableVG> OnGoodUnEquipped = delegate {};
public static Action<VirtualGood, UpgradeVG> OnGoodUpgrade = delegate {};
public static Action<PurchasableVirtualItem, string> OnItemPurchased = delegate {};
public static Action<PurchasableVirtualItem> OnItemPurchaseStarted = delegate {};
public static Action<PurchasableVirtualItem> OnMarketPurchaseCancelled = delegate {};
public static Action<PurchasableVirtualItem, string, string> OnMarketPurchase = delegate {};
public static Action<PurchasableVirtualItem> OnMarketPurchaseStarted = delegate {};
public static Action<PurchasableVirtualItem> OnMarketRefund = delegate {};
public static Action<bool> OnRestoreTransactionsFinished = delegate {};
public static Action OnRestoreTransactionsStarted = delegate {};
public static Action OnMarketItemsRefreshStarted = delegate {};
public static Action<List<MarketItem>> OnMarketItemsRefreshFinished = delegate {};
public static Action<string> OnUnexpectedErrorInStore = delegate {};
public static Action OnSoomlaStoreInitialized = delegate {};
#if UNITY_ANDROID && !UNITY_EDITOR
public static Action OnIabServiceStarted = delegate {};
public static Action OnIabServiceStopped = delegate {};
#endif
}
}
| |
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2008 Jonathan Skeet. 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.
#endregion
namespace MoreLinq
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public static partial class MoreEnumerable
{
#region Nested Classes
/// <summary>
/// The private implementation class that produces permutations of a sequence.
/// </summary>
/// <typeparam name="T"></typeparam>
private class PermutationEnumerator<T> : IEnumerator<IList<T>>
{
// NOTE: The algorithm used to generate permutations uses the fact that any set
// can be put into 1-to-1 correspondence with the set of ordinals number (0..n).
// The implementation here is based on the algorithm described by Kenneth H. Rosen,
// in Discrete Mathematics and Its Applications, 2nd edition, pp. 282-284.
//
// There are two significant changes from the original implementation.
// First, the algorithm uses lazy evaluation and streaming to fit well into the
// nature of most LINQ evaluations.
//
// Second, the algorithm has been modified to use dynamically generated nested loop
// state machines, rather than an integral computation of the factorial function
// to determine when to terminate. The original algorithm required a priori knowledge
// of the number of iterations necessary to produce all permutations. This is a
// necessary step to avoid overflowing the range of the permutation arrays used.
// The number of permutation iterations is defined as the factorial of the original
// set size minus 1.
//
// However, there's a fly in the ointment. The factorial function grows VERY rapidly.
// 13! overflows the range of a Int32; while 28! overflows the range of decimal.
// To overcome these limitations, the algorithm relies on the fact that the factorial
// of N is equivalent to the evaluation of N-1 nested loops. Unfortunatley, you can't
// just code up a variable number of nested loops ... this is where .NET generators
// with their elegant 'yield return' syntax come to the rescue.
//
// The methods of the Loop extension class (For and NestedLoops) provide the implementation
// of dynamic nested loops using generators and sequence composition. In a nutshell,
// the two Repeat() functions are the constructor of loops and nested loops, respectively.
// The NestedLoops() function produces a composition of loops where the loop counter
// for each nesting level is defined in a separate sequence passed in the call.
//
// For example: NestedLoops( () => DoSomething(), new[] { 6, 8 } )
//
// is equivalent to: for( int i = 0; i < 6; i++ )
// for( int j = 0; j < 8; j++ )
// DoSomething();
#region Private Fields
private readonly IList<T> m_ValueSet;
private readonly int[] m_Permutation;
private readonly IEnumerable<Action> m_Generator;
private IEnumerator<Action> m_GeneratorIterator;
private bool m_HasMoreResults;
#endregion
#region Constructors
public PermutationEnumerator(IEnumerable<T> valueSet)
{
m_ValueSet = valueSet.ToArray();
m_Permutation = new int[m_ValueSet.Count];
// The nested loop construction below takes into account the fact that:
// 1) for empty sets and sets of cardinality 1, there exists only a single permutation.
// 2) for sets larger than 1 element, the number of nested loops needed is: set.Count-1
m_Generator = NestedLoops(NextPermutation, Enumerable.Range(2, Math.Max(0, m_ValueSet.Count - 1)));
Reset();
}
#endregion
#region IEnumerator Members
public void Reset()
{
if (m_GeneratorIterator != null)
m_GeneratorIterator.Dispose();
// restore lexographic ordering of the permutation indexes
for (var i = 0; i < m_Permutation.Length; i++)
m_Permutation[i] = i;
// start a newiteration over the nested loop generator
m_GeneratorIterator = m_Generator.GetEnumerator();
// we must advance the nestedloop iterator to the initial element,
// this ensures that we only ever produce N!-1 calls to NextPermutation()
m_GeneratorIterator.MoveNext();
m_HasMoreResults = true; // there's always at least one permutation: the original set itself
}
public IList<T> Current { get; private set; }
object IEnumerator.Current
{
get { return Current; }
}
public bool MoveNext()
{
Current = PermuteValueSet();
// check if more permutation left to enumerate
var prevResult = m_HasMoreResults;
m_HasMoreResults = m_GeneratorIterator.MoveNext();
if (m_HasMoreResults)
m_GeneratorIterator.Current(); // produce the next permutation ordering
// we return prevResult rather than m_HasMoreResults because there is always
// at least one permtuation: the original set. Also, this provides a simple way
// to deal with the disparity between sets that have only one loop level (size 0-2)
// and those that have two or more (size > 2).
return prevResult;
}
void IDisposable.Dispose() { }
#endregion
#region Private Methods
/// <summary>
/// Transposes elements in the cached permutation array to produce the next permutation
/// </summary>
private void NextPermutation()
{
// find the largest index j with m_Permutation[j] < m_Permutation[j+1]
var j = m_Permutation.Length - 2;
while (m_Permutation[j] > m_Permutation[j + 1])
j--;
// find index k such that m_Permutation[k] is the smallest integer
// greater than m_Permutation[j] to the right of m_Permutation[j]
var k = m_Permutation.Length - 1;
while (m_Permutation[j] > m_Permutation[k])
k--;
// interchange m_Permutation[j] and m_Permutation[k]
var oldValue = m_Permutation[k];
m_Permutation[k] = m_Permutation[j];
m_Permutation[j] = oldValue;
// move the tail of the permutation after the jth position in increasing order
var x = m_Permutation.Length - 1;
var y = j + 1;
while (x > y)
{
oldValue = m_Permutation[y];
m_Permutation[y] = m_Permutation[x];
m_Permutation[x] = oldValue;
x--;
y++;
}
}
/// <summary>
/// Creates a new list containing the values from the original
/// set in their new permuted order.
/// </summary>
/// <remarks>
/// The reason we return a new permuted value set, rather than reuse
/// an existing collection, is that we have no control over what the
/// consumer will do with the results produced. They could very easily
/// generate and store a set of permutations and only then begin to
/// process them. If we reused the same collection, the caller would
/// be surprised to discover that all of the permutations looked the
/// same.
/// </remarks>
/// <returns>List of permuted source sequence values</returns>
private IList<T> PermuteValueSet()
{
var permutedSet = new T[m_Permutation.Length];
for (var i = 0; i < m_Permutation.Length; i++)
permutedSet[i] = m_ValueSet[m_Permutation[i]];
return permutedSet;
}
#endregion
}
#endregion
/// <summary>
/// Generates a sequence of lists that represent the permutations of the original sequence.
/// </summary>
/// <remarks>
/// A permutation is a unique re-ordering of the elements of the sequence.<br/>
/// This operator returns permutations in a deferred, streaming fashion; however, each
/// permutation is materialized into a new list. There are N! permutations of a sequence,
/// where N => sequence.Count().<br/>
/// Be aware that the original sequence is considered one of the permutations and will be
/// returned as one of the results.
/// </remarks>
/// <typeparam name="T">The type of the elements in the sequence</typeparam>
/// <param name="sequence">The original sequence to permute</param>
/// <returns>A sequence of lists representing permutations of the original sequence</returns>
public static IEnumerable<IList<T>> Permutations<T>(this IEnumerable<T> sequence)
{
if (sequence == null) throw new ArgumentNullException("sequence");
return PermutationsImpl(sequence);
}
private static IEnumerable<IList<T>> PermutationsImpl<T>(IEnumerable<T> sequence)
{
using (var iter = new PermutationEnumerator<T>(sequence))
{
while (iter.MoveNext())
yield return iter.Current;
}
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
using OpenLiveWriter.Interop.Com;
using OpenLiveWriter.Interop.Windows;
namespace OpenLiveWriter.CoreServices
{
/// <summary>
/// General purpose implementation of an Ole DataObject that accepts arbirary
/// binary data (the .NET IDataObject implementation does not allow you to pass
/// arbitrary binary data so if you want to do this you need a class like this).
/// This implementation does not support advise sinks.
/// </summary>
public class OleDataObjectImpl : IOleDataObject, IDisposable
{
/// <summary>
/// Create an OleDataObjectImpl
/// </summary>
public OleDataObjectImpl()
{
}
/// <summary>
/// Dispose the data object
/// </summary>
public void Dispose()
{
if (oleDataEntries != null)
{
foreach ( OleDataEntry dataEntry in oleDataEntries )
Ole32.ReleaseStgMedium( ref dataEntry.stgm ) ;
oleDataEntries = null ;
}
}
/// <summary>
/// Verify the user called Dispose at garbage collection time
/// </summary>
~OleDataObjectImpl()
{
Debug.Assert( oleDataEntries == null, "You must call Dispose on OleDataObjectImpl when finished using it!" ) ;
}
/// <summary>
/// Renders the data described in a FORMATETC structure and transfers it
/// through the STGMEDIUM structure.
/// </summary>
/// <param name="pFormatEtc">Pointer to the FORMATETC structure that defines
/// the format, medium, and target device to use when passing the data. It is
/// possible to specify more than one medium by using the Boolean OR operator,
/// allowing the method to choose the best medium among those specified</param>
/// <param name="pMedium">Pointer to the STGMEDIUM structure that indicates
/// the storage medium containing the returned data through its tymed member,
/// and the responsibility for releasing the medium through the value of its
/// pUnkForRelease member. If pUnkForRelease is NULL, the receiver of the medium
/// is responsible for releasing it; otherwise, pUnkForRelease points to the
/// IUnknown on the appropriate object so its Release method can be called.
/// The medium must be allocated and filled in by IDataObject::GetData</param>
public int GetData(ref FORMATETC pFormatEtc, ref STGMEDIUM pMedium)
{
// check to see if we have data of the requested type
int dataFormatIndex ;
int result = FindDataFormat( ref pFormatEtc, out dataFormatIndex ) ;
// if we do then return a clone of it (returns error code if an
// error occurs during the clone)
if ( result == HRESULT.S_OK )
{
// lookup the entry
OleDataEntry dataEntry = (OleDataEntry) oleDataEntries[dataFormatIndex] ;
// clone the storage and return
return CloneStgMedium( dataEntry.stgm, ref pMedium ) ;
}
// don't have the data, return the error code passed back to us
// from FindDataFormat
else
{
return result ;
}
}
/// <summary>
/// Renders the data described in a FORMATETC structure and transfers it
/// through the STGMEDIUM structure allocated by the caller.
/// </summary>
/// <param name="pFormatEtc">Pointer to the FORMATETC structure that defines
/// the format, medium, and target device to use when passing the data. It is
/// possible to specify more than one medium by using the Boolean OR operator,
/// allowing the method to choose the best medium among those specified</param>
/// <param name="pMedium">Pointer to the STGMEDIUM structure that defines the
/// storage medium containing the data being transferred. The medium must be
/// allocated by the caller and filled in by IDataObject::GetDataHere. The
/// caller must also free the medium. The implementation of this method must
/// always supply a value of NULL for the punkForRelease member of the
/// STGMEDIUM structure to which this parameter points</param>
public int GetDataHere(ref FORMATETC pFormatEtc, ref STGMEDIUM pMedium)
{
// For now we don't support this method. MFC uses the internal method
// AfxCopyStgMedium to implement this -- if we absolutely positively
// need to suppport this then we should base are implementation on
// that code (source is the file atlmfc\src\mfc\olemisc.cpp)
return HRESULT.E_NOTIMPL;
}
/// <summary>
/// Determines whether the data object is capable of rendering the data
/// described in the FORMATETC structure.
/// </summary>
/// <param name="pFormatEtc">Pointer to the FORMATETC structure defining
/// the format, medium, and target device to use for the query</param>
public int QueryGetData(ref FORMATETC pFormatEtc)
{
int dataFormatIndex ;
return FindDataFormat( ref pFormatEtc, out dataFormatIndex ) ;
}
/// <summary>
/// Provides a standard FORMATETC structure that is logically equivalent
/// to one that is more complex. You use this method to determine whether
/// two different FORMATETC structures would return the same data, removing
/// the need for duplicate rendering
/// </summary>
/// <param name="pFormatEtcIn">Pointer to the FORMATETC structure that
/// defines the format, medium, and target device that the caller would
/// like to use to retrieve data in a subsequent call such as
/// IDataObject::GetData. The TYMED member is not significant in this case
/// and should be ignored</param>
/// <param name="pFormatEtcOut">Pointer to a FORMATETC structure that contains
/// the most general information possible for a specific rendering, making it
/// canonically equivalent to pFormatetcIn. The caller must allocate this
/// structure and the GetCanonicalFormatEtc method must fill in the data.
/// To retrieve data in a subsequent call like IDataObject::GetData, the
/// caller uses the supplied value of pFormatetcOut, unless the value supplied
/// is NULL. This value is NULL if the method returns DATA_S_SAMEFORMATETC.
/// The TYMED member is not significant in this case and should be ignored</param>
/// <returns>S_OK if the logically equivilant structure was provided,
/// otherwise returns DATA_S_SAMEFORMATETC indicating the structures
/// are the same (in this case pFormatEtcOut is NULL)</returns>
public int GetCanonicalFormatEtc(ref FORMATETC pFormatEtcIn, ref FORMATETC pFormatEtcOut)
{
return DATA_S.SAMEFORMATETC ;
}
/// <summary>
/// Provides the source data object with data described by a FORMATETC
/// structure and an STGMEDIUM structure
/// </summary>
/// <param name="pFormatEtc">Pointer to the FORMATETC structure defining the
/// format used by the data object when interpreting the data contained in the
/// storage medium</param>
/// <param name="pMedium">Pointer to the STGMEDIUM structure defining the storage
/// medium in which the data is being passed</param>
/// <param name="fRelease">If TRUE, the data object called, which implements
/// IDataObject::SetData, owns the storage medium after the call returns. This
/// means it must free the medium after it has been used by calling the
/// ReleaseStgMedium function. If FALSE, the caller retains ownership of the
/// storage medium and the data object called uses the storage medium for the
/// duration of the call only</param>
public int SetData(ref FORMATETC pFormatEtc, ref STGMEDIUM pMedium, bool fRelease)
{
// check and see if we have an existing format of this type
int dataFormatIndex ;
int result = FindDataFormat( ref pFormatEtc, out dataFormatIndex ) ;
// if we have an existing format of this type then free it and
// remove it from the list
if ( result == HRESULT.S_OK )
{
OleDataEntry oleDataEntry = (OleDataEntry) oleDataEntries[dataFormatIndex] ;
Ole32.ReleaseStgMedium( ref oleDataEntry.stgm ) ;
oleDataEntries.RemoveAt(dataFormatIndex) ;
}
// create an entry to add to our internal list
OleDataEntry dataEntry ;
// if the caller is releasing the data that is being set then just
// copy bit for bit (we are now responsible for freeing the storage)
if ( fRelease )
{
dataEntry = new OleDataEntry( pFormatEtc, pMedium ) ;
}
// if the caller is not releasing the data object to us then
// we only get to use it for the duration of the call -- we need
// to therefore clone the storage so that we have our own
// copy/reference
else
{
// attempt to clone the storage medium
STGMEDIUM mediumClone = new STGMEDIUM() ;
result = CloneStgMedium( pMedium, ref mediumClone ) ;
if ( result != HRESULT.S_OK )
return result ;
// cloned it, initialize the data entry using the cloned storage
dataEntry = new OleDataEntry( pFormatEtc, mediumClone ) ;
}
// add the entry to our internal list
oleDataEntries.Add( dataEntry ) ;
// return OK
return HRESULT.S_OK ;
}
/// <summary>
/// Creates and returns a pointer to an object to enumerate the FORMATETC
/// supported by the data object
/// </summary>
/// <param name="dwDirection">Direction of the data through a value from
/// the enumeration DATADIR</param>
/// <param name="ppEnumFormatEtc">Address of IEnumFORMATETC* pointer variable
/// that receives the interface pointer to the new enumerator object</param>
public int EnumFormatEtc(DATADIR dwDirection, out IEnumFORMATETC ppEnumFormatEtc)
{
// don't support enumeration of set formats
if ( dwDirection == DATADIR.SET )
{
ppEnumFormatEtc = null ;
return HRESULT.E_NOTIMPL ;
}
// return a new enumerator for our data entries
IEnumFORMATETC enumerator = new EnumFORMATETC(oleDataEntries) ;
enumerators.Add(enumerator) ;
ppEnumFormatEtc = enumerator ;
return HRESULT.S_OK ;
}
/// <summary>
/// Creates a connection between a data object and an advise sink so the
/// advise sink can receive notifications of changes in the data object
/// </summary>
/// <param name="pFormatEtc">Pointer to a FORMATETC structure that defines the
/// format, target device, aspect, and medium that will be used for future
/// notifications. For example, one sink may want to know only when the bitmap
/// representation of the data in the data object changes. Another sink may be
/// interested in only the metafile format of the same object. Each advise sink
/// is notified when the data of interest changes. This data is passed back to
/// the advise sink when notification occurs</param>
/// <param name="advf">DWORD that specifies a group of flags for controlling
/// the advisory connection. Valid values are from the enumeration ADVF.
/// However, only some of the possible ADVF values are relevant for this
/// method (see MSDN documentation for more details).</param>
/// <param name="pAdvSink">Pointer to the IAdviseSink interface on the advisory
/// sink that will receive the change notification</param>
/// <param name="pdwConnection">Pointer to a DWORD token that identifies this
/// connection. You can use this token later to delete the advisory connection
/// (by passing it to IDataObject::DUnadvise). If this value is zero, the
/// connection was not established</param>
public int DAdvise(ref FORMATETC pFormatEtc, uint advf, IntPtr pAdvSink, ref uint pdwConnection)
{
return OLE_E.ADVISENOTSUPPORTED ;
}
/// <summary>
/// Destroys a notification previously set up with the DAdvise method
/// </summary>
/// <param name="dwConnection">DWORD token that specifies the connection to remove.
/// Use the value returned by IDataObject::DAdvise when the connection was originally
/// established</param>
public int DUnadvise(uint dwConnection)
{
return OLE_E.ADVISENOTSUPPORTED ;
}
/// <summary>
/// Creates and returns a pointer to an object to enumerate the current
/// advisory connections
/// </summary>
/// <param name="ppEnumAdvise">Address of IEnumSTATDATA* pointer variable that
/// receives the interface pointer to the new enumerator object. If the
/// implementation sets *ppenumAdvise to NULL, there are no connections to
/// advise sinks at this time</param>
public int EnumDAdvise(ref IntPtr ppEnumAdvise)
{
return OLE_E.ADVISENOTSUPPORTED ;
}
/// <summary>
/// Private helper method to find an existing data format
/// </summary>
/// <param name="pFormatEtc">format spec</param>
/// <param name="dataIndex">returned index of data format if we've got it,
/// -1 if we don't have it</param>
/// <returns>S_OK if the data format was found, otherwise the appropriate
/// OLE error code (see QueryGetData for documentation on error codes)</returns>
private int FindDataFormat(ref FORMATETC pFormatEtc, out int dataIndex )
{
// default to data not found
dataIndex = -1 ;
// no support for comparing target devices
if ( pFormatEtc.ptd != IntPtr.Zero )
return DV_E.TARGETDEVICE ;
// iterate through our FORMATETC structures to see if one matches
// this format spec
for ( int i=0; i<oleDataEntries.Count; i++ )
{
// get the data entry
OleDataEntry dataEntry = (OleDataEntry)oleDataEntries[i] ;
// check for matching format spec
if ( (dataEntry.format.cfFormat == pFormatEtc.cfFormat) &&
(dataEntry.format.dwAspect == pFormatEtc.dwAspect) &&
(dataEntry.format.lindex == pFormatEtc.lindex) )
{
// check for matching data type
if ( (dataEntry.format.tymed & pFormatEtc.tymed) > 0 )
{
dataIndex = i ;
return HRESULT.S_OK ;
}
else
return DV_E.TYMED ;
}
}
// no matching format found
return DV_E.FORMATETC ;
}
/// <summary>
/// Create a cloned copy of the the passed storage medium. This method works via
/// a combination of actually copying underling data and incrementing reference
/// counts on embedded objects.
/// </summary>
/// <param name="stgmIn">storage medium in</param>
/// <param name="stgmOut">storage medium out</param>
/// <returns>HRESULT.S_OK if the medium was successfully cloned, various
/// OLE error codes if an error occurs during the clone </returns>
private int CloneStgMedium( STGMEDIUM stgmIn, ref STGMEDIUM stgmOut )
{
// copy storage type
stgmOut.tymed = stgmIn.tymed ;
// copy or add ref count to the actual data
switch( stgmIn.tymed )
{
// global memory blocks get copied
case TYMED.HGLOBAL:
using (HGlobalLock input = new HGlobalLock(stgmIn.contents))
stgmOut.contents = input.Clone() ;
break;
// COM interfaces get copied w/ their ref-count incremented
case TYMED.ISTREAM:
case TYMED.ISTORAGE:
stgmOut.contents = stgmIn.contents ;
Marshal.AddRef( stgmOut.contents ) ;
break ;
// don't know how to clone other storage medium types (return error)
case TYMED.ENHMF:
case TYMED.FILE:
case TYMED.GDI:
case TYMED.MFPICT:
default:
return DV_E.TYMED ;
}
// copy pUnkForRelease and add a reference count on it if there is one
stgmOut.pUnkForRelease = stgmIn.pUnkForRelease ;
if ( stgmOut.pUnkForRelease != IntPtr.Zero )
Marshal.AddRef( stgmOut.pUnkForRelease ) ;
// return success
return HRESULT.S_OK ;
}
/// <summary>
/// Data entries contained within the data object
/// </summary>
private ArrayList oleDataEntries = new ArrayList() ;
/// <summary>
/// Track the enumerators that we have returned so that a .NET reference
/// is maintained to them
/// </summary>
private ArrayList enumerators = new ArrayList() ;
}
/// <summary>
/// Class which represents a data entry being managed by this class
/// </summary>
internal class OleDataEntry
{
public OleDataEntry( FORMATETC fmt, STGMEDIUM stg )
{
format = fmt ;
stgm = stg ;
}
public FORMATETC format = new FORMATETC();
public STGMEDIUM stgm = new STGMEDIUM() ;
}
/// <summary>
/// Implementation of IEnumFORMATETC for OleDataEntry list
/// </summary>
internal class EnumFORMATETC : IEnumFORMATETC
{
/// <summary>
/// Initialize with an array list of OleDataEntry objects
/// </summary>
/// <param name="entries"></param>
public EnumFORMATETC( ArrayList entries )
{
oleDataEntries = entries ;
}
/// <summary>
/// Get the next celt entries from the enumeration
/// </summary>
/// <param name="celt">entries to fetch</param>
/// <param name="rgelt">array to fetch into (allocated by caller)</param>
/// <param name="pceltFetched">number of entries fetched</param>
/// <returns>S_OK if celt entries are supplied, otherwise S_FALSE</returns>
public int Next(uint celt, FORMATETC[] rgelt, IntPtr pceltFetched)
{
// see how many of the requested items we can serve
int itemsRequested = Convert.ToInt32(celt) ;
int itemsToReturn = Math.Min( itemsRequested, oleDataEntries.Count - (currentItem+1) );
// copy the format structures into the caller's array of structures
for (int i=0; i < itemsToReturn; i++ )
{
OleDataEntry dataEntry = (OleDataEntry) oleDataEntries[++currentItem] ;
rgelt[i] = dataEntry.format ;
}
// update the fetch parameter if requested
if ( pceltFetched != IntPtr.Zero )
Marshal.WriteInt32( pceltFetched, itemsToReturn ) ;
// return the correct status code depending upon whether we
// returned all of the items requested
if ( itemsToReturn == itemsRequested )
return HRESULT.S_OK ;
else
return HRESULT.S_FALSE ;
}
/// <summary>
/// Skip the next celt entries
/// </summary>
/// <param name="celt"></param>
[PreserveSig]
public int Skip(uint celt)
{
currentItem += Convert.ToInt32(celt) ;
if ( currentItem < oleDataEntries.Count )
return HRESULT.S_OK ;
else
return HRESULT.S_FALSE ;
}
/// <summary>
/// Reset to the beginning of the enumeration
/// </summary>
public void Reset()
{
currentItem = -1 ;
}
/// <summary>
/// Clone the current enumerator by returning another enumerator with its
/// position the same as the current one
/// </summary>
/// <returns></returns>
public void Clone(out IEnumFORMATETC ppenum)
{
EnumFORMATETC clone = new EnumFORMATETC(oleDataEntries) ;
clone.currentItem = currentItem ;
ppenum = clone ;
}
/// <summary>
/// List of data entries we are enumerating
/// </summary>
private ArrayList oleDataEntries ;
/// <summary>
/// Item are enumerator is currently positioned over
/// </summary>
private int currentItem = -1 ;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Net;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Protocols.TestSuites.Rdp;
using Microsoft.Protocols.TestSuites.Rdpbcgr;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpbcgr;
using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpeudp;
using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpemt;
using Microsoft.Protocols.TestTools.StackSdk.Security.Sspi;
using System.Security.Cryptography.X509Certificates;
namespace Microsoft.Protocols.TestSuites.Rdpeudp
{
public enum SynAndAck_InvalidType
{
/// <summary>
/// Valid Type.
/// </summary>
None,
/// <summary>
/// uUpStreamMtu is larger than 1232.
/// </summary>
LargerUpStreamMtu,
/// <summary>
/// uUpStreamMtu is smaller than 1132.
/// </summary>
SamllerUpStreamMtu,
/// <summary>
/// uDownStreamMtu is larger than 1232.
/// </summary>
LargerDownStreamMtu,
/// <summary>
/// uDownStreamMtu is smaller than 1132.
/// </summary>
SamllerDownStreamMtu,
}
public enum SourcePacket_InvalidType
{
/// <summary>
/// Valid Type.
/// </summary>
None,
/// <summary>
/// The Source Payload of Source packet is larger than 1232.
/// </summary>
LargerSourcePayload,
}
[TestClass]
public partial class RdpeudpTestSuite : RdpTestClassBase
{
#region Variables
private RdpeudpServer rdpeudpServer;
private RdpeudpServerSocket rdpeudpSocketR;
private RdpeudpServerSocket rdpeudpSocketL;
private RdpemtServer rdpemtServerR;
private RdpemtServer rdpemtServerL;
private uint multitransportRequestId = 0;
private int DelayedACKTimer = 200;
private int RetransmitTimer = 200;
private uint? initSequenceNumber = null;
#endregion
#region Class Initialization And Cleanup
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
RdpTestClassBase.BaseInitialize(context);
}
[ClassCleanup]
public static void ClassCleanup()
{
RdpTestClassBase.BaseCleanup();
}
#endregion
#region Test Initialization And Cleanup
protected override void TestInitialize()
{
base.TestInitialize();
this.rdpbcgrAdapter.TurnVerificationOff(!bVerifyRdpbcgrMessage);
}
protected override void TestCleanup()
{
base.TestCleanup();
this.TestSite.Log.Add(LogEntryKind.Comment, "Trigger client to close all RDP connections for clean up.");
int iResult = this.sutControlAdapter.TriggerClientDisconnectAll();
this.TestSite.Log.Add(LogEntryKind.Debug, "The result of TriggerClientDisconnectAll is {0}.", iResult);
if (rdpemtServerL != null)
rdpemtServerL.Dispose();
if (rdpemtServerR != null)
rdpemtServerR.Dispose();
if (rdpeudpServer != null && rdpeudpServer.Running)
rdpeudpServer.Stop();
this.TestSite.Log.Add(LogEntryKind.Comment, "Stop RDP listening.");
this.rdpbcgrAdapter.StopRDPListening();
}
#endregion
#region Private Methods
/// <summary>
/// Get the initial sequence number of the source packet
/// </summary>
/// <param name="udpTransportMode">The transport mode: reliable or lossy</param>
/// <returns>The initial sequence number of the source packet</returns>
private uint getSnInitialSequenceNumber(TransportMode udpTransportMode)
{
if (udpTransportMode == TransportMode.Reliable)
{
return rdpeudpSocketR.SnInitialSequenceNumber;
}
return rdpeudpSocketL.SnInitialSequenceNumber;
}
private uint getSourcePacketSequenceNumber(TransportMode udpTransportMode)
{
if (udpTransportMode == TransportMode.Reliable)
{
return rdpeudpSocketR.CurSnSource;
}
return rdpeudpSocketL.CurSnSource;
}
/// <summary>
/// Start RDP connection.
/// </summary>
private void StartRDPConnection()
{
// Start RDP listening.
this.TestSite.Log.Add(LogEntryKind.Comment, "Starting RDP listening with transport protocol: {0}", transportProtocol.ToString());
this.rdpbcgrAdapter.StartRDPListening(transportProtocol);
#region Trigger Client To Connect
// Trigger client to connect.
this.TestSite.Log.Add(LogEntryKind.Comment, "Triggering SUT to initiate a RDP connection to server.");
triggerClientRDPConnect(transportProtocol);
#endregion
#region RDPBCGR Connection
// Waiting for the transport level connection request.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting the transport layer connection request.");
this.rdpbcgrAdapter.ExpectTransportConnection(RDPSessionType.Normal);
// Waiting for the RDP connection sequence.
this.TestSite.Log.Add(LogEntryKind.Comment, "Establishing RDP connection.");
this.rdpbcgrAdapter.EstablishRDPConnection(selectedProtocol, enMethod, enLevel, true, false, rdpServerVersion, true);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server Save Session Info PDU to SUT to notify user has logged on.");
this.rdpbcgrAdapter.ServerSaveSessionInfo(LogonNotificationType.UserLoggedOn, ErrorNotificationType_Values.LOGON_FAILED_OTHER);
#endregion
}
/// <summary>
/// Send SYN and ACK packet.
/// </summary>
/// <param name="udpTransportMode">Transport mode: Reliable or Lossy</param>
/// <param name="invalidType">invalid type</param>
public void SendSynAndAckPacket(TransportMode udpTransportMode, SynAndAck_InvalidType invalidType, uint? initSequenceNumber = null)
{
RdpeudpServerSocket rdpeudpSocket = rdpeudpSocketR;
if (udpTransportMode == TransportMode.Lossy)
{
rdpeudpSocket = rdpeudpSocketL;
}
if (invalidType == SynAndAck_InvalidType.None)
{
// If invalid type is None, send the packet directly.
rdpeudpSocket.SendSynAndAckPacket(initSequenceNumber);
return;
}
// Create the SYN and ACK packet first.
RdpeudpPacket SynAndAckPacket = CreateInvalidSynAndACKPacket(udpTransportMode, invalidType, initSequenceNumber);
rdpeudpSocket.SendPacket(SynAndAckPacket);
}
/// <summary>
/// Establish a UDP connection.
/// </summary>
/// <param name="udpTransportMode">Transport mode: Reliable or Lossy.</param>
/// <param name="timeout">Wait time.</param>
/// <param name="verifyPacket">Whether verify the received packet.</param>
/// <returns>The accepted socket.</returns>
private RdpeudpSocket EstablishUDPConnection(TransportMode udpTransportMode, TimeSpan timeout, bool verifyPacket = false, bool autoHanlde = false)
{
// Start UDP listening.
if(rdpeudpServer == null)
rdpeudpServer = new RdpeudpServer((IPEndPoint)this.rdpbcgrAdapter.SessionContext.LocalIdentity, autoHanlde);
if(!rdpeudpServer.Running)
rdpeudpServer.Start();
// Send a Server Initiate Multitransport Request PDU.
byte[] securityCookie = new byte[16];
Random rnd = new Random();
rnd.NextBytes(securityCookie);
Multitransport_Protocol_value requestedProtocol = Multitransport_Protocol_value.INITITATE_REQUEST_PROTOCOL_UDPFECR;
if (udpTransportMode == TransportMode.Lossy)
{
requestedProtocol = Multitransport_Protocol_value.INITITATE_REQUEST_PROTOCOL_UDPFECL;
}
this.rdpbcgrAdapter.SendServerInitiateMultitransportRequestPDU(++this.multitransportRequestId, requestedProtocol, securityCookie);
// Create a UDP socket.
RdpeudpServerSocket rdpudpSocket = rdpeudpServer.CreateSocket(((IPEndPoint)this.rdpbcgrAdapter.SessionContext.Identity).Address, udpTransportMode, timeout);
if (rdpudpSocket == null)
{
this.Site.Assert.Fail("Failed to create a UDP socket for the Client : {0}", ((IPEndPoint)this.rdpbcgrAdapter.SessionContext.Identity).Address);
}
if (udpTransportMode == TransportMode.Reliable)
{
this.rdpeudpSocketR = rdpudpSocket;
}
else
{
this.rdpeudpSocketL = rdpudpSocket;
}
// Expect a SYN packet.
RdpeudpPacket synPacket = rdpudpSocket.ExpectSynPacket(timeout);
if (synPacket == null)
{
this.Site.Assert.Fail("Time out when waiting for the SYN packet");
}
// Verify the SYN packet.
if (verifyPacket)
{
VerifySYNPacket(synPacket, udpTransportMode);
}
// Send a SYN and ACK packet.
SendSynAndAckPacket(udpTransportMode, SynAndAck_InvalidType.None, initSequenceNumber);
// Expect an ACK packet or ACK and Source Packet.
RdpeudpPacket ackPacket = rdpudpSocket.ExpectACKPacket(timeout);
if (ackPacket == null)
{
this.Site.Assert.Fail("Time out when waiting for the ACK packet to response the ACK and SYN packet");
}
// Verify the ACK packet.
if (verifyPacket)
{
VerifyACKPacket(ackPacket);
}
// If the packet is an ACK and Source Packet, add the source packet to the un-processed packet.
if (ackPacket.fecHeader.uFlags.HasFlag(RDPUDP_FLAG.RDPUDP_FLAG_DATA))
{
byte[] bytes = PduMarshaler.Marshal(ackPacket, false);
RdpeudpBasePacket stackpacket = new RdpeudpBasePacket(bytes);
rdpudpSocket.ReceivePacket(stackpacket);
}
rdpudpSocket.Connected = true;
return rdpudpSocket;
}
/// <summary>
/// Used to establish a RDPEMT connection.
/// </summary>
/// <param name="udpTransportMode">Transport Mode: Reliable or Lossy.</param>
/// <param name="timeout">Wait time.</param>
private void EstablishRdpemtConnection(TransportMode udpTransportMode, TimeSpan timeout)
{
RdpeudpServerSocket rdpeudpSocket = rdpeudpSocketR;
if (udpTransportMode == TransportMode.Lossy)
{
rdpeudpSocket = rdpeudpSocketL;
}
if (!rdpeudpSocket.AutoHandle)
{
rdpeudpSocket.AutoHandle = true;
}
String certFile = this.Site.Properties["CertificatePath"];
String certPwd = this.Site.Properties["CertificatePassword"];
X509Certificate2 cert = new X509Certificate2(certFile, certPwd);
RdpemtServer rdpemtServer = new RdpemtServer(rdpeudpSocket, cert);
uint receivedRequestId;
byte[] receivedSecurityCookie;
if (!rdpemtServer.ExpectConnect(waitTime, out receivedRequestId, out receivedSecurityCookie))
{
Site.Assert.Fail("RDPEMT tunnel creation failed");
}
rdpeudpSocket.AutoHandle = false;
if (udpTransportMode == TransportMode.Reliable)
{
rdpemtServerR = rdpemtServer;
}
else
{
rdpemtServerL = rdpemtServer;
}
}
/// <summary>
/// Get the First valid UDP Source Packet.
/// </summary>
/// <param name="udpTransportMode"></param>
/// <returns></returns>
private RdpeudpPacket GetFirstValidUdpPacket(TransportMode udpTransportMode)
{
byte[] dataToSent = null;
RdpeudpPacket firstPacket = null;
String certFile = this.Site.Properties["CertificatePath"];
String certPwd = this.Site.Properties["CertificatePassword"];
X509Certificate2 cert = new X509Certificate2(certFile, certPwd);
if (udpTransportMode == TransportMode.Reliable)
{
RdpeudpTLSChannel secChannel = new RdpeudpTLSChannel(rdpeudpSocketR);
secChannel.AuthenticateAsServer(cert);
RdpeudpPacket packet = rdpeudpSocketR.ExpectPacket(waitTime);
if (packet.payload != null)
{
rdpeudpSocketR.ProcessSourceData(packet); // Process Source Data to makesure ACK Vector created next is correct
secChannel.ReceiveBytes(packet.payload);
}
dataToSent = secChannel.GetDataToSent(waitTime);
firstPacket = rdpeudpSocketR.CreateSourcePacket(dataToSent);
}
else
{
RdpeudpDTLSChannel secChannel = new RdpeudpDTLSChannel(rdpeudpSocketL);
secChannel.AuthenticateAsServer(cert);
RdpeudpPacket packet = rdpeudpSocketL.ExpectPacket(waitTime);
if (packet.payload != null)
{
rdpeudpSocketL.ProcessSourceData(packet); // Process Source Data to makesure ACK Vector created next is correct
secChannel.ReceiveBytes(packet.payload);
}
dataToSent = secChannel.GetDataToSent(waitTime);
firstPacket = rdpeudpSocketL.CreateSourcePacket(dataToSent);
}
return firstPacket;
}
/// <summary>
/// Get the next valid rdpeudp packet.
/// </summary>
/// <param name="udpTransportMode">Transport mode: reliable or Lossy.</param>
/// <returns>The next valid rdpeudp packet.</returns>
private RdpeudpPacket GetNextValidUdpPacket(TransportMode udpTransportMode, byte[] data = null)
{
/*This function is used to get a valid rdpeudp packet.
* Using rdpeudpSocket.LossPacket flag to control whether the socket send the packet.
* First set rdpeudpSocket.LossPacket to true and send a tunnal Data, the socket will store the next packet(RDPEUDP socket which contains the encrypted tunnel data) and doesn't send it.
* Then get the stored packet and return it.
*/
RdpemtServer rdpemtServer = rdpemtServerR;
RdpeudpSocket rdpeudpSocket = rdpeudpSocketR;
if (udpTransportMode == TransportMode.Lossy)
{
rdpemtServer = rdpemtServerL;
rdpeudpSocket = rdpeudpSocketL;
}
if (data == null)
data = new byte[1000];
RDP_TUNNEL_DATA tunnelData = rdpemtServer.CreateTunnelDataPdu(data, null);
byte[] unEncryptData = PduMarshaler.Marshal(tunnelData);
byte[] encryptData = null;
if (udpTransportMode == TransportMode.Reliable)
{
RdpeudpTLSChannel secChannel = rdpemtServer.SecureChannel as RdpeudpTLSChannel;
encryptData = secChannel.Encrypt(unEncryptData);
}
else
{
RdpeudpDTLSChannel secChannel = rdpemtServer.SecureChannel as RdpeudpDTLSChannel;
List<byte[]> encryptDataList = secChannel.Encrypt(unEncryptData);
if (encryptDataList != null && encryptDataList.Count > 0)
{
encryptData = encryptDataList[0];
}
}
RdpeudpPacket packet = rdpeudpSocket.CreateSourcePacket(encryptData);
return packet;
}
/// <summary>
/// Send a udp packet.
/// </summary>
/// <param name="udpTransportMode">Transport mode: reliable or lossy.</param>
/// <param name="packet">The packet to send.</param>
private void SendPacket(TransportMode udpTransportMode, RdpeudpPacket packet)
{
RdpeudpSocket rdpeudpSocket = rdpeudpSocketR;
if (udpTransportMode == TransportMode.Lossy)
{
rdpeudpSocket = rdpeudpSocketL;
}
rdpeudpSocket.SendPacket(packet);
}
/// <summary>
/// Get a valid RDPEUDP packet and send it.
/// </summary>
/// <param name="udpTransportMode">Transport mode: reliable or lossy.</param>
private void SendNextValidUdpPacket(TransportMode udpTransportMode, byte[] data = null)
{
RdpemtServer rdpemtServer = rdpemtServerR;
if (udpTransportMode == TransportMode.Lossy)
{
rdpemtServer = rdpemtServerL;
}
if (data == null)
data = new byte[1000];
RDP_TUNNEL_DATA tunnelData = rdpemtServer.CreateTunnelDataPdu(data, null);
rdpemtServer.SendRdpemtPacket(tunnelData);
}
/// <summary>
/// Send an invalid UDP source Packet.
/// </summary>
/// <param name="udpTransportMode"></param>
/// <param name="invalidType"></param>
private void SendInvalidUdpSourcePacket(TransportMode udpTransportMode, SourcePacket_InvalidType invalidType)
{
RdpeudpSocket rdpeudpSocket = rdpeudpSocketR;
RdpemtServer rdpemtServer = rdpemtServerR;
if (udpTransportMode == TransportMode.Lossy)
{
rdpeudpSocket = rdpeudpSocketL;
rdpemtServer = rdpemtServerL;
}
if (invalidType == SourcePacket_InvalidType.LargerSourcePayload)
{
// Change UpStreamMtu of RDPEUDP Socket, so that large data can be sent
ushort upstreamMtu = rdpeudpSocket.UUpStreamMtu;
rdpeudpSocket.UUpStreamMtu = 2000;
byte[] data = new byte[1600];
RDP_TUNNEL_DATA tunnelData = rdpemtServer.CreateTunnelDataPdu(data, null);
rdpemtServer.SendRdpemtPacket(tunnelData);
// Change UpStreamMtu to correct value
rdpeudpSocket.UUpStreamMtu = upstreamMtu;
}
}
/// <summary>
/// Compare two AckVectors.
/// </summary>
/// <param name="vector1">Ack Vector 1.</param>
/// <param name="vector2">Ack Vector 2.</param>
/// <returns></returns>
private bool CompareAckVectors(AckVector[] vector1, AckVector[] vector2)
{
int posForVector1 = 0;
int posForVector2 = 0;
int length1 = vector1[posForVector1].Length+1;
int length2 = vector2[posForVector2].Length+1;
while (posForVector1 < vector1.Length && posForVector2 < vector2.Length)
{
if (vector1[posForVector1].State != vector2[posForVector2].State)
{
return false;
}
if (length1 == length2)
{
posForVector1++;
posForVector2++;
if (!(posForVector1 < vector1.Length && posForVector2 < vector2.Length))
break;
length1 = vector1[posForVector1].Length+1;
length2 = vector2[posForVector2].Length+1;
}
else if (length1 > length2)
{
length1 -= length2;
posForVector2++;
if (!(posForVector1 < vector1.Length && posForVector2 < vector2.Length))
break;
length2 = vector2[posForVector2].Length + 1;
}
else
{
length2 -= length1;
posForVector1++;
if (!(posForVector1 < vector1.Length && posForVector2 < vector2.Length))
break;
length1 = vector1[posForVector1].Length + 1;
}
}
if (posForVector1 < vector1.Length || posForVector2 < vector2.Length)
{
return false;
}
return true;
}
/// <summary>
/// Expect for a Source Packet.
/// </summary>
/// <param name="udpTransportMode">Transport mode: reliable or lossy.</param>
/// <param name="timeout">Wait time</param>
/// <returns></returns>
private RdpeudpPacket WaitForSourcePacket(TransportMode udpTransportMode, TimeSpan timeout, uint sequnceNumber = 0)
{
RdpeudpSocket rdpeudpSocket = rdpeudpSocketR;
if (udpTransportMode == TransportMode.Lossy)
{
rdpeudpSocket = rdpeudpSocketL;
}
DateTime endTime = DateTime.Now + timeout;
while (DateTime.Now < endTime)
{
RdpeudpPacket packet = rdpeudpSocket.ExpectPacket(endTime - DateTime.Now);
if (packet!=null && packet.fecHeader.uFlags.HasFlag(RDPUDP_FLAG.RDPUDP_FLAG_DATA))
{
if (sequnceNumber == 0||packet.sourceHeader.Value.snSourceStart == sequnceNumber)
{
return packet;
}
}
}
return null;
}
/// <summary>
/// Wait for an ACK packet which meets certain conditions.
/// </summary>
/// <param name="udpTransportMode">Transport mode: reliable or lossy.</param>
/// <param name="timeout">Wait time.</param>
/// <param name="expectAckVectors">Expected ack vectors.</param>
/// <param name="hasFlag">Flags, which the ACK packet must contain.</param>
/// <param name="notHasFlag">Flags, which the ACK packet must no contain.</param>
/// <returns></returns>
private RdpeudpPacket WaitForACKPacket(TransportMode udpTransportMode, TimeSpan timeout, AckVector[] expectAckVectors = null, RDPUDP_FLAG hasFlag = 0, RDPUDP_FLAG notHasFlag = 0)
{
RdpeudpSocket rdpeudpSocket = rdpeudpSocketR;
if (udpTransportMode == TransportMode.Lossy)
{
rdpeudpSocket = rdpeudpSocketL;
}
DateTime endTime = DateTime.Now + timeout;
while (DateTime.Now < endTime)
{
RdpeudpPacket ackPacket = rdpeudpSocket.ExpectACKPacket(endTime - DateTime.Now);
if (ackPacket!=null)
{
if (expectAckVectors != null)
{
if (!(ackPacket.ackVectorHeader.HasValue && CompareAckVectors(ackPacket.ackVectorHeader.Value.AckVectorElement, expectAckVectors)))
{
continue;
}
}
if (hasFlag != 0)
{
if ((ackPacket.fecHeader.uFlags & hasFlag) != hasFlag)
{
continue;
}
}
if (notHasFlag != 0)
{
if ((ackPacket.fecHeader.uFlags & notHasFlag) != 0)
{
continue;
}
}
return ackPacket;
}
}
return null;
}
/// <summary>
/// Create invalid SYN and ACK Packet
/// </summary>
/// <param name="udpTransportMode">Transport mode: reliable or lossy</param>
/// <param name="invalidType">Invalid type</param>
/// <param name="initSequenceNumber">init sequence</param>
/// <returns></returns>
private RdpeudpPacket CreateInvalidSynAndACKPacket(TransportMode udpTransportMode, SynAndAck_InvalidType invalidType, uint? initSequenceNumber = null)
{
RdpeudpServerSocket rdpeudpSocket = rdpeudpSocketR;
if (udpTransportMode == TransportMode.Lossy)
{
rdpeudpSocket = rdpeudpSocketL;
}
// Create the SYN and ACK packet.
RdpeudpPacket SynAndAckPacket = new RdpeudpPacket();
SynAndAckPacket.fecHeader.snSourceAck = rdpeudpSocket.SnSourceAck;
SynAndAckPacket.fecHeader.uReceiveWindowSize = rdpeudpSocket.UReceiveWindowSize;
SynAndAckPacket.fecHeader.uFlags = RDPUDP_FLAG.RDPUDP_FLAG_SYN | RDPUDP_FLAG.RDPUDP_FLAG_ACK;
RDPUDP_SYNDATA_PAYLOAD SynPayload = rdpeudpSocket.CreateSynData(initSequenceNumber);
switch (invalidType)
{
case SynAndAck_InvalidType.LargerUpStreamMtu:
SynPayload.uUpStreamMtu = 1232 + 1;
break;
case SynAndAck_InvalidType.SamllerUpStreamMtu:
SynPayload.uUpStreamMtu = 1132 - 1;
break;
case SynAndAck_InvalidType.LargerDownStreamMtu:
SynPayload.uDownStreamMtu = 1232 + 1;
break;
case SynAndAck_InvalidType.SamllerDownStreamMtu:
SynPayload.uDownStreamMtu = 1132 - 1;
break;
}
SynAndAckPacket.SynData = SynPayload;
return SynAndAckPacket;
}
#endregion
#region Packet Verification
/// <summary>
/// Verify SYN packet.
/// </summary>
/// <param name="synPacket">The SYN packet.</param>
/// <param name="udpTransportMode">Transport mode: reliable or lossy.</param>
private void VerifySYNPacket(RdpeudpPacket synPacket, TransportMode udpTransportMode)
{
if (synPacket == null)
{
this.Site.Assert.Fail("The SYN Packet should not be null!");
}
if (synPacket.fecHeader.snSourceAck != uint.MaxValue)
{
this.Site.Assert.Fail("The snSourceAck variable MUST be set to -1 (max value of uint)!");
}
if((synPacket.fecHeader.uFlags & RDPUDP_FLAG.RDPUDP_FLAG_SYN) == 0)
{
this.Site.Assert.Fail("The RDPUDP_FLAG_SYN flag MUST be set in SYN packet!");
}
if (udpTransportMode == TransportMode.Reliable)
{
if ((synPacket.fecHeader.uFlags & RDPUDP_FLAG.RDPUDP_FLAG_SYNLOSSY) == RDPUDP_FLAG.RDPUDP_FLAG_SYNLOSSY)
{
this.Site.Assert.Fail("The RDPUDP_FLAG_SYNLOSSY flag MUST not be set when choose reliable UDP connection!");
}
}
else
{
if ((synPacket.fecHeader.uFlags & RDPUDP_FLAG.RDPUDP_FLAG_SYNLOSSY) == 0)
{
this.Site.Assert.Fail("The RDPUDP_FLAG_SYNLOSSY flag MUST be set When choose lossy UDP connection!");
}
}
if (synPacket.SynData == null)
{
this.Site.Assert.Fail("The SYN Packet should contain a RDPUDP_SYNDATA_PAYLOAD structure!");
}
if (synPacket.SynData.Value.uUpStreamMtu > 1232 || synPacket.SynData.Value.uUpStreamMtu < 1132)
{
this.Site.Assert.Fail("The uUpStreamMtu field MUST be set to a value in the range of 1132 to 1232.");
}
if (synPacket.SynData.Value.uDownStreamMtu > 1232 || synPacket.SynData.Value.uDownStreamMtu < 1132)
{
this.Site.Assert.Fail("The uDownStreamMtu field MUST be set to a value in the range of 1132 to 1232.");
}
}
/// <summary>
/// Verify an ACK Packet.
/// </summary>
/// <param name="ackPacket">The ACK packet.</param>
private void VerifyACKPacket(RdpeudpPacket ackPacket)
{
if (ackPacket == null)
{
this.Site.Assert.Fail("The ACK Packet should not be null!");
}
if ((ackPacket.fecHeader.uFlags & RDPUDP_FLAG.RDPUDP_FLAG_ACK) == 0)
{
this.Site.Assert.Fail("The RDPUDP_FLAG_ACK flag MUST be set in ACK packet!");
}
}
#endregion
}
}
| |
using System.Collections;
using JetBrains.Annotations;
using Mod;
using Mod.Exceptions;
using Photon;
using Photon.Enums;
using UnityEngine;
// ReSharper disable once CheckNamespace
public class Bullet : Photon.MonoBehaviour
{
private Vector3 heightOffSet = Vector3.up * 0.48f;
private bool isdestroying;
private float killTime;
private float killTime2;
private Vector3 launchOffSet = Vector3.zero;
private bool left = true;
public bool leviMode;
public float leviShootTime;
private LineRenderer lineRenderer;
private GameObject master;
private GameObject myRef;
public TITAN myTitan;
private ArrayList nodes = new ArrayList();
private int phase;
private GameObject rope;
private int spiralcount;
private ArrayList spiralNodes;
private Vector3 velocity = Vector3.zero;
private Vector3 velocity2 = Vector3.zero;
public void checkTitan()
{
GameObject obj2 = Camera.main.GetComponent<IN_GAME_MAIN_CAMERA>().main_object;
if (obj2 != null && this.master != null && this.master == obj2)
{
LayerMask mask = 1 << LayerMask.NameToLayer("PlayerAttackBox");
if (Physics.Raycast(transform.position, this.velocity, out var hit, 10f, mask.value))
{
if (hit.collider.name.Contains("PlayerDetectorRC"))
{
TITAN component = hit.collider.transform.root.gameObject.GetComponent<TITAN>();
if (component != null)
{
if (this.myTitan == null)
{
this.myTitan = component;
this.myTitan.isHooked = true;
}
else if (this.myTitan != component)
{
this.myTitan.isHooked = false;
this.myTitan = component;
this.myTitan.isHooked = true;
}
}
}
}
}
}
public void disable()
{
this.phase = 2;
this.killTime = 0f;
if (IN_GAME_MAIN_CAMERA.GameType == GameType.Multiplayer)
photonView.RPC(Rpc.SetHookPhase, PhotonTargets.Others, 2);
}
private void FixedUpdate()
{
if (!(this.phase != 2 && this.phase != 1 || !this.leviMode))
{
this.spiralcount++;
if (this.spiralcount >= 60)
{
this.isdestroying = true;
this.removeMe();
return;
}
}
if (!(IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer || photonView.isMine))
{
if (this.phase == 0)
{
gameObject.transform.position += this.velocity * Time.deltaTime * 50f + this.velocity2 * Time.deltaTime;
this.nodes.Add(new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, gameObject.transform.position.z));
}
}
else if (this.phase == 0)
{
RaycastHit hit;
this.checkTitan();
Transform transform3 = gameObject.transform;
transform3.position += this.velocity * Time.deltaTime * 50f + this.velocity2 * Time.deltaTime;
LayerMask mask = 1 << LayerMask.NameToLayer("EnemyBox");
LayerMask mask2 = 1 << LayerMask.NameToLayer("Ground");
LayerMask mask3 = 1 << LayerMask.NameToLayer("NetworkObject");
LayerMask mask4 = mask | mask2 | mask3;
bool flag2 = false;
bool flag3 = false;
if (this.nodes.Count > 1)
{
flag3 = Physics.Linecast((Vector3) this.nodes[this.nodes.Count - 2], gameObject.transform.position, out hit, mask4.value);
}
else
{
flag3 = Physics.Linecast((Vector3) this.nodes[this.nodes.Count - 1], gameObject.transform.position, out hit, mask4.value);
}
if (flag3)
{
bool flag4 = true;
if (hit.collider.transform.gameObject.layer == LayerMask.NameToLayer("EnemyBox"))
{
if (IN_GAME_MAIN_CAMERA.GameType == GameType.Multiplayer)
photonView.RPC(Rpc.SetHookedObject, PhotonTargets.Others, hit.collider.transform.root.gameObject.GetPhotonView().viewID);
this.master.GetComponent<HERO>().lastHook = hit.collider.transform.root;
transform.parent = hit.collider.transform;
}
else if (hit.collider.transform.gameObject.layer == LayerMask.NameToLayer("Ground"))
{
this.master.GetComponent<HERO>().lastHook = null;
}
else if (hit.collider.transform.gameObject.layer == LayerMask.NameToLayer("NetworkObject") && hit.collider.transform.gameObject.CompareTag("Player") && !this.leviMode)
{
if (IN_GAME_MAIN_CAMERA.GameType == GameType.Multiplayer)
{
photonView.RPC(Rpc.SetHookedObject, PhotonTargets.Others, hit.collider.transform.root.gameObject.GetPhotonView().viewID);
}
this.master.GetComponent<HERO>().hookToHuman(hit.collider.transform.root.gameObject, transform.position);
transform.parent = hit.collider.transform;
this.master.GetComponent<HERO>().lastHook = null;
}
else
{
flag4 = false;
}
if (this.phase == 2)
{
flag4 = false;
}
if (flag4)
{
this.master.GetComponent<HERO>().launch(hit.point, this.left, this.leviMode);
transform.position = hit.point;
if (this.phase != 2)
{
this.phase = 1;
if (IN_GAME_MAIN_CAMERA.GameType == GameType.Multiplayer)
{
photonView.RPC(Rpc.SetHookPhase, PhotonTargets.Others, 1);
photonView.RPC(Rpc.SetHookPosition, PhotonTargets.Others, transform.position);
}
if (this.leviMode)
{
this.getSpiral(this.master.transform.position, this.master.transform.rotation.eulerAngles);
}
flag2 = true;
}
}
}
this.nodes.Add(new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, gameObject.transform.position.z));
if (!flag2)
{
this.killTime2 += Time.deltaTime;
if (this.killTime2 > 0.8f)
{
this.phase = 4;
if (IN_GAME_MAIN_CAMERA.GameType == GameType.Multiplayer)
{
photonView.RPC(Rpc.SetHookPhase, PhotonTargets.Others, 4);
}
}
}
}
}
private void getSpiral(Vector3 masterposition, Vector3 masterrotation)
{
float num = 1.2f;
float num2 = 30f;
float num3 = 2f;
float num4 = 0.5f;
num = 30f;
num3 = 0.05f + this.spiralcount * 0.03f;
if (this.spiralcount < 5)
{
num = Vector2.Distance(new Vector2(masterposition.x, masterposition.z), new Vector2(gameObject.transform.position.x, gameObject.transform.position.z));
}
else
{
num = 1.2f + (60 - this.spiralcount) * 0.1f;
}
num4 -= this.spiralcount * 0.06f;
float num6 = num / num2;
float num7 = num3 / num2;
float num8 = num7 * 2f * 3.141593f;
num4 *= 6.283185f;
this.spiralNodes = new ArrayList();
for (int i = 1; i <= num2; i++)
{
float num10 = i * num6 * (1f + 0.05f * i);
float f = i * num8 + num4 + 1.256637f + masterrotation.y * 0.0173f;
float x = Mathf.Cos(f) * num10;
float z = -Mathf.Sin(f) * num10;
this.spiralNodes.Add(new Vector3(x, 0f, z));
}
}
public bool isHooked()
{
return this.phase == 1;
}
[RPC]
[UsedImplicitly]
private void KillObject()
{
Destroy(this.rope);
Destroy(gameObject);
}
public void launch(Vector3 v, Vector3 v2, string launcher_ref, bool isLeft, GameObject hero, bool isLeviMode = false)
{
if (this.phase != 2)
{
this.master = hero;
this.velocity = v;
float f = Mathf.Acos(Vector3.Dot(v.normalized, v2.normalized)) * 57.29578f;
if (Mathf.Abs(f) > 90f)
{
this.velocity2 = Vector3.zero;
}
else
{
this.velocity2 = Vector3.Project(v2, v);
}
switch (launcher_ref)
{
case "hookRefL1":
this.myRef = hero.GetComponent<HERO>().hookRefL1;
break;
case "hookRefL2":
this.myRef = hero.GetComponent<HERO>().hookRefL2;
break;
case "hookRefR1":
this.myRef = hero.GetComponent<HERO>().hookRefR1;
break;
case "hookRefR2":
this.myRef = hero.GetComponent<HERO>().hookRefR2;
break;
}
this.nodes = new ArrayList
{
this.myRef.transform.position
};
this.phase = 0;
this.leviMode = isLeviMode;
this.left = isLeft;
if (IN_GAME_MAIN_CAMERA.GameType != GameType.Singleplayer && photonView.isMine)
{
photonView.RPC(Rpc.HookOwner, PhotonTargets.Others, hero.GetComponent<HERO>().photonView.viewID, launcher_ref);
photonView.RPC(Rpc.setVelocityAndLeft, PhotonTargets.Others, v, velocity2, left);
}
transform.position = this.myRef.transform.position;
transform.rotation = Quaternion.LookRotation(v.normalized);
}
}
[RPC]
[UsedImplicitly]
private void MyMasterIs(int id, string launcherRef, PhotonMessageInfo info)
{
if (!PhotonView.TryParse(id, out PhotonView view))
return;
master = view.gameObject;
switch (launcherRef)
{
case "hookRefL1":
myRef = master.GetComponent<HERO>().hookRefL1;
break;
case "hookRefL2":
myRef = master.GetComponent<HERO>().hookRefL2;
break;
case "hookRefR1":
myRef = master.GetComponent<HERO>().hookRefR1;
break;
case "hookRefR2":
myRef = master.GetComponent<HERO>().hookRefR2;
break;
default:
throw new NotAllowedException(nameof(MyMasterIs), info);
}
}
[RPC]
[UsedImplicitly]
private void NetLaunch(Vector3 newPosition)
{
this.nodes = new ArrayList
{
newPosition
};
}
[RPC]
[UsedImplicitly]
private void NetUpdateLeviSpiral(Vector3 newPosition, Vector3 masterPosition, Vector3 masterrotation)
{
this.phase = 2;
this.leviMode = true;
this.getSpiral(masterPosition, masterrotation);
Vector3 vector = masterPosition - (Vector3) this.spiralNodes[0];
this.lineRenderer.SetVertexCount(this.spiralNodes.Count - (int) (this.spiralcount * 0.5f));
for (int i = 0; i <= this.spiralNodes.Count - 1 - this.spiralcount * 0.5f; i++)
{
if (this.spiralcount < 5)
{
Vector3 position = (Vector3) this.spiralNodes[i] + vector;
float num2 = this.spiralNodes.Count - 1 - this.spiralcount * 0.5f;
position = new Vector3(position.x, position.y * ((num2 - i) / num2) + newPosition.y * (i / num2), position.z);
this.lineRenderer.SetPosition(i, position);
}
else
{
this.lineRenderer.SetPosition(i, (Vector3) this.spiralNodes[i] + vector);
}
}
}
[RPC]
[UsedImplicitly]
private void NetUpdatePhase1(Vector3 newPosition, Vector3 masterPosition)
{
this.lineRenderer.SetVertexCount(2);
this.lineRenderer.SetPosition(0, newPosition);
this.lineRenderer.SetPosition(1, masterPosition);
transform.position = newPosition;
}
private void OnDestroy()
{
if (GameManager.instance != null)
{
GameManager.instance.Hooks.Remove(this);
}
if (this.myTitan != null)
{
this.myTitan.isHooked = false;
}
Destroy(this.rope);
}
public void removeMe()
{
this.isdestroying = true;
if (IN_GAME_MAIN_CAMERA.GameType != GameType.Singleplayer && photonView.isMine)
{
PhotonNetwork.Destroy(photonView);
PhotonNetwork.RemoveRPCs(photonView);
}
else if (IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer)
{
Destroy(this.rope);
Destroy(gameObject);
}
}
private void SetLinePhase()
{
if (this.master == null)
{
if (rope != null)
Destroy(rope);
Destroy(gameObject);
}
else if (this.nodes.Count > 0 && myRef != null && lineRenderer != null)
{
Vector3 vector = this.myRef.transform.position - (Vector3) this.nodes[0];
lineRenderer.SetVertexCount(this.nodes.Count);
for (int i = 0; i <= this.nodes.Count - 1; i++)
lineRenderer.SetPosition(i, (Vector3) this.nodes[i] + vector * Mathf.Pow(0.75f, i));
if (this.nodes.Count > 1)
lineRenderer.SetPosition(1, this.myRef.transform.position);
}
}
[RPC]
[UsedImplicitly]
private void SetPhase(int value)
{
this.phase = value;
}
[RPC]
[UsedImplicitly]
private void SetVelocityAndLeft(Vector3 value, Vector3 v2, bool l)
{
this.velocity = value;
this.velocity2 = v2;
this.left = l;
transform.rotation = Quaternion.LookRotation(value.normalized);
}
private void Start()
{
this.rope = (GameObject) Instantiate(Resources.Load("rope"));
this.lineRenderer = this.rope.GetComponent<LineRenderer>();
GameManager.instance.Hooks.Add(this);
}
[RPC]
[UsedImplicitly]
private void TieMeTo(Vector3 p)
{
transform.position = p;
}
[RPC]
[UsedImplicitly]
private void TieMeToOBJ(int id)
{
if (PhotonView.TryParse(id, out PhotonView view))
transform.parent = view.gameObject.transform;
}
public void DoUpdate()
{
if (this.master == null)
{
this.removeMe();
}
else if (!this.isdestroying)
{
if (this.leviMode)
{
this.leviShootTime += Time.deltaTime;
if (this.leviShootTime > 0.4f)
{
this.phase = 2;
gameObject.GetComponent<MeshRenderer>().enabled = false;
}
}
if (this.phase == 0)
{
this.SetLinePhase();
}
else if (this.phase == 1)
{
Vector3 vector = transform.position - this.myRef.transform.position;
float magnitude = this.master.rigidbody.velocity.magnitude;
float f = vector.magnitude;
int num3 = (int) ((f + magnitude) / 5f);
num3 = Mathf.Clamp(num3, 2, 6);
this.lineRenderer.SetVertexCount(num3);
this.lineRenderer.SetPosition(0, this.myRef.transform.position);
int index = 1;
float num5 = Mathf.Pow(f, 0.3f);
while (index < num3)
{
int num6 = num3 / 2;
float num7 = Mathf.Abs(index - num6);
float num8 = (num6 - num7) / num6;
num8 = Mathf.Pow(num8, 0.5f);
float max = (num5 + magnitude) * 0.0015f * num8;
this.lineRenderer.SetPosition(index, new Vector3(Random.Range(-max, max), Random.Range(-max, max), Random.Range(-max, max)) + this.myRef.transform.position + vector * (index / (float)num3) - Vector3.up * num5 * 0.05f * num8 - this.master.rigidbody.velocity * 0.001f * num8 * num5);
index++;
}
this.lineRenderer.SetPosition(num3 - 1, transform.position);
}
else if (this.phase == 2)
{
if (!this.leviMode)
{
this.lineRenderer.SetVertexCount(2);
this.lineRenderer.SetPosition(0, transform.position);
this.lineRenderer.SetPosition(1, this.myRef.transform.position);
this.killTime += Time.deltaTime * 0.2f;
this.lineRenderer.SetWidth(0.1f - this.killTime, 0.1f - this.killTime);
if (this.killTime > 0.1f)
{
this.removeMe();
}
}
else
{
this.getSpiral(this.master.transform.position, this.master.transform.rotation.eulerAngles);
Vector3 vector4 = this.myRef.transform.position - (Vector3) this.spiralNodes[0];
this.lineRenderer.SetVertexCount(this.spiralNodes.Count - (int) (this.spiralcount * 0.5f));
for (int i = 0; i <= this.spiralNodes.Count - 1 - this.spiralcount * 0.5f; i++)
{
if (this.spiralcount < 5)
{
Vector3 position = (Vector3) this.spiralNodes[i] + vector4;
float num11 = this.spiralNodes.Count - 1 - this.spiralcount * 0.5f;
position = new Vector3(position.x, position.y * ((num11 - i) / num11) + gameObject.transform.position.y * (i / num11), position.z);
this.lineRenderer.SetPosition(i, position);
}
else
{
this.lineRenderer.SetPosition(i, (Vector3) this.spiralNodes[i] + vector4);
}
}
}
}
else if (this.phase == 4)
{
gameObject.transform.position += this.velocity + this.velocity2 * Time.deltaTime;
this.nodes.Add(new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, gameObject.transform.position.z));
Vector3 vector10 = this.myRef.transform.position - (Vector3) this.nodes[0];
for (int j = 0; j <= this.nodes.Count - 1; j++)
{
this.lineRenderer.SetVertexCount(this.nodes.Count);
this.lineRenderer.SetPosition(j, (Vector3) this.nodes[j] + vector10 * Mathf.Pow(0.5f, j));
}
this.killTime2 += Time.deltaTime;
if (this.killTime2 > 0.8f)
{
this.killTime += Time.deltaTime * 0.2f;
this.lineRenderer.SetWidth(0.1f - this.killTime, 0.1f - this.killTime);
if (this.killTime > 0.1f)
{
this.removeMe();
}
}
}
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Resources;
using Microsoft.Build.CommandLine;
using Microsoft.Build.Construction;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Shouldly;
using Xunit;
namespace Microsoft.Build.UnitTests
{
public class CommandLineSwitchesTests
{
public CommandLineSwitchesTests()
{
// Make sure resources are initialized
MSBuildApp.Initialize();
}
[Fact]
public void BogusSwitchIdentificationTests()
{
CommandLineSwitches.ParameterlessSwitch parameterlessSwitch;
string duplicateSwitchErrorMessage;
Assert.False(CommandLineSwitches.IsParameterlessSwitch("bogus", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.Invalid, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
Assert.False(CommandLineSwitches.IsParameterizedSwitch("bogus", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Invalid, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.Null(missingParametersErrorMessage);
Assert.False(unquoteParameters);
}
[Fact]
public void HelpSwitchIdentificationTests()
{
CommandLineSwitches.ParameterlessSwitch parameterlessSwitch;
string duplicateSwitchErrorMessage;
Assert.True(CommandLineSwitches.IsParameterlessSwitch("help", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.Help, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("HELP", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.Help, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("Help", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.Help, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("h", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.Help, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("H", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.Help, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("?", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.Help, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
}
[Fact]
public void VersionSwitchIdentificationTests()
{
CommandLineSwitches.ParameterlessSwitch parameterlessSwitch;
string duplicateSwitchErrorMessage;
Assert.True(CommandLineSwitches.IsParameterlessSwitch("version", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.Version, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("Version", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.Version, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("VERSION", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.Version, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("ver", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.Version, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("VER", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.Version, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("Ver", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.Version, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
}
[Fact]
public void NoLogoSwitchIdentificationTests()
{
CommandLineSwitches.ParameterlessSwitch parameterlessSwitch;
string duplicateSwitchErrorMessage;
Assert.True(CommandLineSwitches.IsParameterlessSwitch("nologo", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.NoLogo, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("NOLOGO", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.NoLogo, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("NoLogo", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.NoLogo, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
}
[Fact]
public void NoAutoResponseSwitchIdentificationTests()
{
CommandLineSwitches.ParameterlessSwitch parameterlessSwitch;
string duplicateSwitchErrorMessage;
Assert.True(CommandLineSwitches.IsParameterlessSwitch("noautoresponse", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.NoAutoResponse, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("NOAUTORESPONSE", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.NoAutoResponse, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("NoAutoResponse", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.NoAutoResponse, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("noautorsp", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.NoAutoResponse, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("NOAUTORSP", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.NoAutoResponse, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("NoAutoRsp", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.NoAutoResponse, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
}
[Fact]
public void NoConsoleLoggerSwitchIdentificationTests()
{
CommandLineSwitches.ParameterlessSwitch parameterlessSwitch;
string duplicateSwitchErrorMessage;
Assert.True(CommandLineSwitches.IsParameterlessSwitch("noconsolelogger", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("NOCONSOLELOGGER", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("NoConsoleLogger", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("noconlog", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("NOCONLOG", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("NoConLog", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
}
[Fact]
public void FileLoggerSwitchIdentificationTests()
{
CommandLineSwitches.ParameterlessSwitch parameterlessSwitch;
string duplicateSwitchErrorMessage;
Assert.True(CommandLineSwitches.IsParameterlessSwitch("fileLogger", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.FileLogger, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("FILELOGGER", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.FileLogger, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("FileLogger", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.FileLogger, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("fl", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.FileLogger, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("FL", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.FileLogger, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
}
[Fact]
public void DistributedFileLoggerSwitchIdentificationTests()
{
CommandLineSwitches.ParameterlessSwitch parameterlessSwitch;
string duplicateSwitchErrorMessage;
Assert.True(CommandLineSwitches.IsParameterlessSwitch("distributedfilelogger", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.DistributedFileLogger, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("DISTRIBUTEDFILELOGGER", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.DistributedFileLogger, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("DistributedFileLogger", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.DistributedFileLogger, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("dfl", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.DistributedFileLogger, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("DFL", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.DistributedFileLogger, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
}
[Fact]
public void FileLoggerParametersIdentificationTests()
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
Assert.True(CommandLineSwitches.IsParameterizedSwitch("flp", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.FileLoggerParameters, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("FLP", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.FileLoggerParameters, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("fileLoggerParameters", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.FileLoggerParameters, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("FILELOGGERPARAMETERS", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.FileLoggerParameters, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
}
#if FEATURE_NODE_REUSE
[Fact]
public void NodeReuseParametersIdentificationTests()
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
Assert.True(CommandLineSwitches.IsParameterizedSwitch("nr", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.NodeReuse, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("NR", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.NodeReuse, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("nodereuse", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.NodeReuse, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("NodeReuse", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.NodeReuse, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
}
#endif
[Fact]
public void ProjectSwitchIdentificationTests()
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
Assert.True(CommandLineSwitches.IsParameterizedSwitch(null, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Project, parameterizedSwitch);
Assert.NotNull(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.Null(missingParametersErrorMessage);
Assert.True(unquoteParameters);
// for the virtual project switch, we match on null, not empty string
Assert.False(CommandLineSwitches.IsParameterizedSwitch(String.Empty, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Invalid, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.Null(missingParametersErrorMessage);
Assert.False(unquoteParameters);
}
[Fact]
public void IgnoreProjectExtensionsSwitchIdentificationTests()
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
Assert.True(CommandLineSwitches.IsParameterizedSwitch("ignoreprojectextensions", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.IgnoreProjectExtensions, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("IgnoreProjectExtensions", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.IgnoreProjectExtensions, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("IGNOREPROJECTEXTENSIONS", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.IgnoreProjectExtensions, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("ignore", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.IgnoreProjectExtensions, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("IGNORE", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.IgnoreProjectExtensions, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
}
[Fact]
public void TargetSwitchIdentificationTests()
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
Assert.True(CommandLineSwitches.IsParameterizedSwitch("target", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Target, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("TARGET", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Target, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("Target", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Target, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("t", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Target, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("T", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Target, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
}
[Fact]
public void PropertySwitchIdentificationTests()
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
Assert.True(CommandLineSwitches.IsParameterizedSwitch("property", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Property, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("PROPERTY", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Property, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("Property", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Property, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("p", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Property, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("P", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Property, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
}
[Fact]
public void LoggerSwitchIdentificationTests()
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
Assert.True(CommandLineSwitches.IsParameterizedSwitch("logger", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Logger, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.False(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("LOGGER", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Logger, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.False(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("Logger", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Logger, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.False(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("l", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Logger, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.False(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("L", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Logger, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.False(unquoteParameters);
}
[Fact]
public void VerbositySwitchIdentificationTests()
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
Assert.True(CommandLineSwitches.IsParameterizedSwitch("verbosity", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Verbosity, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("VERBOSITY", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Verbosity, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("Verbosity", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Verbosity, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("v", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Verbosity, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("V", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Verbosity, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
}
[Fact]
public void DetailedSummarySwitchIndentificationTests()
{
CommandLineSwitches.ParameterlessSwitch parameterlessSwitch;
string duplicateSwitchErrorMessage;
Assert.True(CommandLineSwitches.IsParameterlessSwitch("ds", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.DetailedSummary, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("DS", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.DetailedSummary, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("Ds", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.DetailedSummary, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("detailedsummary", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.DetailedSummary, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("DETAILEDSUMMARY", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.DetailedSummary, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.True(CommandLineSwitches.IsParameterlessSwitch("DetailedSummary", out parameterlessSwitch, out duplicateSwitchErrorMessage));
Assert.Equal(CommandLineSwitches.ParameterlessSwitch.DetailedSummary, parameterlessSwitch);
Assert.Null(duplicateSwitchErrorMessage);
}
[Fact]
public void MaxCPUCountSwitchIdentificationTests()
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
Assert.True(CommandLineSwitches.IsParameterizedSwitch("m", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.MaxCPUCount, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("M", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.MaxCPUCount, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("maxcpucount", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.MaxCPUCount, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("MAXCPUCOUNT", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.MaxCPUCount, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.NotNull(missingParametersErrorMessage);
Assert.True(unquoteParameters);
}
#if FEATURE_XML_SCHEMA_VALIDATION
[Fact]
public void ValidateSwitchIdentificationTests()
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
Assert.True(CommandLineSwitches.IsParameterizedSwitch("validate", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Validate, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.Null(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("VALIDATE", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Validate, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.Null(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("Validate", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Validate, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.Null(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("val", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Validate, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.Null(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("VAL", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Validate, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.Null(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("Val", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Validate, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.Null(missingParametersErrorMessage);
Assert.True(unquoteParameters);
}
#endif
[Fact]
public void PreprocessSwitchIdentificationTests()
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
Assert.True(CommandLineSwitches.IsParameterizedSwitch("preprocess", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Preprocess, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.Null(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("pp", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Preprocess, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.Null(missingParametersErrorMessage);
Assert.True(unquoteParameters);
}
[Fact]
public void IsolateProjectsSwitchIdentificationTests()
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
Assert.True(CommandLineSwitches.IsParameterizedSwitch("isolate", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.IsolateProjects, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.Null(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.False(emptyParametersAllowed);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("ISOLATE", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.IsolateProjects, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.Null(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.False(emptyParametersAllowed);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("isolateprojects", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.IsolateProjects, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.Null(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.False(emptyParametersAllowed);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("isolateProjects", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.IsolateProjects, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.Null(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.False(emptyParametersAllowed);
}
[Fact]
public void GraphBuildSwitchIdentificationTests()
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
Assert.True(CommandLineSwitches.IsParameterizedSwitch("graph", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.GraphBuild, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.Null(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.False(emptyParametersAllowed);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("GRAPH", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.GraphBuild, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.Null(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.False(emptyParametersAllowed);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("graphbuild", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.GraphBuild, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.Null(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.False(emptyParametersAllowed);
Assert.True(CommandLineSwitches.IsParameterizedSwitch("graphBuild", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.GraphBuild, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.Null(missingParametersErrorMessage);
Assert.True(unquoteParameters);
Assert.False(emptyParametersAllowed);
}
[Fact]
public void InputResultsCachesSupportsMultipleOccurrence()
{
CommandLineSwitches switches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(){"/irc", "/irc:a;b", "/irc:c;d"}, switches);
switches[CommandLineSwitches.ParameterizedSwitch.InputResultsCaches].ShouldBe(new []{null, "a", "b", "c", "d"});
switches.HaveErrors().ShouldBeFalse();
}
[Fact]
public void OutputResultsCache()
{
CommandLineSwitches switches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(){"/orc:a"}, switches);
switches[CommandLineSwitches.ParameterizedSwitch.OutputResultsCache].ShouldBe(new []{"a"});
switches.HaveErrors().ShouldBeFalse();
}
[Fact]
public void OutputResultsCachesDoesNotSupportMultipleOccurrences()
{
CommandLineSwitches switches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(){"/orc:a", "/orc:b"}, switches);
switches.HaveErrors().ShouldBeTrue();
}
[Fact]
public void SetParameterlessSwitchTests()
{
CommandLineSwitches switches = new CommandLineSwitches();
switches.SetParameterlessSwitch(CommandLineSwitches.ParameterlessSwitch.NoLogo, "/nologo");
Assert.Equal("/nologo", switches.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.NoLogo));
Assert.True(switches.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.NoLogo));
Assert.True(switches[CommandLineSwitches.ParameterlessSwitch.NoLogo]);
// set it again
switches.SetParameterlessSwitch(CommandLineSwitches.ParameterlessSwitch.NoLogo, "-NOLOGO");
Assert.Equal("-NOLOGO", switches.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.NoLogo));
Assert.True(switches.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.NoLogo));
Assert.True(switches[CommandLineSwitches.ParameterlessSwitch.NoLogo]);
// we didn't set this switch
Assert.Null(switches.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.Version));
Assert.False(switches.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.Version));
Assert.False(switches[CommandLineSwitches.ParameterlessSwitch.Version]);
}
[Fact]
public void SetParameterizedSwitchTests1()
{
CommandLineSwitches switches = new CommandLineSwitches();
Assert.True(switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Verbosity, "/v:q", "q", false, true, false));
Assert.Equal("/v:q", switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Verbosity));
Assert.True(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Verbosity));
string[] parameters = switches[CommandLineSwitches.ParameterizedSwitch.Verbosity];
Assert.NotNull(parameters);
Assert.Single(parameters);
Assert.Equal("q", parameters[0]);
// set it again -- this is bogus, because the /verbosity switch doesn't allow multiple parameters, but for the
// purposes of testing the SetParameterizedSwitch() method, it doesn't matter
Assert.True(switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Verbosity, "/verbosity:\"diag\";minimal", "\"diag\";minimal", true, true, false));
Assert.Equal("/v:q /verbosity:\"diag\";minimal", switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Verbosity));
Assert.True(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Verbosity));
parameters = switches[CommandLineSwitches.ParameterizedSwitch.Verbosity];
Assert.NotNull(parameters);
Assert.Equal(3, parameters.Length);
Assert.Equal("q", parameters[0]);
Assert.Equal("diag", parameters[1]);
Assert.Equal("minimal", parameters[2]);
}
[Fact]
public void SetParameterizedSwitchTests2()
{
CommandLineSwitches switches = new CommandLineSwitches();
// we haven't set this switch yet
Assert.Null(switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Target));
Assert.False(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target));
string[] parameters = switches[CommandLineSwitches.ParameterizedSwitch.Target];
Assert.NotNull(parameters);
Assert.Empty(parameters);
// fake/missing parameters -- this is bogus because the /target switch allows multiple parameters but we're turning
// that off here just for testing purposes
Assert.False(switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Target, "/t:\"", "\"", false, true, false));
// switch has been set
Assert.Equal("/t:\"", switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Target));
Assert.True(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target));
parameters = switches[CommandLineSwitches.ParameterizedSwitch.Target];
// but no parameters
Assert.NotNull(parameters);
Assert.Empty(parameters);
// more fake/missing parameters
Assert.False(switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Target, "/t:A,\"\";B", "A,\"\";B", true, true, false));
Assert.Equal("/t:\" /t:A,\"\";B", switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Target));
Assert.True(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target));
parameters = switches[CommandLineSwitches.ParameterizedSwitch.Target];
// now we have some parameters
Assert.NotNull(parameters);
Assert.Equal(2, parameters.Length);
Assert.Equal("A", parameters[0]);
Assert.Equal("B", parameters[1]);
}
[Fact]
public void SetParameterizedSwitchTests3()
{
CommandLineSwitches switches = new CommandLineSwitches();
// we haven't set this switch yet
Assert.Null(switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Logger));
Assert.False(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Logger));
string[] parameters = switches[CommandLineSwitches.ParameterizedSwitch.Logger];
Assert.NotNull(parameters);
Assert.Empty(parameters);
// don't unquote fake/missing parameters
Assert.True(switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Logger, "/l:\"", "\"", false, false, false));
Assert.Equal("/l:\"", switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Logger));
Assert.True(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Logger));
parameters = switches[CommandLineSwitches.ParameterizedSwitch.Logger];
Assert.NotNull(parameters);
Assert.Single(parameters);
Assert.Equal("\"", parameters[0]);
// don't unquote multiple fake/missing parameters -- this is bogus because the /logger switch does not take multiple
// parameters, but for testing purposes this is fine
Assert.True(switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Logger, "/LOGGER:\"\",asm;\"p,a;r\"", "\"\",asm;\"p,a;r\"", true, false, false));
Assert.Equal("/l:\" /LOGGER:\"\",asm;\"p,a;r\"", switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Logger));
Assert.True(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Logger));
parameters = switches[CommandLineSwitches.ParameterizedSwitch.Logger];
Assert.NotNull(parameters);
Assert.Equal(4, parameters.Length);
Assert.Equal("\"", parameters[0]);
Assert.Equal("\"\"", parameters[1]);
Assert.Equal("asm", parameters[2]);
Assert.Equal("\"p,a;r\"", parameters[3]);
}
[Fact]
public void SetParameterizedSwitchTestsAllowEmpty()
{
CommandLineSwitches switches = new CommandLineSwitches();
Assert.True(switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.WarningsAsErrors, "/warnaserror", "", multipleParametersAllowed: true, unquoteParameters: false, emptyParametersAllowed: true));
Assert.True(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.WarningsAsErrors));
string[] parameters = switches[CommandLineSwitches.ParameterizedSwitch.WarningsAsErrors];
Assert.NotNull(parameters);
Assert.True(parameters.Length > 0);
Assert.Null(parameters.Last());
}
[Fact]
public void AppendErrorTests1()
{
CommandLineSwitches switchesLeft = new CommandLineSwitches();
CommandLineSwitches switchesRight = new CommandLineSwitches();
Assert.False(switchesLeft.HaveErrors());
Assert.False(switchesRight.HaveErrors());
switchesLeft.Append(switchesRight);
Assert.False(switchesLeft.HaveErrors());
Assert.False(switchesRight.HaveErrors());
switchesLeft.SetUnknownSwitchError("/bogus");
Assert.True(switchesLeft.HaveErrors());
Assert.False(switchesRight.HaveErrors());
switchesLeft.Append(switchesRight);
Assert.True(switchesLeft.HaveErrors());
Assert.False(switchesRight.HaveErrors());
VerifySwitchError(switchesLeft, "/bogus");
switchesRight.Append(switchesLeft);
Assert.True(switchesLeft.HaveErrors());
Assert.True(switchesRight.HaveErrors());
VerifySwitchError(switchesLeft, "/bogus");
VerifySwitchError(switchesRight, "/bogus");
}
[Fact]
public void AppendErrorTests2()
{
CommandLineSwitches switchesLeft = new CommandLineSwitches();
CommandLineSwitches switchesRight = new CommandLineSwitches();
Assert.False(switchesLeft.HaveErrors());
Assert.False(switchesRight.HaveErrors());
switchesLeft.SetUnknownSwitchError("/bogus");
switchesRight.SetUnexpectedParametersError("/nologo:foo");
Assert.True(switchesLeft.HaveErrors());
Assert.True(switchesRight.HaveErrors());
VerifySwitchError(switchesLeft, "/bogus");
VerifySwitchError(switchesRight, "/nologo:foo");
switchesLeft.Append(switchesRight);
VerifySwitchError(switchesLeft, "/bogus");
VerifySwitchError(switchesRight, "/nologo:foo");
}
[Fact]
public void AppendParameterlessSwitchesTests()
{
CommandLineSwitches switchesLeft = new CommandLineSwitches();
switchesLeft.SetParameterlessSwitch(CommandLineSwitches.ParameterlessSwitch.Help, "/?");
Assert.True(switchesLeft.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.Help));
Assert.False(switchesLeft.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger));
CommandLineSwitches switchesRight1 = new CommandLineSwitches();
switchesRight1.SetParameterlessSwitch(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger, "/noconlog");
Assert.False(switchesRight1.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.Help));
Assert.True(switchesRight1.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger));
switchesLeft.Append(switchesRight1);
Assert.Equal("/noconlog", switchesLeft.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger));
Assert.True(switchesLeft.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger));
Assert.True(switchesLeft[CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger]);
// this switch is not affected
Assert.Equal("/?", switchesLeft.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.Help));
Assert.True(switchesLeft.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.Help));
Assert.True(switchesLeft[CommandLineSwitches.ParameterlessSwitch.Help]);
CommandLineSwitches switchesRight2 = new CommandLineSwitches();
switchesRight2.SetParameterlessSwitch(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger, "/NOCONSOLELOGGER");
Assert.False(switchesRight2.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.Help));
Assert.True(switchesRight2.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger));
switchesLeft.Append(switchesRight2);
Assert.Equal("/NOCONSOLELOGGER", switchesLeft.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger));
Assert.True(switchesLeft.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger));
Assert.True(switchesLeft[CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger]);
Assert.Equal("/?", switchesLeft.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.Help));
Assert.True(switchesLeft.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.Help));
Assert.True(switchesLeft[CommandLineSwitches.ParameterlessSwitch.Help]);
Assert.False(switchesLeft.HaveErrors());
}
[Fact]
public void AppendParameterizedSwitchesTests1()
{
CommandLineSwitches switchesLeft = new CommandLineSwitches();
switchesLeft.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Project, "tempproject.proj", "tempproject.proj", false, true, false);
Assert.True(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Project));
Assert.False(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target));
CommandLineSwitches switchesRight = new CommandLineSwitches();
switchesRight.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Target, "/t:build", "build", true, true, false);
Assert.False(switchesRight.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Project));
Assert.True(switchesRight.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target));
switchesLeft.Append(switchesRight);
Assert.Equal("tempproject.proj", switchesLeft.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Project));
Assert.True(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Project));
string[] parameters = switchesLeft[CommandLineSwitches.ParameterizedSwitch.Project];
Assert.NotNull(parameters);
Assert.Single(parameters);
Assert.Equal("tempproject.proj", parameters[0]);
Assert.Equal("/t:build", switchesLeft.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Target));
Assert.True(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target));
parameters = switchesLeft[CommandLineSwitches.ParameterizedSwitch.Target];
Assert.NotNull(parameters);
Assert.Single(parameters);
Assert.Equal("build", parameters[0]);
}
[Fact]
public void AppendParameterizedSwitchesTests2()
{
CommandLineSwitches switchesLeft = new CommandLineSwitches();
switchesLeft.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Target, "/target:Clean", "Clean", true, true, false);
Assert.True(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target));
CommandLineSwitches switchesRight = new CommandLineSwitches();
switchesRight.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Target, "/t:\"RESOURCES\";build", "\"RESOURCES\";build", true, true, false);
Assert.True(switchesRight.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target));
switchesLeft.Append(switchesRight);
Assert.Equal("/t:\"RESOURCES\";build", switchesLeft.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Target));
Assert.True(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target));
string[] parameters = switchesLeft[CommandLineSwitches.ParameterizedSwitch.Target];
Assert.NotNull(parameters);
Assert.Equal(3, parameters.Length);
Assert.Equal("Clean", parameters[0]);
Assert.Equal("RESOURCES", parameters[1]);
Assert.Equal("build", parameters[2]);
}
[Fact]
public void AppendParameterizedSwitchesTests3()
{
CommandLineSwitches switchesLeft = new CommandLineSwitches();
switchesLeft.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Project, "tempproject.proj", "tempproject.proj", false, true, false);
Assert.True(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Project));
CommandLineSwitches switchesRight = new CommandLineSwitches();
switchesRight.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Project, "Rhubarb.proj", "Rhubarb.proj", false, true, false);
Assert.True(switchesRight.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Project));
switchesLeft.Append(switchesRight);
Assert.Equal("tempproject.proj", switchesLeft.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Project));
Assert.True(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Project));
string[] parameters = switchesLeft[CommandLineSwitches.ParameterizedSwitch.Project];
Assert.NotNull(parameters);
Assert.Single(parameters);
Assert.Equal("tempproject.proj", parameters[0]);
Assert.True(switchesLeft.HaveErrors());
VerifySwitchError(switchesLeft, "Rhubarb.proj");
}
[Fact]
public void InvalidToolsVersionErrors()
{
Assert.Throws<InitializationException>(() =>
{
string filename = null;
try
{
filename = FileUtilities.GetTemporaryFile();
ProjectRootElement project = ProjectRootElement.Create();
project.Save(filename);
MSBuildApp.BuildProject(
filename,
null,
"ScoobyDoo",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase),
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase),
new ILogger[] { },
LoggerVerbosity.Normal,
new DistributedLoggerRecord[] { },
#if FEATURE_XML_SCHEMA_VALIDATION
false,
null,
#endif
1,
true,
new StringWriter(),
false,
warningsAsErrors: null,
warningsAsMessages: null,
enableRestore: false,
profilerLogger: null,
enableProfiler: false,
interactive: false,
isolateProjects: false,
graphBuild: false,
inputResultsCaches: null,
outputResultsCache: null
);
}
finally
{
if (File.Exists(filename)) File.Delete(filename);
}
}
);
}
[Fact]
public void TestHaveAnySwitchesBeenSet()
{
// Check if method works with parameterized switch
CommandLineSwitches switches = new CommandLineSwitches();
Assert.False(switches.HaveAnySwitchesBeenSet());
switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Verbosity, "/v:q", "q", false, true, false);
Assert.True(switches.HaveAnySwitchesBeenSet());
// Check if method works with parameterless switches
switches = new CommandLineSwitches();
Assert.False(switches.HaveAnySwitchesBeenSet());
switches.SetParameterlessSwitch(CommandLineSwitches.ParameterlessSwitch.Help, "/?");
Assert.True(switches.HaveAnySwitchesBeenSet());
}
#if FEATURE_NODE_REUSE
/// <summary>
/// /nodereuse:false /nodereuse:true should result in "true"
/// </summary>
[Fact]
public void ProcessNodeReuseSwitchTrueLast()
{
bool nodeReuse = MSBuildApp.ProcessNodeReuseSwitch(new string[] { "false", "true" });
Assert.True(nodeReuse);
}
/// <summary>
/// /nodereuse:true /nodereuse:false should result in "false"
/// </summary>
[Fact]
public void ProcessNodeReuseSwitchFalseLast()
{
bool nodeReuse = MSBuildApp.ProcessNodeReuseSwitch(new string[] { "true", "false" });
Assert.False(nodeReuse);
}
#endif
/// <summary>
/// Regress DDB #143341:
/// msbuild /clp:v=quiet /clp:v=diag /m:2
/// gave console logger in quiet verbosity; expected diagnostic
/// </summary>
[Fact]
public void ExtractAnyLoggerParameterPickLast()
{
string result = MSBuildApp.ExtractAnyLoggerParameter("v=diag;v=q", new string[] { "v", "verbosity" });
Assert.Equal("v=q", result);
}
/// <summary>
/// Verifies that when the /warnaserror switch is not specified, the set of warnings is null.
/// </summary>
[Fact]
public void ProcessWarnAsErrorSwitchNotSpecified()
{
CommandLineSwitches commandLineSwitches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(new[] { "" }), commandLineSwitches);
Assert.Null(MSBuildApp.ProcessWarnAsErrorSwitch(commandLineSwitches));
}
/// <summary>
/// Verifies that the /warnaserror switch is parsed properly when codes are specified.
/// </summary>
[Fact]
public void ProcessWarnAsErrorSwitchWithCodes()
{
ISet<string> expectedWarningsAsErrors = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "a", "B", "c", "D", "e" };
CommandLineSwitches commandLineSwitches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(new[]
{
"\"/warnaserror: a,B ; c \"", // Leading, trailing, leading and trailing whitespace
"/warnaserror:A,b,C", // Repeats of different case
"\"/warnaserror:, ,,\"", // Empty items
"/err:D,d;E,e", // A different source with new items and uses the short form
"/warnaserror:a", // A different source with a single duplicate
"/warnaserror:a,b", // A different source with multiple duplicates
}), commandLineSwitches);
ISet<string> actualWarningsAsErrors = MSBuildApp.ProcessWarnAsErrorSwitch(commandLineSwitches);
Assert.NotNull(actualWarningsAsErrors);
Assert.Equal(expectedWarningsAsErrors, actualWarningsAsErrors, StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Verifies that an empty /warnaserror switch clears the list of codes.
/// </summary>
[Fact]
public void ProcessWarnAsErrorSwitchEmptySwitchClearsSet()
{
CommandLineSwitches commandLineSwitches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(new[]
{
"/warnaserror:a;b;c",
"/warnaserror",
}), commandLineSwitches);
ISet<string> actualWarningsAsErrors = MSBuildApp.ProcessWarnAsErrorSwitch(commandLineSwitches);
Assert.NotNull(actualWarningsAsErrors);
Assert.Empty(actualWarningsAsErrors);
}
/// <summary>
/// Verifies that when values are specified after an empty /warnaserror switch that they are added to the cleared list.
/// </summary>
[Fact]
public void ProcessWarnAsErrorSwitchValuesAfterEmptyAddOn()
{
ISet<string> expectedWarningsAsErors = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "e", "f", "g" };
CommandLineSwitches commandLineSwitches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(new[]
{
"/warnaserror:a;b;c",
"/warnaserror",
"/warnaserror:e;f;g",
}), commandLineSwitches);
ISet<string> actualWarningsAsErrors = MSBuildApp.ProcessWarnAsErrorSwitch(commandLineSwitches);
Assert.NotNull(actualWarningsAsErrors);
Assert.Equal(expectedWarningsAsErors, actualWarningsAsErrors, StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Verifies that the /warnaserror switch is parsed properly when no codes are specified.
/// </summary>
[Fact]
public void ProcessWarnAsErrorSwitchEmpty()
{
CommandLineSwitches commandLineSwitches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(new [] { "/warnaserror" }), commandLineSwitches);
ISet<string> actualWarningsAsErrors = MSBuildApp.ProcessWarnAsErrorSwitch(commandLineSwitches);
Assert.NotNull(actualWarningsAsErrors);
Assert.Empty(actualWarningsAsErrors);
}
/// <summary>
/// Verifies that when the /warnasmessage switch is used with no values that an error is shown.
/// </summary>
[Fact]
public void ProcessWarnAsMessageSwitchEmpty()
{
CommandLineSwitches commandLineSwitches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(new[] { "/warnasmessage" }), commandLineSwitches);
VerifySwitchError(commandLineSwitches, "/warnasmessage", AssemblyResources.GetString("MissingWarnAsMessageParameterError"));
}
/// <summary>
/// Verifies that the /warnasmessage switch is parsed properly when codes are specified.
/// </summary>
[Fact]
public void ProcessWarnAsMessageSwitchWithCodes()
{
ISet<string> expectedWarningsAsMessages = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "a", "B", "c", "D", "e" };
CommandLineSwitches commandLineSwitches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(new[]
{
"\"/warnasmessage: a,B ; c \"", // Leading, trailing, leading and trailing whitespace
"/warnasmessage:A,b,C", // Repeats of different case
"\"/warnasmessage:, ,,\"", // Empty items
"/nowarn:D,d;E,e", // A different source with new items and uses the short form
"/warnasmessage:a", // A different source with a single duplicate
"/warnasmessage:a,b", // A different source with multiple duplicates
}), commandLineSwitches);
ISet<string> actualWarningsAsMessages = MSBuildApp.ProcessWarnAsMessageSwitch(commandLineSwitches);
Assert.NotNull(actualWarningsAsMessages);
Assert.Equal(expectedWarningsAsMessages, actualWarningsAsMessages, StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Verifies that when the /profileevaluation switch is used with no values "no-file" is specified.
/// </summary>
[Fact]
public void ProcessProfileEvaluationEmpty()
{
CommandLineSwitches commandLineSwitches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(new[] { "/profileevaluation" }), commandLineSwitches);
commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.ProfileEvaluation][0].ShouldBe("no-file");
}
[Fact]
public void ProcessBooleanSwitchTest()
{
MSBuildApp.ProcessBooleanSwitch(new string[0], defaultValue: true, resourceName: null).ShouldBeTrue();
MSBuildApp.ProcessBooleanSwitch(new string[0], defaultValue: false, resourceName: null).ShouldBeFalse();
MSBuildApp.ProcessBooleanSwitch(new [] { "true" }, defaultValue: false, resourceName: null).ShouldBeTrue();
MSBuildApp.ProcessBooleanSwitch(new[] { "false" }, defaultValue: true, resourceName: null).ShouldBeFalse();
Should.Throw<CommandLineSwitchException>(() => MSBuildApp.ProcessBooleanSwitch(new[] { "invalid" }, defaultValue: true, resourceName: "InvalidRestoreValue"));
}
/// <summary>
/// Verifies that when the /profileevaluation switch is used with invalid filenames an error is shown.
/// </summary>
[MemberData(nameof(GetInvalidFilenames))]
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, ".NET Core 2.1+ no longer validates paths: https://github.com/dotnet/corefx/issues/27779#issuecomment-371253486")]
[Theory]
public void ProcessProfileEvaluationInvalidFilename(string filename)
{
bool enableProfiler = false;
Should.Throw(
() => MSBuildApp.ProcessProfileEvaluationSwitch(new[] {filename}, new ArrayList(), out enableProfiler),
typeof(CommandLineSwitchException));
}
public static IEnumerable<object[]> GetInvalidFilenames()
{
yield return new object[] { $"a_file_with${Path.GetInvalidFileNameChars().First()}invalid_chars" };
yield return new object[] { $"C:\\a_path\\with{Path.GetInvalidPathChars().First()}invalid\\chars" };
}
#if FEATURE_RESOURCEMANAGER_GETRESOURCESET
/// <summary>
/// Verifies that help messages are correctly formed with the right width and leading spaces.
/// </summary>
[Fact]
public void HelpMessagesAreValid()
{
ResourceManager resourceManager = new ResourceManager("MSBuild.Strings", typeof(AssemblyResources).Assembly);
const string switchLeadingSpaces = " ";
const string otherLineLeadingSpaces = " ";
const string examplesLeadingSpaces = " ";
foreach (KeyValuePair<string, string> item in resourceManager.GetResourceSet(CultureInfo.CurrentUICulture, createIfNotExists: true, tryParents: true)
.Cast<DictionaryEntry>().Where(i => i.Key is string && ((string)i.Key).StartsWith("HelpMessage_"))
.Select(i => new KeyValuePair<string, string>((string)i.Key, (string)i.Value)))
{
string[] helpMessageLines = item.Value.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < helpMessageLines.Length; i++)
{
// All lines should be 80 characters or less
Assert.True(helpMessageLines[i].Length <= 80, $"Line {i + 1} of '{item.Key}' should be no longer than 80 characters.");
string trimmedLine = helpMessageLines[i].Trim();
if (i == 0)
{
if (trimmedLine.StartsWith("-") || trimmedLine.StartsWith("@"))
{
// If the first line in a switch it needs a certain amount of leading spaces
Assert.StartsWith(switchLeadingSpaces, helpMessageLines[i]);
}
else
{
// Otherwise it should have no leading spaces because it's a section
Assert.False(helpMessageLines[i].StartsWith(" "));
}
}
else
{
// Ignore empty lines
if (!String.IsNullOrWhiteSpace(helpMessageLines[i]))
{
if (item.Key.Contains("Examples"))
{
// Examples require a certain number of leading spaces
Assert.StartsWith(examplesLeadingSpaces, helpMessageLines[i]);
}
else if (trimmedLine.StartsWith("-") || trimmedLine.StartsWith("@"))
{
// Switches require a certain number of leading spaces
Assert.StartsWith(switchLeadingSpaces, helpMessageLines[i]);
}
else
{
// All other lines require a certain number of leading spaces
Assert.StartsWith(otherLineLeadingSpaces, helpMessageLines[i]);
}
}
}
}
}
}
#endif
/// <summary>
/// Verifies that a switch collection has an error registered for the given command line arg.
/// </summary>
private void VerifySwitchError(CommandLineSwitches switches, string badCommandLineArg, string expectedMessage = null)
{
bool caughtError = false;
try
{
switches.ThrowErrors();
}
catch (CommandLineSwitchException e)
{
Assert.Equal(badCommandLineArg, e.CommandLineArg);
caughtError = true;
if (expectedMessage != null)
{
Assert.Contains(expectedMessage, e.Message);
}
// so I can see the message in NUnit's "Standard Out" window
Console.WriteLine(e.Message);
}
finally
{
Assert.True(caughtError);
}
}
}
}
| |
// 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.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
/// <summary>Provides an implementation of a file stream for Unix files.</summary>
public partial class FileStream : Stream
{
/// <summary>File mode.</summary>
private FileMode _mode;
/// <summary>Advanced options requested when opening the file.</summary>
private FileOptions _options;
/// <summary>If the file was opened with FileMode.Append, the length of the file when opened; otherwise, -1.</summary>
private long _appendStart = -1;
/// <summary>
/// Extra state used by the file stream when _useAsyncIO is true. This includes
/// the semaphore used to serialize all operation, the buffer/offset/count provided by the
/// caller for ReadAsync/WriteAsync operations, and the last successful task returned
/// synchronously from ReadAsync which can be reused if the count matches the next request.
/// Only initialized when <see cref="_useAsyncIO"/> is true.
/// </summary>
private AsyncState _asyncState;
/// <summary>Lazily-initialized value for whether the file supports seeking.</summary>
private bool? _canSeek;
private SafeFileHandle OpenHandle(FileMode mode, FileShare share, FileOptions options)
{
// FileStream performs most of the general argument validation. We can assume here that the arguments
// are all checked and consistent (e.g. non-null-or-empty path; valid enums in mode, access, share, and options; etc.)
// Store the arguments
_mode = mode;
_options = options;
if (_useAsyncIO)
_asyncState = new AsyncState();
// Translate the arguments into arguments for an open call.
Interop.Sys.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, _access, share, options);
// If the file gets created a new, we'll select the permissions for it. Most Unix utilities by default use 666 (read and
// write for all), so we do the same (even though this doesn't match Windows, where by default it's possible to write out
// a file and then execute it). No matter what we choose, it'll be subject to the umask applied by the system, such that the
// actual permissions will typically be less than what we select here.
const Interop.Sys.Permissions OpenPermissions =
Interop.Sys.Permissions.S_IRUSR | Interop.Sys.Permissions.S_IWUSR |
Interop.Sys.Permissions.S_IRGRP | Interop.Sys.Permissions.S_IWGRP |
Interop.Sys.Permissions.S_IROTH | Interop.Sys.Permissions.S_IWOTH;
// Open the file and store the safe handle.
return SafeFileHandle.Open(_path, openFlags, (int)OpenPermissions);
}
private static bool GetDefaultIsAsync(SafeFileHandle handle) => handle.IsAsync ?? DefaultIsAsync;
/// <summary>Initializes a stream for reading or writing a Unix file.</summary>
/// <param name="mode">How the file should be opened.</param>
/// <param name="share">What other access to the file should be allowed. This is currently ignored.</param>
private void Init(FileMode mode, FileShare share, string originalPath)
{
_fileHandle.IsAsync = _useAsyncIO;
// Lock the file if requested via FileShare. This is only advisory locking. FileShare.None implies an exclusive
// lock on the file and all other modes use a shared lock. While this is not as granular as Windows, not mandatory,
// and not atomic with file opening, it's better than nothing.
Interop.Sys.LockOperations lockOperation = (share == FileShare.None) ? Interop.Sys.LockOperations.LOCK_EX : Interop.Sys.LockOperations.LOCK_SH;
if (Interop.Sys.FLock(_fileHandle, lockOperation | Interop.Sys.LockOperations.LOCK_NB) < 0)
{
// The only error we care about is EWOULDBLOCK, which indicates that the file is currently locked by someone
// else and we would block trying to access it. Other errors, such as ENOTSUP (locking isn't supported) or
// EACCES (the file system doesn't allow us to lock), will only hamper FileStream's usage without providing value,
// given again that this is only advisory / best-effort.
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EWOULDBLOCK)
{
throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false);
}
}
// These provide hints around how the file will be accessed. Specifying both RandomAccess
// and Sequential together doesn't make sense as they are two competing options on the same spectrum,
// so if both are specified, we prefer RandomAccess (behavior on Windows is unspecified if both are provided).
Interop.Sys.FileAdvice fadv =
(_options & FileOptions.RandomAccess) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_RANDOM :
(_options & FileOptions.SequentialScan) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_SEQUENTIAL :
0;
if (fadv != 0)
{
CheckFileCall(Interop.Sys.PosixFAdvise(_fileHandle, 0, 0, fadv),
ignoreNotSupported: true); // just a hint.
}
if (_mode == FileMode.Append)
{
// Jump to the end of the file if opened as Append.
_appendStart = SeekCore(_fileHandle, 0, SeekOrigin.End);
}
else if (mode == FileMode.Create || mode == FileMode.Truncate)
{
// Truncate the file now if the file mode requires it. This ensures that the file only will be truncated
// if opened successfully.
CheckFileCall(Interop.Sys.FTruncate(_fileHandle, 0));
}
}
/// <summary>Initializes a stream from an already open file handle (file descriptor).</summary>
private void InitFromHandle(SafeFileHandle handle, FileAccess access, bool useAsyncIO)
{
if (useAsyncIO)
_asyncState = new AsyncState();
if (CanSeekCore(handle)) // use non-virtual CanSeekCore rather than CanSeek to avoid making virtual call during ctor
SeekCore(handle, 0, SeekOrigin.Current);
}
/// <summary>Translates the FileMode, FileAccess, and FileOptions values into flags to be passed when opening the file.</summary>
/// <param name="mode">The FileMode provided to the stream's constructor.</param>
/// <param name="access">The FileAccess provided to the stream's constructor</param>
/// <param name="share">The FileShare provided to the stream's constructor</param>
/// <param name="options">The FileOptions provided to the stream's constructor</param>
/// <returns>The flags value to be passed to the open system call.</returns>
private static Interop.Sys.OpenFlags PreOpenConfigurationFromOptions(FileMode mode, FileAccess access, FileShare share, FileOptions options)
{
// Translate FileMode. Most of the values map cleanly to one or more options for open.
Interop.Sys.OpenFlags flags = default(Interop.Sys.OpenFlags);
switch (mode)
{
default:
case FileMode.Open: // Open maps to the default behavior for open(...). No flags needed.
case FileMode.Truncate: // We truncate the file after getting the lock
break;
case FileMode.Append: // Append is the same as OpenOrCreate, except that we'll also separately jump to the end later
case FileMode.OpenOrCreate:
case FileMode.Create: // We truncate the file after getting the lock
flags |= Interop.Sys.OpenFlags.O_CREAT;
break;
case FileMode.CreateNew:
flags |= (Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL);
break;
}
// Translate FileAccess. All possible values map cleanly to corresponding values for open.
switch (access)
{
case FileAccess.Read:
flags |= Interop.Sys.OpenFlags.O_RDONLY;
break;
case FileAccess.ReadWrite:
flags |= Interop.Sys.OpenFlags.O_RDWR;
break;
case FileAccess.Write:
flags |= Interop.Sys.OpenFlags.O_WRONLY;
break;
}
// Handle Inheritable, other FileShare flags are handled by Init
if ((share & FileShare.Inheritable) == 0)
{
flags |= Interop.Sys.OpenFlags.O_CLOEXEC;
}
// Translate some FileOptions; some just aren't supported, and others will be handled after calling open.
// - Asynchronous: Handled in ctor, setting _useAsync and SafeFileHandle.IsAsync to true
// - DeleteOnClose: Doesn't have a Unix equivalent, but we approximate it in Dispose
// - Encrypted: No equivalent on Unix and is ignored
// - RandomAccess: Implemented after open if posix_fadvise is available
// - SequentialScan: Implemented after open if posix_fadvise is available
// - WriteThrough: Handled here
if ((options & FileOptions.WriteThrough) != 0)
{
flags |= Interop.Sys.OpenFlags.O_SYNC;
}
return flags;
}
/// <summary>Gets a value indicating whether the current stream supports seeking.</summary>
public override bool CanSeek => CanSeekCore(_fileHandle);
/// <summary>Gets a value indicating whether the current stream supports seeking.</summary>
/// <remarks>
/// Separated out of CanSeek to enable making non-virtual call to this logic.
/// We also pass in the file handle to allow the constructor to use this before it stashes the handle.
/// </remarks>
private bool CanSeekCore(SafeFileHandle fileHandle)
{
if (fileHandle.IsClosed)
{
return false;
}
if (!_canSeek.HasValue)
{
// Lazily-initialize whether we're able to seek, tested by seeking to our current location.
_canSeek = Interop.Sys.LSeek(fileHandle, 0, Interop.Sys.SeekWhence.SEEK_CUR) >= 0;
}
return _canSeek.Value;
}
private long GetLengthInternal()
{
// Get the length of the file as reported by the OS
Interop.Sys.FileStatus status;
CheckFileCall(Interop.Sys.FStat(_fileHandle, out status));
long length = status.Size;
// But we may have buffered some data to be written that puts our length
// beyond what the OS is aware of. Update accordingly.
if (_writePos > 0 && _filePosition + _writePos > length)
{
length = _writePos + _filePosition;
}
return length;
}
/// <summary>Releases the unmanaged resources used by the stream.</summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
try
{
if (_fileHandle != null && !_fileHandle.IsClosed)
{
// Flush any remaining data in the file
try
{
FlushWriteBuffer();
}
catch (Exception e) when (IsIoRelatedException(e) && !disposing)
{
// On finalization, ignore failures from trying to flush the write buffer,
// e.g. if this stream is wrapping a pipe and the pipe is now broken.
}
// If DeleteOnClose was requested when constructed, delete the file now.
// (Unix doesn't directly support DeleteOnClose, so we mimic it here.)
if (_path != null && (_options & FileOptions.DeleteOnClose) != 0)
{
// Since we still have the file open, this will end up deleting
// it (assuming we're the only link to it) once it's closed, but the
// name will be removed immediately.
Interop.Sys.Unlink(_path); // ignore errors; it's valid that the path may no longer exist
}
}
}
finally
{
if (_fileHandle != null && !_fileHandle.IsClosed)
{
_fileHandle.Dispose();
}
base.Dispose(disposing);
}
}
/// <summary>Flushes the OS buffer. This does not flush the internal read/write buffer.</summary>
private void FlushOSBuffer()
{
if (Interop.Sys.FSync(_fileHandle) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
switch (errorInfo.Error)
{
case Interop.Error.EROFS:
case Interop.Error.EINVAL:
case Interop.Error.ENOTSUP:
// Ignore failures due to the FileStream being bound to a special file that
// doesn't support synchronization. In such cases there's nothing to flush.
break;
default:
throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false);
}
}
}
private void FlushWriteBufferForWriteByte()
{
_asyncState?.Wait();
try { FlushWriteBuffer(); }
finally { _asyncState?.Release(); }
}
/// <summary>Writes any data in the write buffer to the underlying stream and resets the buffer.</summary>
private void FlushWriteBuffer()
{
AssertBufferInvariants();
if (_writePos > 0)
{
WriteNative(new ReadOnlySpan<byte>(GetBuffer(), 0, _writePos));
_writePos = 0;
}
}
/// <summary>Asynchronously clears all buffers for this stream, causing any buffered data to be written to the underlying device.</summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous flush operation.</returns>
private Task FlushAsyncInternal(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}
if (_fileHandle.IsClosed)
{
throw Error.GetFileNotOpen();
}
// As with Win32FileStream, flush the buffers synchronously to avoid race conditions.
try
{
FlushInternalBuffer();
}
catch (Exception e)
{
return Task.FromException(e);
}
// We then separately flush to disk asynchronously. This is only
// necessary if we support writing; otherwise, we're done.
if (CanWrite)
{
return Task.Factory.StartNew(
state => ((FileStream)state).FlushOSBuffer(),
this,
cancellationToken,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
}
else
{
return Task.CompletedTask;
}
}
/// <summary>Sets the length of this stream to the given value.</summary>
/// <param name="value">The new length of the stream.</param>
private void SetLengthInternal(long value)
{
FlushInternalBuffer();
if (_appendStart != -1 && value < _appendStart)
{
throw new IOException(SR.IO_SetLengthAppendTruncate);
}
long origPos = _filePosition;
VerifyOSHandlePosition();
if (_filePosition != value)
{
SeekCore(_fileHandle, value, SeekOrigin.Begin);
}
CheckFileCall(Interop.Sys.FTruncate(_fileHandle, value));
// Return file pointer to where it was before setting length
if (origPos != value)
{
if (origPos < value)
{
SeekCore(_fileHandle, origPos, SeekOrigin.Begin);
}
else
{
SeekCore(_fileHandle, 0, SeekOrigin.End);
}
}
}
/// <summary>Reads a block of bytes from the stream and writes the data in a given buffer.</summary>
private int ReadSpan(Span<byte> destination)
{
PrepareForReading();
// Are there any bytes available in the read buffer? If yes,
// we can just return from the buffer. If the buffer is empty
// or has no more available data in it, we can either refill it
// (and then read from the buffer into the user's buffer) or
// we can just go directly into the user's buffer, if they asked
// for more data than we'd otherwise buffer.
int numBytesAvailable = _readLength - _readPos;
bool readFromOS = false;
if (numBytesAvailable == 0)
{
// If we're not able to seek, then we're not able to rewind the stream (i.e. flushing
// a read buffer), in which case we don't want to use a read buffer. Similarly, if
// the user has asked for more data than we can buffer, we also want to skip the buffer.
if (!CanSeek || (destination.Length >= _bufferLength))
{
// Read directly into the user's buffer
_readPos = _readLength = 0;
return ReadNative(destination);
}
else
{
// Read into our buffer.
_readLength = numBytesAvailable = ReadNative(GetBuffer());
_readPos = 0;
if (numBytesAvailable == 0)
{
return 0;
}
// Note that we did an OS read as part of this Read, so that later
// we don't try to do one again if what's in the buffer doesn't
// meet the user's request.
readFromOS = true;
}
}
// Now that we know there's data in the buffer, read from it into the user's buffer.
Debug.Assert(numBytesAvailable > 0, "Data must be in the buffer to be here");
int bytesRead = Math.Min(numBytesAvailable, destination.Length);
new Span<byte>(GetBuffer(), _readPos, bytesRead).CopyTo(destination);
_readPos += bytesRead;
// We may not have had enough data in the buffer to completely satisfy the user's request.
// While Read doesn't require that we return as much data as the user requested (any amount
// up to the requested count is fine), FileStream on Windows tries to do so by doing a
// subsequent read from the file if we tried to satisfy the request with what was in the
// buffer but the buffer contained less than the requested count. To be consistent with that
// behavior, we do the same thing here on Unix. Note that we may still get less the requested
// amount, as the OS may give us back fewer than we request, either due to reaching the end of
// file, or due to its own whims.
if (!readFromOS && bytesRead < destination.Length)
{
Debug.Assert(_readPos == _readLength, "bytesToRead should only be < destination.Length if numBytesAvailable < destination.Length");
_readPos = _readLength = 0; // no data left in the read buffer
bytesRead += ReadNative(destination.Slice(bytesRead));
}
return bytesRead;
}
/// <summary>Unbuffered, reads a block of bytes from the file handle into the given buffer.</summary>
/// <param name="buffer">The buffer into which data from the file is read.</param>
/// <returns>
/// The total number of bytes read into the buffer. This might be less than the number of bytes requested
/// if that number of bytes are not currently available, or zero if the end of the stream is reached.
/// </returns>
private unsafe int ReadNative(Span<byte> buffer)
{
FlushWriteBuffer(); // we're about to read; dump the write buffer
VerifyOSHandlePosition();
int bytesRead;
fixed (byte* bufPtr = &MemoryMarshal.GetReference(buffer))
{
bytesRead = CheckFileCall(Interop.Sys.Read(_fileHandle, bufPtr, buffer.Length));
Debug.Assert(bytesRead <= buffer.Length);
}
_filePosition += bytesRead;
return bytesRead;
}
/// <summary>
/// Asynchronously reads a sequence of bytes from the current stream and advances
/// the position within the stream by the number of bytes read.
/// </summary>
/// <param name="destination">The buffer to write the data into.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <param name="synchronousResult">If the operation completes synchronously, the number of bytes read.</param>
/// <returns>A task that represents the asynchronous read operation.</returns>
private Task<int> ReadAsyncInternal(Memory<byte> destination, CancellationToken cancellationToken, out int synchronousResult)
{
Debug.Assert(_useAsyncIO);
if (!CanRead) // match Windows behavior; this gets thrown synchronously
{
throw Error.GetReadNotSupported();
}
// Serialize operations using the semaphore.
Task waitTask = _asyncState.WaitAsync();
// If we got ownership immediately, and if there's enough data in our buffer
// to satisfy the full request of the caller, hand back the buffered data.
// While it would be a legal implementation of the Read contract, we don't
// hand back here less than the amount requested so as to match the behavior
// in ReadCore that will make a native call to try to fulfill the remainder
// of the request.
if (waitTask.Status == TaskStatus.RanToCompletion)
{
int numBytesAvailable = _readLength - _readPos;
if (numBytesAvailable >= destination.Length)
{
try
{
PrepareForReading();
new Span<byte>(GetBuffer(), _readPos, destination.Length).CopyTo(destination.Span);
_readPos += destination.Length;
synchronousResult = destination.Length;
return null;
}
catch (Exception exc)
{
synchronousResult = 0;
return Task.FromException<int>(exc);
}
finally
{
_asyncState.Release();
}
}
}
// Otherwise, issue the whole request asynchronously.
synchronousResult = 0;
_asyncState.Memory = destination;
return waitTask.ContinueWith((t, s) =>
{
// The options available on Unix for writing asynchronously to an arbitrary file
// handle typically amount to just using another thread to do the synchronous write,
// which is exactly what this implementation does. This does mean there are subtle
// differences in certain FileStream behaviors between Windows and Unix when multiple
// asynchronous operations are issued against the stream to execute concurrently; on
// Unix the operations will be serialized due to the usage of a semaphore, but the
// position /length information won't be updated until after the write has completed,
// whereas on Windows it may happen before the write has completed.
Debug.Assert(t.Status == TaskStatus.RanToCompletion);
var thisRef = (FileStream)s;
try
{
Memory<byte> memory = thisRef._asyncState.Memory;
thisRef._asyncState.Memory = default(Memory<byte>);
return thisRef.ReadSpan(memory.Span);
}
finally { thisRef._asyncState.Release(); }
}, this, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default);
}
/// <summary>Reads from the file handle into the buffer, overwriting anything in it.</summary>
private int FillReadBufferForReadByte()
{
_asyncState?.Wait();
try { return ReadNative(_buffer); }
finally { _asyncState?.Release(); }
}
/// <summary>Writes a block of bytes to the file stream.</summary>
/// <param name="source">The buffer containing data to write to the stream.</param>
private void WriteSpan(ReadOnlySpan<byte> source)
{
PrepareForWriting();
// If no data is being written, nothing more to do.
if (source.Length == 0)
{
return;
}
// If there's already data in our write buffer, then we need to go through
// our buffer to ensure data isn't corrupted.
if (_writePos > 0)
{
// If there's space remaining in the buffer, then copy as much as
// we can from the user's buffer into ours.
int spaceRemaining = _bufferLength - _writePos;
if (spaceRemaining >= source.Length)
{
source.CopyTo(new Span<byte>(GetBuffer()).Slice(_writePos));
_writePos += source.Length;
return;
}
else if (spaceRemaining > 0)
{
source.Slice(0, spaceRemaining).CopyTo(new Span<byte>(GetBuffer()).Slice(_writePos));
_writePos += spaceRemaining;
source = source.Slice(spaceRemaining);
}
// At this point, the buffer is full, so flush it out.
FlushWriteBuffer();
}
// Our buffer is now empty. If using the buffer would slow things down (because
// the user's looking to write more data than we can store in the buffer),
// skip the buffer. Otherwise, put the remaining data into the buffer.
Debug.Assert(_writePos == 0);
if (source.Length >= _bufferLength)
{
WriteNative(source);
}
else
{
source.CopyTo(new Span<byte>(GetBuffer()));
_writePos = source.Length;
}
}
/// <summary>Unbuffered, writes a block of bytes to the file stream.</summary>
/// <param name="source">The buffer containing data to write to the stream.</param>
private unsafe void WriteNative(ReadOnlySpan<byte> source)
{
VerifyOSHandlePosition();
fixed (byte* bufPtr = &MemoryMarshal.GetReference(source))
{
int offset = 0;
int count = source.Length;
while (count > 0)
{
int bytesWritten = CheckFileCall(Interop.Sys.Write(_fileHandle, bufPtr + offset, count));
_filePosition += bytesWritten;
offset += bytesWritten;
count -= bytesWritten;
}
}
}
/// <summary>
/// Asynchronously writes a sequence of bytes to the current stream, advances
/// the current position within this stream by the number of bytes written, and
/// monitors cancellation requests.
/// </summary>
/// <param name="source">The buffer to write data from.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
private ValueTask WriteAsyncInternal(ReadOnlyMemory<byte> source, CancellationToken cancellationToken)
{
Debug.Assert(_useAsyncIO);
if (cancellationToken.IsCancellationRequested)
return new ValueTask(Task.FromCanceled(cancellationToken));
if (_fileHandle.IsClosed)
throw Error.GetFileNotOpen();
if (!CanWrite) // match Windows behavior; this gets thrown synchronously
{
throw Error.GetWriteNotSupported();
}
// Serialize operations using the semaphore.
Task waitTask = _asyncState.WaitAsync();
// If we got ownership immediately, and if there's enough space in our buffer
// to buffer the entire write request, then do so and we're done.
if (waitTask.Status == TaskStatus.RanToCompletion)
{
int spaceRemaining = _bufferLength - _writePos;
if (spaceRemaining >= source.Length)
{
try
{
PrepareForWriting();
source.Span.CopyTo(new Span<byte>(GetBuffer(), _writePos, source.Length));
_writePos += source.Length;
return default;
}
catch (Exception exc)
{
return new ValueTask(Task.FromException(exc));
}
finally
{
_asyncState.Release();
}
}
}
// Otherwise, issue the whole request asynchronously.
_asyncState.ReadOnlyMemory = source;
return new ValueTask(waitTask.ContinueWith((t, s) =>
{
// The options available on Unix for writing asynchronously to an arbitrary file
// handle typically amount to just using another thread to do the synchronous write,
// which is exactly what this implementation does. This does mean there are subtle
// differences in certain FileStream behaviors between Windows and Unix when multiple
// asynchronous operations are issued against the stream to execute concurrently; on
// Unix the operations will be serialized due to the usage of a semaphore, but the
// position/length information won't be updated until after the write has completed,
// whereas on Windows it may happen before the write has completed.
Debug.Assert(t.Status == TaskStatus.RanToCompletion);
var thisRef = (FileStream)s;
try
{
ReadOnlyMemory<byte> readOnlyMemory = thisRef._asyncState.ReadOnlyMemory;
thisRef._asyncState.ReadOnlyMemory = default(ReadOnlyMemory<byte>);
thisRef.WriteSpan(readOnlyMemory.Span);
}
finally { thisRef._asyncState.Release(); }
}, this, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default));
}
/// <summary>Sets the current position of this stream to the given value.</summary>
/// <param name="offset">The point relative to origin from which to begin seeking. </param>
/// <param name="origin">
/// Specifies the beginning, the end, or the current position as a reference
/// point for offset, using a value of type SeekOrigin.
/// </param>
/// <returns>The new position in the stream.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
if (origin < SeekOrigin.Begin || origin > SeekOrigin.End)
{
throw new ArgumentException(SR.Argument_InvalidSeekOrigin, nameof(origin));
}
if (_fileHandle.IsClosed)
{
throw Error.GetFileNotOpen();
}
if (!CanSeek)
{
throw Error.GetSeekNotSupported();
}
VerifyOSHandlePosition();
// Flush our write/read buffer. FlushWrite will output any write buffer we have and reset _bufferWritePos.
// We don't call FlushRead, as that will do an unnecessary seek to rewind the read buffer, and since we're
// about to seek and update our position, we can simply update the offset as necessary and reset our read
// position and length to 0. (In the future, for some simple cases we could potentially add an optimization
// here to just move data around in the buffer for short jumps, to avoid re-reading the data from disk.)
FlushWriteBuffer();
if (origin == SeekOrigin.Current)
{
offset -= (_readLength - _readPos);
}
_readPos = _readLength = 0;
// Keep track of where we were, in case we're in append mode and need to verify
long oldPos = 0;
if (_appendStart >= 0)
{
oldPos = SeekCore(_fileHandle, 0, SeekOrigin.Current);
}
// Jump to the new location
long pos = SeekCore(_fileHandle, offset, origin);
// Prevent users from overwriting data in a file that was opened in append mode.
if (_appendStart != -1 && pos < _appendStart)
{
SeekCore(_fileHandle, oldPos, SeekOrigin.Begin);
throw new IOException(SR.IO_SeekAppendOverwrite);
}
// Return the new position
return pos;
}
/// <summary>Sets the current position of this stream to the given value.</summary>
/// <param name="offset">The point relative to origin from which to begin seeking. </param>
/// <param name="origin">
/// Specifies the beginning, the end, or the current position as a reference
/// point for offset, using a value of type SeekOrigin.
/// </param>
/// <returns>The new position in the stream.</returns>
private long SeekCore(SafeFileHandle fileHandle, long offset, SeekOrigin origin)
{
Debug.Assert(!fileHandle.IsClosed && (GetType() != typeof(FileStream) || CanSeekCore(fileHandle))); // verify that we can seek, but only if CanSeek won't be a virtual call (which could happen in the ctor)
Debug.Assert(origin >= SeekOrigin.Begin && origin <= SeekOrigin.End);
long pos = CheckFileCall(Interop.Sys.LSeek(fileHandle, offset, (Interop.Sys.SeekWhence)(int)origin)); // SeekOrigin values are the same as Interop.libc.SeekWhence values
_filePosition = pos;
return pos;
}
private long CheckFileCall(long result, bool ignoreNotSupported = false)
{
if (result < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (!(ignoreNotSupported && errorInfo.Error == Interop.Error.ENOTSUP))
{
throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false);
}
}
return result;
}
private int CheckFileCall(int result, bool ignoreNotSupported = false)
{
CheckFileCall((long)result, ignoreNotSupported);
return result;
}
/// <summary>State used when the stream is in async mode.</summary>
private sealed class AsyncState : SemaphoreSlim
{
internal ReadOnlyMemory<byte> ReadOnlyMemory;
internal Memory<byte> Memory;
/// <summary>Initialize the AsyncState.</summary>
internal AsyncState() : base(initialCount: 1, maxCount: 1) { }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Resources;
using Microsoft.Phone.Tasks;
using Microsoft.Devices;
using rhoruntime;
using ZXing;
namespace rho {
namespace BarcodeImpl
{
public class Barcode : BarcodeBase
{
public static int vibrateTimeMs = 100;
private BarcodeReaderLib.OpticalReaderTask _barcodeScanTask = null;
private IBarcodeReader _barcodeReader = new BarcodeReader();
static EventWaitHandle _waitHandle = new AutoResetEvent(false);
static String _recognizeResult = "";
private IMethodResult _methodResult = null;
private string _effectiveRubyCallbackURL = null;
private String _prevScanResult = "";
public Barcode()
{
if (BarcodeReaderLib.OpticalReaderTask.Instance == null)
_barcodeScanTask = new BarcodeReaderLib.OpticalReaderTask();
else
_barcodeScanTask = BarcodeReaderLib.OpticalReaderTask.Instance;
_barcodeScanTask.Completed += BarcodeScanTask_Completed;
}
public override void setNativeImpl(string strID, long native)
{
base.setNativeImpl(strID, native);
IMethodResult pResult = new CMethodResultImpl();
setProperty("scannerType", "camera", pResult);
}
public override void getAutoEnter(IMethodResult oResult) { }
public override void setAutoEnter(bool autoEnter, IMethodResult oResult) { }
public override void getAutoTab(IMethodResult oResult) { }
public override void setAutoTab(bool autoTab, IMethodResult oResult) { }
public override void getHapticFeedback(IMethodResult oResult) { }
public override void setHapticFeedback(bool hapticFeedback, IMethodResult oResult) { }
public override void getLinearSecurityLevel(IMethodResult oResult) { }
public override void setLinearSecurityLevel(string linearSecurityLevel, IMethodResult oResult) { }
public override void getScanTimeout(IMethodResult oResult) { }
public override void setScanTimeout(int scanTimeout, IMethodResult oResult) { }
public override void getRasterMode(IMethodResult oResult) { }
public override void setRasterMode(string rasterMode, IMethodResult oResult) { }
public override void getRasterHeight(IMethodResult oResult) { }
public override void setRasterHeight(int rasterHeight, IMethodResult oResult) { }
public override void getAimType(IMethodResult oResult) { }
public override void setAimType(string aimType, IMethodResult oResult) { }
public override void getTimedAimDuration(IMethodResult oResult) { }
public override void setTimedAimDuration(int timedAimDuration, IMethodResult oResult) { }
public override void getSameSymbolTimeout(IMethodResult oResult) { }
public override void setSameSymbolTimeout(int sameSymbolTimeout, IMethodResult oResult) { }
public override void getDifferentSymbolTimeout(IMethodResult oResult) { }
public override void setDifferentSymbolTimeout(int differentSymbolTimeout, IMethodResult oResult) { }
public override void getAimMode(IMethodResult oResult) { }
public override void setAimMode(string aimMode, IMethodResult oResult) { }
public override void getPicklistMode(IMethodResult oResult) { }
public override void setPicklistMode(string picklistMode, IMethodResult oResult) { }
public override void getViewfinderMode(IMethodResult oResult) { }
public override void setViewfinderMode(string viewfinderMode, IMethodResult oResult) { }
public override void getViewfinderX(IMethodResult oResult) { }
public override void setViewfinderX(int viewfinderX, IMethodResult oResult) { }
public override void getViewfinderY(IMethodResult oResult) { }
public override void setViewfinderY(int viewfinderY, IMethodResult oResult) { }
public override void getViewfinderWidth(IMethodResult oResult) { }
public override void setViewfinderWidth(int viewfinderWidth, IMethodResult oResult) { }
public override void getViewfinderHeight(IMethodResult oResult) { }
public override void setViewfinderHeight(int viewfinderHeight, IMethodResult oResult) { }
public override void getViewfinderFeedback(IMethodResult oResult) { }
public override void setViewfinderFeedback(string viewfinderFeedback, IMethodResult oResult) { }
public override void getViewfinderFeedbackTime(IMethodResult oResult) { }
public override void setViewfinderFeedbackTime(int viewfinderFeedbackTime, IMethodResult oResult) { }
public override void getFocusMode(IMethodResult oResult) { }
public override void setFocusMode(string focusMode, IMethodResult oResult) { }
public override void getIlluminationMode(IMethodResult oResult) { }
public override void setIlluminationMode(string illuminationMode, IMethodResult oResult) { }
public override void getDpmMode(IMethodResult oResult) { }
public override void setDpmMode(bool dpmMode, IMethodResult oResult) { }
public override void getInverse1dMode(IMethodResult oResult) { }
public override void setInverse1dMode(string inverse1dMode, IMethodResult oResult) { }
public override void getPoorQuality1dMode(IMethodResult oResult) { }
public override void setPoorQuality1dMode(bool poorQuality1dMode, IMethodResult oResult) { }
public override void getBeamWidth(IMethodResult oResult) { }
public override void setBeamWidth(string beamWidth, IMethodResult oResult) { }
public override void getDbpMode(IMethodResult oResult) { }
public override void setDbpMode(string dbpMode, IMethodResult oResult) { }
public override void getKlasseEins(IMethodResult oResult) { }
public override void setKlasseEins(bool klasseEins, IMethodResult oResult) { }
public override void getAdaptiveScanning(IMethodResult oResult) { }
public override void setAdaptiveScanning(bool adaptiveScanning, IMethodResult oResult) { }
public override void getBidirectionalRedundancy(IMethodResult oResult) { }
public override void setBidirectionalRedundancy(bool bidirectionalRedundancy, IMethodResult oResult) { }
public override void getBarcodeDataFormat(IMethodResult oResult) { }
public override void setBarcodeDataFormat(string barcodeDataFormat, IMethodResult oResult) { }
public override void getDataBufferSize(IMethodResult oResult) { }
public override void setDataBufferSize(int dataBufferSize, IMethodResult oResult) { }
public override void getConnectionIdleTimeout(IMethodResult oResult) { }
public override void setConnectionIdleTimeout(int connectionIdleTimeout, IMethodResult oResult) { }
public override void getDisconnectBtOnDisable(IMethodResult oResult) { }
public override void setDisconnectBtOnDisable(bool disconnectBtOnDisable, IMethodResult oResult) { }
public override void getDisplayBtAddressBarcodeOnEnable(IMethodResult oResult) { }
public override void setDisplayBtAddressBarcodeOnEnable(bool displayBtAddressBarcodeOnEnable, IMethodResult oResult) { }
public override void getEnableTimeout(IMethodResult oResult) { }
public override void setEnableTimeout(int enableTimeout, IMethodResult oResult) { }
public override void getFriendlyName(IMethodResult oResult) { }
public override void getLcdMode(IMethodResult oResult) { }
public override void setLcdMode(bool lcdMode, IMethodResult oResult) { }
public override void getLowBatteryScan(IMethodResult oResult) { }
public override void setLowBatteryScan(bool lowBatteryScan, IMethodResult oResult) { }
public override void getTriggerConnected(IMethodResult oResult) { }
public override void setTriggerConnected(bool triggerConnected, IMethodResult oResult) { }
public override void getDisableScannerDuringNavigate(IMethodResult oResult) { }
public override void setDisableScannerDuringNavigate(bool disableScannerDuringNavigate, IMethodResult oResult) { }
public override void getDecodeVolume(IMethodResult oResult) { }
public override void setDecodeVolume(int decodeVolume, IMethodResult oResult) { }
public override void getDecodeDuration(IMethodResult oResult) { }
public override void setDecodeDuration(int decodeDuration, IMethodResult oResult) { }
public override void getDecodeFrequency(IMethodResult oResult) { }
public override void setDecodeFrequency(int decodeFrequency, IMethodResult oResult) { }
public override void getInvalidDecodeFrequency(IMethodResult oResult) { }
public override void setInvalidDecodeFrequency(int invalidDecodeFrequency, IMethodResult oResult) { }
public override void getDecodeSound(IMethodResult oResult) { }
public override void setDecodeSound(string decodeSound, IMethodResult oResult) { }
public override void getInvalidDecodeSound(IMethodResult oResult) { }
public override void setInvalidDecodeSound(string invalidDecodeSound, IMethodResult oResult) { }
public override void getAllDecoders(IMethodResult oResult) { }
public override void setAllDecoders(bool allDecoders, IMethodResult oResult) { }
public override void getAztec(IMethodResult oResult) { }
public override void setAztec(bool aztec, IMethodResult oResult) { }
public override void getChinese2of5(IMethodResult oResult) { }
public override void setChinese2of5(bool chinese2of5, IMethodResult oResult) { }
public override void getCodabar(IMethodResult oResult) { }
public override void setCodabar(bool codabar, IMethodResult oResult) { }
public override void getCodabarClsiEditing(IMethodResult oResult) { }
public override void setCodabarClsiEditing(bool codabarClsiEditing, IMethodResult oResult) { }
public override void getCodabarMaxLength(IMethodResult oResult) { }
public override void setCodabarMaxLength(int codabarMaxLength, IMethodResult oResult) { }
public override void getCodabarMinLength(IMethodResult oResult) { }
public override void setCodabarMinLength(int codabarMinLength, IMethodResult oResult) { }
public override void getCodabarNotisEditing(IMethodResult oResult) { }
public override void setCodabarNotisEditing(bool codabarNotisEditing, IMethodResult oResult) { }
public override void getCodabarRedundancy(IMethodResult oResult) { }
public override void setCodabarRedundancy(bool codabarRedundancy, IMethodResult oResult) { }
public override void getCode11(IMethodResult oResult) { }
public override void setCode11(bool code11, IMethodResult oResult) { }
public override void getCode11checkDigitCount(IMethodResult oResult) { }
public override void setCode11checkDigitCount(string code11checkDigitCount, IMethodResult oResult) { }
public override void getCode11maxLength(IMethodResult oResult) { }
public override void setCode11maxLength(int code11maxLength, IMethodResult oResult) { }
public override void getCode11minLength(IMethodResult oResult) { }
public override void setCode11minLength(int code11minLength, IMethodResult oResult) { }
public override void getCode11redundancy(IMethodResult oResult) { }
public override void setCode11redundancy(bool code11redundancy, IMethodResult oResult) { }
public override void getCode11reportCheckDigit(IMethodResult oResult) { }
public override void setCode11reportCheckDigit(bool code11reportCheckDigit, IMethodResult oResult) { }
public override void getCode128(IMethodResult oResult) { }
public override void setCode128(bool code128, IMethodResult oResult) { }
public override void getCode128checkIsBtTable(IMethodResult oResult) { }
public override void setCode128checkIsBtTable(bool code128checkIsBtTable, IMethodResult oResult) { }
public override void getCode128ean128(IMethodResult oResult) { }
public override void setCode128ean128(bool code128ean128, IMethodResult oResult) { }
public override void getCode128isbt128(IMethodResult oResult) { }
public override void setCode128isbt128(bool code128isbt128, IMethodResult oResult) { }
public override void getCode128isbt128ConcatMode(IMethodResult oResult) { }
public override void setCode128isbt128ConcatMode(string code128isbt128ConcatMode, IMethodResult oResult) { }
public override void getCode128maxLength(IMethodResult oResult) { }
public override void setCode128maxLength(int code128maxLength, IMethodResult oResult) { }
public override void getCode128minLength(IMethodResult oResult) { }
public override void setCode128minLength(int code128minLength, IMethodResult oResult) { }
public override void getCode128other128(IMethodResult oResult) { }
public override void setCode128other128(bool code128other128, IMethodResult oResult) { }
public override void getCode128redundancy(IMethodResult oResult) { }
public override void setCode128redundancy(bool code128redundancy, IMethodResult oResult) { }
public override void getCode128securityLevel(IMethodResult oResult) { }
public override void setCode128securityLevel(int code128securityLevel, IMethodResult oResult) { }
public override void getCompositeAb(IMethodResult oResult) { }
public override void setCompositeAb(bool compositeAb, IMethodResult oResult) { }
public override void getCompositeAbUccLinkMode(IMethodResult oResult) { }
public override void setCompositeAbUccLinkMode(string compositeAbUccLinkMode, IMethodResult oResult) { }
public override void getCompositeAbUseUpcPreambleCheckDigitRules(IMethodResult oResult) { }
public override void setCompositeAbUseUpcPreambleCheckDigitRules(bool compositeAbUseUpcPreambleCheckDigitRules, IMethodResult oResult) { }
public override void getCompositeC(IMethodResult oResult) { }
public override void setCompositeC(bool compositeC, IMethodResult oResult) { }
public override void getCode39(IMethodResult oResult) { }
public override void setCode39(bool code39, IMethodResult oResult) { }
public override void getCode39code32Prefix(IMethodResult oResult) { }
public override void setCode39code32Prefix(bool code39code32Prefix, IMethodResult oResult) { }
public override void getCode39convertToCode32(IMethodResult oResult) { }
public override void setCode39convertToCode32(bool code39convertToCode32, IMethodResult oResult) { }
public override void getCode39fullAscii(IMethodResult oResult) { }
public override void setCode39fullAscii(bool code39fullAscii, IMethodResult oResult) { }
public override void getCode39maxLength(IMethodResult oResult) { }
public override void setCode39maxLength(int code39maxLength, IMethodResult oResult) { }
public override void getCode39minLength(IMethodResult oResult) { }
public override void setCode39minLength(int code39minLength, IMethodResult oResult) { }
public override void getCode39redundancy(IMethodResult oResult) { }
public override void setCode39redundancy(bool code39redundancy, IMethodResult oResult) { }
public override void getCode39reportCheckDigit(IMethodResult oResult) { }
public override void setCode39reportCheckDigit(bool code39reportCheckDigit, IMethodResult oResult) { }
public override void getCode39securityLevel(IMethodResult oResult) { }
public override void setCode39securityLevel(int code39securityLevel, IMethodResult oResult) { }
public override void getCode39verifyCheckDigit(IMethodResult oResult) { }
public override void setCode39verifyCheckDigit(bool code39verifyCheckDigit, IMethodResult oResult) { }
public override void getCode93(IMethodResult oResult) { }
public override void setCode93(bool code93, IMethodResult oResult) { }
public override void getCode93maxLength(IMethodResult oResult) { }
public override void setCode93maxLength(int code93maxLength, IMethodResult oResult) { }
public override void getCode93minLength(IMethodResult oResult) { }
public override void setCode93minLength(int code93minLength, IMethodResult oResult) { }
public override void getCode93redundancy(IMethodResult oResult) { }
public override void setCode93redundancy(bool code93redundancy, IMethodResult oResult) { }
public override void getD2of5(IMethodResult oResult) { }
public override void setD2of5(bool d2of5, IMethodResult oResult) { }
public override void getD2of5maxLength(IMethodResult oResult) { }
public override void setD2of5maxLength(int d2of5maxLength, IMethodResult oResult) { }
public override void getD2of5minLength(IMethodResult oResult) { }
public override void setD2of5minLength(int d2of5minLength, IMethodResult oResult) { }
public override void getD2of5redundancy(IMethodResult oResult) { }
public override void setD2of5redundancy(bool d2of5redundancy, IMethodResult oResult) { }
public override void getDatamatrix(IMethodResult oResult) { }
public override void setDatamatrix(bool datamatrix, IMethodResult oResult) { }
public override void getEan13(IMethodResult oResult) { }
public override void setEan13(bool ean13, IMethodResult oResult) { }
public override void getEan8(IMethodResult oResult) { }
public override void setEan8(bool ean8, IMethodResult oResult) { }
public override void getEan8convertToEan13(IMethodResult oResult) { }
public override void setEan8convertToEan13(bool ean8convertToEan13, IMethodResult oResult) { }
public override void getI2of5(IMethodResult oResult) { }
public override void setI2of5(bool i2of5, IMethodResult oResult) { }
public override void getI2of5convertToEan13(IMethodResult oResult) { }
public override void setI2of5convertToEan13(bool i2of5convertToEan13, IMethodResult oResult) { }
public override void getI2of5maxLength(IMethodResult oResult) { }
public override void setI2of5maxLength(int i2of5maxLength, IMethodResult oResult) { }
public override void getI2of5minLength(IMethodResult oResult) { }
public override void setI2of5minLength(int i2of5minLength, IMethodResult oResult) { }
public override void getI2of5redundancy(IMethodResult oResult) { }
public override void setI2of5redundancy(bool i2of5redundancy, IMethodResult oResult) { }
public override void getI2of5reportCheckDigit(IMethodResult oResult) { }
public override void setI2of5reportCheckDigit(bool i2of5reportCheckDigit, IMethodResult oResult) { }
public override void getI2of5verifyCheckDigit(IMethodResult oResult) { }
public override void setI2of5verifyCheckDigit(string i2of5verifyCheckDigit, IMethodResult oResult) { }
public override void getKorean3of5(IMethodResult oResult) { }
public override void setKorean3of5(bool korean3of5, IMethodResult oResult) { }
public override void getKorean3of5redundancy(IMethodResult oResult) { }
public override void setKorean3of5redundancy(bool korean3of5redundancy, IMethodResult oResult) { }
public override void getKorean3of5maxLength(IMethodResult oResult) { }
public override void setKorean3of5maxLength(int korean3of5maxLength, IMethodResult oResult) { }
public override void getKorean3of5minLength(IMethodResult oResult) { }
public override void setKorean3of5minLength(int korean3of5minLength, IMethodResult oResult) { }
public override void getMacroPdf(IMethodResult oResult) { }
public override void setMacroPdf(bool macroPdf, IMethodResult oResult) { }
public override void getMacroPdfBufferLabels(IMethodResult oResult) { }
public override void setMacroPdfBufferLabels(bool macroPdfBufferLabels, IMethodResult oResult) { }
public override void getMacroPdfConvertToPdf417(IMethodResult oResult) { }
public override void setMacroPdfConvertToPdf417(bool macroPdfConvertToPdf417, IMethodResult oResult) { }
public override void getMacroPdfExclusive(IMethodResult oResult) { }
public override void setMacroPdfExclusive(bool macroPdfExclusive, IMethodResult oResult) { }
public override void getMacroMicroPdf(IMethodResult oResult) { }
public override void setMacroMicroPdf(bool macroMicroPdf, IMethodResult oResult) { }
public override void getMacroMicroPdfBufferLabels(IMethodResult oResult) { }
public override void setMacroMicroPdfBufferLabels(bool macroMicroPdfBufferLabels, IMethodResult oResult) { }
public override void getMacroMicroPdfConvertToMicroPdf(IMethodResult oResult) { }
public override void setMacroMicroPdfConvertToMicroPdf(bool macroMicroPdfConvertToMicroPdf, IMethodResult oResult) { }
public override void getMacroMicroPdfExclusive(IMethodResult oResult) { }
public override void setMacroMicroPdfExclusive(bool macroMicroPdfExclusive, IMethodResult oResult) { }
public override void getMacroMicroPdfReportAppendInfo(IMethodResult oResult) { }
public override void setMacroMicroPdfReportAppendInfo(bool macroMicroPdfReportAppendInfo, IMethodResult oResult) { }
public override void getMatrix2of5(IMethodResult oResult) { }
public override void setMatrix2of5(bool matrix2of5, IMethodResult oResult) { }
public override void getMatrix2of5maxLength(IMethodResult oResult) { }
public override void setMatrix2of5maxLength(int matrix2of5maxLength, IMethodResult oResult) { }
public override void getMatrix2of5minLength(IMethodResult oResult) { }
public override void setMatrix2of5minLength(int matrix2of5minLength, IMethodResult oResult) { }
public override void getMatrix2of5reportCheckDigit(IMethodResult oResult) { }
public override void setMatrix2of5reportCheckDigit(bool matrix2of5reportCheckDigit, IMethodResult oResult) { }
public override void getMatrix2of5verifyCheckDigit(IMethodResult oResult) { }
public override void setMatrix2of5verifyCheckDigit(bool matrix2of5verifyCheckDigit, IMethodResult oResult) { }
public override void getMaxiCode(IMethodResult oResult) { }
public override void setMaxiCode(bool maxiCode, IMethodResult oResult) { }
public override void getMicroPdf(IMethodResult oResult) { }
public override void setMicroPdf(bool microPdf, IMethodResult oResult) { }
public override void getMicroQr(IMethodResult oResult) { }
public override void setMicroQr(bool microQr, IMethodResult oResult) { }
public override void getMsi(IMethodResult oResult) { }
public override void setMsi(bool msi, IMethodResult oResult) { }
public override void getMsiCheckDigits(IMethodResult oResult){}
public override void setMsiCheckDigits(string msiCheckDigits, IMethodResult oResult) { }
public override void getMsiCheckDigitScheme(IMethodResult oResult) { }
public override void setMsiCheckDigitScheme(string msiCheckDigitScheme, IMethodResult oResult) { }
public override void getMsiMaxLength(IMethodResult oResult) { }
public override void setMsiMaxLength(int msiMaxLength, IMethodResult oResult) { }
public override void getMsiMinLength(IMethodResult oResult) { }
public override void setMsiMinLength(int msiMinLength, IMethodResult oResult) { }
public override void getMsiRedundancy(IMethodResult oResult) { }
public override void setMsiRedundancy(bool msiRedundancy, IMethodResult oResult) { }
public override void getMsiReportCheckDigit(IMethodResult oResult) { }
public override void setMsiReportCheckDigit(bool msiReportCheckDigit, IMethodResult oResult) { }
public override void getPdf417(IMethodResult oResult) { }
public override void setPdf417(bool pdf417, IMethodResult oResult) { }
public override void getSignature(IMethodResult oResult) { }
public override void setSignature(bool signature, IMethodResult oResult) { }
public override void getSignatureImageHeight(IMethodResult oResult) { }
public override void setSignatureImageHeight(int signatureImageHeight, IMethodResult oResult) { }
public override void getSignatureImageWidth(IMethodResult oResult) { }
public override void setSignatureImageWidth(int signatureImageWidth, IMethodResult oResult) { }
public override void getSignatureImageQuality(IMethodResult oResult) { }
public override void setSignatureImageQuality(int signatureImageQuality, IMethodResult oResult) { }
public override void getAusPostal(IMethodResult oResult) { }
public override void setAusPostal(bool ausPostal, IMethodResult oResult) { }
public override void getCanPostal(IMethodResult oResult) { }
public override void setCanPostal(bool canPostal, IMethodResult oResult) { }
public override void getDutchPostal(IMethodResult oResult) { }
public override void setDutchPostal(bool dutchPostal, IMethodResult oResult) { }
public override void getJapPostal(IMethodResult oResult) { }
public override void setJapPostal(bool japPostal, IMethodResult oResult) { }
public override void getUkPostal(IMethodResult oResult) { }
public override void setUkPostal(bool ukPostal, IMethodResult oResult) { }
public override void getUkPostalReportCheckDigit(IMethodResult oResult) { }
public override void setUkPostalReportCheckDigit(bool ukPostalReportCheckDigit, IMethodResult oResult) { }
public override void getUs4state(IMethodResult oResult) { }
public override void setUs4state(bool us4state, IMethodResult oResult) { }
public override void getUs4stateFics(IMethodResult oResult) { }
public override void setUs4stateFics(bool us4stateFics, IMethodResult oResult) { }
public override void getUsPlanet(IMethodResult oResult) { }
public override void setUsPlanet(bool usPlanet, IMethodResult oResult) { }
public override void getUsPlanetReportCheckDigit(IMethodResult oResult) { }
public override void setUsPlanetReportCheckDigit(bool usPlanetReportCheckDigit, IMethodResult oResult) { }
public override void getUsPostNet(IMethodResult oResult) { }
public override void setUsPostNet(bool usPostNet, IMethodResult oResult) { }
public override void getUsPostNetReportCheckDigit(IMethodResult oResult) { }
public override void setUsPostNetReportCheckDigit(bool usPostNetReportCheckDigit, IMethodResult oResult) { }
public override void getQrCode(IMethodResult oResult) { }
public override void setQrCode(bool qrCode, IMethodResult oResult) { }
public override void getGs1dataBar(IMethodResult oResult) { }
public override void setGs1dataBar(bool gs1dataBar, IMethodResult oResult) { }
public override void getGs1dataBarExpanded(IMethodResult oResult) { }
public override void setGs1dataBarExpanded(bool gs1dataBarExpanded, IMethodResult oResult) { }
public override void getGs1dataBarLimited(IMethodResult oResult) { }
public override void setGs1dataBarLimited(bool gs1dataBarLimited, IMethodResult oResult) { }
public override void getTlc39(IMethodResult oResult) { }
public override void setTlc39(bool tlc39, IMethodResult oResult) { }
public override void getTrioptic39(IMethodResult oResult) { }
public override void setTrioptic39(bool trioptic39, IMethodResult oResult) { }
public override void getTrioptic39Redundancy(IMethodResult oResult) { }
public override void setTrioptic39Redundancy(bool trioptic39Redundancy, IMethodResult oResult) { }
public override void getUpcEanBookland(IMethodResult oResult) { }
public override void setUpcEanBookland(bool upcEanBookland, IMethodResult oResult) { }
public override void getUpcEanBooklandFormat(IMethodResult oResult) { }
public override void setUpcEanBooklandFormat(string upcEanBooklandFormat, IMethodResult oResult) { }
public override void getUpcEanConvertGs1dataBarToUpcEan(IMethodResult oResult) { }
public override void setUpcEanConvertGs1dataBarToUpcEan(bool upcEanConvertGs1dataBarToUpcEan, IMethodResult oResult) { }
public override void getUpcEanCoupon(IMethodResult oResult) { }
public override void setUpcEanCoupon(bool upcEanCoupon, IMethodResult oResult) { }
public override void getUpcEanLinearDecode(IMethodResult oResult) { }
public override void setUpcEanLinearDecode(bool upcEanLinearDecode, IMethodResult oResult) { }
public override void getUpcEanRandomWeightCheckDigit(IMethodResult oResult) { }
public override void setUpcEanRandomWeightCheckDigit(bool upcEanRandomWeightCheckDigit, IMethodResult oResult) { }
public override void getUpcEanRetryCount(IMethodResult oResult) { }
public override void setUpcEanRetryCount(int upcEanRetryCount, IMethodResult oResult) { }
public override void getUpcEanSecurityLevel(IMethodResult oResult) { }
public override void setUpcEanSecurityLevel(int upcEanSecurityLevel, IMethodResult oResult) { }
public override void getUpcEanSupplemental2(IMethodResult oResult) { }
public override void setUpcEanSupplemental2(bool upcEanSupplemental2, IMethodResult oResult) { }
public override void getUpcEanSupplemental5(IMethodResult oResult) { }
public override void setUpcEanSupplemental5(bool upcEanSupplemental5, IMethodResult oResult) { }
public override void getUpcEanSupplementalMode(IMethodResult oResult) { }
public override void setUpcEanSupplementalMode(string upcEanSupplementalMode, IMethodResult oResult) { }
public override void getUpca(IMethodResult oResult) { }
public override void setUpca(bool upca, IMethodResult oResult) { }
public override void getUpcaPreamble(IMethodResult oResult) { }
public override void setUpcaPreamble(string upcaPreamble, IMethodResult oResult) { }
public override void getUpcaReportCheckDigit(IMethodResult oResult) { }
public override void setUpcaReportCheckDigit(bool upcaReportCheckDigit, IMethodResult oResult) { }
public override void getUpce0(IMethodResult oResult) { }
public override void setUpce0(bool upce0, IMethodResult oResult) { }
public override void getUpce0convertToUpca(IMethodResult oResult) { }
public override void setUpce0convertToUpca(bool upce0convertToUpca, IMethodResult oResult) { }
public override void getUpce0preamble(IMethodResult oResult) { }
public override void setUpce0preamble(string upce0preamble, IMethodResult oResult) { }
public override void getUpce0reportCheckDigit(IMethodResult oResult) { }
public override void setUpce0reportCheckDigit(bool upce0reportCheckDigit, IMethodResult oResult) { }
public override void getUpce1(IMethodResult oResult) { }
public override void setUpce1(bool upce1, IMethodResult oResult) { }
public override void getUpce1convertToUpca(IMethodResult oResult) { }
public override void setUpce1convertToUpca(bool upce1convertToUpca, IMethodResult oResult) { }
public override void getUpce1preamble(IMethodResult oResult) { }
public override void setUpce1preamble(string upce1preamble, IMethodResult oResult) { }
public override void getUpce1reportCheckDigit(IMethodResult oResult) { }
public override void setUpce1reportCheckDigit(bool upce1reportCheckDigit, IMethodResult oResult) { }
public override void getWebcode(IMethodResult oResult) { }
public override void setWebcode(bool webcode, IMethodResult oResult) { }
public override void getWebcodeDecodeGtSubtype(IMethodResult oResult) { }
public override void setWebcodeDecodeGtSubtype(bool webcodeDecodeGtSubtype, IMethodResult oResult) { }
public override void getRsmModelNumber(IMethodResult oResult) { }
public override void getRsmSerialNumber(IMethodResult oResult) { }
public override void getRsmDateOfManufacture(IMethodResult oResult) { }
public override void getRsmDateOfService(IMethodResult oResult) { }
public override void getRsmBluetoothAddress(IMethodResult oResult) { }
public override void getRsmFirmwareVersion(IMethodResult oResult) { }
public override void getRsmDeviceClass(IMethodResult oResult) { }
public override void getRsmBatteryStatus(IMethodResult oResult) { }
public override void getRsmBatteryCapacity(IMethodResult oResult) { }
public override void getRsmBatteryId(IMethodResult oResult) { }
public override void getRsmBluetoothAuthentication(IMethodResult oResult) { }
public override void setRsmBluetoothAuthentication(bool rsmBluetoothAuthentication, IMethodResult oResult) { }
public override void getRsmBluetoothEncryption(IMethodResult oResult) { }
public override void setRsmBluetoothEncryption(bool rsmBluetoothEncryption, IMethodResult oResult) { }
public override void getRsmBluetoothPinCode(IMethodResult oResult) { }
public override void setRsmBluetoothPinCode(string rsmBluetoothPinCode, IMethodResult oResult) { }
public override void getRsmBluetoothPinCodeType(IMethodResult oResult) { }
public override void setRsmBluetoothPinCodeType(string rsmBluetoothPinCodeType, IMethodResult oResult) { }
public override void getRsmBluetoothReconnectionAttempts(IMethodResult oResult) { }
public override void setRsmBluetoothReconnectionAttempts(int rsmBluetoothReconnectionAttempts, IMethodResult oResult) { }
public override void getRsmBluetoothBeepOnReconnectAttempt(IMethodResult oResult) { }
public override void setRsmBluetoothBeepOnReconnectAttempt(bool rsmBluetoothBeepOnReconnectAttempt, IMethodResult oResult) { }
public override void getRsmBluetoothHidAutoReconnect(IMethodResult oResult) { }
public override void setRsmBluetoothHidAutoReconnect(string rsmBluetoothHidAutoReconnect, IMethodResult oResult) { }
public override void getRsmBluetoothFriendlyName(IMethodResult oResult) { }
public override void setRsmBluetoothFriendlyName(string rsmBluetoothFriendlyName, IMethodResult oResult) { }
public override void getRsmBluetoothInquiryMode(IMethodResult oResult) { }
public override void setRsmBluetoothInquiryMode(string rsmBluetoothInquiryMode, IMethodResult oResult) { }
public override void getRsmBluetoothAutoReconnect(IMethodResult oResult) { }
public override void setRsmBluetoothAutoReconnect(string rsmBluetoothAutoReconnect, IMethodResult oResult) { }
public override void getRsmForceSavePairingBarcode(IMethodResult oResult) { }
public override void setRsmForceSavePairingBarcode(bool rsmForceSavePairingBarcode, IMethodResult oResult) { }
public override void getRsmLowBatteryIndication(IMethodResult oResult) { }
public override void setRsmLowBatteryIndication(bool rsmLowBatteryIndication, IMethodResult oResult) { }
public override void getRsmLowBatteryIndicationCycle(IMethodResult oResult) { }
public override void setRsmLowBatteryIndicationCycle(int rsmLowBatteryIndicationCycle, IMethodResult oResult) { }
public override void getRsmScanLineWidth(IMethodResult oResult) { }
public override void setRsmScanLineWidth(string rsmScanLineWidth, IMethodResult oResult) { }
public override void getRsmGoodScansDelay(IMethodResult oResult) { }
public override void setRsmGoodScansDelay(int rsmGoodScansDelay, IMethodResult oResult) { }
public override void getRsmDecodeFeedback(IMethodResult oResult) { }
public override void setRsmDecodeFeedback(bool rsmDecodeFeedback, IMethodResult oResult) { }
public override void getRsmIgnoreCode128Usps(IMethodResult oResult) { }
public override void setRsmIgnoreCode128Usps(bool rsmIgnoreCode128Usps, IMethodResult oResult) { }
public override void getRsmScanTriggerWakeup(IMethodResult oResult) { }
public override void setRsmScanTriggerWakeup(bool rsmScanTriggerWakeup, IMethodResult oResult) { }
public override void getRsmMems(IMethodResult oResult) { }
public override void setRsmMems(bool rsmMems, IMethodResult oResult) { }
public override void getRsmProximityEnable(IMethodResult oResult) { }
public override void setRsmProximityEnable(bool rsmProximityEnable, IMethodResult oResult) { }
public override void getRsmProximityContinuous(IMethodResult oResult) { }
public override void setRsmProximityContinuous(bool rsmProximityContinuous, IMethodResult oResult) { }
public override void getRsmProximityDistance(IMethodResult oResult) { }
public override void setRsmProximityDistance(string rsmProximityDistance, IMethodResult oResult) { }
public override void getRsmPagingEnable(IMethodResult oResult) { }
public override void setRsmPagingEnable(bool rsmPagingEnable, IMethodResult oResult) { }
public override void getRsmPagingBeepSequence(IMethodResult oResult) { }
public override void setRsmPagingBeepSequence(int rsmPagingBeepSequence, IMethodResult oResult) { }
public override void registerBluetoothStatus(IMethodResult oResult) { }
public override void getScannerType(IMethodResult oResult) { }
public override void commandRemoteScanner(string command, IMethodResult oResult) { }
/* --------------------------------------------------------------------------------------------------------- */
bool _isEnable = false;
public override void enable(IReadOnlyDictionary<string, string> propertyMap, IMethodResult oResult)
{
_isEnable = true;
}
public override void start(IMethodResult oResult)
{
// implement this method in C# here
}
public override void stop(IMethodResult oResult)
{
// implement this method in C# here
}
public override void disable(IMethodResult oResult)
{
_isEnable = false;
}
public override void barcode_recognize(string imageFilePath, IMethodResult oResult)
{
_recognizeResult = "";
_methodResult = oResult;
StreamResourceInfo info = Application.GetResourceStream(new Uri(imageFilePath, UriKind.Relative));
BitmapSource bmSrc = null;
DispatchInvoke(() =>
{
bmSrc = new BitmapImage();
bmSrc.SetSource(info.Stream);
WriteableBitmap writableBitmap = new WriteableBitmap(bmSrc);
writableBitmap.Invalidate();
_barcodeReader.TryHarder = true;
_barcodeReader.ResultFound += BarcodeRecognizeTask_Completed;
_barcodeReader.Decode(writableBitmap);
_waitHandle.Set();
});
_waitHandle.WaitOne();
oResult.set(_recognizeResult);
}
void BarcodeRecognizeTask_Completed(Result obj)
{
_recognizeResult = obj.Text;
}
public override void getSupportedProperties(IMethodResult oResult)
{
List<String> propsList = new List<String>();
oResult.set(propsList);
}
public override void take(IReadOnlyDictionary<string, string> propertyMap, IMethodResult oResult)
{
_methodResult = oResult;
DispatchInvoke(() =>
{
_barcodeScanTask.Show();
});
}
public override void take_barcode(string rubyCallbackURL, IReadOnlyDictionary<string, string> propertyMap, IMethodResult oResult)
{
take(null, oResult);
}
static Mutex _m = new Mutex();
private void BarcodeScanTask_Completed(object sender, BarcodeReaderLib.OpticalReaderResult readerResult)
{
System.Diagnostics.Debug.WriteLine("BarcodeScanTask_Completed 1");
if (readerResult.TaskResult == TaskResult.None || _methodResult == null)
return;
if (readerResult.TaskResult == TaskResult.Cancel)
{
new Thread(() =>
{
_m.WaitOne();
System.Diagnostics.Debug.WriteLine("BarcodeScanTask_Completed cancel");
Dictionary<string, string> result = new Dictionary<string, string>();
result.Add("status", "cancel");
result.Add("barcode", "");
_methodResult.set(result);
_methodResult = null;
_m.ReleaseMutex();
}).Start();
return;
}
VibrateController.Default.Start(TimeSpan.FromMilliseconds(Barcode.vibrateTimeMs));
System.Diagnostics.Debug.WriteLine("BarcodeScanTask_Completed 2");
_prevScanResult = readerResult.Text;
CRhoRuntime.getInstance().logEvent(String.Format("Barcode: {0} = {1}",
readerResult.Format,
readerResult.Text)
);
new Thread(() =>
{
_m.WaitOne();
System.Diagnostics.Debug.WriteLine("BarcodeScanTask_Completed send data");
Dictionary<string, string> result = new Dictionary<string, string>();
result.Add("status", "ok");
result.Add("barcode", readerResult.Text);
_methodResult.set(result);
_m.ReleaseMutex();
}).Start();
}
}
public class BarcodeSingleton : BarcodeSingletonBase
{
public BarcodeSingleton()
{
}
public override void enumerate(IMethodResult oResult)
{
List<String> scannerEnum = new List<String>();
scannerEnum.Add("CameraScanner1");
oResult.set(scannerEnum);
}
}
public class BarcodeFactory : BarcodeFactoryBase
{
}
}
}
| |
using Signum.Engine.Authorization;
using Signum.Engine.Basics;
using Signum.Engine.DynamicQuery;
using Signum.Engine.Maps;
using Signum.Engine.Operations;
using Signum.Engine.UserAssets;
using Signum.Engine.ViewLog;
using Signum.Entities;
using Signum.Entities.Authorization;
using Signum.Entities.Basics;
using Signum.Entities.DynamicQuery;
using Signum.Entities.UserAssets;
using Signum.Entities.UserQueries;
using Signum.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Signum.Engine.UserQueries
{
public static class UserQueryLogic
{
public static ResetLazy<Dictionary<Lite<UserQueryEntity>, UserQueryEntity>> UserQueries = null!;
public static ResetLazy<Dictionary<Type, List<Lite<UserQueryEntity>>>> UserQueriesByTypeForQuickLinks = null!;
public static ResetLazy<Dictionary<object, List<Lite<UserQueryEntity>>>> UserQueriesByQuery = null!;
public static void Start(SchemaBuilder sb)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
QueryLogic.Start(sb);
PermissionAuthLogic.RegisterPermissions(UserQueryPermission.ViewUserQuery);
UserAssetsImporter.RegisterName<UserQueryEntity>("UserQuery");
sb.Schema.Synchronizing += Schema_Synchronizing;
sb.Schema.Table<QueryEntity>().PreDeleteSqlSync += e =>
Administrator.UnsafeDeletePreCommand(Database.Query<UserQueryEntity>().Where(a => a.Query == e));
sb.Include<UserQueryEntity>()
.WithSave(UserQueryOperation.Save)
.WithDelete(UserQueryOperation.Delete)
.WithQuery(() => uq => new
{
Entity = uq,
uq.Id,
uq.DisplayName,
uq.Query,
uq.EntityType,
});
sb.Schema.EntityEvents<UserQueryEntity>().Retrieved += UserQueryLogic_Retrieved;
UserQueries = sb.GlobalLazy(() => Database.Query<UserQueryEntity>().ToDictionary(a => a.ToLite()),
new InvalidateWith(typeof(UserQueryEntity)));
UserQueriesByQuery = sb.GlobalLazy(() => UserQueries.Value.Values.Where(a => a.EntityType == null).SelectCatch(uq => KeyValuePair.Create(uq.Query.ToQueryName(), uq.ToLite())).GroupToDictionary(),
new InvalidateWith(typeof(UserQueryEntity)));
UserQueriesByTypeForQuickLinks = sb.GlobalLazy(() => UserQueries.Value.Values.Where(a => a.EntityType != null && !a.HideQuickLink).SelectCatch(uq => KeyValuePair.Create(TypeLogic.IdToType.GetOrThrow(uq.EntityType!.Id), uq.ToLite())).GroupToDictionary(),
new InvalidateWith(typeof(UserQueryEntity)));
}
}
public static QueryRequest ToQueryRequest(this UserQueryEntity userQuery)
{
var qr = new QueryRequest()
{
QueryName = userQuery.Query.ToQueryName(),
GroupResults = userQuery.GroupResults,
};
qr.Filters = userQuery.Filters.ToFilterList();
qr.Columns = MergeColumns(userQuery);
qr.Orders = userQuery.Orders.Select(qo => new Order(qo.Token.Token, qo.OrderType)).ToList();
qr.Pagination = userQuery.GetPagination() ?? new Pagination.All();
return qr;
}
static List<Column> MergeColumns(UserQueryEntity uq)
{
QueryDescription qd = QueryLogic.Queries.QueryDescription(uq.Query.ToQueryName());
switch (uq.ColumnsMode)
{
case ColumnOptionsMode.Add:
return qd.Columns.Where(cd => !cd.IsEntity).Select(cd => new Column(cd, qd.QueryName)).Concat(uq.Columns.Select(co => ToColumn(co))).ToList();
case ColumnOptionsMode.Remove:
return qd.Columns.Where(cd => !cd.IsEntity && !uq.Columns.Any(co => co.Token.TokenString == cd.Name)).Select(cd => new Column(cd, qd.QueryName)).ToList();
case ColumnOptionsMode.Replace:
return uq.Columns.Select(co => ToColumn(co)).ToList();
default:
throw new InvalidOperationException("{0} is not a valid ColumnOptionMode".FormatWith(uq.ColumnsMode));
}
}
private static Column ToColumn(QueryColumnEmbedded co)
{
return new Column(co.Token.Token, co.DisplayName.DefaultText(co.Token.Token.NiceName()));
}
public static UserQueryEntity ParseAndSave(this UserQueryEntity userQuery)
{
if (!userQuery.IsNew || userQuery.queryName == null)
throw new InvalidOperationException("userQuery should be new and have queryName");
userQuery.Query = QueryLogic.GetQueryEntity(userQuery.queryName);
QueryDescription description = QueryLogic.Queries.QueryDescription(userQuery.queryName);
userQuery.ParseData(description);
return userQuery.Execute(UserQueryOperation.Save);
}
static void UserQueryLogic_Retrieved(UserQueryEntity userQuery, PostRetrievingContext ctx)
{
object? queryName = userQuery.Query.ToQueryNameCatch();
if(queryName == null)
return;
QueryDescription description = QueryLogic.Queries.QueryDescription(queryName);
userQuery.ParseData(description);
}
public static List<Lite<UserQueryEntity>> GetUserQueries(object queryName)
{
var isAllowed = Schema.Current.GetInMemoryFilter<UserQueryEntity>(userInterface: false);
return UserQueriesByQuery.Value.TryGetC(queryName).EmptyIfNull()
.Where(e => isAllowed(UserQueries.Value.GetOrThrow(e))).ToList();
}
public static List<Lite<UserQueryEntity>> GetUserQueriesEntity(Type entityType)
{
var isAllowed = Schema.Current.GetInMemoryFilter<UserQueryEntity>(userInterface: false);
return UserQueriesByTypeForQuickLinks.Value.TryGetC(entityType).EmptyIfNull()
.Where(e => isAllowed(UserQueries.Value.GetOrThrow(e))).ToList();
}
public static List<Lite<UserQueryEntity>> Autocomplete(string subString, int limit)
{
var isAllowed = Schema.Current.GetInMemoryFilter<UserQueryEntity>(userInterface: false);
return UserQueries.Value.Where(a => a.Value.EntityType == null && isAllowed(a.Value))
.Select(a => a.Key).Autocomplete(subString, limit).ToList();
}
public static UserQueryEntity RetrieveUserQuery(this Lite<UserQueryEntity> userQuery)
{
using (ViewLogLogic.LogView(userQuery, "UserQuery"))
{
var result = UserQueries.Value.GetOrThrow(userQuery);
var isAllowed = Schema.Current.GetInMemoryFilter<UserQueryEntity>(userInterface: false);
if (!isAllowed(result))
throw new EntityNotFoundException(userQuery.EntityType, userQuery.Id);
return result;
}
}
public static void RegisterUserTypeCondition(SchemaBuilder sb, TypeConditionSymbol typeCondition)
{
sb.Schema.Settings.AssertImplementedBy((UserQueryEntity uq) => uq.Owner, typeof(UserEntity));
TypeConditionLogic.RegisterCompile<UserQueryEntity>(typeCondition,
uq => uq.Owner.Is(UserEntity.Current));
}
public static void RegisterRoleTypeCondition(SchemaBuilder sb, TypeConditionSymbol typeCondition)
{
sb.Schema.Settings.AssertImplementedBy((UserQueryEntity uq) => uq.Owner, typeof(RoleEntity));
TypeConditionLogic.RegisterCompile<UserQueryEntity>(typeCondition,
uq => AuthLogic.CurrentRoles().Contains(uq.Owner) || uq.Owner == null);
}
static SqlPreCommand? Schema_Synchronizing(Replacements replacements)
{
if (!replacements.Interactive)
return null;
var list = Database.Query<UserQueryEntity>().ToList();
var table = Schema.Current.Table(typeof(UserQueryEntity));
SqlPreCommand? cmd = list.Select(uq => ProcessUserQuery(replacements, table, uq)).Combine(Spacing.Double);
return cmd;
}
static SqlPreCommand? ProcessUserQuery(Replacements replacements, Table table, UserQueryEntity uq)
{
Console.Write(".");
try
{
using (DelayedConsole.Delay(() => SafeConsole.WriteLineColor(ConsoleColor.White, "UserQuery: " + uq.DisplayName)))
using (DelayedConsole.Delay(() => Console.WriteLine(" Query: " + uq.Query.Key)))
{
if (uq.Filters.Any(a => a.Token?.ParseException != null) ||
uq.Columns.Any(a => a.Token?.ParseException != null) ||
uq.Orders.Any(a => a.Token.ParseException != null))
{
QueryDescription qd = QueryLogic.Queries.QueryDescription(uq.Query.ToQueryName());
var options = uq.GroupResults ? (SubTokensOptions.CanElement | SubTokensOptions.CanAggregate) : SubTokensOptions.CanElement;
if (uq.Filters.Any())
{
using (DelayedConsole.Delay(() => Console.WriteLine(" Filters:")))
{
foreach (var item in uq.Filters.ToList())
{
if (item.Token == null)
continue;
QueryTokenEmbedded token = item.Token;
switch (QueryTokenSynchronizer.FixToken(replacements, ref token, qd, options | SubTokensOptions.CanAnyAll, "{0} {1}".FormatWith(item.Operation, item.ValueString), allowRemoveToken: true, allowReCreate: false))
{
case FixTokenResult.Nothing: break;
case FixTokenResult.DeleteEntity: return table.DeleteSqlSync(uq, u => u.Guid == uq.Guid);
case FixTokenResult.RemoveToken: uq.Filters.Remove(item); break;
case FixTokenResult.SkipEntity: return null;
case FixTokenResult.Fix: item.Token = token; break;
default: break;
}
}
}
}
if (uq.Columns.Any())
{
using (DelayedConsole.Delay(() => Console.WriteLine(" Columns:")))
{
foreach (var item in uq.Columns.ToList())
{
QueryTokenEmbedded token = item.Token;
switch (QueryTokenSynchronizer.FixToken(replacements, ref token, qd, options, item.DisplayName.HasText() ? "'{0}'".FormatWith(item.DisplayName) : null, allowRemoveToken: true, allowReCreate: false))
{
case FixTokenResult.Nothing: break;
case FixTokenResult.DeleteEntity:; return table.DeleteSqlSync(uq, u => u.Guid == uq.Guid);
case FixTokenResult.RemoveToken: uq.Columns.Remove(item); break;
case FixTokenResult.SkipEntity: return null;
case FixTokenResult.Fix: item.Token = token; break;
default: break;
}
}
}
}
if (uq.Orders.Any())
{
using (DelayedConsole.Delay(() => Console.WriteLine(" Orders:")))
{
foreach (var item in uq.Orders.ToList())
{
QueryTokenEmbedded token = item.Token;
switch (QueryTokenSynchronizer.FixToken(replacements, ref token, qd, options, item.OrderType.ToString(), allowRemoveToken: true, allowReCreate: false))
{
case FixTokenResult.Nothing: break;
case FixTokenResult.DeleteEntity: return table.DeleteSqlSync(uq, u => u.Guid == uq.Guid);
case FixTokenResult.RemoveToken: uq.Orders.Remove(item); break;
case FixTokenResult.SkipEntity: return null;
case FixTokenResult.Fix: item.Token = token; break;
default: break;
}
}
}
}
}
foreach (var item in uq.Filters.Where(f => !f.IsGroup).ToList())
{
retry:
string? val = item.ValueString;
switch (QueryTokenSynchronizer.FixValue(replacements, item.Token!.Token.Type, ref val, allowRemoveToken: true, isList: item.Operation!.Value.IsList()))
{
case FixTokenResult.Nothing: break;
case FixTokenResult.DeleteEntity: return table.DeleteSqlSync(uq, u => u.Guid == uq.Guid);
case FixTokenResult.RemoveToken: uq.Filters.Remove(item); break;
case FixTokenResult.SkipEntity: return null;
case FixTokenResult.Fix: item.ValueString = val; goto retry;
}
}
if (uq.AppendFilters)
uq.Filters.Clear();
if (!uq.ShouldHaveElements && uq.ElementsPerPage.HasValue)
uq.ElementsPerPage = null;
if (uq.ShouldHaveElements && !uq.ElementsPerPage.HasValue)
uq.ElementsPerPage = 20;
using (replacements.WithReplacedDatabaseName())
return table.UpdateSqlSync(uq, u => u.Guid == uq.Guid, includeCollections: true);
}
}
catch (Exception e)
{
return new SqlPreCommandSimple("-- Exception in {0}: {1}".FormatWith(uq.BaseToString(), e.Message));
}
}
}
}
| |
using EIDSS.Reports.BaseControls.Filters;
namespace EIDSS.Reports.Parameterized.Human.AJ.Keepers
{
partial class ComparativeTwoYearsAZReportKeeper
{
#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(ComparativeTwoYearsAZReportKeeper));
this.StartYearLabel = new System.Windows.Forms.Label();
this.Year1SpinEdit = new DevExpress.XtraEditors.SpinEdit();
this.Year2SpinEdit = new DevExpress.XtraEditors.SpinEdit();
this.EndYearLabel = new System.Windows.Forms.Label();
this.CounterLookUp = new DevExpress.XtraEditors.LookUpEdit();
this.CounterLabel = new System.Windows.Forms.Label();
this.OrganizationFilter = new EIDSS.Reports.BaseControls.Filters.HumOrganizationFilter();
this.regionFilter = new EIDSS.Reports.BaseControls.Filters.RegionFilter();
this.rayonFilter = new EIDSS.Reports.BaseControls.Filters.RayonFilter();
this.diagnosisFilter = new EIDSS.Reports.BaseControls.Filters.HumSingleDiagnosisFilter();
this.pnlSettings.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.ceUseArchiveData.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.Year1SpinEdit.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.Year2SpinEdit.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CounterLookUp.Properties)).BeginInit();
this.SuspendLayout();
//
// pnlSettings
//
this.pnlSettings.Controls.Add(this.diagnosisFilter);
this.pnlSettings.Controls.Add(this.OrganizationFilter);
this.pnlSettings.Controls.Add(this.regionFilter);
this.pnlSettings.Controls.Add(this.rayonFilter);
this.pnlSettings.Controls.Add(this.CounterLookUp);
this.pnlSettings.Controls.Add(this.CounterLabel);
this.pnlSettings.Controls.Add(this.Year2SpinEdit);
this.pnlSettings.Controls.Add(this.Year1SpinEdit);
this.pnlSettings.Controls.Add(this.EndYearLabel);
this.pnlSettings.Controls.Add(this.StartYearLabel);
resources.ApplyResources(this.pnlSettings, "pnlSettings");
this.pnlSettings.Controls.SetChildIndex(this.GenerateReportButton, 0);
this.pnlSettings.Controls.SetChildIndex(this.StartYearLabel, 0);
this.pnlSettings.Controls.SetChildIndex(this.EndYearLabel, 0);
this.pnlSettings.Controls.SetChildIndex(this.ceUseArchiveData, 0);
this.pnlSettings.Controls.SetChildIndex(this.Year1SpinEdit, 0);
this.pnlSettings.Controls.SetChildIndex(this.Year2SpinEdit, 0);
this.pnlSettings.Controls.SetChildIndex(this.CounterLabel, 0);
this.pnlSettings.Controls.SetChildIndex(this.CounterLookUp, 0);
this.pnlSettings.Controls.SetChildIndex(this.rayonFilter, 0);
this.pnlSettings.Controls.SetChildIndex(this.regionFilter, 0);
this.pnlSettings.Controls.SetChildIndex(this.OrganizationFilter, 0);
this.pnlSettings.Controls.SetChildIndex(this.diagnosisFilter, 0);
//
// ceUseArchiveData
//
resources.ApplyResources(this.ceUseArchiveData, "ceUseArchiveData");
this.ceUseArchiveData.Properties.Appearance.Font = ((System.Drawing.Font)(resources.GetObject("ceUseArchiveData.Properties.Appearance.Font")));
this.ceUseArchiveData.Properties.Appearance.Options.UseFont = true;
this.ceUseArchiveData.Properties.AppearanceDisabled.Font = ((System.Drawing.Font)(resources.GetObject("ceUseArchiveData.Properties.AppearanceDisabled.Font")));
this.ceUseArchiveData.Properties.AppearanceDisabled.Options.UseFont = true;
this.ceUseArchiveData.Properties.AppearanceFocused.Font = ((System.Drawing.Font)(resources.GetObject("ceUseArchiveData.Properties.AppearanceFocused.Font")));
this.ceUseArchiveData.Properties.AppearanceFocused.Options.UseFont = true;
this.ceUseArchiveData.Properties.AppearanceReadOnly.Font = ((System.Drawing.Font)(resources.GetObject("ceUseArchiveData.Properties.AppearanceReadOnly.Font")));
this.ceUseArchiveData.Properties.AppearanceReadOnly.Options.UseFont = true;
//
// GenerateReportButton
//
resources.ApplyResources(this.GenerateReportButton, "GenerateReportButton");
bv.common.Resources.BvResourceManagerChanger.GetResourceManager(typeof(ComparativeTwoYearsAZReportKeeper), out resources);
// Form Is Localizable: True
//
// StartYearLabel
//
resources.ApplyResources(this.StartYearLabel, "StartYearLabel");
this.StartYearLabel.ForeColor = System.Drawing.Color.Black;
this.StartYearLabel.Name = "StartYearLabel";
//
// Year1SpinEdit
//
resources.ApplyResources(this.Year1SpinEdit, "Year1SpinEdit");
this.Year1SpinEdit.Name = "Year1SpinEdit";
this.Year1SpinEdit.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.Year1SpinEdit.Properties.Mask.EditMask = resources.GetString("Year1SpinEdit.Properties.Mask.EditMask");
this.Year1SpinEdit.Properties.Mask.MaskType = ((DevExpress.XtraEditors.Mask.MaskType)(resources.GetObject("Year1SpinEdit.Properties.Mask.MaskType")));
this.Year1SpinEdit.Properties.MaxValue = new decimal(new int[] {
2030,
0,
0,
0});
this.Year1SpinEdit.Properties.MinValue = new decimal(new int[] {
2000,
0,
0,
0});
this.Year1SpinEdit.EditValueChanged += new System.EventHandler(this.seYear1_EditValueChanged);
//
// Year2SpinEdit
//
resources.ApplyResources(this.Year2SpinEdit, "Year2SpinEdit");
this.Year2SpinEdit.Name = "Year2SpinEdit";
this.Year2SpinEdit.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.Year2SpinEdit.Properties.Mask.EditMask = resources.GetString("Year2SpinEdit.Properties.Mask.EditMask");
this.Year2SpinEdit.Properties.Mask.MaskType = ((DevExpress.XtraEditors.Mask.MaskType)(resources.GetObject("Year2SpinEdit.Properties.Mask.MaskType")));
this.Year2SpinEdit.Properties.MaxValue = new decimal(new int[] {
2030,
0,
0,
0});
this.Year2SpinEdit.Properties.MinValue = new decimal(new int[] {
2000,
0,
0,
0});
this.Year2SpinEdit.EditValueChanged += new System.EventHandler(this.seYear2_EditValueChanged);
//
// EndYearLabel
//
resources.ApplyResources(this.EndYearLabel, "EndYearLabel");
this.EndYearLabel.ForeColor = System.Drawing.Color.Black;
this.EndYearLabel.Name = "EndYearLabel";
//
// CounterLookUp
//
resources.ApplyResources(this.CounterLookUp, "CounterLookUp");
this.CounterLookUp.Name = "CounterLookUp";
this.CounterLookUp.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("CounterLookUp.Properties.Buttons")))),
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("CounterLookUp.Properties.Buttons1"))))});
this.CounterLookUp.Properties.DropDownRows = 12;
this.CounterLookUp.Properties.NullText = resources.GetString("CounterLookUp.Properties.NullText");
this.CounterLookUp.EditValueChanged += new System.EventHandler(this.CounterLookUp_EditValueChanged);
//
// CounterLabel
//
resources.ApplyResources(this.CounterLabel, "CounterLabel");
this.CounterLabel.ForeColor = System.Drawing.Color.Black;
this.CounterLabel.Name = "CounterLabel";
//
// OrganizationFilter
//
this.OrganizationFilter.Appearance.Options.UseFont = true;
resources.ApplyResources(this.OrganizationFilter, "OrganizationFilter");
this.OrganizationFilter.Name = "OrganizationFilter";
this.OrganizationFilter.ValueChanged += new System.EventHandler<EIDSS.Reports.BaseControls.Filters.SingleFilterEventArgs>(this.OrganizationFilter_ValueChanged);
//
// regionFilter
//
this.regionFilter.Appearance.Font = ((System.Drawing.Font)(resources.GetObject("regionFilter.Appearance.Font")));
this.regionFilter.Appearance.Options.UseFont = true;
resources.ApplyResources(this.regionFilter, "regionFilter");
this.regionFilter.Name = "regionFilter";
this.regionFilter.ValueChanged += new System.EventHandler<EIDSS.Reports.BaseControls.Filters.SingleFilterEventArgs>(this.regionFilter_ValueChanged);
//
// rayonFilter
//
this.rayonFilter.Appearance.Options.UseFont = true;
resources.ApplyResources(this.rayonFilter, "rayonFilter");
this.rayonFilter.Name = "rayonFilter";
this.rayonFilter.ValueChanged += new System.EventHandler<EIDSS.Reports.BaseControls.Filters.SingleFilterEventArgs>(this.rayonFilter_ValueChanged);
//
// diagnosisFilter
//
this.diagnosisFilter.AdditionalFilter = null;
this.diagnosisFilter.Appearance.Options.UseFont = true;
resources.ApplyResources(this.diagnosisFilter, "diagnosisFilter");
this.diagnosisFilter.Name = "diagnosisFilter";
//
// ComparativeTwoYearsAZReportKeeper
//
resources.ApplyResources(this, "$this");
this.HeaderHeight = 170;
this.Name = "ComparativeTwoYearsAZReportKeeper";
this.pnlSettings.ResumeLayout(false);
this.pnlSettings.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.ceUseArchiveData.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.Year1SpinEdit.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.Year2SpinEdit.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CounterLookUp.Properties)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Label StartYearLabel;
private DevExpress.XtraEditors.SpinEdit Year1SpinEdit;
private DevExpress.XtraEditors.SpinEdit Year2SpinEdit;
private System.Windows.Forms.Label EndYearLabel;
private DevExpress.XtraEditors.LookUpEdit CounterLookUp;
private System.Windows.Forms.Label CounterLabel;
private HumOrganizationFilter OrganizationFilter;
private RegionFilter regionFilter;
private RayonFilter rayonFilter;
private HumSingleDiagnosisFilter diagnosisFilter;
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Lasso.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Windows;
using System.Windows.Ink;
using System.Windows.Media;
using System.Collections.Generic;
using System.Globalization;
namespace MS.Internal.Ink
{
#region Lasso
/// <summary>
/// Represents a lasso for selecting/cutting ink strokes with.
/// Lasso is a sequence of points defining a complex region (polygon)
/// </summary>
internal class Lasso
{
#region Constructors
/// <summary>
/// Default c-tor. Used in incremental hit-testing.
/// </summary>
internal Lasso()
{
_points = new List<Point>();
}
#endregion
#region API
/// <summary>
/// Returns the bounds of the lasso
/// </summary>
internal Rect Bounds
{
get { return _bounds; }
set { _bounds = value;}
}
/// <summary>
/// Tells whether the lasso captures any area
/// </summary>
internal bool IsEmpty
{
get
{
System.Diagnostics.Debug.Assert(_points != null);
// The value is based on the assumption that the lasso is normalized
// i.e. it has no duplicate points or collinear sibling segments.
return (_points.Count < 3);
}
}
/// <summary>
/// Returns the count of points in the lasso
/// </summary>
internal int PointCount
{
get
{
System.Diagnostics.Debug.Assert(_points != null);
return _points.Count;
}
}
/// <summary>
/// Index-based read-only accessor to lasso points
/// </summary>
/// <param name="index">index of the point to return</param>
/// <returns>a point in the lasso</returns>
internal Point this[int index]
{
get
{
System.Diagnostics.Debug.Assert(_points != null);
System.Diagnostics.Debug.Assert((0 <= index) && (index < _points.Count));
return _points[index];
}
}
/// <summary>
/// Extends the lasso by appending more points
/// </summary>
/// <param name="points">new points</param>
internal void AddPoints(IEnumerable<Point> points)
{
System.Diagnostics.Debug.Assert(null != points);
foreach (Point point in points)
{
AddPoint(point);
}
}
/// <summary>
/// Appends a point to the lasso
/// </summary>
/// <param name="point">new lasso point</param>
internal void AddPoint(Point point)
{
System.Diagnostics.Debug.Assert(_points != null);
if (!Filter(point))
{
// The point is not filtered, add it to the lasso
AddPointImpl(point);
}
}
/// <summary>
/// This method implement the core algorithm to check whether a point is within a polygon
/// that are formed by the lasso points.
/// </summary>
/// <param name="point"></param>
/// <returns>true if the point is contained within the lasso; false otherwise </returns>
internal bool Contains(Point point)
{
System.Diagnostics.Debug.Assert(_points != null);
if (false == _bounds.Contains(point))
{
return false;
}
bool isHigher = false;
int last = _points.Count;
while (--last >= 0)
{
if (!DoubleUtil.AreClose(_points[last].Y,point.Y))
{
isHigher = (point.Y < _points[last].Y);
break;
}
}
bool isInside = false;
Point prevLassoPoint = _points[_points.Count - 1];
for (int i = 0; i < _points.Count; i++)
{
Point lassoPoint = _points[i];
if (DoubleUtil.AreClose(lassoPoint.Y, point.Y))
{
if (DoubleUtil.AreClose(lassoPoint.X, point.X))
{
isInside = true;
break;
}
if ((0 != i) && DoubleUtil.AreClose(prevLassoPoint.Y, point.Y) &&
DoubleUtil.GreaterThanOrClose(point.X, Math.Min(prevLassoPoint.X, lassoPoint.X)) &&
DoubleUtil.LessThanOrClose(point.X, Math.Max(prevLassoPoint.X, lassoPoint.X)))
{
isInside = true;
break;
}
}
else if (isHigher != (point.Y < lassoPoint.Y))
{
isHigher = !isHigher;
if (DoubleUtil.GreaterThanOrClose(point.X, Math.Max(prevLassoPoint.X, lassoPoint.X)))
{
// there certainly is an intersection on the left
isInside = !isInside;
}
else if (DoubleUtil.GreaterThanOrClose(point.X, Math.Min(prevLassoPoint.X, lassoPoint.X)))
{
// The X of the point lies within the x ranges for the segment.
// Calculate the x value of the point where the segment intersects with the line.
Vector lassoSegment = lassoPoint - prevLassoPoint;
System.Diagnostics.Debug.Assert(lassoSegment.Y != 0);
double x = prevLassoPoint.X + (lassoSegment.X / lassoSegment.Y) * (point.Y - prevLassoPoint.Y);
if (DoubleUtil.GreaterThanOrClose(point.X, x))
{
isInside = !isInside;
}
}
}
prevLassoPoint = lassoPoint;
}
return isInside;
}
internal StrokeIntersection[] HitTest(StrokeNodeIterator iterator)
{
System.Diagnostics.Debug.Assert(_points != null);
System.Diagnostics.Debug.Assert(iterator != null);
if (_points.Count < 3)
{
//
// it takes at least 3 points to create a lasso
//
return new StrokeIntersection[0];
}
//
// We're about to perform hit testing with a lasso.
// To do so we need to iterate through each StrokeNode.
// As we do, we calculate the bounding rect between it
// and the previous StrokeNode and store this in 'currentStrokeSegmentBounds'
//
// Next, we check to see if that StrokeNode pair's bounding box intersects
// with the bounding box of the Lasso points. If not, we continue iterating through
// StrokeNode pairs.
//
// If it does, we do a more granular hit test by pairing points in the Lasso, getting
// their bounding box and seeing if that bounding box intersects our current StrokeNode
// pair
//
Point lastNodePosition = new Point();
Point lassoLastPoint = _points[_points.Count - 1];
Rect currentStrokeSegmentBounds = Rect.Empty;
// Initilize the current crossing to be an empty one
LassoCrossing currentCrossing = LassoCrossing.EmptyCrossing;
// Creat a list to hold all the crossings
List<LassoCrossing> crossingList = new List<LassoCrossing>();
for (int i = 0; i < iterator.Count; i++)
{
StrokeNode strokeNode = iterator[i];
Rect nodeBounds = strokeNode.GetBounds();
currentStrokeSegmentBounds.Union(nodeBounds);
// Skip the node if it's outside of the lasso's bounds
if (currentStrokeSegmentBounds.IntersectsWith(_bounds) == true)
{
// currentStrokeSegmentBounds, made up of the bounding box of
// this StrokeNode unioned with the last StrokeNode,
// intersects the lasso bounding box.
//
// Now we need to iterate through the lasso points and find out where they cross
//
Point lastPoint = lassoLastPoint;
foreach (Point point in _points)
{
//
// calculate a segment of the lasso from the last point
// to the current point
//
Rect lassoSegmentBounds = new Rect(lastPoint, point);
//
// see if this lasso segment intersects with the current stroke segment
//
if (!currentStrokeSegmentBounds.IntersectsWith(lassoSegmentBounds))
{
lastPoint = point;
continue;
}
//
// the lasso segment DOES intersect with the current stroke segment
// find out precisely where
//
StrokeFIndices strokeFIndices = strokeNode.CutTest(lastPoint, point);
lastPoint = point;
if (strokeFIndices.IsEmpty)
{
// current lasso segment does not hit the stroke segment, continue with the next lasso point
continue;
}
// Create a potentially new crossing for the current hit testing result.
LassoCrossing potentialNewCrossing = new LassoCrossing(strokeFIndices, strokeNode);
// Try to merge with the current crossing. If the merge is succussful (return true), the new crossing is actually
// continueing the current crossing, so do not start a new crossing. Otherwise, start a new one and add the existing
// one to the list.
if (!currentCrossing.Merge(potentialNewCrossing))
{
// start a new crossing and add the existing on to the list
crossingList.Add(currentCrossing);
currentCrossing = potentialNewCrossing;
}
}
}
// Continue with the next node
currentStrokeSegmentBounds = nodeBounds;
lastNodePosition = strokeNode.Position;
}
// Adding the last crossing to the list, if valid
if (!currentCrossing.IsEmpty)
{
crossingList.Add(currentCrossing);
}
// Handle the special case of no intersection at all
if (crossingList.Count == 0)
{
// the stroke was either completely inside the lasso
// or outside the lasso
if (this.Contains(lastNodePosition))
{
StrokeIntersection[] strokeIntersections = new StrokeIntersection[1];
strokeIntersections[0] = StrokeIntersection.Full;
return strokeIntersections;
}
else
{
return new StrokeIntersection[0];
}
}
// It is still possible that the current crossing list is not sorted or overlapping.
// Sort the list and merge the overlapping ones.
SortAndMerge(ref crossingList);
// Produce the hit test results and store them in a list
List<StrokeIntersection> strokeIntersectionList = new List<StrokeIntersection>();
ProduceHitTestResults(crossingList, strokeIntersectionList);
return strokeIntersectionList.ToArray();
}
/// <summary>
/// Sort and merge the crossing list
/// </summary>
/// <param name="crossingList">The crossing list to sort/merge</param>
private static void SortAndMerge(ref List<LassoCrossing> crossingList)
{
// Sort the crossings based on the BeginFIndex values
crossingList.Sort();
List<LassoCrossing> mergedList = new List<LassoCrossing>();
LassoCrossing mcrossing = LassoCrossing.EmptyCrossing;
foreach (LassoCrossing crossing in crossingList)
{
System.Diagnostics.Debug.Assert(!crossing.IsEmpty && crossing.StartNode.IsValid && crossing.EndNode.IsValid);
if (!mcrossing.Merge(crossing))
{
System.Diagnostics.Debug.Assert(!mcrossing.IsEmpty && mcrossing.StartNode.IsValid && mcrossing.EndNode.IsValid);
mergedList.Add(mcrossing);
mcrossing = crossing;
}
}
if (!mcrossing.IsEmpty)
{
System.Diagnostics.Debug.Assert(!mcrossing.IsEmpty && mcrossing.StartNode.IsValid && mcrossing.EndNode.IsValid);
mergedList.Add(mcrossing);
}
crossingList = mergedList;
}
/// <summary>
/// Helper function to find out whether a point is inside the lasso
/// </summary>
private bool SegmentWithinLasso(StrokeNode strokeNode, double fIndex)
{
bool currentSegmentWithinLasso;
if (DoubleUtil.AreClose(fIndex, StrokeFIndices.BeforeFirst))
{
// This should check against the very first stroke node
currentSegmentWithinLasso = this.Contains(strokeNode.GetPointAt(0f));
}
else if (DoubleUtil.AreClose(fIndex, StrokeFIndices.AfterLast))
{
// This should check against the last stroke node
currentSegmentWithinLasso = this.Contains(strokeNode.Position);
}
else
{
currentSegmentWithinLasso = this.Contains(strokeNode.GetPointAt(fIndex));
}
return currentSegmentWithinLasso;
}
/// <summary>
/// Helper function to find out the hit test result
/// </summary>
private void ProduceHitTestResults(
List<LassoCrossing> crossingList, List<StrokeIntersection> strokeIntersections)
{
bool previousSegmentInsideLasso = false;
for (int x = 0; x <= crossingList.Count; x++)
{
bool currentSegmentWithinLasso = false;
bool canMerge = true;
StrokeIntersection si = new StrokeIntersection();
if (x == 0)
{
si.HitBegin = StrokeFIndices.BeforeFirst;
si.InBegin = StrokeFIndices.BeforeFirst;
}
else
{
si.InBegin = crossingList[x - 1].FIndices.EndFIndex;
si.HitBegin = crossingList[x - 1].FIndices.BeginFIndex;
currentSegmentWithinLasso = SegmentWithinLasso(crossingList[x - 1].EndNode, si.InBegin);
}
if (x == crossingList.Count)
{
// NTRAID#WINOS-1132904-2005/04/27-XIAOTU: For a special case when the last intersection is something like (1.2, AL).
// As a result the last InSegment should be empty.
if (DoubleUtil.AreClose(si.InBegin, StrokeFIndices.AfterLast))
{
si.InEnd = StrokeFIndices.BeforeFirst;
}
else
{
si.InEnd = StrokeFIndices.AfterLast;
}
si.HitEnd = StrokeFIndices.AfterLast;
}
else
{
si.InEnd = crossingList[x].FIndices.BeginFIndex;
// NTRAID#WINOS-1132904-2005/04/27-XIAOTU: For a speical case when the first intersection is something like (BF, 0.67).
// As a result the first InSegment should be empty
if (DoubleUtil.AreClose(si.InEnd, StrokeFIndices.BeforeFirst))
{
System.Diagnostics.Debug.Assert(DoubleUtil.AreClose(si.InBegin, StrokeFIndices.BeforeFirst));
si.InBegin = StrokeFIndices.AfterLast;
}
si.HitEnd = crossingList[x].FIndices.EndFIndex;
currentSegmentWithinLasso = SegmentWithinLasso(crossingList[x].StartNode, si.InEnd);
// NTRAID#WINOS-1141831-2005/04/27-XIAOTU: If both the start and end position of the current crossing is
// outside the lasso, the crossing is a hit-only intersection, i.e., the in-segment is empty.
if (!currentSegmentWithinLasso && !SegmentWithinLasso(crossingList[x].EndNode, si.HitEnd))
{
currentSegmentWithinLasso = true;
si.HitBegin = crossingList[x].FIndices.BeginFIndex;
si.InBegin = StrokeFIndices.AfterLast;
si.InEnd = StrokeFIndices.BeforeFirst;
canMerge = false;
}
}
if (currentSegmentWithinLasso)
{
if (x > 0 && previousSegmentInsideLasso && canMerge)
{
// we need to consolidate with the previous segment
StrokeIntersection previousIntersection = strokeIntersections[strokeIntersections.Count - 1];
// For example: previousIntersection = [BF, AL, BF, 0.0027], si = [BF, 0.0027, 0.049, 0.063]
if (previousIntersection.InSegment.IsEmpty)
{
previousIntersection.InBegin = si.InBegin;
}
previousIntersection.InEnd = si.InEnd;
previousIntersection.HitEnd = si.HitEnd;
strokeIntersections[strokeIntersections.Count - 1] = previousIntersection;
}
else
{
strokeIntersections.Add(si);
}
if (DoubleUtil.AreClose(si.HitEnd, StrokeFIndices.AfterLast))
{
// The strokeIntersections already cover the end of the stroke. No need to continue.
return;
}
}
previousSegmentInsideLasso = currentSegmentWithinLasso;
}
}
/// <summary>
/// This flag is set to true when a lasso point has been modified or removed
/// from the list, which will invalidate incremental lasso hitteting
/// </summary>
internal bool IsIncrementalLassoDirty
{
get
{
return _incrementalLassoDirty;
}
set
{
_incrementalLassoDirty = value;
}
}
/// <summary>
/// Get a reference to the lasso points store
/// </summary>
protected List<Point> PointsList
{
get
{
return _points;
}
}
/// <summary>
/// Filter out duplicate points (and maybe in the futuer colinear points).
/// Return true if the point should be filtered
/// </summary>
protected virtual bool Filter(Point point)
{
// First point should not be filtered
if (0 == _points.Count)
{
return false;
}
// ISSUE-2004/06/14-vsmirnov - If the new segment is collinear with the last one,
// don't add the point but modify the last point instead.
Point lastPoint = _points[_points.Count - 1];
Vector vector = point - lastPoint;
// The point will be filtered out, i.e. not added to the list, if the distance to the previous point is
// within the tolerance
return (Math.Abs(vector.X) < MinDistance && Math.Abs(vector.Y) < MinDistance);
}
/// <summary>
/// Implemtnation of add point
/// </summary>
/// <param name="point"></param>
protected virtual void AddPointImpl(Point point)
{
_points.Add(point);
_bounds.Union(point);
}
#endregion
#region Fields
private List<Point> _points;
private Rect _bounds = Rect.Empty;
private bool _incrementalLassoDirty = false;
private static readonly double MinDistance = 1.0;
#endregion
/// <summary>
/// Simple helper struct used to track where the lasso crosses a stroke
/// we should consider making this a class if generics perf is bad for structs
/// </summary>
private struct LassoCrossing : IComparable
{
internal StrokeFIndices FIndices;
internal StrokeNode StartNode;
internal StrokeNode EndNode;
/// <summary>
/// Constructor
/// </summary>
/// <param name="newFIndices"></param>
/// <param name="strokeNode"></param>
public LassoCrossing(StrokeFIndices newFIndices, StrokeNode strokeNode)
{
System.Diagnostics.Debug.Assert(!newFIndices.IsEmpty);
System.Diagnostics.Debug.Assert(strokeNode.IsValid);
FIndices = newFIndices;
StartNode = EndNode = strokeNode;
}
/// <summary>
/// ToString
/// </summary>
public override string ToString()
{
return FIndices.ToString();
}
/// <summary>
/// Construct an empty LassoCrossing
/// </summary>
public static LassoCrossing EmptyCrossing
{
get
{
LassoCrossing crossing = new LassoCrossing();
crossing.FIndices = StrokeFIndices.Empty;
return crossing;
}
}
/// <summary>
/// Return true if this crossing is an empty one; false otherwise
/// </summary>
public bool IsEmpty
{
get { return FIndices.IsEmpty;}
}
/// <summary>
/// Implement the interface used for comparison
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public int CompareTo(object obj)
{
System.Diagnostics.Debug.Assert(obj is LassoCrossing);
LassoCrossing crossing = (LassoCrossing)obj;
if (crossing.IsEmpty && this.IsEmpty)
{
return 0;
}
else if (crossing.IsEmpty)
{
return 1;
}
else if (this.IsEmpty)
{
return -1;
}
else
{
return FIndices.CompareTo(crossing.FIndices);
}
}
/// <summary>
/// Merge two crossings into one.
/// </summary>
/// <param name="crossing"></param>
/// <returns>Return true if these two crossings are actually overlapping and merged; false otherwise</returns>
public bool Merge(LassoCrossing crossing)
{
if (crossing.IsEmpty)
{
return false;
}
if (FIndices.IsEmpty && !crossing.IsEmpty)
{
FIndices = crossing.FIndices;
StartNode = crossing.StartNode;
EndNode = crossing.EndNode;
return true;
}
if(DoubleUtil.GreaterThanOrClose(crossing.FIndices.EndFIndex, FIndices.BeginFIndex) &&
DoubleUtil.GreaterThanOrClose(FIndices.EndFIndex, crossing.FIndices.BeginFIndex))
{
if (DoubleUtil.LessThan(crossing.FIndices.BeginFIndex, FIndices.BeginFIndex))
{
FIndices.BeginFIndex = crossing.FIndices.BeginFIndex;
StartNode = crossing.StartNode;
}
if (DoubleUtil.GreaterThan(crossing.FIndices.EndFIndex, FIndices.EndFIndex))
{
FIndices.EndFIndex = crossing.FIndices.EndFIndex;
EndNode = crossing.EndNode;
}
return true;
}
return false;
}
}
}
#endregion
#region Single-Loop Lasso
/// <summary>
/// Implement a special lasso that considers only the first loop
/// </summary>
internal class SingleLoopLasso : Lasso
{
/// <summary>
/// Default constructor
/// </summary>
internal SingleLoopLasso() : base(){}
/// <summary>
/// Return true if the point will be filtered out and should NOT be added to the list
/// </summary>
protected override bool Filter(Point point)
{
List<Point> points = PointsList;
// First point should not be filtered
if (0 == points.Count)
{
// Just add the new point to the lasso
return false;
}
// Don't add this point if the lasso already has a loop; or
// if it's filtered by base class's filter.
if (true == _hasLoop || true == base.Filter(point))
{
// Don't add this point to the lasso.
return true;
}
double intersection = 0f;
// Now check whether the line lastPoint->point intersect with the
// existing lasso.
if (true == GetIntersectionWithExistingLasso(point, ref intersection))
{
System.Diagnostics.Debug.Assert(intersection >= 0 && intersection <= points.Count - 2);
if (intersection == points.Count - 2)
{
return true;
}
// Adding the new point will form a loop
int i = (int) intersection;
if (!DoubleUtil.AreClose(i, intersection))
{
// Move points[i] to the intersection position
Point intersectionPoint = new Point(0, 0);
intersectionPoint.X = points[i].X + (intersection - i) * (points[i + 1].X - points[i].X);
intersectionPoint.Y = points[i].Y + (intersection - i) * (points[i + 1].Y - points[i].Y);
points[i] = intersectionPoint;
IsIncrementalLassoDirty = true;
}
// Since the lasso has a self loop and the loop starts at points[i], points[0] to
// points[i-1] should be removed
if (i > 0)
{
points.RemoveRange(0, i /*count*/); // Remove points[0] to points[i-1]
IsIncrementalLassoDirty = true;
}
if (true == IsIncrementalLassoDirty)
{
// Update the bounds
Rect bounds = Rect.Empty;
for (int j = 0; j < points.Count; j++)
{
bounds.Union(points[j]);
}
Bounds = bounds;
}
// The lasso has a self_loop, any more points will be neglected.
_hasLoop = true;
// Don't add this point to the lasso.
return true;
}
// Just add the new point to the lasso
return false;
}
protected override void AddPointImpl(Point point)
{
_prevBounds = Bounds;
base.AddPointImpl(point);
}
/// <summary>
/// If the line _points[Count -1]->point insersect with the existing lasso, return true
/// and bIndex value is set to a doulbe value representing position of the intersection.
/// </summary>
private bool GetIntersectionWithExistingLasso(Point point, ref double bIndex)
{
List<Point> points = PointsList;
int count = points.Count;
Rect newRect = new Rect(points[count - 1], point);
if (false == _prevBounds.IntersectsWith(newRect))
{
// The point is not contained in the bound of the existing lasso, no intersection.
return false;
}
for (int i = 0; i < count -2; i++)
{
Rect currRect = new Rect(points[i], points[i+1]);
if (!currRect.IntersectsWith(newRect))
{
continue;
}
double s = FindIntersection(points[count-1] - points[i], /*hitBegin*/
point - points[i], /*hitEnd*/
new Vector(0, 0), /*orgBegin*/
points[i+1] - points[i] /*orgEnd*/);
if (s >=0 && s <= 1)
{
// Intersection found, adjust the fIndex
bIndex = i + s;
return true;
}
}
// No intersection
return false;
}
/// <summary>
/// Finds the intersection between the segment [hitBegin, hitEnd] and the segment [orgBegin, orgEnd].
/// </summary>
private static double FindIntersection(Vector hitBegin, Vector hitEnd, Vector orgBegin, Vector orgEnd)
{
System.Diagnostics.Debug.Assert(hitEnd != hitBegin && orgBegin != orgEnd);
//----------------------------------------------------------------------
// Source: http://isc.faqs.org/faqs/graphics/algorithms-faq/
// Subject 1.03: How do I find intersections of 2 2D line segments?
//
// Let A,B,C,D be 2-space position vectors. Then the directed line
// segments AB & CD are given by:
//
// AB=A+r(B-A), r in [0,1]
// CD=C+s(D-C), s in [0,1]
//
// If AB & CD intersect, then
//
// A+r(B-A)=C+s(D-C), or Ax+r(Bx-Ax)=Cx+s(Dx-Cx)
// Ay+r(By-Ay)=Cy+s(Dy-Cy) for some r,s in [0,1]
//
// Solving the above for r and s yields
//
// (Ay-Cy)(Dx-Cx)-(Ax-Cx)(Dy-Cy)
// r = ----------------------------- (eqn 1)
// (Bx-Ax)(Dy-Cy)-(By-Ay)(Dx-Cx)
//
// (Ay-Cy)(Bx-Ax)-(Ax-Cx)(By-Ay)
// s = ----------------------------- (eqn 2)
// (Bx-Ax)(Dy-Cy)-(By-Ay)(Dx-Cx)
//
// Let P be the position vector of the intersection point, then
//
// P=A+r(B-A) or Px=Ax+r(Bx-Ax) and Py=Ay+r(By-Ay)
//
// By examining the values of r & s, you can also determine some
// other limiting conditions:
// If 0 <= r <= 1 && 0 <= s <= 1, intersection exists
// r < 0 or r > 1 or s < 0 or s > 1 line segments do not intersect
// If the denominator in eqn 1 is zero, AB & CD are parallel
// If the numerator in eqn 1 is also zero, AB & CD are collinear.
// If they are collinear, then the segments may be projected to the x-
// or y-axis, and overlap of the projected intervals checked.
//
// If the intersection point of the 2 lines are needed (lines in this
// context mean infinite lines) regardless whether the two line
// segments intersect, then
// If r > 1, P is located on extension of AB
// If r < 0, P is located on extension of BA
// If s > 1, P is located on extension of CD
// If s < 0, P is located on extension of DC
// Also note that the denominators of eqn 1 & 2 are identical.
//
// References:
// [O'Rourke (C)] pp. 249-51
// [Gems III] pp. 199-202 "Faster Line Segment Intersection,"
//----------------------------------------------------------------------
// Calculate the vectors.
Vector AB = orgEnd - orgBegin; // B - A
Vector CA = orgBegin - hitBegin; // A - C
Vector CD = hitEnd - hitBegin; // D - C
double det = Vector.Determinant(AB, CD);
if (DoubleUtil.IsZero(det))
{
// The segments are parallel. no intersection
return NoIntersection;
}
double r = AdjustFIndex(Vector.Determinant(AB, CA) / det);
if (r >= 0 && r <= 1)
{
// The line defined AB does cross the segment CD.
double s = AdjustFIndex(Vector.Determinant(CD, CA) / det);
if (s >= 0 && s <= 1)
{
// The crossing point is on the segment AB as well.
// Intersection found.
return s;
}
}
// No intersection found
return NoIntersection;
}
/// <summary>
/// Clears double's computation fuzz around 0 and 1
/// </summary>
internal static double AdjustFIndex(double findex)
{
return DoubleUtil.IsZero(findex) ? 0 : (DoubleUtil.IsOne(findex) ? 1 : findex);
}
private bool _hasLoop = false;
private Rect _prevBounds = Rect.Empty;
private static readonly double NoIntersection = StrokeFIndices.BeforeFirst;
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Media;
using Avalonia.Platform;
using SkiaSharp;
namespace Avalonia.Skia
{
/// <summary>
/// Skia formatted text implementation.
/// </summary>
internal class FormattedTextImpl : IFormattedTextImpl
{
public FormattedTextImpl(
string text,
Typeface typeface,
double fontSize,
TextAlignment textAlignment,
TextWrapping wrapping,
Size constraint,
IReadOnlyList<FormattedTextStyleSpan> spans)
{
Text = text ?? string.Empty;
// Replace 0 characters with zero-width spaces (200B)
Text = Text.Replace((char)0, (char)0x200B);
var glyphTypeface = (GlyphTypefaceImpl)typeface.GlyphTypeface.PlatformImpl;
_paint = new SKPaint
{
TextEncoding = SKTextEncoding.Utf16,
IsStroke = false,
IsAntialias = true,
LcdRenderText = true,
SubpixelText = true,
IsLinearText = true,
Typeface = glyphTypeface.Typeface,
TextSize = (float)fontSize,
TextAlign = textAlignment.ToSKTextAlign()
};
//currently Skia does not measure properly with Utf8 !!!
//Paint.TextEncoding = SKTextEncoding.Utf8;
_wrapping = wrapping;
_constraint = constraint;
if (spans != null)
{
foreach (var span in spans)
{
if (span.ForegroundBrush != null)
{
SetForegroundBrush(span.ForegroundBrush, span.StartIndex, span.Length);
}
}
}
Rebuild();
}
public Size Constraint => _constraint;
public Rect Bounds => _bounds;
public IEnumerable<FormattedTextLine> GetLines()
{
return _lines;
}
public TextHitTestResult HitTestPoint(Point point)
{
float y = (float)point.Y;
AvaloniaFormattedTextLine line = default;
float nextTop = 0;
foreach(var currentLine in _skiaLines)
{
if(currentLine.Top <= y)
{
line = currentLine;
nextTop = currentLine.Top + currentLine.Height;
}
else
{
nextTop = currentLine.Top;
break;
}
}
if (!line.Equals(default(AvaloniaFormattedTextLine)))
{
var rects = GetRects();
for (int c = line.Start; c < line.Start + line.TextLength; c++)
{
var rc = rects[c];
if (rc.Contains(point))
{
return new TextHitTestResult
{
IsInside = !(line.TextLength > line.Length),
TextPosition = c,
IsTrailing = (point.X - rc.X) > rc.Width / 2
};
}
}
int offset = 0;
if (point.X >= (rects[line.Start].X + line.Width) && line.Length > 0)
{
offset = line.TextLength > line.Length ?
line.Length : (line.Length - 1);
}
if (y < nextTop)
{
return new TextHitTestResult
{
IsInside = false,
TextPosition = line.Start + offset,
IsTrailing = Text.Length == (line.Start + offset + 1)
};
}
}
bool end = point.X > _bounds.Width || point.Y > _lines.Sum(l => l.Height);
return new TextHitTestResult()
{
IsInside = false,
IsTrailing = end,
TextPosition = end ? Text.Length - 1 : 0
};
}
public Rect HitTestTextPosition(int index)
{
if (string.IsNullOrEmpty(Text))
{
var alignmentOffset = TransformX(0, 0, _paint.TextAlign);
return new Rect(alignmentOffset, 0, 0, _lineHeight);
}
var rects = GetRects();
if (index >= Text.Length || index < 0)
{
var r = rects.LastOrDefault();
var c = Text[Text.Length - 1];
switch (c)
{
case '\n':
case '\r':
return new Rect(r.X, r.Y, 0, _lineHeight);
default:
return new Rect(r.X + r.Width, r.Y, 0, _lineHeight);
}
}
return rects[index];
}
public IEnumerable<Rect> HitTestTextRange(int index, int length)
{
List<Rect> result = new List<Rect>();
var rects = GetRects();
int lastIndex = index + length - 1;
foreach (var line in _skiaLines.Where(l =>
(l.Start + l.Length) > index &&
lastIndex >= l.Start))
{
int lineEndIndex = line.Start + (line.Length > 0 ? line.Length - 1 : 0);
double left = rects[line.Start > index ? line.Start : index].X;
double right = rects[lineEndIndex > lastIndex ? lastIndex : lineEndIndex].Right;
result.Add(new Rect(left, line.Top, right - left, line.Height));
}
return result;
}
public override string ToString()
{
return Text;
}
internal void Draw(DrawingContextImpl context,
SKCanvas canvas,
SKPoint origin,
DrawingContextImpl.PaintWrapper foreground,
bool canUseLcdRendering)
{
/* TODO: This originated from Native code, it might be useful for debugging character positions as
* we improve the FormattedText support. Will need to port this to C# obviously. Rmove when
* not needed anymore.
SkPaint dpaint;
ctx->Canvas->save();
ctx->Canvas->translate(origin.fX, origin.fY);
for (int c = 0; c < Lines.size(); c++)
{
dpaint.setARGB(255, 0, 0, 0);
SkRect rc;
rc.fLeft = 0;
rc.fTop = Lines[c].Top;
rc.fRight = Lines[c].Width;
rc.fBottom = rc.fTop + LineOffset;
ctx->Canvas->drawRect(rc, dpaint);
}
for (int c = 0; c < Length; c++)
{
dpaint.setARGB(255, c % 10 * 125 / 10 + 125, (c * 7) % 10 * 250 / 10, (c * 13) % 10 * 250 / 10);
dpaint.setStyle(SkPaint::kFill_Style);
ctx->Canvas->drawRect(Rects[c], dpaint);
}
ctx->Canvas->restore();
*/
using (var paint = _paint.Clone())
{
IDisposable currd = null;
var currentWrapper = foreground;
SKPaint currentPaint = null;
try
{
ApplyWrapperTo(ref currentPaint, foreground, ref currd, paint, canUseLcdRendering);
bool hasCusomFGBrushes = _foregroundBrushes.Any();
for (int c = 0; c < _skiaLines.Count; c++)
{
AvaloniaFormattedTextLine line = _skiaLines[c];
float x = TransformX(origin.X, 0, paint.TextAlign);
if (!hasCusomFGBrushes)
{
var subString = Text.Substring(line.Start, line.Length);
canvas.DrawText(subString, x, origin.Y + line.Top + _lineOffset, paint);
}
else
{
float currX = x;
string subStr;
float measure;
int len;
float factor;
switch (paint.TextAlign)
{
case SKTextAlign.Left:
factor = 0;
break;
case SKTextAlign.Center:
factor = 0.5f;
break;
case SKTextAlign.Right:
factor = 1;
break;
default:
throw new ArgumentOutOfRangeException();
}
var textLine = Text.Substring(line.Start, line.Length);
currX -= textLine.Length == 0 ? 0 : paint.MeasureText(textLine) * factor;
for (int i = line.Start; i < line.Start + line.Length;)
{
var fb = GetNextForegroundBrush(ref line, i, out len);
if (fb != null)
{
//TODO: figure out how to get the brush size
currentWrapper = context.CreatePaint(new SKPaint { IsAntialias = true }, fb,
new Size());
}
else
{
if (!currentWrapper.Equals(foreground)) currentWrapper.Dispose();
currentWrapper = foreground;
}
subStr = Text.Substring(i, len);
measure = paint.MeasureText(subStr);
currX += measure * factor;
ApplyWrapperTo(ref currentPaint, currentWrapper, ref currd, paint, canUseLcdRendering);
canvas.DrawText(subStr, currX, origin.Y + line.Top + _lineOffset, paint);
i += len;
currX += measure * (1 - factor);
}
}
}
}
finally
{
if (!currentWrapper.Equals(foreground)) currentWrapper.Dispose();
currd?.Dispose();
}
}
}
private const float MAX_LINE_WIDTH = 10000;
private readonly List<KeyValuePair<FBrushRange, IBrush>> _foregroundBrushes =
new List<KeyValuePair<FBrushRange, IBrush>>();
private readonly List<FormattedTextLine> _lines = new List<FormattedTextLine>();
private readonly SKPaint _paint;
private readonly List<Rect> _rects = new List<Rect>();
public string Text { get; }
private readonly TextWrapping _wrapping;
private Size _constraint = new Size(double.PositiveInfinity, double.PositiveInfinity);
private float _lineHeight = 0;
private float _lineOffset = 0;
private Rect _bounds;
private List<AvaloniaFormattedTextLine> _skiaLines;
private static void ApplyWrapperTo(ref SKPaint current, DrawingContextImpl.PaintWrapper wrapper,
ref IDisposable curr, SKPaint paint, bool canUseLcdRendering)
{
if (current == wrapper.Paint)
return;
curr?.Dispose();
curr = wrapper.ApplyTo(paint);
paint.LcdRenderText = canUseLcdRendering;
}
private static bool IsBreakChar(char c)
{
//white space or zero space whitespace
return char.IsWhiteSpace(c) || c == '\u200B';
}
private static int LineBreak(string textInput, int textIndex, int stop,
SKPaint paint, float maxWidth,
out int trailingCount)
{
int lengthBreak;
if (maxWidth == -1)
{
lengthBreak = stop - textIndex;
}
else
{
float measuredWidth;
string subText = textInput.Substring(textIndex, stop - textIndex);
lengthBreak = (int)paint.BreakText(subText, maxWidth, out measuredWidth);
}
//Check for white space or line breakers before the lengthBreak
int startIndex = textIndex;
int index = textIndex;
int word_start = textIndex;
bool prevBreak = true;
trailingCount = 0;
while (index < stop)
{
int prevText = index;
char currChar = textInput[index++];
bool currBreak = IsBreakChar(currChar);
if (!currBreak && prevBreak)
{
word_start = prevText;
}
prevBreak = currBreak;
if (index > startIndex + lengthBreak)
{
if (currBreak)
{
// eat the rest of the whitespace
while (index < stop && IsBreakChar(textInput[index]))
{
index++;
}
trailingCount = index - prevText;
}
else
{
// backup until a whitespace (or 1 char)
if (word_start == startIndex)
{
if (prevText > startIndex)
{
index = prevText;
}
}
else
{
index = word_start;
}
}
break;
}
if ('\n' == currChar)
{
int ret = index - startIndex;
int lineBreakSize = 1;
if (index < stop)
{
currChar = textInput[index++];
if ('\r' == currChar)
{
ret = index - startIndex;
++lineBreakSize;
}
}
trailingCount = lineBreakSize;
return ret;
}
if ('\r' == currChar)
{
int ret = index - startIndex;
int lineBreakSize = 1;
if (index < stop)
{
currChar = textInput[index++];
if ('\n' == currChar)
{
ret = index - startIndex;
++lineBreakSize;
}
}
trailingCount = lineBreakSize;
return ret;
}
}
return index - startIndex;
}
private void BuildRects()
{
// Build character rects
SKTextAlign align = _paint.TextAlign;
for (int li = 0; li < _skiaLines.Count; li++)
{
var line = _skiaLines[li];
float prevRight = TransformX(0, line.Width, align);
double nextTop = line.Top + line.Height;
if (li + 1 < _skiaLines.Count)
{
nextTop = _skiaLines[li + 1].Top;
}
for (int i = line.Start; i < line.Start + line.TextLength; i++)
{
float w = _paint.MeasureText(Text[i].ToString());
_rects.Add(new Rect(
prevRight,
line.Top,
w,
nextTop - line.Top));
prevRight += w;
}
}
}
private IBrush GetNextForegroundBrush(ref AvaloniaFormattedTextLine line, int index, out int length)
{
IBrush result = null;
int len = length = line.Start + line.Length - index;
if (_foregroundBrushes.Any())
{
var bi = _foregroundBrushes.FindIndex(b =>
b.Key.StartIndex <= index &&
b.Key.EndIndex > index
);
if (bi > -1)
{
var match = _foregroundBrushes[bi];
len = match.Key.EndIndex - index;
result = match.Value;
if (len > 0 && len < length)
{
length = len;
}
}
int endIndex = index + length;
int max = bi == -1 ? _foregroundBrushes.Count : bi;
var next = _foregroundBrushes.Take(max)
.Where(b => b.Key.StartIndex < endIndex &&
b.Key.StartIndex > index)
.OrderBy(b => b.Key.StartIndex)
.FirstOrDefault();
if (next.Value != null)
{
length = next.Key.StartIndex - index;
}
}
return result;
}
private List<Rect> GetRects()
{
if (Text.Length > _rects.Count)
{
BuildRects();
}
return _rects;
}
private void Rebuild()
{
var length = Text.Length;
_lines.Clear();
_rects.Clear();
_skiaLines = new List<AvaloniaFormattedTextLine>();
int curOff = 0;
float curY = 0;
var metrics = _paint.FontMetrics;
var mTop = metrics.Top; // The greatest distance above the baseline for any glyph (will be <= 0).
var mBottom = metrics.Bottom; // The greatest distance below the baseline for any glyph (will be >= 0).
var mLeading = metrics.Leading; // The recommended distance to add between lines of text (will be >= 0).
var mDescent = metrics.Descent; //The recommended distance below the baseline. Will be >= 0.
var mAscent = metrics.Ascent; //The recommended distance above the baseline. Will be <= 0.
var lastLineDescent = mBottom - mDescent;
// This seems like the best measure of full vertical extent
// matches Direct2D line height
_lineHeight = mDescent - mAscent;
// Rendering is relative to baseline
_lineOffset = (-metrics.Ascent);
string subString;
float widthConstraint = double.IsPositiveInfinity(_constraint.Width)
? -1
: (float)_constraint.Width;
while(curOff < length)
{
float lineWidth = -1;
int measured;
int trailingnumber = 0;
float constraint = -1;
if (_wrapping == TextWrapping.Wrap)
{
constraint = widthConstraint <= 0 ? MAX_LINE_WIDTH : widthConstraint;
if (constraint > MAX_LINE_WIDTH)
constraint = MAX_LINE_WIDTH;
}
measured = LineBreak(Text, curOff, length, _paint, constraint, out trailingnumber);
AvaloniaFormattedTextLine line = new AvaloniaFormattedTextLine();
line.Start = curOff;
line.TextLength = measured;
subString = Text.Substring(line.Start, line.TextLength);
lineWidth = _paint.MeasureText(subString);
line.Length = measured - trailingnumber;
line.Width = lineWidth;
line.Height = _lineHeight;
line.Top = curY;
_skiaLines.Add(line);
curY += _lineHeight;
curY += mLeading;
curOff += measured;
//if this is the last line and there are trailing newline characters then
//insert a additional line
if (curOff >= length)
{
var subStringMinusNewlines = subString.TrimEnd('\n', '\r');
var lengthDiff = subString.Length - subStringMinusNewlines.Length;
if (lengthDiff > 0)
{
AvaloniaFormattedTextLine lastLine = new AvaloniaFormattedTextLine();
lastLine.TextLength = lengthDiff;
lastLine.Start = curOff - lengthDiff;
var lastLineSubString = Text.Substring(line.Start, line.TextLength);
var lastLineWidth = _paint.MeasureText(lastLineSubString);
lastLine.Length = 0;
lastLine.Width = lastLineWidth;
lastLine.Height = _lineHeight;
lastLine.Top = curY;
_skiaLines.Add(lastLine);
curY += _lineHeight;
curY += mLeading;
}
}
}
// Now convert to Avalonia data formats
_lines.Clear();
float maxX = 0;
for (var c = 0; c < _skiaLines.Count; c++)
{
var w = _skiaLines[c].Width;
if (maxX < w)
maxX = w;
_lines.Add(new FormattedTextLine(_skiaLines[c].TextLength, _skiaLines[c].Height));
}
if (_skiaLines.Count == 0)
{
_lines.Add(new FormattedTextLine(0, _lineHeight));
_bounds = new Rect(0, 0, 0, _lineHeight);
}
else
{
var lastLine = _skiaLines[_skiaLines.Count - 1];
_bounds = new Rect(0, 0, maxX, lastLine.Top + lastLine.Height);
if (double.IsPositiveInfinity(Constraint.Width))
{
return;
}
switch (_paint.TextAlign)
{
case SKTextAlign.Center:
_bounds = new Rect(Constraint).CenterRect(_bounds);
break;
case SKTextAlign.Right:
_bounds = new Rect(
Constraint.Width - _bounds.Width,
0,
_bounds.Width,
_bounds.Height);
break;
}
}
}
private float TransformX(float originX, float lineWidth, SKTextAlign align)
{
float x = 0;
if (align == SKTextAlign.Left)
{
x = originX;
}
else
{
double width = Constraint.Width > 0 && !double.IsPositiveInfinity(Constraint.Width) ?
Constraint.Width :
_bounds.Width;
switch (align)
{
case SKTextAlign.Center: x = originX + (float)(width - lineWidth) / 2; break;
case SKTextAlign.Right: x = originX + (float)(width - lineWidth); break;
}
}
return x;
}
private void SetForegroundBrush(IBrush brush, int startIndex, int length)
{
var key = new FBrushRange(startIndex, length);
int index = _foregroundBrushes.FindIndex(v => v.Key.Equals(key));
if (index > -1)
{
_foregroundBrushes.RemoveAt(index);
}
if (brush != null)
{
brush = brush.ToImmutable();
_foregroundBrushes.Insert(0, new KeyValuePair<FBrushRange, IBrush>(key, brush));
}
}
private struct AvaloniaFormattedTextLine
{
public float Height;
public int Length;
public int Start;
public int TextLength;
public float Top;
public float Width;
};
private struct FBrushRange
{
public FBrushRange(int startIndex, int length)
{
StartIndex = startIndex;
Length = length;
}
public int EndIndex => StartIndex + Length;
public int Length { get; private set; }
public int StartIndex { get; private set; }
public bool Intersects(int index, int len) =>
(index + len) > StartIndex &&
(StartIndex + Length) > index;
public override string ToString()
{
return $"{StartIndex}-{EndIndex}";
}
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="System.HAGroupBinding", Namespace="urn:iControl")]
public partial class SystemHAGroup : iControlInterface {
public SystemHAGroup() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// add_cluster
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void add_cluster(
string [] ha_groups,
string [] [] clusters,
long [] [] weights
) {
this.Invoke("add_cluster", new object [] {
ha_groups,
clusters,
weights});
}
public System.IAsyncResult Beginadd_cluster(string [] ha_groups,string [] [] clusters,long [] [] weights, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_cluster", new object[] {
ha_groups,
clusters,
weights}, callback, asyncState);
}
public void Endadd_cluster(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_pool
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void add_pool(
string [] ha_groups,
string [] [] pools,
long [] [] weights
) {
this.Invoke("add_pool", new object [] {
ha_groups,
pools,
weights});
}
public System.IAsyncResult Beginadd_pool(string [] ha_groups,string [] [] pools,long [] [] weights, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_pool", new object[] {
ha_groups,
pools,
weights}, callback, asyncState);
}
public void Endadd_pool(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_trunk
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void add_trunk(
string [] ha_groups,
string [] [] trunks,
long [] [] weights
) {
this.Invoke("add_trunk", new object [] {
ha_groups,
trunks,
weights});
}
public System.IAsyncResult Beginadd_trunk(string [] ha_groups,string [] [] trunks,long [] [] weights, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_trunk", new object[] {
ha_groups,
trunks,
weights}, callback, asyncState);
}
public void Endadd_trunk(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void create(
string [] ha_groups
) {
this.Invoke("create", new object [] {
ha_groups});
}
public System.IAsyncResult Begincreate(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
ha_groups}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_high_availability_groups
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void delete_all_high_availability_groups(
) {
this.Invoke("delete_all_high_availability_groups", new object [0]);
}
public System.IAsyncResult Begindelete_all_high_availability_groups(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_high_availability_groups", new object[0], callback, asyncState);
}
public void Enddelete_all_high_availability_groups(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_high_availability_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void delete_high_availability_group(
string [] ha_groups
) {
this.Invoke("delete_high_availability_group", new object [] {
ha_groups});
}
public System.IAsyncResult Begindelete_high_availability_group(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_high_availability_group", new object[] {
ha_groups}, callback, asyncState);
}
public void Enddelete_high_availability_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_active_score
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_active_score(
string [] ha_groups
) {
object [] results = this.Invoke("get_active_score", new object [] {
ha_groups});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_active_score(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_active_score", new object[] {
ha_groups}, callback, asyncState);
}
public long [] Endget_active_score(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_cluster
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_cluster(
string [] ha_groups
) {
object [] results = this.Invoke("get_cluster", new object [] {
ha_groups});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_cluster(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_cluster", new object[] {
ha_groups}, callback, asyncState);
}
public string [] [] Endget_cluster(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_cluster_attribute
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public SystemHAGroupHAGroupClusterAttribute [] [] get_cluster_attribute(
string [] ha_groups,
string [] [] clusters
) {
object [] results = this.Invoke("get_cluster_attribute", new object [] {
ha_groups,
clusters});
return ((SystemHAGroupHAGroupClusterAttribute [] [])(results[0]));
}
public System.IAsyncResult Beginget_cluster_attribute(string [] ha_groups,string [] [] clusters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_cluster_attribute", new object[] {
ha_groups,
clusters}, callback, asyncState);
}
public SystemHAGroupHAGroupClusterAttribute [] [] Endget_cluster_attribute(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((SystemHAGroupHAGroupClusterAttribute [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_cluster_attribute_minimum_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_cluster_attribute_minimum_threshold(
string [] ha_groups,
string [] [] clusters
) {
object [] results = this.Invoke("get_cluster_attribute_minimum_threshold", new object [] {
ha_groups,
clusters});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_cluster_attribute_minimum_threshold(string [] ha_groups,string [] [] clusters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_cluster_attribute_minimum_threshold", new object[] {
ha_groups,
clusters}, callback, asyncState);
}
public long [] [] Endget_cluster_attribute_minimum_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_cluster_attribute_sufficient_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_cluster_attribute_sufficient_threshold(
string [] ha_groups,
string [] [] clusters
) {
object [] results = this.Invoke("get_cluster_attribute_sufficient_threshold", new object [] {
ha_groups,
clusters});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_cluster_attribute_sufficient_threshold(string [] ha_groups,string [] [] clusters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_cluster_attribute_sufficient_threshold", new object[] {
ha_groups,
clusters}, callback, asyncState);
}
public long [] [] Endget_cluster_attribute_sufficient_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_cluster_attribute_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_cluster_attribute_threshold(
string [] ha_groups,
string [] [] clusters
) {
object [] results = this.Invoke("get_cluster_attribute_threshold", new object [] {
ha_groups,
clusters});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_cluster_attribute_threshold(string [] ha_groups,string [] [] clusters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_cluster_attribute_threshold", new object[] {
ha_groups,
clusters}, callback, asyncState);
}
public long [] [] Endget_cluster_attribute_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_cluster_attribute_value
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_cluster_attribute_value(
string [] ha_groups,
string [] [] clusters
) {
object [] results = this.Invoke("get_cluster_attribute_value", new object [] {
ha_groups,
clusters});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_cluster_attribute_value(string [] ha_groups,string [] [] clusters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_cluster_attribute_value", new object[] {
ha_groups,
clusters}, callback, asyncState);
}
public long [] [] Endget_cluster_attribute_value(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_cluster_score
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_cluster_score(
string [] ha_groups,
string [] [] clusters
) {
object [] results = this.Invoke("get_cluster_score", new object [] {
ha_groups,
clusters});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_cluster_score(string [] ha_groups,string [] [] clusters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_cluster_score", new object[] {
ha_groups,
clusters}, callback, asyncState);
}
public long [] [] Endget_cluster_score(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_cluster_weight
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_cluster_weight(
string [] ha_groups,
string [] [] clusters
) {
object [] results = this.Invoke("get_cluster_weight", new object [] {
ha_groups,
clusters});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_cluster_weight(string [] ha_groups,string [] [] clusters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_cluster_weight", new object[] {
ha_groups,
clusters}, callback, asyncState);
}
public long [] [] Endget_cluster_weight(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] ha_groups
) {
object [] results = this.Invoke("get_description", new object [] {
ha_groups});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
ha_groups}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_enabled_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_enabled_state(
string [] ha_groups
) {
object [] results = this.Invoke("get_enabled_state", new object [] {
ha_groups});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_enabled_state(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_enabled_state", new object[] {
ha_groups}, callback, asyncState);
}
public CommonEnabledState [] Endget_enabled_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_pool
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_pool(
string [] ha_groups
) {
object [] results = this.Invoke("get_pool", new object [] {
ha_groups});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_pool(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_pool", new object[] {
ha_groups}, callback, asyncState);
}
public string [] [] Endget_pool(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_pool_attribute
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public SystemHAGroupHAGroupPoolAttribute [] [] get_pool_attribute(
string [] ha_groups,
string [] [] pools
) {
object [] results = this.Invoke("get_pool_attribute", new object [] {
ha_groups,
pools});
return ((SystemHAGroupHAGroupPoolAttribute [] [])(results[0]));
}
public System.IAsyncResult Beginget_pool_attribute(string [] ha_groups,string [] [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_pool_attribute", new object[] {
ha_groups,
pools}, callback, asyncState);
}
public SystemHAGroupHAGroupPoolAttribute [] [] Endget_pool_attribute(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((SystemHAGroupHAGroupPoolAttribute [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_pool_attribute_minimum_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_pool_attribute_minimum_threshold(
string [] ha_groups,
string [] [] pools
) {
object [] results = this.Invoke("get_pool_attribute_minimum_threshold", new object [] {
ha_groups,
pools});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_pool_attribute_minimum_threshold(string [] ha_groups,string [] [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_pool_attribute_minimum_threshold", new object[] {
ha_groups,
pools}, callback, asyncState);
}
public long [] [] Endget_pool_attribute_minimum_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_pool_attribute_sufficient_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_pool_attribute_sufficient_threshold(
string [] ha_groups,
string [] [] pools
) {
object [] results = this.Invoke("get_pool_attribute_sufficient_threshold", new object [] {
ha_groups,
pools});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_pool_attribute_sufficient_threshold(string [] ha_groups,string [] [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_pool_attribute_sufficient_threshold", new object[] {
ha_groups,
pools}, callback, asyncState);
}
public long [] [] Endget_pool_attribute_sufficient_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_pool_attribute_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_pool_attribute_threshold(
string [] ha_groups,
string [] [] pools
) {
object [] results = this.Invoke("get_pool_attribute_threshold", new object [] {
ha_groups,
pools});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_pool_attribute_threshold(string [] ha_groups,string [] [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_pool_attribute_threshold", new object[] {
ha_groups,
pools}, callback, asyncState);
}
public long [] [] Endget_pool_attribute_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_pool_attribute_value
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_pool_attribute_value(
string [] ha_groups,
string [] [] pools
) {
object [] results = this.Invoke("get_pool_attribute_value", new object [] {
ha_groups,
pools});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_pool_attribute_value(string [] ha_groups,string [] [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_pool_attribute_value", new object[] {
ha_groups,
pools}, callback, asyncState);
}
public long [] [] Endget_pool_attribute_value(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_pool_score
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_pool_score(
string [] ha_groups,
string [] [] pools
) {
object [] results = this.Invoke("get_pool_score", new object [] {
ha_groups,
pools});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_pool_score(string [] ha_groups,string [] [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_pool_score", new object[] {
ha_groups,
pools}, callback, asyncState);
}
public long [] [] Endget_pool_score(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_pool_weight
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_pool_weight(
string [] ha_groups,
string [] [] pools
) {
object [] results = this.Invoke("get_pool_weight", new object [] {
ha_groups,
pools});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_pool_weight(string [] ha_groups,string [] [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_pool_weight", new object[] {
ha_groups,
pools}, callback, asyncState);
}
public long [] [] Endget_pool_weight(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_total_score
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_total_score(
string [] ha_groups
) {
object [] results = this.Invoke("get_total_score", new object [] {
ha_groups});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_total_score(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_total_score", new object[] {
ha_groups}, callback, asyncState);
}
public long [] Endget_total_score(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_trunk
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_trunk(
string [] ha_groups
) {
object [] results = this.Invoke("get_trunk", new object [] {
ha_groups});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_trunk(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_trunk", new object[] {
ha_groups}, callback, asyncState);
}
public string [] [] Endget_trunk(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_trunk_attribute
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public SystemHAGroupHAGroupTrunkAttribute [] [] get_trunk_attribute(
string [] ha_groups,
string [] [] trunks
) {
object [] results = this.Invoke("get_trunk_attribute", new object [] {
ha_groups,
trunks});
return ((SystemHAGroupHAGroupTrunkAttribute [] [])(results[0]));
}
public System.IAsyncResult Beginget_trunk_attribute(string [] ha_groups,string [] [] trunks, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_trunk_attribute", new object[] {
ha_groups,
trunks}, callback, asyncState);
}
public SystemHAGroupHAGroupTrunkAttribute [] [] Endget_trunk_attribute(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((SystemHAGroupHAGroupTrunkAttribute [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_trunk_attribute_minimum_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_trunk_attribute_minimum_threshold(
string [] ha_groups,
string [] [] trunks
) {
object [] results = this.Invoke("get_trunk_attribute_minimum_threshold", new object [] {
ha_groups,
trunks});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_trunk_attribute_minimum_threshold(string [] ha_groups,string [] [] trunks, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_trunk_attribute_minimum_threshold", new object[] {
ha_groups,
trunks}, callback, asyncState);
}
public long [] [] Endget_trunk_attribute_minimum_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_trunk_attribute_sufficient_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_trunk_attribute_sufficient_threshold(
string [] ha_groups,
string [] [] trunks
) {
object [] results = this.Invoke("get_trunk_attribute_sufficient_threshold", new object [] {
ha_groups,
trunks});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_trunk_attribute_sufficient_threshold(string [] ha_groups,string [] [] trunks, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_trunk_attribute_sufficient_threshold", new object[] {
ha_groups,
trunks}, callback, asyncState);
}
public long [] [] Endget_trunk_attribute_sufficient_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_trunk_attribute_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_trunk_attribute_threshold(
string [] ha_groups,
string [] [] trunks
) {
object [] results = this.Invoke("get_trunk_attribute_threshold", new object [] {
ha_groups,
trunks});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_trunk_attribute_threshold(string [] ha_groups,string [] [] trunks, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_trunk_attribute_threshold", new object[] {
ha_groups,
trunks}, callback, asyncState);
}
public long [] [] Endget_trunk_attribute_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_trunk_attribute_value
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_trunk_attribute_value(
string [] ha_groups,
string [] [] trunks
) {
object [] results = this.Invoke("get_trunk_attribute_value", new object [] {
ha_groups,
trunks});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_trunk_attribute_value(string [] ha_groups,string [] [] trunks, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_trunk_attribute_value", new object[] {
ha_groups,
trunks}, callback, asyncState);
}
public long [] [] Endget_trunk_attribute_value(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_trunk_score
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_trunk_score(
string [] ha_groups,
string [] [] trunks
) {
object [] results = this.Invoke("get_trunk_score", new object [] {
ha_groups,
trunks});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_trunk_score(string [] ha_groups,string [] [] trunks, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_trunk_score", new object[] {
ha_groups,
trunks}, callback, asyncState);
}
public long [] [] Endget_trunk_score(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_trunk_weight
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_trunk_weight(
string [] ha_groups,
string [] [] trunks
) {
object [] results = this.Invoke("get_trunk_weight", new object [] {
ha_groups,
trunks});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_trunk_weight(string [] ha_groups,string [] [] trunks, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_trunk_weight", new object[] {
ha_groups,
trunks}, callback, asyncState);
}
public long [] [] Endget_trunk_weight(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// remove_all_clusters
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void remove_all_clusters(
string [] ha_groups
) {
this.Invoke("remove_all_clusters", new object [] {
ha_groups});
}
public System.IAsyncResult Beginremove_all_clusters(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_clusters", new object[] {
ha_groups}, callback, asyncState);
}
public void Endremove_all_clusters(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_all_pools
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void remove_all_pools(
string [] ha_groups
) {
this.Invoke("remove_all_pools", new object [] {
ha_groups});
}
public System.IAsyncResult Beginremove_all_pools(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_pools", new object[] {
ha_groups}, callback, asyncState);
}
public void Endremove_all_pools(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_all_trunks
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void remove_all_trunks(
string [] ha_groups
) {
this.Invoke("remove_all_trunks", new object [] {
ha_groups});
}
public System.IAsyncResult Beginremove_all_trunks(string [] ha_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_trunks", new object[] {
ha_groups}, callback, asyncState);
}
public void Endremove_all_trunks(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_cluster
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void remove_cluster(
string [] ha_groups,
string [] [] clusters
) {
this.Invoke("remove_cluster", new object [] {
ha_groups,
clusters});
}
public System.IAsyncResult Beginremove_cluster(string [] ha_groups,string [] [] clusters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_cluster", new object[] {
ha_groups,
clusters}, callback, asyncState);
}
public void Endremove_cluster(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_pool
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void remove_pool(
string [] ha_groups,
string [] [] pools
) {
this.Invoke("remove_pool", new object [] {
ha_groups,
pools});
}
public System.IAsyncResult Beginremove_pool(string [] ha_groups,string [] [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_pool", new object[] {
ha_groups,
pools}, callback, asyncState);
}
public void Endremove_pool(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_trunk
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void remove_trunk(
string [] ha_groups,
string [] [] trunks
) {
this.Invoke("remove_trunk", new object [] {
ha_groups,
trunks});
}
public System.IAsyncResult Beginremove_trunk(string [] ha_groups,string [] [] trunks, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_trunk", new object[] {
ha_groups,
trunks}, callback, asyncState);
}
public void Endremove_trunk(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_active_score
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_active_score(
string [] ha_groups,
long [] scores
) {
this.Invoke("set_active_score", new object [] {
ha_groups,
scores});
}
public System.IAsyncResult Beginset_active_score(string [] ha_groups,long [] scores, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_active_score", new object[] {
ha_groups,
scores}, callback, asyncState);
}
public void Endset_active_score(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_cluster_attribute
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_cluster_attribute(
string [] ha_groups,
string [] [] clusters,
SystemHAGroupHAGroupClusterAttribute [] [] attributes
) {
this.Invoke("set_cluster_attribute", new object [] {
ha_groups,
clusters,
attributes});
}
public System.IAsyncResult Beginset_cluster_attribute(string [] ha_groups,string [] [] clusters,SystemHAGroupHAGroupClusterAttribute [] [] attributes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_cluster_attribute", new object[] {
ha_groups,
clusters,
attributes}, callback, asyncState);
}
public void Endset_cluster_attribute(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_cluster_attribute_minimum_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_cluster_attribute_minimum_threshold(
string [] ha_groups,
string [] [] clusters,
long [] [] thresholds
) {
this.Invoke("set_cluster_attribute_minimum_threshold", new object [] {
ha_groups,
clusters,
thresholds});
}
public System.IAsyncResult Beginset_cluster_attribute_minimum_threshold(string [] ha_groups,string [] [] clusters,long [] [] thresholds, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_cluster_attribute_minimum_threshold", new object[] {
ha_groups,
clusters,
thresholds}, callback, asyncState);
}
public void Endset_cluster_attribute_minimum_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_cluster_attribute_sufficient_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_cluster_attribute_sufficient_threshold(
string [] ha_groups,
string [] [] clusters,
long [] [] thresholds
) {
this.Invoke("set_cluster_attribute_sufficient_threshold", new object [] {
ha_groups,
clusters,
thresholds});
}
public System.IAsyncResult Beginset_cluster_attribute_sufficient_threshold(string [] ha_groups,string [] [] clusters,long [] [] thresholds, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_cluster_attribute_sufficient_threshold", new object[] {
ha_groups,
clusters,
thresholds}, callback, asyncState);
}
public void Endset_cluster_attribute_sufficient_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_cluster_attribute_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_cluster_attribute_threshold(
string [] ha_groups,
string [] [] clusters,
long [] [] thresholds
) {
this.Invoke("set_cluster_attribute_threshold", new object [] {
ha_groups,
clusters,
thresholds});
}
public System.IAsyncResult Beginset_cluster_attribute_threshold(string [] ha_groups,string [] [] clusters,long [] [] thresholds, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_cluster_attribute_threshold", new object[] {
ha_groups,
clusters,
thresholds}, callback, asyncState);
}
public void Endset_cluster_attribute_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_cluster_weight
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_cluster_weight(
string [] ha_groups,
string [] [] clusters,
long [] [] weights
) {
this.Invoke("set_cluster_weight", new object [] {
ha_groups,
clusters,
weights});
}
public System.IAsyncResult Beginset_cluster_weight(string [] ha_groups,string [] [] clusters,long [] [] weights, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_cluster_weight", new object[] {
ha_groups,
clusters,
weights}, callback, asyncState);
}
public void Endset_cluster_weight(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_description(
string [] ha_groups,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
ha_groups,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] ha_groups,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
ha_groups,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_enabled_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_enabled_state(
string [] ha_groups,
CommonEnabledState [] states
) {
this.Invoke("set_enabled_state", new object [] {
ha_groups,
states});
}
public System.IAsyncResult Beginset_enabled_state(string [] ha_groups,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_enabled_state", new object[] {
ha_groups,
states}, callback, asyncState);
}
public void Endset_enabled_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_pool_attribute
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_pool_attribute(
string [] ha_groups,
string [] [] pools,
SystemHAGroupHAGroupPoolAttribute [] [] attributes
) {
this.Invoke("set_pool_attribute", new object [] {
ha_groups,
pools,
attributes});
}
public System.IAsyncResult Beginset_pool_attribute(string [] ha_groups,string [] [] pools,SystemHAGroupHAGroupPoolAttribute [] [] attributes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_pool_attribute", new object[] {
ha_groups,
pools,
attributes}, callback, asyncState);
}
public void Endset_pool_attribute(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_pool_attribute_minimum_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_pool_attribute_minimum_threshold(
string [] ha_groups,
string [] [] pools,
long [] [] thresholds
) {
this.Invoke("set_pool_attribute_minimum_threshold", new object [] {
ha_groups,
pools,
thresholds});
}
public System.IAsyncResult Beginset_pool_attribute_minimum_threshold(string [] ha_groups,string [] [] pools,long [] [] thresholds, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_pool_attribute_minimum_threshold", new object[] {
ha_groups,
pools,
thresholds}, callback, asyncState);
}
public void Endset_pool_attribute_minimum_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_pool_attribute_sufficient_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_pool_attribute_sufficient_threshold(
string [] ha_groups,
string [] [] pools,
long [] [] thresholds
) {
this.Invoke("set_pool_attribute_sufficient_threshold", new object [] {
ha_groups,
pools,
thresholds});
}
public System.IAsyncResult Beginset_pool_attribute_sufficient_threshold(string [] ha_groups,string [] [] pools,long [] [] thresholds, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_pool_attribute_sufficient_threshold", new object[] {
ha_groups,
pools,
thresholds}, callback, asyncState);
}
public void Endset_pool_attribute_sufficient_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_pool_attribute_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_pool_attribute_threshold(
string [] ha_groups,
string [] [] pools,
long [] [] thresholds
) {
this.Invoke("set_pool_attribute_threshold", new object [] {
ha_groups,
pools,
thresholds});
}
public System.IAsyncResult Beginset_pool_attribute_threshold(string [] ha_groups,string [] [] pools,long [] [] thresholds, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_pool_attribute_threshold", new object[] {
ha_groups,
pools,
thresholds}, callback, asyncState);
}
public void Endset_pool_attribute_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_pool_weight
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_pool_weight(
string [] ha_groups,
string [] [] pools,
long [] [] weights
) {
this.Invoke("set_pool_weight", new object [] {
ha_groups,
pools,
weights});
}
public System.IAsyncResult Beginset_pool_weight(string [] ha_groups,string [] [] pools,long [] [] weights, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_pool_weight", new object[] {
ha_groups,
pools,
weights}, callback, asyncState);
}
public void Endset_pool_weight(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_trunk_attribute
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_trunk_attribute(
string [] ha_groups,
string [] [] trunks,
SystemHAGroupHAGroupTrunkAttribute [] [] attributes
) {
this.Invoke("set_trunk_attribute", new object [] {
ha_groups,
trunks,
attributes});
}
public System.IAsyncResult Beginset_trunk_attribute(string [] ha_groups,string [] [] trunks,SystemHAGroupHAGroupTrunkAttribute [] [] attributes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_trunk_attribute", new object[] {
ha_groups,
trunks,
attributes}, callback, asyncState);
}
public void Endset_trunk_attribute(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_trunk_attribute_minimum_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_trunk_attribute_minimum_threshold(
string [] ha_groups,
string [] [] trunks,
long [] [] thresholds
) {
this.Invoke("set_trunk_attribute_minimum_threshold", new object [] {
ha_groups,
trunks,
thresholds});
}
public System.IAsyncResult Beginset_trunk_attribute_minimum_threshold(string [] ha_groups,string [] [] trunks,long [] [] thresholds, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_trunk_attribute_minimum_threshold", new object[] {
ha_groups,
trunks,
thresholds}, callback, asyncState);
}
public void Endset_trunk_attribute_minimum_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_trunk_attribute_sufficient_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_trunk_attribute_sufficient_threshold(
string [] ha_groups,
string [] [] trunks,
long [] [] thresholds
) {
this.Invoke("set_trunk_attribute_sufficient_threshold", new object [] {
ha_groups,
trunks,
thresholds});
}
public System.IAsyncResult Beginset_trunk_attribute_sufficient_threshold(string [] ha_groups,string [] [] trunks,long [] [] thresholds, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_trunk_attribute_sufficient_threshold", new object[] {
ha_groups,
trunks,
thresholds}, callback, asyncState);
}
public void Endset_trunk_attribute_sufficient_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_trunk_attribute_threshold
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_trunk_attribute_threshold(
string [] ha_groups,
string [] [] trunks,
long [] [] thresholds
) {
this.Invoke("set_trunk_attribute_threshold", new object [] {
ha_groups,
trunks,
thresholds});
}
public System.IAsyncResult Beginset_trunk_attribute_threshold(string [] ha_groups,string [] [] trunks,long [] [] thresholds, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_trunk_attribute_threshold", new object[] {
ha_groups,
trunks,
thresholds}, callback, asyncState);
}
public void Endset_trunk_attribute_threshold(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_trunk_weight
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/HAGroup",
RequestNamespace="urn:iControl:System/HAGroup", ResponseNamespace="urn:iControl:System/HAGroup")]
public void set_trunk_weight(
string [] ha_groups,
string [] [] trunks,
long [] [] weights
) {
this.Invoke("set_trunk_weight", new object [] {
ha_groups,
trunks,
weights});
}
public System.IAsyncResult Beginset_trunk_weight(string [] ha_groups,string [] [] trunks,long [] [] weights, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_trunk_weight", new object[] {
ha_groups,
trunks,
weights}, callback, asyncState);
}
public void Endset_trunk_weight(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "System.HAGroup.HAGroupClusterAttribute", Namespace = "urn:iControl")]
public enum SystemHAGroupHAGroupClusterAttribute
{
HA_GROUP_CLUSTER_UNKNOWN,
HA_GROUP_CLUSTER_PERCENT_MEMBERS_UP,
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "System.HAGroup.HAGroupPoolAttribute", Namespace = "urn:iControl")]
public enum SystemHAGroupHAGroupPoolAttribute
{
HA_GROUP_POOL_UNKNOWN,
HA_GROUP_POOL_PERCENT_MEMBERS_UP,
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "System.HAGroup.HAGroupTrunkAttribute", Namespace = "urn:iControl")]
public enum SystemHAGroupHAGroupTrunkAttribute
{
HA_GROUP_TRUNK_UNKNOWN,
HA_GROUP_TRUNK_PERCENT_MEMBERS_UP,
}
//=======================================================================
// Structs
//=======================================================================
}
| |
using System;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using BASeCamp.BASeBlock.Particles;
namespace BASeCamp.BASeBlock
{
/// <summary>
/// used to assign certain default behaviours to a GamePowerup, specifically
/// some visual distinctions between "good" and "bad" powerups.
/// </summary>
public abstract class PowerupAttribute : Attribute
{
public abstract void PerformFrame(GamePowerUp powerup, BCBlockGameState gamestate);
public abstract void Draw(GamePowerUp powerup,Graphics g);
}
public class ColouredGamePowerupAttribute : PowerupAttribute
{
private Color _Color;
private float _Radius;
private Image drawimage = null;
public ColouredGamePowerupAttribute(Color usecolor, float Radius)
{
_Color = usecolor;
_Radius = Radius;
drawimage = LightOrb.DrawLightOrb(new Size((int)(Radius * 2), (int)(Radius * 2)), usecolor);
}
public override void Draw(GamePowerUp powerup,Graphics g)
{
g.DrawImage(drawimage, powerup.CenterPoint().X - _Radius, powerup.CenterPoint().Y - _Radius);
}
public override void PerformFrame(GamePowerUp powerup, BCBlockGameState gamestate)
{
//nothing needed.
}
}
public class PositivePowerupAttribute : ColouredGamePowerupAttribute
{
public PositivePowerupAttribute()
: base(Color.Green, 32)
{
}
}
public class PowerupCollectionEditor : BaseMultiEditor
{
public PowerupCollectionEditor(Type ptype)
: base(ptype)
{
}
protected override Type[] CreateNewItemTypes()
{
return GamePowerUp.GetPowerUpTypes();
}
}
public class GamePowerUp : AnimatedSprite
{
//public delegate
//public delegate bool PerformFrameFunction(BCBlockGameState bb, ref List<GameObject> AddObjects,ref List<GameObject> removeobjects);
//public PointF Velocity= new PointF(0,2);
public static readonly SizeF defaultSize = new SizeF(24, 12);
public delegate bool CollectPowerupfunction(BCBlockGameState bb);
protected CollectPowerupfunction usefunction;
//tweaked for extensibility...
public static Type[] GetPowerUpTypes()
{
//return BCBlockGameState.MTypeManager[typeof(GamePowerUp)].ManagedTypes.ToArray();
return BCBlockGameState.MTypeManager[typeof(GamePowerUp)].ManagedTypes.ToArray();
// return new Type[] {typeof(NullPowerUp),typeof(FrustratorPowerup), typeof (PaddlePlusPowerup), typeof (PaddleMinusPowerup),typeof(AddBallPowerup),typeof(StickyPaddlePowerUp),typeof(TerminatorPowerUp),typeof(LifeUpPowerUp),typeof(EnemySpawnerPowerUp),
// typeof(MagnetPowerup),typeof(IcePowerUp),typeof(BallSplitterPowerup),typeof(ExtraLifePowerup),typeof(ShieldPowerup)
// };
}
public static float[] GetPowerUpChance()
{
Type[] inspecttypes = GetPowerUpTypes();
float[] returnfloat = new float[inspecttypes.Length];
for (int i = 0; i < inspecttypes.Length; i++)
{
float usechance = 1f;
//check for static "PowerupChance()" routine.
MethodInfo getchanceproc = inspecttypes[i].GetMethod("PowerupChance", BindingFlags.Static);
if (getchanceproc != null)
{
try
{
usechance = (float)getchanceproc.Invoke(null, new object[0]);
}
catch
{
usechance = 1f;
}
}
returnfloat[i] = usechance;
}
return returnfloat;
/* return new float[]
{ 10f, //null
2f, //Frustrator
2f, //PaddlePlus
3f, //PaddleMinus
5f, //AddBallPowerup
2f, //StickyPaddlePowerUp
1f, //TerminatorPowerUp
1f, //LifeUpPowerUp
2f, //EnemySpawnerPowerup
3f, //MagnetPowerup
0f, //IcePowerup
2f, //BallSplitterPowerup
0.4f, //Extra life
1f //shield
};*/
}
protected void AddScore(BCBlockGameState ParentGame, int scoreadd)
{
AddScore(ParentGame, scoreadd, "");
}
public override void Draw(Graphics g)
{
Object[] result = GetType().GetCustomAttributes(typeof(PowerupAttribute), true);
foreach (Object iterate in result)
{
if (iterate is PowerupAttribute)
{
((PowerupAttribute)iterate).Draw(this, g);
}
}
base.Draw(g);
}
protected void AddScore(BCBlockGameState ParentGame, int scoreadd, String prefixString)
{
//PointF MidPoint = new PointF(mBlockrect.Left + (mBlockrect.Width / 2), mBlockrect.Top + (mBlockrect.Height / 2));
String usestring;
PointF MidPoint = new PointF(Location.X + Size.Width / 2, Location.Y + Size.Height / 2);
int addedscore = scoreadd + (Math.Sign(scoreadd) * ParentGame.GameObjects.Count * 10);
if (String.IsNullOrEmpty(prefixString))
usestring = addedscore.ToString();
else
usestring = prefixString + "(" + addedscore.ToString() + ")";
ParentGame.GameScore += addedscore;
//ParentGame.GameObjects.AddLast(new BasicFadingText(usestring, MidPoint, new PointF(((float)BCBlockGameState.rgen.NextDouble() * 0.2f) * -0.1f, ((float)BCBlockGameState.rgen.NextDouble()) * -0.7f), new Font(BCBlockGameState.GetMonospaceFont(), 16), null, null));
ParentGame.Defer(() => ParentGame.GameScore += addedscore);
ParentGame.GameObjects.AddLast(new BasicFadingText(usestring, MidPoint, new PointF(((float)BCBlockGameState.rgen.NextDouble() * 0.2f) * -0.1f, ((float)BCBlockGameState.rgen.NextDouble()) * -0.7f), new Font(BCBlockGameState.GetMonospaceFont(), 16), null, null));
//ParentGame.EnqueueMessage(usestring);
}
public GamePowerUp(PointF Location, SizeF ObjectSize, Image ImageUse, CollectPowerupfunction powerupfunc)
: base(Location, ObjectSize, new Image[] { ImageUse }, 0, 0, 3)
{
NextAttributesFunc = null;
usefunction = powerupfunc;
}
public GamePowerUp(PointF Location, SizeF ObjectSize, Image[] Imagesuse, int framedelay, CollectPowerupfunction powerupfunc)
: base(Location, ObjectSize, Imagesuse, 0, 0, framedelay)
{
//VelocityChange = new VelocityChangerLeafy();
NextAttributesFunc = null;
usefunction = powerupfunc;
}
public GamePowerUp(PointF Location, SizeF ObjectSize, String[] ImageFrameskeys, int framedelay, CollectPowerupfunction powerupfunc)
: base(Location, ObjectSize, ImageFrameskeys, 0, 0, framedelay)
{
usefunction = powerupfunc;
}
private bool TouchesPaddle(Paddle paddlecheck)
{
if (paddlecheck == null) return false;
return new RectangleF(Location, Size).IntersectsWith(paddlecheck.Getrect());
}
public override bool PerformFrame(BCBlockGameState gamestate)
{
//return base.PerformFrame(gamestate, ref AddObjects, ref removeobjects);
base.PerformFrame(gamestate);
if (TouchesPaddle(gamestate.PlayerPaddle))
{
//call into each behaviour. If any return true, we want to reject.
if (!gamestate.PlayerPaddle.Behaviours.Any((b) => b.getPowerup(gamestate, gamestate.PlayerPaddle, this)))
{
bool retval = usefunction(gamestate);
// removeobjects.Add(this);
return retval;
}
else
{
return true;
}
}
if (Location.Y > gamestate.GameArea.Height)
return true;
else if (Location.Y < gamestate.GameArea.Top)
{
Location = new PointF(Location.X, 1);
Velocity = new PointF(Velocity.X, Math.Abs(Velocity.Y));
}
if (Location.X > gamestate.GameArea.Width)
{
//bounce off right wall.
Location = new PointF(getRectangle().Right - getRectangle().Width + 1, Location.Y);
Velocity = new PointF(Math.Abs(Velocity.X), Velocity.Y);
}
else if (Location.X < gamestate.GameArea.Left)
{
//bounce off left wall.
}
Object[] result = GetType().GetCustomAttributes(typeof(PowerupAttribute), true);
foreach (Object iterate in result)
{
if (iterate is PowerupAttribute)
{
((PowerupAttribute)iterate).PerformFrame(this, gamestate);
}
}
return false;
// return usefunction(gamestate,ref AddObjects, ref removeobjects);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Configuration;
using Orleans.Runtime;
using Orleans.TestingHost;
using TestExtensions;
using UnitTests.GrainInterfaces;
using Xunit;
using Xunit.Abstractions;
namespace UnitTests.MembershipTests
{
public class LivenessTestsBase : TestClusterPerTest
{
private readonly ITestOutputHelper output;
private const int numAdditionalSilos = 1;
private const int numGrains = 20;
public LivenessTestsBase(ITestOutputHelper output)
{
this.output = output;
}
protected async Task Do_Liveness_OracleTest_1()
{
output.WriteLine("ClusterId= {0}", this.HostedCluster.Options.ClusterId);
SiloHandle silo3 = await this.HostedCluster.StartAdditionalSiloAsync();
IManagementGrain mgmtGrain = this.GrainFactory.GetGrain<IManagementGrain>(0);
Dictionary<SiloAddress, SiloStatus> statuses = await mgmtGrain.GetHosts(false);
foreach (var pair in statuses)
{
output.WriteLine(" ######## Silo {0}, status: {1}", pair.Key, pair.Value);
Assert.Equal(SiloStatus.Active, pair.Value);
}
Assert.Equal(3, statuses.Count);
IPEndPoint address = silo3.SiloAddress.Endpoint;
output.WriteLine("About to stop {0}", address);
await this.HostedCluster.StopSiloAsync(silo3);
// TODO: Should we be allowing time for changes to percolate?
output.WriteLine("----------------");
statuses = await mgmtGrain.GetHosts(false);
foreach (var pair in statuses)
{
output.WriteLine(" ######## Silo {0}, status: {1}", pair.Key, pair.Value);
IPEndPoint silo = pair.Key.Endpoint;
if (silo.Equals(address))
{
Assert.True(pair.Value == SiloStatus.ShuttingDown
|| pair.Value == SiloStatus.Stopping
|| pair.Value == SiloStatus.Dead,
string.Format("SiloStatus for {0} should now be ShuttingDown or Stopping or Dead instead of {1}", silo, pair.Value));
}
else
{
Assert.Equal(SiloStatus.Active, pair.Value);
}
}
}
protected async Task Do_Liveness_OracleTest_2(int silo2Kill, bool restart = true, bool startTimers = false)
{
await this.HostedCluster.StartAdditionalSilosAsync(numAdditionalSilos);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
for (int i = 0; i < numGrains; i++)
{
await SendTraffic(i + 1, startTimers);
}
SiloHandle silo2KillHandle = this.HostedCluster.Silos[silo2Kill];
logger.Info("\n\n\n\nAbout to kill {0}\n\n\n", silo2KillHandle.SiloAddress.Endpoint);
if (restart)
await this.HostedCluster.RestartSiloAsync(silo2KillHandle);
else
await this.HostedCluster.KillSiloAsync(silo2KillHandle);
bool didKill = !restart;
await this.HostedCluster.WaitForLivenessToStabilizeAsync(didKill);
logger.Info("\n\n\n\nAbout to start sending msg to grain again\n\n\n");
for (int i = 0; i < numGrains; i++)
{
await SendTraffic(i + 1);
}
for (int i = numGrains; i < 2 * numGrains; i++)
{
await SendTraffic(i + 1);
}
logger.Info("======================================================");
}
protected async Task Do_Liveness_OracleTest_3()
{
var moreSilos = await this.HostedCluster.StartAdditionalSilosAsync(1);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
await TestTraffic();
logger.Info("\n\n\n\nAbout to stop a first silo.\n\n\n");
var siloToStop = this.HostedCluster.SecondarySilos[0];
await this.HostedCluster.StopSiloAsync(siloToStop);
await TestTraffic();
logger.Info("\n\n\n\nAbout to re-start a first silo.\n\n\n");
await this.HostedCluster.RestartStoppedSecondarySiloAsync(siloToStop.Name);
await TestTraffic();
logger.Info("\n\n\n\nAbout to stop a second silo.\n\n\n");
await this.HostedCluster.StopSiloAsync(moreSilos[0]);
await TestTraffic();
logger.Info("======================================================");
}
private async Task TestTraffic()
{
logger.Info("\n\n\n\nAbout to start sending msg to grain again.\n\n\n");
// same grains
for (int i = 0; i < numGrains; i++)
{
await SendTraffic(i + 1);
}
// new random grains
for (int i = 0; i < numGrains; i++)
{
await SendTraffic(random.Next(10000));
}
}
private async Task SendTraffic(long key, bool startTimers = false)
{
try
{
ILivenessTestGrain grain = this.GrainFactory.GetGrain<ILivenessTestGrain>(key);
Assert.Equal(key, grain.GetPrimaryKeyLong());
Assert.Equal(key.ToString(CultureInfo.InvariantCulture), await grain.GetLabel());
await LogGrainIdentity(logger, grain);
if (startTimers)
{
await grain.StartTimer();
}
}
catch (Exception exc)
{
logger.Info("Exception making grain call: {0}", exc);
throw;
}
}
private async Task LogGrainIdentity(ILogger logger, ILivenessTestGrain grain)
{
logger.Info("Grain {0}, activation {1} on {2}",
await grain.GetGrainReference(),
await grain.GetUniqueId(),
await grain.GetRuntimeInstanceId());
}
}
public class LivenessTests_MembershipGrain : LivenessTestsBase
{
public LivenessTests_MembershipGrain(ITestOutputHelper output) : base(output)
{
}
protected override void ConfigureTestCluster(TestClusterBuilder builder)
{
builder.AddClientBuilderConfigurator<ClientConfigurator>();
}
public class ClientConfigurator : IClientBuilderConfigurator
{
public void Configure(IConfiguration configuration, IClientBuilder clientBuilder)
{
clientBuilder.Configure<GatewayOptions>(options => options.PreferedGatewayIndex = 1);
}
}
[Fact, TestCategory("Functional"), TestCategory("Membership")]
public async Task Liveness_Grain_1()
{
await Do_Liveness_OracleTest_1();
}
[Fact, TestCategory("Functional"), TestCategory("Membership")]
public async Task Liveness_Grain_2_Restart_GW()
{
await Do_Liveness_OracleTest_2(1);
}
[Fact, TestCategory("Functional"), TestCategory("Membership")]
public async Task Liveness_Grain_3_Restart_Silo_1()
{
await Do_Liveness_OracleTest_2(2);
}
[Fact, TestCategory("Functional"), TestCategory("Membership")]
public async Task Liveness_Grain_4_Kill_Silo_1_With_Timers()
{
await Do_Liveness_OracleTest_2(2, false, true);
}
//[Fact, TestCategory("Functional"), TestCategory("Membership")]
/*public async Task Liveness_Grain_5_ShutdownRestartZeroLoss()
{
await Do_Liveness_OracleTest_3();
}*/
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using Microsoft.Cci.Extensions.CSharp;
using Microsoft.Cci.Filters;
using Microsoft.Cci.Writers.Syntax;
namespace Microsoft.Cci.Writers.CSharp
{
public partial class CSDeclarationWriter : ICciDeclarationWriter
{
private readonly ISyntaxWriter _writer;
private readonly ICciFilter _filter;
private bool _forCompilation;
private bool _forCompilationIncludeGlobalprefix;
private bool _forCompilationThrowPlatformNotSupported;
private bool _includeFakeAttributes;
public CSDeclarationWriter(ISyntaxWriter writer)
: this(writer, new PublicOnlyCciFilter())
{
}
public CSDeclarationWriter(ISyntaxWriter writer, ICciFilter filter)
: this(writer, filter, true)
{
}
public CSDeclarationWriter(ISyntaxWriter writer, ICciFilter filter, bool forCompilation)
{
Contract.Requires(writer != null);
_writer = writer;
_filter = filter;
_forCompilation = forCompilation;
_forCompilationIncludeGlobalprefix = false;
_forCompilationThrowPlatformNotSupported = false;
_includeFakeAttributes = false;
}
public CSDeclarationWriter(ISyntaxWriter writer, ICciFilter filter, bool forCompilation, bool includePseudoCustomAttributes = false)
: this(writer, filter, forCompilation)
{
_includeFakeAttributes = includePseudoCustomAttributes;
}
public bool ForCompilation
{
get { return _forCompilation; }
set { _forCompilation = value; }
}
public bool ForCompilationIncludeGlobalPrefix
{
get { return _forCompilationIncludeGlobalprefix; }
set { _forCompilationIncludeGlobalprefix = value; }
}
public bool ForCompilationThrowPlatformNotSupported
{
get { return _forCompilationThrowPlatformNotSupported; }
set { _forCompilationThrowPlatformNotSupported = value; }
}
public ISyntaxWriter SyntaxtWriter { get { return _writer; } }
public ICciFilter Filter { get { return _filter; } }
public void WriteDeclaration(IDefinition definition)
{
if (definition == null)
return;
IAssembly assembly = definition as IAssembly;
if (assembly != null)
{
WriteAssemblyDeclaration(assembly);
return;
}
INamespaceDefinition ns = definition as INamespaceDefinition;
if (ns != null)
{
WriteNamespaceDeclaration(ns);
return;
}
ITypeDefinition type = definition as ITypeDefinition;
if (type != null)
{
WriteTypeDeclaration(type);
return;
}
ITypeDefinitionMember member = definition as ITypeDefinitionMember;
if (member != null)
{
WriteMemberDeclaration(member);
return;
}
DummyInternalConstructor ctor = definition as DummyInternalConstructor;
if (ctor != null)
{
WritePrivateConstructor(ctor.ContainingType);
return;
}
INamedEntity named = definition as INamedEntity;
if (named != null)
{
WriteIdentifier(named.Name);
return;
}
_writer.Write("Unknown definition type {0}", definition.ToString());
}
public void WriteAttribute(ICustomAttribute attribute)
{
WriteSymbol("[");
WriteAttribute(attribute, null);
WriteSymbol("]");
}
public void WriteAssemblyDeclaration(IAssembly assembly)
{
WriteAttributes(assembly.Attributes, prefix: "assembly");
WriteAttributes(assembly.SecurityAttributes, prefix: "assembly");
}
public void WriteMemberDeclaration(ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
{
WriteMethodDefinition(method);
return;
}
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
{
WritePropertyDefinition(property);
return;
}
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
{
WriteEventDefinition(evnt);
return;
}
IFieldDefinition field = member as IFieldDefinition;
if (field != null)
{
WriteFieldDefinition(field);
return;
}
_writer.Write("Unknown member definitions type {0}", member.ToString());
}
private void WriteVisibility(TypeMemberVisibility visibility)
{
switch (visibility)
{
case TypeMemberVisibility.Public:
WriteKeyword("public"); break;
case TypeMemberVisibility.Private:
WriteKeyword("private"); break;
case TypeMemberVisibility.Assembly:
WriteKeyword("internal"); break;
case TypeMemberVisibility.Family:
WriteKeyword("protected"); break;
case TypeMemberVisibility.FamilyOrAssembly:
WriteKeyword("protected"); WriteKeyword("internal"); break;
case TypeMemberVisibility.FamilyAndAssembly:
WriteKeyword("internal"); WriteKeyword("protected"); break; // Is this right?
default:
WriteKeyword("<Unknown-Visibility>"); break;
}
}
// Writer Helpers these are the only methods that should directly acess _writer
private void WriteKeyword(string keyword, bool noSpace = false)
{
_writer.WriteKeyword(keyword);
if (!noSpace) WriteSpace();
}
private void WriteSymbol(string symbol, bool addSpace = false)
{
_writer.WriteSymbol(symbol);
if (addSpace)
WriteSpace();
}
private void Write(string literal)
{
_writer.Write(literal);
}
private void WriteTypeName(ITypeReference type, bool noSpace = false, bool isDynamic = false)
{
if (isDynamic)
{
WriteKeyword("dynamic", noSpace: noSpace);
return;
}
NameFormattingOptions namingOptions = NameFormattingOptions.TypeParameters | NameFormattingOptions.UseTypeKeywords;
if (_forCompilationIncludeGlobalprefix)
namingOptions |= NameFormattingOptions.UseGlobalPrefix;
if (!_forCompilation)
namingOptions |= NameFormattingOptions.OmitContainingNamespace;
string name = TypeHelper.GetTypeName(type, namingOptions);
if (CSharpCciExtensions.IsKeyword(name))
_writer.WriteKeyword(name);
else
_writer.WriteTypeName(name);
if (!noSpace) WriteSpace();
}
public void WriteIdentifier(string id)
{
WriteIdentifier(id, true);
}
public void WriteIdentifier(string id, bool escape)
{
// Escape keywords
if (escape && CSharpCciExtensions.IsKeyword(id))
id = "@" + id;
_writer.WriteIdentifier(id);
}
private void WriteIdentifier(IName name)
{
WriteIdentifier(name.Value);
}
private void WriteSpace()
{
_writer.Write(" ");
}
private void WriteList<T>(IEnumerable<T> list, Action<T> writeItem)
{
_writer.WriteList(list, writeItem);
}
}
}
| |
/*
Copyright (c) 2005 Poderosa Project, All Rights Reserved.
This file is a part of the Granados SSH Client Library that is subject to
the license included in the distributed package.
You may not use this file except in compliance with the license.
$Id: ConfigAttr.cs,v 1.2 2005/04/20 09:06:03 okajima Exp $
*/
using System;
using System.Diagnostics;
using System.Reflection;
using System.Text;
namespace Poderosa.Config
{
[AttributeUsage(AttributeTargets.Field, AllowMultiple=false)]
public abstract class ConfigElementAttribute : Attribute {
protected string _externalName;
protected FieldInfo _fieldInfo;
public FieldInfo FieldInfo {
get {
return _fieldInfo;
}
set {
_fieldInfo = value;
_externalName = ToExternalName(_fieldInfo.Name);
}
}
public string ExternalName {
get {
return _externalName;
}
}
public static string ToExternalName(string value) {
//if the field name starts with '_', strip it off
if(value[0]=='_')
return value.Substring(1);
else
return value;
}
public abstract void ExportTo(object holder, ConfigNode node);
public abstract void ImportFrom(object holder, ConfigNode node);
public abstract void Reset(object holder);
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple=false)]
public class ConfigIntElementAttribute : ConfigElementAttribute {
private int _initial;
public int Initial {
get {
return _initial;
}
set {
_initial = value;
}
}
public override void ExportTo(object holder, ConfigNode node) {
int value = (int)_fieldInfo.GetValue(holder);
if(value!=_initial)
node[_externalName] = value.ToString();
}
public override void ImportFrom(object holder, ConfigNode node) {
_fieldInfo.SetValue(holder, ParseInt(node[_externalName], _initial));
}
public override void Reset(object holder) {
_fieldInfo.SetValue(holder, _initial);
}
public static int ParseInt(string value, int defaultvalue) {
try {
if(value==null || value.Length==0)
return defaultvalue;
else
return Int32.Parse(value);
}
catch(Exception) {
return defaultvalue;
}
}
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple=false)]
public class ConfigBoolElementAttribute : ConfigElementAttribute {
private bool _initial;
public bool Initial {
get {
return _initial;
}
set {
_initial = value;
}
}
public override void ExportTo(object holder, ConfigNode node) {
bool value = (bool)_fieldInfo.GetValue(holder);
if(value!=_initial)
node[_externalName] = value.ToString();
}
public override void ImportFrom(object holder, ConfigNode node) {
_fieldInfo.SetValue(holder, ParseBool(node[_externalName], _initial));
}
public override void Reset(object holder) {
_fieldInfo.SetValue(holder, _initial);
}
public static bool ParseBool(string value, bool defaultvalue) {
try {
if(value==null || value.Length==0)
return defaultvalue;
else
return Boolean.Parse(value);
}
catch(Exception) {
return defaultvalue;
}
}
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple=false)]
public class ConfigFloatElementAttribute : ConfigElementAttribute {
private float _initial;
public float Initial {
get {
return _initial;
}
set {
_initial = value;
}
}
public override void ExportTo(object holder, ConfigNode node) {
float value = (float)_fieldInfo.GetValue(holder);
if(value!=_initial)
node[_externalName] = value.ToString();
}
public override void ImportFrom(object holder, ConfigNode node) {
_fieldInfo.SetValue(holder, ParseFloat(node[_externalName], _initial));
}
public override void Reset(object holder) {
_fieldInfo.SetValue(holder, _initial);
}
public static float ParseFloat(string value, float defaultvalue) {
try {
if(value==null || value.Length==0)
return defaultvalue;
else
return Single.Parse(value);
}
catch(Exception) {
return defaultvalue;
}
}
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple=false)]
public class ConfigStringElementAttribute : ConfigElementAttribute {
private string _initial;
public string Initial {
get {
return _initial;
}
set {
_initial = value;
}
}
public override void ExportTo(object holder, ConfigNode node) {
string value = _fieldInfo.GetValue(holder) as string;
if(value!=_initial)
node[_externalName] = value==null? "" : value;
}
public override void ImportFrom(object holder, ConfigNode node) {
string t = node[_externalName];
_fieldInfo.SetValue(holder, t==null? _initial : t);
}
public override void Reset(object holder) {
_fieldInfo.SetValue(holder, _initial);
}
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple=false)]
public class ConfigStringArrayElementAttribute : ConfigElementAttribute {
private string[] _initial;
public string[] Initial {
get {
return _initial;
}
set {
_initial = value;
}
}
public override void ExportTo(object holder, ConfigNode node) {
string[] t = (string[])_fieldInfo.GetValue(holder);
StringBuilder bld = new StringBuilder();
foreach(string a in t) {
if(bld.Length>0) bld.Append(',');
bld.Append(a);
}
node[_externalName] = bld.ToString();
}
public override void ImportFrom(object holder, ConfigNode node) {
string t = node[_externalName];
_fieldInfo.SetValue(holder, t==null? _initial : t.Split(','));
}
public override void Reset(object holder) {
_fieldInfo.SetValue(holder, _initial);
}
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple=false)]
public class ConfigEnumElementAttribute : ConfigElementAttribute {
private ValueType _initial;
private Type _enumType;
public ConfigEnumElementAttribute(Type t) {
_enumType = t;
}
public int InitialAsInt {
get {
return (int)_initial;
}
set {
_initial = (ValueType)value;
}
}
public Type Type {
get {
return _enumType;
}
}
public override void ExportTo(object holder, ConfigNode node) {
ValueType value = (ValueType)_fieldInfo.GetValue(holder);
if(value!=_initial)
node[_externalName] = value.ToString();
}
public override void ImportFrom(object holder, ConfigNode node) {
object v = ParseEnum(_enumType, node[_externalName], _initial);
_fieldInfo.SetValue(holder, v);
}
public override void Reset(object holder) {
_fieldInfo.SetValue(holder, Enum.ToObject(_enumType, (int)_initial));
}
public static ValueType ParseEnum(Type enumtype, string t, ValueType defaultvalue) {
try {
if(t==null || t.Length==0)
return (ValueType)Enum.ToObject(enumtype, (int)defaultvalue);
else
return (ValueType)Enum.Parse(enumtype, t, false);
}
catch(FormatException) {
return (ValueType)Enum.ToObject(enumtype, (int)defaultvalue);
}
}
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple=false)]
public class ConfigFlagElementAttribute : ConfigElementAttribute {
private int _initial;
private int _max;
private Type _enumType;
public ConfigFlagElementAttribute(Type t) {
_enumType = t;
}
public int Initial {
get {
return _initial;
}
set {
_initial = value;
}
}
public int Max {
get {
return _max;
}
set {
_max = value;
}
}
public Type Type {
get {
return _enumType;
}
}
public override void ExportTo(object holder, ConfigNode node) {
int value = (int)_fieldInfo.GetValue(holder);
StringBuilder bld = new StringBuilder();
for(int i=1; i<=_max; i<<=1) {
if((i & value)!=0) {
if(bld.Length>0) bld.Append(',');
bld.Append(Enum.GetName(_enumType, i));
}
}
node[_externalName] = bld.ToString();
}
public override void ImportFrom(object holder, ConfigNode node) {
string value = node[_externalName];
if(value==null)
_fieldInfo.SetValue(holder, Enum.ToObject(_enumType, (int)_initial));
else {
int r = 0;
foreach(string t in value.Split(','))
r |= (int)Enum.Parse(_enumType, t, false);
_fieldInfo.SetValue(holder, Enum.ToObject(_enumType, (int)r));
}
}
public override void Reset(object holder) {
_fieldInfo.SetValue(holder, Enum.ToObject(_enumType, (int)_initial));
}
}
}
| |
using System;
using System.Linq;
namespace ClosedXML.Excel
{
using System.Collections.Generic;
internal class XLFilterColumn : IXLFilterColumn
{
private readonly XLAutoFilter _autoFilter;
private readonly Int32 _column;
public XLFilterColumn(XLAutoFilter autoFilter, Int32 column)
{
_autoFilter = autoFilter;
_column = column;
}
#region IXLFilterColumn Members
public void Clear()
{
if (_autoFilter.Filters.ContainsKey(_column))
_autoFilter.Filters.Remove(_column);
}
public IXLFilteredColumn AddFilter<T>(T value) where T : IComparable<T>
{
if (typeof(T) == typeof(String))
{
ApplyCustomFilter(value, XLFilterOperator.Equal,
v =>
v.ToString().Equals(value.ToString(), StringComparison.InvariantCultureIgnoreCase),
XLFilterType.Regular);
}
else
{
ApplyCustomFilter(value, XLFilterOperator.Equal,
v => v.CastTo<T>().CompareTo(value) == 0, XLFilterType.Regular);
}
return new XLFilteredColumn(_autoFilter, _column);
}
public IXLDateTimeGroupFilteredColumn AddDateGroupFilter(DateTime date, XLDateTimeGrouping dateTimeGrouping)
{
Func<Object, Boolean> condition = date2 => XLDateTimeGroupFilteredColumn.IsMatch(date, (DateTime)date2, dateTimeGrouping);
_autoFilter.IsEnabled = true;
if (_autoFilter.Filters.TryGetValue(_column, out List<XLFilter> filterList))
filterList.Add(
new XLFilter
{
Value = date,
Operator = XLFilterOperator.Equal,
Connector = XLConnector.Or,
Condition = condition,
DateTimeGrouping = dateTimeGrouping
}
);
else
{
_autoFilter.Filters.Add(
_column,
new List<XLFilter>
{
new XLFilter
{
Value = date,
Operator = XLFilterOperator.Equal,
Connector = XLConnector.Or,
Condition = condition,
DateTimeGrouping = dateTimeGrouping
}
}
);
}
_autoFilter.Column(_column).FilterType = XLFilterType.DateTimeGrouping;
var ws = _autoFilter.Range.Worksheet as XLWorksheet;
ws.SuspendEvents();
var rows = _autoFilter.Range.Rows(2, _autoFilter.Range.RowCount());
foreach (IXLRangeRow row in rows)
{
if (row.Cell(_column).DataType == XLDataType.DateTime && condition(row.Cell(_column).GetDateTime()))
row.WorksheetRow().Unhide();
else
row.WorksheetRow().Hide();
}
ws.ResumeEvents();
return new XLDateTimeGroupFilteredColumn(_autoFilter, _column);
}
public void Top(Int32 value, XLTopBottomType type = XLTopBottomType.Items)
{
_autoFilter.Column(_column).TopBottomPart = XLTopBottomPart.Top;
SetTopBottom(value, type);
}
public void Bottom(Int32 value, XLTopBottomType type = XLTopBottomType.Items)
{
_autoFilter.Column(_column).TopBottomPart = XLTopBottomPart.Bottom;
SetTopBottom(value, type, false);
}
public void AboveAverage()
{
ShowAverage(true);
}
public void BelowAverage()
{
ShowAverage(false);
}
public IXLFilterConnector EqualTo<T>(T value) where T : IComparable<T>
{
if (typeof(T) == typeof(String))
{
return ApplyCustomFilter(value, XLFilterOperator.Equal,
v =>
v.ToString().Equals(value.ToString(),
StringComparison.InvariantCultureIgnoreCase));
}
return ApplyCustomFilter(value, XLFilterOperator.Equal,
v => v.CastTo<T>().CompareTo(value) == 0);
}
public IXLFilterConnector NotEqualTo<T>(T value) where T : IComparable<T>
{
if (typeof(T) == typeof(String))
{
return ApplyCustomFilter(value, XLFilterOperator.NotEqual,
v =>
!v.ToString().Equals(value.ToString(),
StringComparison.InvariantCultureIgnoreCase));
}
return ApplyCustomFilter(value, XLFilterOperator.NotEqual,
v => v.CastTo<T>().CompareTo(value) != 0);
}
public IXLFilterConnector GreaterThan<T>(T value) where T : IComparable<T>
{
return ApplyCustomFilter(value, XLFilterOperator.GreaterThan,
v => v.CastTo<T>().CompareTo(value) > 0);
}
public IXLFilterConnector LessThan<T>(T value) where T : IComparable<T>
{
return ApplyCustomFilter(value, XLFilterOperator.LessThan,
v => v.CastTo<T>().CompareTo(value) < 0);
}
public IXLFilterConnector EqualOrGreaterThan<T>(T value) where T : IComparable<T>
{
return ApplyCustomFilter(value, XLFilterOperator.EqualOrGreaterThan,
v => v.CastTo<T>().CompareTo(value) >= 0);
}
public IXLFilterConnector EqualOrLessThan<T>(T value) where T : IComparable<T>
{
return ApplyCustomFilter(value, XLFilterOperator.EqualOrLessThan,
v => v.CastTo<T>().CompareTo(value) <= 0);
}
public void Between<T>(T minValue, T maxValue) where T : IComparable<T>
{
EqualOrGreaterThan(minValue).And.EqualOrLessThan(maxValue);
}
public void NotBetween<T>(T minValue, T maxValue) where T : IComparable<T>
{
LessThan(minValue).Or.GreaterThan(maxValue);
}
public static Func<String, Object, Boolean> BeginsWithFunction { get; } = (value, input) => ((string)input).StartsWith(value, StringComparison.InvariantCultureIgnoreCase);
public IXLFilterConnector BeginsWith(String value)
{
return ApplyCustomFilter(value + "*", XLFilterOperator.Equal, s => BeginsWithFunction(value, s));
}
public IXLFilterConnector NotBeginsWith(String value)
{
return ApplyCustomFilter(value + "*", XLFilterOperator.NotEqual, s => !BeginsWithFunction(value, s));
}
public static Func<String, Object, Boolean> EndsWithFunction { get; } = (value, input) => ((string)input).EndsWith(value, StringComparison.InvariantCultureIgnoreCase);
public IXLFilterConnector EndsWith(String value)
{
return ApplyCustomFilter("*" + value, XLFilterOperator.Equal, s => EndsWithFunction(value, s));
}
public IXLFilterConnector NotEndsWith(String value)
{
return ApplyCustomFilter("*" + value, XLFilterOperator.NotEqual, s => !EndsWithFunction(value, s));
}
public static Func<String, Object, Boolean> ContainsFunction { get; } = (value, input) => ((string)input).IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0;
public IXLFilterConnector Contains(String value)
{
return ApplyCustomFilter("*" + value + "*", XLFilterOperator.Equal, s => ContainsFunction(value, s));
}
public IXLFilterConnector NotContains(String value)
{
return ApplyCustomFilter("*" + value + "*", XLFilterOperator.Equal, s => !ContainsFunction(value, s));
}
public XLFilterType FilterType { get; set; }
public Int32 TopBottomValue { get; set; }
public XLTopBottomType TopBottomType { get; set; }
public XLTopBottomPart TopBottomPart { get; set; }
public XLFilterDynamicType DynamicType { get; set; }
public Double DynamicValue { get; set; }
#endregion IXLFilterColumn Members
private void SetTopBottom(Int32 value, XLTopBottomType type, Boolean takeTop = true)
{
_autoFilter.IsEnabled = true;
_autoFilter.Column(_column).SetFilterType(XLFilterType.TopBottom)
.SetTopBottomValue(value)
.SetTopBottomType(type);
var values = GetValues(value, type, takeTop);
Clear();
_autoFilter.Filters.Add(_column, new List<XLFilter>());
Boolean addToList = true;
var ws = _autoFilter.Range.Worksheet as XLWorksheet;
ws.SuspendEvents();
var rows = _autoFilter.Range.Rows(2, _autoFilter.Range.RowCount());
foreach (IXLRangeRow row in rows)
{
Boolean foundOne = false;
foreach (double val in values)
{
Func<Object, Boolean> condition = v => (v as IComparable).CompareTo(val) == 0;
if (addToList)
{
_autoFilter.Filters[_column].Add(new XLFilter
{
Value = val,
Operator = XLFilterOperator.Equal,
Connector = XLConnector.Or,
Condition = condition
});
}
var cell = row.Cell(_column);
if (cell.DataType != XLDataType.Number || !condition(cell.GetDouble())) continue;
row.WorksheetRow().Unhide();
foundOne = true;
}
if (!foundOne)
row.WorksheetRow().Hide();
addToList = false;
}
ws.ResumeEvents();
}
private IEnumerable<double> GetValues(int value, XLTopBottomType type, bool takeTop)
{
var column = _autoFilter.Range.Column(_column);
var subColumn = column.Column(2, column.CellCount());
var cellsUsed = subColumn.CellsUsed(c => c.DataType == XLDataType.Number);
if (takeTop)
{
if (type == XLTopBottomType.Items)
{
return cellsUsed.Select(c => c.GetDouble()).OrderByDescending(d => d).Take(value).Distinct();
}
var numerics1 = cellsUsed.Select(c => c.GetDouble());
Int32 valsToTake1 = numerics1.Count() * value / 100;
return numerics1.OrderByDescending(d => d).Take(valsToTake1).Distinct();
}
if (type == XLTopBottomType.Items)
{
return cellsUsed.Select(c => c.GetDouble()).OrderBy(d => d).Take(value).Distinct();
}
var numerics = cellsUsed.Select(c => c.GetDouble());
Int32 valsToTake = numerics.Count() * value / 100;
return numerics.OrderBy(d => d).Take(valsToTake).Distinct();
}
private void ShowAverage(Boolean aboveAverage)
{
_autoFilter.IsEnabled = true;
_autoFilter.Column(_column).SetFilterType(XLFilterType.Dynamic)
.SetDynamicType(aboveAverage
? XLFilterDynamicType.AboveAverage
: XLFilterDynamicType.BelowAverage);
var values = GetAverageValues(aboveAverage);
Clear();
_autoFilter.Filters.Add(_column, new List<XLFilter>());
Boolean addToList = true;
var ws = _autoFilter.Range.Worksheet as XLWorksheet;
ws.SuspendEvents();
var rows = _autoFilter.Range.Rows(2, _autoFilter.Range.RowCount());
foreach (IXLRangeRow row in rows)
{
Boolean foundOne = false;
foreach (double val in values)
{
Func<Object, Boolean> condition = v => (v as IComparable).CompareTo(val) == 0;
if (addToList)
{
_autoFilter.Filters[_column].Add(new XLFilter
{
Value = val,
Operator = XLFilterOperator.Equal,
Connector = XLConnector.Or,
Condition = condition
});
}
var cell = row.Cell(_column);
if (cell.DataType != XLDataType.Number || !condition(cell.GetDouble())) continue;
row.WorksheetRow().Unhide();
foundOne = true;
}
if (!foundOne)
row.WorksheetRow().Hide();
addToList = false;
}
ws.ResumeEvents();
}
private IEnumerable<double> GetAverageValues(bool aboveAverage)
{
var column = _autoFilter.Range.Column(_column);
var subColumn = column.Column(2, column.CellCount());
Double average = subColumn.CellsUsed(c => c.DataType == XLDataType.Number).Select(c => c.GetDouble())
.Average();
if (aboveAverage)
{
return
subColumn.CellsUsed(c => c.DataType == XLDataType.Number).Select(c => c.GetDouble())
.Where(c => c > average).Distinct();
}
return
subColumn.CellsUsed(c => c.DataType == XLDataType.Number).Select(c => c.GetDouble())
.Where(c => c < average).Distinct();
}
private IXLFilterConnector ApplyCustomFilter<T>(T value, XLFilterOperator op, Func<Object, Boolean> condition,
XLFilterType filterType = XLFilterType.Custom)
where T : IComparable<T>
{
_autoFilter.IsEnabled = true;
if (filterType == XLFilterType.Custom)
{
Clear();
_autoFilter.Filters.Add(_column,
new List<XLFilter>
{
new XLFilter
{
Value = value,
Operator = op,
Connector = XLConnector.Or,
Condition = condition
}
});
}
else
{
if (_autoFilter.Filters.TryGetValue(_column, out List<XLFilter> filterList))
filterList.Add(new XLFilter
{
Value = value,
Operator = op,
Connector = XLConnector.Or,
Condition = condition
});
else
{
_autoFilter.Filters.Add(_column,
new List<XLFilter>
{
new XLFilter
{
Value = value,
Operator = op,
Connector = XLConnector.Or,
Condition = condition
}
});
}
}
_autoFilter.Column(_column).FilterType = filterType;
_autoFilter.Reapply();
return new XLFilterConnector(_autoFilter, _column);
}
public IXLFilterColumn SetFilterType(XLFilterType value) { FilterType = value; return this; }
public IXLFilterColumn SetTopBottomValue(Int32 value) { TopBottomValue = value; return this; }
public IXLFilterColumn SetTopBottomType(XLTopBottomType value) { TopBottomType = value; return this; }
public IXLFilterColumn SetTopBottomPart(XLTopBottomPart value) { TopBottomPart = value; return this; }
public IXLFilterColumn SetDynamicType(XLFilterDynamicType value) { DynamicType = value; return this; }
public IXLFilterColumn SetDynamicValue(Double value) { DynamicValue = value; return this; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Xml.Linq;
namespace NuGet
{
public static class XElementExtensions
{
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters",
Justification = "We don't care about base types")]
public static string GetOptionalAttributeValue(this XElement element, string localName,
string namespaceName = null)
{
XAttribute attr;
if (String.IsNullOrEmpty(namespaceName))
{
attr = element.Attribute(localName);
}
else
{
attr = element.Attribute(XName.Get(localName, namespaceName));
}
return attr != null ? attr.Value : null;
}
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters",
Justification = "We don't care about base types")]
public static string GetOptionalElementValue(this XElement element, string localName,
string namespaceName = null)
{
XElement child;
if (String.IsNullOrEmpty(namespaceName))
{
child = element.Element(localName);
}
else
{
child = element.Element(XName.Get(localName, namespaceName));
}
return child != null ? child.Value : null;
}
public static IEnumerable<XElement> ElementsNoNamespace(this XContainer container, string localName)
{
return container.Elements().Where(e => e.Name.LocalName == localName);
}
public static IEnumerable<XElement> ElementsNoNamespace(this IEnumerable<XContainer> source, string localName)
{
return source.Elements().Where(e => e.Name.LocalName == localName);
}
// REVIEW: We can use a stack if the perf is bad for Except and MergeWith
public static XElement Except(this XElement source, XElement target)
{
if (target == null)
{
return source;
}
IEnumerable<XAttribute> attributesToRemove = from e in source.Attributes()
where AttributeEquals(e, target.Attribute(e.Name))
select e;
// Remove the attributes
foreach (XAttribute a in attributesToRemove.ToList())
{
a.Remove();
}
foreach (XElement sourceChild in source.Elements().ToList())
{
XElement targetChild = FindElement(target, sourceChild);
if (targetChild != null && !HasConflict(sourceChild, targetChild))
{
Except(sourceChild, targetChild);
bool hasContent = sourceChild.HasAttributes || sourceChild.HasElements;
if (!hasContent)
{
// Remove the element if there is no content
sourceChild.Remove();
targetChild.Remove();
}
}
}
return source;
}
public static XElement MergeWith(this XElement source, XElement target)
{
return MergeWith(source, target, null);
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "No reason to create a new type")]
public static XElement MergeWith(this XElement source, XElement target,
IDictionary<XName, Action<XElement, XElement>> nodeActions)
{
if (target == null)
{
return source;
}
// Merge the attributes
foreach (XAttribute targetAttribute in target.Attributes())
{
XAttribute sourceAttribute = source.Attribute(targetAttribute.Name);
if (sourceAttribute == null)
{
source.Add(targetAttribute);
}
}
// Go through the elements to be merged
foreach (XElement targetChild in target.Elements())
{
XElement sourceChild = FindElement(source, targetChild);
if (sourceChild != null && !HasConflict(sourceChild, targetChild))
{
// Other wise merge recursively
sourceChild.MergeWith(targetChild, nodeActions);
}
else
{
Action<XElement, XElement> nodeAction;
if (nodeActions != null && nodeActions.TryGetValue(targetChild.Name, out nodeAction))
{
nodeAction(source, targetChild);
}
else
{
// If that element is null then add that node
source.Add(targetChild);
}
}
}
return source;
}
private static XElement FindElement(XElement source, XElement targetChild)
{
// Get all of the elements in the source that match this name
List<XElement> sourceElements = source.Elements(targetChild.Name).ToList();
// Try to find the best matching element based on attribute names and values
sourceElements.Sort((a, b) => Compare(targetChild, a, b));
return sourceElements.FirstOrDefault();
}
private static int Compare(XElement target, XElement left, XElement right)
{
Debug.Assert(left.Name == right.Name);
// First check how much attribute names and values match
int leftExactMathes = CountMatches(left, target, AttributeEquals);
int rightExactMathes = CountMatches(right, target, AttributeEquals);
if (leftExactMathes == rightExactMathes)
{
// Then check which names match
int leftNameMatches = CountMatches(left, target, (a, b) => a.Name == b.Name);
int rightNameMatches = CountMatches(right, target, (a, b) => a.Name == b.Name);
return rightNameMatches.CompareTo(leftNameMatches);
}
return rightExactMathes.CompareTo(leftExactMathes);
}
private static int CountMatches(XElement left, XElement right, Func<XAttribute, XAttribute, bool> matcher)
{
return (from la in left.Attributes()
from ta in right.Attributes()
where matcher(la, ta)
select la).Count();
}
private static bool HasConflict(XElement source, XElement target)
{
// Get all attributes as name value pairs
Dictionary<XName, string> sourceAttr = source.Attributes().ToDictionary(a => a.Name, a => a.Value);
// Loop over all the other attributes and see if there are
foreach (XAttribute targetAttr in target.Attributes())
{
string sourceValue;
// if any of the attributes are in the source (names match) but the value doesn't match then we've found a conflict
if (sourceAttr.TryGetValue(targetAttr.Name, out sourceValue) && sourceValue != targetAttr.Value)
{
return true;
}
}
return false;
}
public static void RemoveAttributes(this XElement element, Func<XAttribute, bool> condition)
{
element.Attributes()
.Where(condition)
.ToList()
.Remove();
element.Descendants()
.ToList()
.ForEach(e => RemoveAttributes(e, condition));
}
private static bool AttributeEquals(XAttribute source, XAttribute target)
{
if (source == null && target == null)
{
return true;
}
if (source == null || target == null)
{
return false;
}
return source.Name == target.Name && source.Value == target.Value;
}
}
}
| |
// -----------------------------------------------------------------------
// <copyright file="RawDeliveryDataParserBase.cs" company="Rare Crowds Inc">
// Copyright 2012-2013 Rare Crowds, 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.
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using DataAccessLayer;
using Diagnostics;
namespace DynamicAllocationActivities
{
/// <summary>Helper class to provide common delivery data parsing functionality.</summary>
internal abstract class RawDeliveryDataParserBase : IRawDeliveryDataParser
{
////Canonical property names
/// <summary>Name of hour field in delivery data dictionary record</summary>
public const string HourFieldName = "Hour";
/// <summary>Name of campaign Id field in delivery data dictionary record</summary>
public const string CampaignIdFieldName = "CampaignId";
/// <summary>Name of allocation Id field in delivery data dictionary record</summary>
public const string AllocationIdFieldName = "AllocationId";
/// <summary>Name of impressions field in delivery data dictionary record</summary>
public const string ImpressionsFieldName = "Impressions";
/// <summary>Name of ecpm field in delivery data dictionary record</summary>
public const string EcpmFieldName = "Ecpm";
/// <summary>Name of media spend field in delivery data dictionary record</summary>
public const string MediaSpendFieldName = "Spend";
/// <summary>Name of clicks field in delivery data dictionary record</summary>
public const string ClicksFieldName = "Clicks";
/// <summary>Default field canonizer</summary>
protected static readonly Func<string, string> DefaultFieldCanonizer = s => s;
/// <summary>Gets the field names that appear in a canonical delivery data record.</summary>
internal static string[] CanonicalKeys
{
get
{
return new[]
{
CampaignIdFieldName,
AllocationIdFieldName,
HourFieldName,
ImpressionsFieldName,
EcpmFieldName,
MediaSpendFieldName,
ClicksFieldName
};
}
}
/// <summary>
/// Gets FieldMap
/// A light weight schema for mapping data source name to an internal name and serialization type.
/// EntityProperty is used as a way to capture name and type (values are dummies)
/// </summary>
protected abstract Dictionary<string, Tuple<EntityProperty, bool, Func<string, string>>> FieldMap { get; }
/// <summary>Parse raw delivery data records. Tolerant of multiple header records from concatonated reports.</summary>
/// <param name="records">An array of records (one record per array element).</param>
/// <returns>A canonical representation of the delivery data - one dictionary of name/value pairs per record.</returns>
public virtual IList<Dictionary<string, PropertyValue>> ParseRawRecords(string[] records)
{
return this.ParseRawCsvRecords(records);
}
/// <summary>Split individual records of a raw delivery data file into a list of one string per record.</summary>
/// <param name="rawDeliveryData">The raw delivery data string.</param>
/// <returns>A list of strings - one per record</returns>
public virtual IList<string> SplitRecords(string rawDeliveryData)
{
return SplitAndTrim(rawDeliveryData, "\r\n");
}
/// <summary>Split and Trim...</summary>
/// <param name="source">The source.</param>
/// <param name="delimiter">The delimiter.</param>
/// <returns>A list of strings</returns>
protected static List<string> SplitAndTrim(string source, string delimiter)
{
return source.Split(new[] { delimiter }, StringSplitOptions.None)
.Select(r => r.Trim()).ToList();
}
/// <summary>Parse raw delivery data in CSV form. Tolerant of multiple header records from concatonated reports.</summary>
/// <param name="records">An array of CSV records (one comma delimited record per array element).</param>
/// <returns>A canonical representation of the delivery data - one dictionary of name/value pairs per record.</returns>
protected List<Dictionary<string, PropertyValue>> ParseRawCsvRecords(string[] records)
{
if (records == null || records.Length == 0)
{
return new List<Dictionary<string, PropertyValue>>();
}
// Build a dictionary with our delivery data
var deliveryData = new Dictionary<string, Dictionary<string, PropertyValue>>();
// Header treated case-insensitive
var header = SplitAndTrim(records[0], ",").Select(h => h.ToLowerInvariant()).ToList();
var colCount = header.Count;
// Ignore the first record (header)
for (int rowIndex = 1; rowIndex < records.Length; rowIndex++)
{
var colValues = SplitAndTrim(records[rowIndex], ",");
// Blank row or bad row
if (colValues.Count != colCount)
{
LogManager.Log(
LogLevels.Trace,
"DfpReportCsvParser.ParseRawRecords - Invalid row, column count does not match header count. Row = {0}",
records[rowIndex]);
continue;
}
// Skip subsequent headers (from concatenating multiple delivery data CSVs)
if (colValues.All(col => header.Contains(col.ToLowerInvariant())))
{
continue;
}
// Populate a dictionary with the values for this row
var record = new Dictionary<string, PropertyValue>();
for (int colIndex = 0; colIndex < colCount; colIndex++)
{
var col = colValues[colIndex];
// If we encounter a key we don't understand ignore it
if (!this.FieldMap.ContainsKey(header[colIndex]))
{
LogManager.Log(
LogLevels.Trace,
"DfpReportCsvParser.ParseRawRecords - Ignoring column: {0}",
header[colIndex]);
continue;
}
var template = this.FieldMap[header[colIndex]];
// If we encounter a type that is not compatible with what we expect fail out with null
try
{
// The template maps source name to target name and a tuple. The first item in the tuple contains a default
// propertyValue with expected type and default value. The second contains a flag indicating whether a value is required or a
// reasonable default exists.
var entityProperty = template.Item1;
var fieldRequired = template.Item2;
var propertyName = entityProperty.Name;
var expectedType = entityProperty.Value.DynamicType;
var propertyValue = entityProperty.Value;
var canonizer = template.Item3;
// Special handling for fields that need it
col = canonizer(col);
// If the column value is empty and defaults are not allowed, fail out
if (string.IsNullOrEmpty(col) && fieldRequired)
{
LogManager.Log(
LogLevels.Trace,
"DfpReportCsvParser.ParseRawRecords - Requirded value is empty: {0}",
header[colIndex]);
return null;
}
// Now just build our property value
if (!string.IsNullOrEmpty(col))
{
propertyValue = new PropertyValue(expectedType, col);
}
record.Add(propertyName, propertyValue);
}
catch (ArgumentException)
{
LogManager.Log(
LogLevels.Trace,
"DfpReportCsvParser.ParseRawRecords - Failed to deserialize value: {0}, {1}",
header[colIndex],
col);
return null;
}
}
record = this.CanonizeRecord(record);
var key = "{0}:{1}".FormatInvariant(
record[AllocationIdFieldName],
record[HourFieldName]);
deliveryData[key] = record;
}
return new List<Dictionary<string, PropertyValue>>(deliveryData.Values);
}
/// <summary>Build a record that contains only canonical delivery data field names.</summary>
/// <param name="sourceRecord">The source record.</param>
/// <returns>A new canonical record.</returns>
protected virtual Dictionary<string, PropertyValue> CanonizeRecord(IDictionary<string, PropertyValue> sourceRecord)
{
return sourceRecord.ToDictionary();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using Dapper;
using MicroOrm.Dapper.Repositories.Extensions;
using MicroOrm.Dapper.Repositories.SqlGenerator;
namespace MicroOrm.Dapper.Repositories
{
/// <summary>
/// Base Repository
/// </summary>
public partial class ReadOnlyDapperRepository<TEntity>
where TEntity : class
{
/// <summary>
/// Execute Join query
/// </summary>
protected virtual IEnumerable<TEntity> ExecuteJoinQuery<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(
SqlQuery sqlQuery,
IDbTransaction transaction,
params Expression<Func<TEntity, object>>[] includes)
{
if (!SqlGenerator.KeySqlProperties.Any())
throw new NotSupportedException("Join doesn't support without [Key] attribute");
var type = typeof(TEntity);
var childProperties = new List<PropertyInfo>();
var childKeyProperties = new List<PropertyInfo>();
var keyProperties = SqlGenerator.KeySqlProperties.Select(q => q.PropertyInfo).ToArray();
foreach (var s in includes)
{
var prop = ExpressionHelper.GetPropertyName(s);
var childProp = type.GetProperty(prop);
if (childProp == null)
continue;
childProperties.Add(childProp);
var childType = childProp.PropertyType.IsGenericType ? childProp.PropertyType.GenericTypeArguments[0] : childProp.PropertyType;
var properties = childType.FindClassProperties().Where(ExpressionHelper.GetPrimitivePropertiesPredicate());
childKeyProperties.AddRange(properties.Where(p => p.GetCustomAttributes<KeyAttribute>().Any()));
}
if (!childKeyProperties.Any())
throw new NotSupportedException("Join doesn't support without [Key] attribute");
var lookup = new Dictionary<object, TEntity>();
const bool buffered = true;
var spiltOn = string.Join(",", childKeyProperties.Select(q => q.Name));
switch (includes.Length)
{
case 1:
Connection.Query<TEntity, TChild1, TEntity>(sqlQuery.GetSql(), (entity, child1) =>
EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1),
sqlQuery.Param, transaction, buffered, spiltOn);
break;
case 2:
Connection.Query<TEntity, TChild1, TChild2, TEntity>(sqlQuery.GetSql(), (entity, child1, child2) =>
EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1,
child2),
sqlQuery.Param, transaction, buffered, spiltOn);
break;
case 3:
Connection.Query<TEntity, TChild1, TChild2, TChild3, TEntity>(sqlQuery.GetSql(), (entity, child1, child2, child3) =>
EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1,
child2, child3),
sqlQuery.Param, transaction, buffered, spiltOn);
break;
case 4:
Connection.Query<TEntity, TChild1, TChild2, TChild3, TChild4, TEntity>(sqlQuery.GetSql(), (entity, child1, child2, child3, child4) =>
EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1,
child2, child3, child4),
sqlQuery.Param, transaction, buffered, spiltOn);
break;
case 5:
Connection.Query<TEntity, TChild1, TChild2, TChild3, TChild4, TChild5, TEntity>(sqlQuery.GetSql(), (entity, child1, child2, child3, child4, child5) =>
EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1,
child2, child3, child4, child5),
sqlQuery.Param, transaction, buffered, spiltOn);
break;
case 6:
Connection.Query<TEntity, TChild1, TChild2, TChild3, TChild4, TChild5, TChild6, TEntity>(sqlQuery.GetSql(),
(entity, child1, child2, child3, child4, child5, child6) =>
EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1,
child2, child3, child4, child5, child6),
sqlQuery.Param, transaction, buffered, spiltOn);
break;
default:
throw new NotSupportedException();
}
return lookup.Values;
}
/// <summary>
/// Execute Join query
/// </summary>
protected virtual async Task<IEnumerable<TEntity>> ExecuteJoinQueryAsync<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(
SqlQuery sqlQuery,
IDbTransaction transaction,
params Expression<Func<TEntity, object>>[] includes)
{
if (!SqlGenerator.KeySqlProperties.Any())
throw new NotSupportedException("Join doesn't support without [Key] attribute");
var type = typeof(TEntity);
var childProperties = new List<PropertyInfo>();
var childKeyProperties = new List<PropertyInfo>();
var keyProperties = SqlGenerator.KeySqlProperties.Select(q => q.PropertyInfo).ToArray();
foreach (var s in includes)
{
var prop = ExpressionHelper.GetPropertyName(s);
var childProp = type.GetProperty(prop);
if (childProp == null)
continue;
childProperties.Add(childProp);
var childType = childProp.PropertyType.IsGenericType ? childProp.PropertyType.GenericTypeArguments[0] : childProp.PropertyType;
var properties = childType.FindClassProperties().Where(ExpressionHelper.GetPrimitivePropertiesPredicate());
childKeyProperties.AddRange(properties.Where(p => p.GetCustomAttributes<KeyAttribute>().Any()));
}
if (!childKeyProperties.Any())
throw new NotSupportedException("Join doesn't support without [Key] attribute");
var lookup = new Dictionary<object, TEntity>();
const bool buffered = true;
var spiltOn = string.Join(",", childKeyProperties.Select(q => q.Name));
switch (includes.Length)
{
case 1:
await Connection.QueryAsync<TEntity, TChild1, TEntity>(sqlQuery.GetSql(), (entity, child1) =>
EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1),
sqlQuery.Param, transaction, buffered, spiltOn);
break;
case 2:
await Connection.QueryAsync<TEntity, TChild1, TChild2, TEntity>(sqlQuery.GetSql(), (entity, child1, child2) =>
EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1,
child2),
sqlQuery.Param, transaction, buffered, spiltOn);
break;
case 3:
await Connection.QueryAsync<TEntity, TChild1, TChild2, TChild3, TEntity>(sqlQuery.GetSql(), (entity, child1, child2, child3) =>
EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1,
child2, child3),
sqlQuery.Param, transaction, buffered, spiltOn);
break;
case 4:
await Connection.QueryAsync<TEntity, TChild1, TChild2, TChild3, TChild4, TEntity>(sqlQuery.GetSql(), (entity, child1, child2, child3, child4) =>
EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1,
child2, child3, child4),
sqlQuery.Param, transaction, buffered, spiltOn);
break;
case 5:
await Connection.QueryAsync<TEntity, TChild1, TChild2, TChild3, TChild4, TChild5, TEntity>(sqlQuery.GetSql(),
(entity, child1, child2, child3, child4, child5) =>
EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1,
child2, child3, child4, child5),
sqlQuery.Param, transaction, buffered, spiltOn);
break;
case 6:
await Connection.QueryAsync<TEntity, TChild1, TChild2, TChild3, TChild4, TChild5, TChild6, TEntity>(sqlQuery.GetSql(),
(entity, child1, child2, child3, child4, child5, child6) =>
EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(lookup, keyProperties, childKeyProperties, childProperties, entity, child1,
child2, child3, child4, child5, child6),
sqlQuery.Param, transaction, buffered, spiltOn);
break;
default:
throw new NotSupportedException();
}
return lookup.Values;
}
private static TEntity EntityJoinMapping<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(IDictionary<object, TEntity> lookup, PropertyInfo[] keyProperties,
IList<PropertyInfo> childKeyProperties, IList<PropertyInfo> childProperties, TEntity entity, params object[] childs)
{
var compositeKeyProperty = string.Join("|", keyProperties.Select(q => q.GetValue(entity).ToString()));
if (!lookup.TryGetValue(compositeKeyProperty, out var target))
lookup.Add(compositeKeyProperty, target = entity);
for (var i = 0; i < childs.Length; i++)
{
var child = childs[i];
var childProperty = childProperties[i];
var childKeyProperty = childKeyProperties[i];
if (childProperty.PropertyType.IsGenericType)
{
var list = (IList) childProperty.GetValue(target);
if (list == null)
{
switch (i)
{
case 0:
list = new List<TChild1>();
break;
case 1:
list = new List<TChild2>();
break;
case 2:
list = new List<TChild3>();
break;
case 3:
list = new List<TChild4>();
break;
case 4:
list = new List<TChild5>();
break;
case 5:
list = new List<TChild6>();
break;
default:
throw new NotSupportedException();
}
childProperty.SetValue(target, list);
}
if (child == null)
continue;
var childKey = childKeyProperty.GetValue(child);
var exist = (from object item in list select childKeyProperty.GetValue(item)).Contains(childKey);
if (!exist)
list.Add(child);
}
else
{
childProperty.SetValue(target, child);
}
}
return target;
}
/// <summary>
/// Dummy type for excluding from multi-map
/// </summary>
// ReSharper disable once ClassNeverInstantiated.Local
private class DontMap
{
}
}
}
| |
using Lucene.Net.Diagnostics;
using System;
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using BytesRef = Lucene.Net.Util.BytesRef;
using FieldInvertState = Lucene.Net.Index.FieldInvertState;
using NumericDocValues = Lucene.Net.Index.NumericDocValues;
using SmallSingle = Lucene.Net.Util.SmallSingle;
namespace Lucene.Net.Search.Similarities
{
/*
* 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>
/// A subclass of <see cref="Similarity"/> that provides a simplified API for its
/// descendants. Subclasses are only required to implement the <see cref="Score(BasicStats, float, float)"/>
/// and <see cref="ToString()"/> methods. Implementing
/// <see cref="Explain(Explanation, BasicStats, int, float, float)"/> is optional,
/// inasmuch as <see cref="SimilarityBase"/> already provides a basic explanation of the score
/// and the term frequency. However, implementers of a subclass are encouraged to
/// include as much detail about the scoring method as possible.
/// <para/>
/// Note: multi-word queries such as phrase queries are scored in a different way
/// than Lucene's default ranking algorithm: whereas it "fakes" an IDF value for
/// the phrase as a whole (since it does not know it), this class instead scores
/// phrases as a summation of the individual term scores.
/// <para/>
/// @lucene.experimental
/// </summary>
public abstract class SimilarityBase : Similarity
{
/// <summary>
/// For <see cref="Log2(double)"/>. Precomputed for efficiency reasons. </summary>
private static readonly double LOG_2 = Math.Log(2);
/// <summary>
/// True if overlap tokens (tokens with a position of increment of zero) are
/// discounted from the document's length.
/// </summary>
private bool discountOverlaps = true; // LUCENENET Specific: made private, since it can be get/set through property
/// <summary>
/// Sole constructor. (For invocation by subclass
/// constructors, typically implicit.)
/// </summary>
protected SimilarityBase() // LUCENENET: CA1012: Abstract types should not have constructors (marked protected)
{
}
/// <summary>
/// Determines whether overlap tokens (Tokens with
/// 0 position increment) are ignored when computing
/// norm. By default this is <c>true</c>, meaning overlap
/// tokens do not count when computing norms.
/// <para/>
/// @lucene.experimental
/// </summary>
/// <seealso cref="ComputeNorm(FieldInvertState)"/>
public virtual bool DiscountOverlaps
{
get => discountOverlaps;
set => discountOverlaps = value;
}
public override sealed SimWeight ComputeWeight(float queryBoost, CollectionStatistics collectionStats, params TermStatistics[] termStats)
{
BasicStats[] stats = new BasicStats[termStats.Length];
for (int i = 0; i < termStats.Length; i++)
{
stats[i] = NewStats(collectionStats.Field, queryBoost);
FillBasicStats(stats[i], collectionStats, termStats[i]);
}
return stats.Length == 1 ? stats[0] : new MultiSimilarity.MultiStats(stats) as SimWeight;
}
/// <summary>
/// Factory method to return a custom stats object </summary>
protected internal virtual BasicStats NewStats(string field, float queryBoost)
{
return new BasicStats(field, queryBoost);
}
/// <summary>
/// Fills all member fields defined in <see cref="BasicStats"/> in <paramref name="stats"/>.
/// Subclasses can override this method to fill additional stats.
/// </summary>
protected internal virtual void FillBasicStats(BasicStats stats, CollectionStatistics collectionStats, TermStatistics termStats)
{
// #positions(field) must be >= #positions(term)
if (Debugging.AssertsEnabled) Debugging.Assert(collectionStats.SumTotalTermFreq == -1 || collectionStats.SumTotalTermFreq >= termStats.TotalTermFreq);
long numberOfDocuments = collectionStats.MaxDoc;
long docFreq = termStats.DocFreq;
long totalTermFreq = termStats.TotalTermFreq;
// codec does not supply totalTermFreq: substitute docFreq
if (totalTermFreq == -1)
{
totalTermFreq = docFreq;
}
long numberOfFieldTokens;
float avgFieldLength;
long sumTotalTermFreq = collectionStats.SumTotalTermFreq;
if (sumTotalTermFreq <= 0)
{
// field does not exist;
// We have to provide something if codec doesnt supply these measures,
// or if someone omitted frequencies for the field... negative values cause
// NaN/Inf for some scorers.
numberOfFieldTokens = docFreq;
avgFieldLength = 1;
}
else
{
numberOfFieldTokens = sumTotalTermFreq;
avgFieldLength = (float)numberOfFieldTokens / numberOfDocuments;
}
// TODO: add sumDocFreq for field (numberOfFieldPostings)
stats.NumberOfDocuments = numberOfDocuments;
stats.NumberOfFieldTokens = numberOfFieldTokens;
stats.AvgFieldLength = avgFieldLength;
stats.DocFreq = docFreq;
stats.TotalTermFreq = totalTermFreq;
}
/// <summary>
/// Scores the document <c>doc</c>.
/// <para>Subclasses must apply their scoring formula in this class.</para> </summary>
/// <param name="stats"> the corpus level statistics. </param>
/// <param name="freq"> the term frequency. </param>
/// <param name="docLen"> the document length. </param>
/// <returns> the score. </returns>
public abstract float Score(BasicStats stats, float freq, float docLen);
/// <summary>
/// Subclasses should implement this method to explain the score. <paramref name="expl"/>
/// already contains the score, the name of the class and the doc id, as well
/// as the term frequency and its explanation; subclasses can add additional
/// clauses to explain details of their scoring formulae.
/// <para>The default implementation does nothing.</para>
/// </summary>
/// <param name="expl"> the explanation to extend with details. </param>
/// <param name="stats"> the corpus level statistics. </param>
/// <param name="doc"> the document id. </param>
/// <param name="freq"> the term frequency. </param>
/// <param name="docLen"> the document length. </param>
protected internal virtual void Explain(Explanation expl, BasicStats stats, int doc, float freq, float docLen)
{
}
/// <summary>
/// Explains the score. The implementation here provides a basic explanation
/// in the format <em>Score(name-of-similarity, doc=doc-id,
/// freq=term-frequency), computed from:</em>, and
/// attaches the score (computed via the <see cref="Score(BasicStats, float, float)"/>
/// method) and the explanation for the term frequency. Subclasses content with
/// this format may add additional details in
/// <see cref="Explain(Explanation, BasicStats, int, float, float)"/>.
/// </summary>
/// <param name="stats"> the corpus level statistics. </param>
/// <param name="doc"> the document id. </param>
/// <param name="freq"> the term frequency and its explanation. </param>
/// <param name="docLen"> the document length. </param>
/// <returns> the explanation. </returns>
public virtual Explanation Explain(BasicStats stats, int doc, Explanation freq, float docLen)
{
Explanation result = new Explanation();
result.Value = Score(stats, freq.Value, docLen);
result.Description = "score(" + this.GetType().Name + ", doc=" + doc + ", freq=" + freq.Value + "), computed from:";
result.AddDetail(freq);
Explain(result, stats, doc, freq.Value, docLen);
return result;
}
public override SimScorer GetSimScorer(SimWeight stats, AtomicReaderContext context)
{
if (stats is MultiSimilarity.MultiStats multiStats)
{
// a multi term query (e.g. phrase). return the summation,
// scoring almost as if it were boolean query
SimWeight[] subStats = multiStats.subStats;
SimScorer[] subScorers = new SimScorer[subStats.Length];
for (int i = 0; i < subScorers.Length; i++)
{
BasicStats basicstats = (BasicStats)subStats[i];
subScorers[i] = new BasicSimScorer(this, basicstats, context.AtomicReader.GetNormValues(basicstats.Field));
}
return new MultiSimilarity.MultiSimScorer(subScorers);
}
else
{
BasicStats basicstats = (BasicStats)stats;
return new BasicSimScorer(this, basicstats, context.AtomicReader.GetNormValues(basicstats.Field));
}
}
/// <summary>
/// Subclasses must override this method to return the name of the <see cref="Similarity"/>
/// and preferably the values of parameters (if any) as well.
/// </summary>
public override abstract string ToString();
// ------------------------------ Norm handling ------------------------------
/// <summary>
/// Norm -> document length map. </summary>
private static readonly float[] NORM_TABLE = LoadNormTable();
private static float[] LoadNormTable() // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006)
{
float[] normTable = new float[256];
for (int i = 0; i < 256; i++)
{
float floatNorm = SmallSingle.SByte315ToSingle((sbyte)i);
normTable[i] = 1.0f / (floatNorm * floatNorm);
}
return normTable;
}
/// <summary>
/// Encodes the document length in the same way as <see cref="TFIDFSimilarity"/>. </summary>
public override long ComputeNorm(FieldInvertState state)
{
float numTerms;
if (discountOverlaps)
{
numTerms = state.Length - state.NumOverlap;
}
else
{
numTerms = state.Length;
}
return EncodeNormValue(state.Boost, numTerms);
}
/// <summary>
/// Decodes a normalization factor (document length) stored in an index. </summary>
/// <see cref="EncodeNormValue(float,float)"/>
protected internal virtual float DecodeNormValue(byte norm)
{
return NORM_TABLE[norm & 0xFF]; // & 0xFF maps negative bytes to positive above 127
}
/// <summary>
/// Encodes the length to a byte via <see cref="SmallSingle"/>. </summary>
protected internal virtual byte EncodeNormValue(float boost, float length)
{
return SmallSingle.SingleToByte315((boost / (float)Math.Sqrt(length)));
}
// ----------------------------- Static methods ------------------------------
/// <summary>
/// Returns the base two logarithm of <c>x</c>. </summary>
public static double Log2(double x)
{
// Put this to a 'util' class if we need more of these.
return Math.Log(x) / LOG_2;
}
// --------------------------------- Classes ---------------------------------
/// <summary>
/// Delegates the <see cref="Score(int, float)"/> and
/// <see cref="Explain(int, Explanation)"/> methods to
/// <see cref="SimilarityBase.Score(BasicStats, float, float)"/> and
/// <see cref="SimilarityBase.Explain(BasicStats, int, Explanation, float)"/>,
/// respectively.
/// </summary>
private class BasicSimScorer : SimScorer
{
private readonly SimilarityBase outerInstance;
private readonly BasicStats stats;
private readonly NumericDocValues norms;
internal BasicSimScorer(SimilarityBase outerInstance, BasicStats stats, NumericDocValues norms)
{
this.outerInstance = outerInstance;
this.stats = stats;
this.norms = norms;
}
public override float Score(int doc, float freq)
{
// We have to supply something in case norms are omitted
return outerInstance.Score(stats, freq, norms is null ? 1F : outerInstance.DecodeNormValue((byte)norms.Get(doc)));
}
public override Explanation Explain(int doc, Explanation freq)
{
return outerInstance.Explain(stats, doc, freq, norms is null ? 1F : outerInstance.DecodeNormValue((byte)norms.Get(doc)));
}
public override float ComputeSlopFactor(int distance)
{
return 1.0f / (distance + 1);
}
public override float ComputePayloadFactor(int doc, int start, int end, BytesRef payload)
{
return 1f;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Codecs.Lucene40
{
using Lucene.Net.Support;
using Bits = Lucene.Net.Util.Bits;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum;
using DocsEnum = Lucene.Net.Index.DocsEnum;
using FieldInfo = Lucene.Net.Index.FieldInfo;
using FieldInfos = Lucene.Net.Index.FieldInfos;
using Fields = Lucene.Net.Index.Fields;
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IndexInput = Lucene.Net.Store.IndexInput;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using SegmentInfo = Lucene.Net.Index.SegmentInfo;
using Terms = Lucene.Net.Index.Terms;
using TermsEnum = Lucene.Net.Index.TermsEnum;
/// <summary>
/// Lucene 4.0 Term Vectors reader.
/// <p>
/// It reads .tvd, .tvf, and .tvx files.
/// </summary>
/// <seealso cref= Lucene40TermVectorsFormat </seealso>
public class Lucene40TermVectorsReader : TermVectorsReader, IDisposable
{
internal const sbyte STORE_POSITIONS_WITH_TERMVECTOR = 0x1;
internal const sbyte STORE_OFFSET_WITH_TERMVECTOR = 0x2;
internal const sbyte STORE_PAYLOAD_WITH_TERMVECTOR = 0x4;
/// <summary>
/// Extension of vectors fields file </summary>
internal const string VECTORS_FIELDS_EXTENSION = "tvf";
/// <summary>
/// Extension of vectors documents file </summary>
internal const string VECTORS_DOCUMENTS_EXTENSION = "tvd";
/// <summary>
/// Extension of vectors index file </summary>
internal const string VECTORS_INDEX_EXTENSION = "tvx";
internal const string CODEC_NAME_FIELDS = "Lucene40TermVectorsFields";
internal const string CODEC_NAME_DOCS = "Lucene40TermVectorsDocs";
internal const string CODEC_NAME_INDEX = "Lucene40TermVectorsIndex";
internal const int VERSION_NO_PAYLOADS = 0;
internal const int VERSION_PAYLOADS = 1;
internal const int VERSION_START = VERSION_NO_PAYLOADS;
internal const int VERSION_CURRENT = VERSION_PAYLOADS;
internal static readonly long HEADER_LENGTH_FIELDS = CodecUtil.HeaderLength(CODEC_NAME_FIELDS);
internal static readonly long HEADER_LENGTH_DOCS = CodecUtil.HeaderLength(CODEC_NAME_DOCS);
internal static readonly long HEADER_LENGTH_INDEX = CodecUtil.HeaderLength(CODEC_NAME_INDEX);
private FieldInfos FieldInfos;
private IndexInput Tvx;
private IndexInput Tvd;
private IndexInput Tvf;
private int Size_Renamed;
private int NumTotalDocs;
/// <summary>
/// Used by clone. </summary>
internal Lucene40TermVectorsReader(FieldInfos fieldInfos, IndexInput tvx, IndexInput tvd, IndexInput tvf, int size, int numTotalDocs)
{
this.FieldInfos = fieldInfos;
this.Tvx = tvx;
this.Tvd = tvd;
this.Tvf = tvf;
this.Size_Renamed = size;
this.NumTotalDocs = numTotalDocs;
}
/// <summary>
/// Sole constructor. </summary>
public Lucene40TermVectorsReader(Directory d, SegmentInfo si, FieldInfos fieldInfos, IOContext context)
{
string segment = si.Name;
int size = si.DocCount;
bool success = false;
try
{
string idxName = IndexFileNames.SegmentFileName(segment, "", VECTORS_INDEX_EXTENSION);
Tvx = d.OpenInput(idxName, context);
int tvxVersion = CodecUtil.CheckHeader(Tvx, CODEC_NAME_INDEX, VERSION_START, VERSION_CURRENT);
string fn = IndexFileNames.SegmentFileName(segment, "", VECTORS_DOCUMENTS_EXTENSION);
Tvd = d.OpenInput(fn, context);
int tvdVersion = CodecUtil.CheckHeader(Tvd, CODEC_NAME_DOCS, VERSION_START, VERSION_CURRENT);
fn = IndexFileNames.SegmentFileName(segment, "", VECTORS_FIELDS_EXTENSION);
Tvf = d.OpenInput(fn, context);
int tvfVersion = CodecUtil.CheckHeader(Tvf, CODEC_NAME_FIELDS, VERSION_START, VERSION_CURRENT);
Debug.Assert(HEADER_LENGTH_INDEX == Tvx.FilePointer);
Debug.Assert(HEADER_LENGTH_DOCS == Tvd.FilePointer);
Debug.Assert(HEADER_LENGTH_FIELDS == Tvf.FilePointer);
Debug.Assert(tvxVersion == tvdVersion);
Debug.Assert(tvxVersion == tvfVersion);
NumTotalDocs = (int)(Tvx.Length() - HEADER_LENGTH_INDEX >> 4);
this.Size_Renamed = NumTotalDocs;
Debug.Assert(size == 0 || NumTotalDocs == size);
this.FieldInfos = fieldInfos;
success = true;
}
finally
{
// With lock-less commits, it's entirely possible (and
// fine) to hit a FileNotFound exception above. In
// this case, we want to explicitly close any subset
// of things that were opened so that we don't have to
// wait for a GC to do so.
if (!success)
{
try
{
Dispose();
} // ensure we throw our original exception
catch (Exception t)
{
}
}
}
}
// Used for bulk copy when merging
internal virtual IndexInput TvdStream
{
get
{
return Tvd;
}
}
// Used for bulk copy when merging
internal virtual IndexInput TvfStream
{
get
{
return Tvf;
}
}
// Not private to avoid synthetic access$NNN methods
internal virtual void SeekTvx(int docNum)
{
Tvx.Seek(docNum * 16L + HEADER_LENGTH_INDEX);
}
/// <summary>
/// Retrieve the length (in bytes) of the tvd and tvf
/// entries for the next numDocs starting with
/// startDocID. this is used for bulk copying when
/// merging segments, if the field numbers are
/// congruent. Once this returns, the tvf & tvd streams
/// are seeked to the startDocID.
/// </summary>
internal void RawDocs(int[] tvdLengths, int[] tvfLengths, int startDocID, int numDocs)
{
if (Tvx == null)
{
CollectionsHelper.Fill(tvdLengths, 0);
CollectionsHelper.Fill(tvfLengths, 0);
return;
}
SeekTvx(startDocID);
long tvdPosition = Tvx.ReadLong();
Tvd.Seek(tvdPosition);
long tvfPosition = Tvx.ReadLong();
Tvf.Seek(tvfPosition);
long lastTvdPosition = tvdPosition;
long lastTvfPosition = tvfPosition;
int count = 0;
while (count < numDocs)
{
int docID = startDocID + count + 1;
Debug.Assert(docID <= NumTotalDocs);
if (docID < NumTotalDocs)
{
tvdPosition = Tvx.ReadLong();
tvfPosition = Tvx.ReadLong();
}
else
{
tvdPosition = Tvd.Length();
tvfPosition = Tvf.Length();
Debug.Assert(count == numDocs - 1);
}
tvdLengths[count] = (int)(tvdPosition - lastTvdPosition);
tvfLengths[count] = (int)(tvfPosition - lastTvfPosition);
count++;
lastTvdPosition = tvdPosition;
lastTvfPosition = tvfPosition;
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
IOUtils.Close(Tvx, Tvd, Tvf);
}
///
/// <returns> The number of documents in the reader </returns>
internal virtual int Size()
{
return Size_Renamed;
}
private class TVFields : Fields
{
private readonly Lucene40TermVectorsReader OuterInstance;
internal readonly int[] FieldNumbers;
internal readonly long[] FieldFPs;
internal readonly IDictionary<int, int> FieldNumberToIndex = new Dictionary<int, int>();
public TVFields(Lucene40TermVectorsReader outerInstance, int docID)
{
this.OuterInstance = outerInstance;
outerInstance.SeekTvx(docID);
outerInstance.Tvd.Seek(outerInstance.Tvx.ReadLong());
int fieldCount = outerInstance.Tvd.ReadVInt();
Debug.Assert(fieldCount >= 0);
if (fieldCount != 0)
{
FieldNumbers = new int[fieldCount];
FieldFPs = new long[fieldCount];
for (int fieldUpto = 0; fieldUpto < fieldCount; fieldUpto++)
{
int fieldNumber = outerInstance.Tvd.ReadVInt();
FieldNumbers[fieldUpto] = fieldNumber;
FieldNumberToIndex[fieldNumber] = fieldUpto;
}
long position = outerInstance.Tvx.ReadLong();
FieldFPs[0] = position;
for (int fieldUpto = 1; fieldUpto < fieldCount; fieldUpto++)
{
position += outerInstance.Tvd.ReadVLong();
FieldFPs[fieldUpto] = position;
}
}
else
{
// TODO: we can improve writer here, eg write 0 into
// tvx file, so we know on first read from tvx that
// this doc has no TVs
FieldNumbers = null;
FieldFPs = null;
}
}
public override IEnumerator<string> GetEnumerator()
{
return GetFieldInfoEnumerable().GetEnumerator();
}
private IEnumerable<string> GetFieldInfoEnumerable()
{
int fieldUpto = 0;
while (FieldNumbers != null && fieldUpto < FieldNumbers.Length)
{
yield return OuterInstance.FieldInfos.FieldInfo(FieldNumbers[fieldUpto++]).Name;
}
}
public override Terms Terms(string field)
{
FieldInfo fieldInfo = OuterInstance.FieldInfos.FieldInfo(field);
if (fieldInfo == null)
{
// No such field
return null;
}
int fieldIndex;
if (!FieldNumberToIndex.TryGetValue(fieldInfo.Number, out fieldIndex))
{
// Term vectors were not indexed for this field
return null;
}
return new TVTerms(OuterInstance, FieldFPs[fieldIndex]);
}
public override int Size
{
get
{
if (FieldNumbers == null)
{
return 0;
}
else
{
return FieldNumbers.Length;
}
}
}
}
private class TVTerms : Terms
{
private readonly Lucene40TermVectorsReader OuterInstance;
internal readonly int NumTerms;
internal readonly long TvfFPStart;
internal readonly bool StorePositions;
internal readonly bool StoreOffsets;
internal readonly bool StorePayloads;
public TVTerms(Lucene40TermVectorsReader outerInstance, long tvfFP)
{
this.OuterInstance = outerInstance;
outerInstance.Tvf.Seek(tvfFP);
NumTerms = outerInstance.Tvf.ReadVInt();
byte bits = outerInstance.Tvf.ReadByte();
StorePositions = (bits & STORE_POSITIONS_WITH_TERMVECTOR) != 0;
StoreOffsets = (bits & STORE_OFFSET_WITH_TERMVECTOR) != 0;
StorePayloads = (bits & STORE_PAYLOAD_WITH_TERMVECTOR) != 0;
TvfFPStart = outerInstance.Tvf.FilePointer;
}
public override TermsEnum Iterator(TermsEnum reuse)
{
TVTermsEnum termsEnum;
if (reuse is TVTermsEnum)
{
termsEnum = (TVTermsEnum)reuse;
if (!termsEnum.CanReuse(OuterInstance.Tvf))
{
termsEnum = new TVTermsEnum(OuterInstance);
}
}
else
{
termsEnum = new TVTermsEnum(OuterInstance);
}
termsEnum.Reset(NumTerms, TvfFPStart, StorePositions, StoreOffsets, StorePayloads);
return termsEnum;
}
public override long Size()
{
return NumTerms;
}
public override long SumTotalTermFreq
{
get
{
return -1;
}
}
public override long SumDocFreq
{
get
{
// Every term occurs in just one doc:
return NumTerms;
}
}
public override int DocCount
{
get
{
return 1;
}
}
public override IComparer<BytesRef> Comparator
{
get
{
// TODO: really indexer hardwires
// this...? I guess codec could buffer and re-sort...
return BytesRef.UTF8SortedAsUnicodeComparer;
}
}
public override bool HasFreqs()
{
return true;
}
public override bool HasOffsets()
{
return StoreOffsets;
}
public override bool HasPositions()
{
return StorePositions;
}
public override bool HasPayloads()
{
return StorePayloads;
}
}
private class TVTermsEnum : TermsEnum
{
private readonly Lucene40TermVectorsReader OuterInstance;
private readonly IndexInput OrigTVF;
private readonly IndexInput Tvf;
private int NumTerms;
private int NextTerm;
private int Freq;
private readonly BytesRef LastTerm = new BytesRef();
private readonly BytesRef Term_Renamed = new BytesRef();
private bool StorePositions;
private bool StoreOffsets;
private bool StorePayloads;
private long TvfFP;
internal int[] Positions;
internal int[] StartOffsets;
internal int[] EndOffsets;
// one shared byte[] for any term's payloads
internal int[] PayloadOffsets;
internal int LastPayloadLength;
internal byte[] PayloadData;
// NOTE: tvf is pre-positioned by caller
public TVTermsEnum(Lucene40TermVectorsReader outerInstance)
{
this.OuterInstance = outerInstance;
this.OrigTVF = outerInstance.Tvf;
Tvf = (IndexInput)OrigTVF.Clone();
}
public virtual bool CanReuse(IndexInput tvf)
{
return tvf == OrigTVF;
}
public virtual void Reset(int numTerms, long tvfFPStart, bool storePositions, bool storeOffsets, bool storePayloads)
{
this.NumTerms = numTerms;
this.StorePositions = storePositions;
this.StoreOffsets = storeOffsets;
this.StorePayloads = storePayloads;
NextTerm = 0;
Tvf.Seek(tvfFPStart);
TvfFP = tvfFPStart;
Positions = null;
StartOffsets = null;
EndOffsets = null;
PayloadOffsets = null;
PayloadData = null;
LastPayloadLength = -1;
}
// NOTE: slow! (linear scan)
public override SeekStatus SeekCeil(BytesRef text)
{
if (NextTerm != 0)
{
int cmp = text.CompareTo(Term_Renamed);
if (cmp < 0)
{
NextTerm = 0;
Tvf.Seek(TvfFP);
}
else if (cmp == 0)
{
return SeekStatus.FOUND;
}
}
while (Next() != null)
{
int cmp = text.CompareTo(Term_Renamed);
if (cmp < 0)
{
return SeekStatus.NOT_FOUND;
}
else if (cmp == 0)
{
return SeekStatus.FOUND;
}
}
return SeekStatus.END;
}
public override void SeekExact(long ord)
{
throw new System.NotSupportedException();
}
public override BytesRef Next()
{
if (NextTerm >= NumTerms)
{
return null;
}
Term_Renamed.CopyBytes(LastTerm);
int start = Tvf.ReadVInt();
int deltaLen = Tvf.ReadVInt();
Term_Renamed.Length = start + deltaLen;
Term_Renamed.Grow(Term_Renamed.Length);
Tvf.ReadBytes(Term_Renamed.Bytes, start, deltaLen);
Freq = Tvf.ReadVInt();
if (StorePayloads)
{
Positions = new int[Freq];
PayloadOffsets = new int[Freq];
int totalPayloadLength = 0;
int pos = 0;
for (int posUpto = 0; posUpto < Freq; posUpto++)
{
int code = Tvf.ReadVInt();
pos += (int)((uint)code >> 1);
Positions[posUpto] = pos;
if ((code & 1) != 0)
{
// length change
LastPayloadLength = Tvf.ReadVInt();
}
PayloadOffsets[posUpto] = totalPayloadLength;
totalPayloadLength += LastPayloadLength;
Debug.Assert(totalPayloadLength >= 0);
}
PayloadData = new byte[totalPayloadLength];
Tvf.ReadBytes(PayloadData, 0, PayloadData.Length);
} // no payloads
else if (StorePositions)
{
// TODO: we could maybe reuse last array, if we can
// somehow be careful about consumer never using two
// D&PEnums at once...
Positions = new int[Freq];
int pos = 0;
for (int posUpto = 0; posUpto < Freq; posUpto++)
{
pos += Tvf.ReadVInt();
Positions[posUpto] = pos;
}
}
if (StoreOffsets)
{
StartOffsets = new int[Freq];
EndOffsets = new int[Freq];
int offset = 0;
for (int posUpto = 0; posUpto < Freq; posUpto++)
{
StartOffsets[posUpto] = offset + Tvf.ReadVInt();
offset = EndOffsets[posUpto] = StartOffsets[posUpto] + Tvf.ReadVInt();
}
}
LastTerm.CopyBytes(Term_Renamed);
NextTerm++;
return Term_Renamed;
}
public override BytesRef Term()
{
return Term_Renamed;
}
public override long Ord()
{
throw new System.NotSupportedException();
}
public override int DocFreq()
{
return 1;
}
public override long TotalTermFreq()
{
return Freq;
}
public override DocsEnum Docs(Bits liveDocs, DocsEnum reuse, int flags) // ignored
{
TVDocsEnum docsEnum;
if (reuse != null && reuse is TVDocsEnum)
{
docsEnum = (TVDocsEnum)reuse;
}
else
{
docsEnum = new TVDocsEnum();
}
docsEnum.Reset(liveDocs, Freq);
return docsEnum;
}
public override DocsAndPositionsEnum DocsAndPositions(Bits liveDocs, DocsAndPositionsEnum reuse, int flags)
{
if (!StorePositions && !StoreOffsets)
{
return null;
}
TVDocsAndPositionsEnum docsAndPositionsEnum;
if (reuse != null && reuse is TVDocsAndPositionsEnum)
{
docsAndPositionsEnum = (TVDocsAndPositionsEnum)reuse;
}
else
{
docsAndPositionsEnum = new TVDocsAndPositionsEnum();
}
docsAndPositionsEnum.Reset(liveDocs, Positions, StartOffsets, EndOffsets, PayloadOffsets, PayloadData);
return docsAndPositionsEnum;
}
public override IComparer<BytesRef> Comparator
{
get
{
return BytesRef.UTF8SortedAsUnicodeComparer;
}
}
}
// NOTE: sort of a silly class, since you can get the
// freq() already by TermsEnum.totalTermFreq
private class TVDocsEnum : DocsEnum
{
internal bool DidNext;
internal int Doc = -1;
internal int Freq_Renamed;
internal Bits LiveDocs;
public override int Freq()
{
return Freq_Renamed;
}
public override int DocID()
{
return Doc;
}
public override int NextDoc()
{
if (!DidNext && (LiveDocs == null || LiveDocs.Get(0)))
{
DidNext = true;
return (Doc = 0);
}
else
{
return (Doc = NO_MORE_DOCS);
}
}
public override int Advance(int target)
{
return SlowAdvance(target);
}
public virtual void Reset(Bits liveDocs, int freq)
{
this.LiveDocs = liveDocs;
this.Freq_Renamed = freq;
this.Doc = -1;
DidNext = false;
}
public override long Cost()
{
return 1;
}
}
private sealed class TVDocsAndPositionsEnum : DocsAndPositionsEnum
{
private bool DidNext;
private int Doc = -1;
private int NextPos;
private Bits LiveDocs;
private int[] Positions;
private int[] StartOffsets;
private int[] EndOffsets;
private int[] PayloadOffsets;
private readonly BytesRef Payload_Renamed = new BytesRef();
private byte[] PayloadBytes;
public override int Freq()
{
if (Positions != null)
{
return Positions.Length;
}
else
{
Debug.Assert(StartOffsets != null);
return StartOffsets.Length;
}
}
public override int DocID()
{
return Doc;
}
public override int NextDoc()
{
if (!DidNext && (LiveDocs == null || LiveDocs.Get(0)))
{
DidNext = true;
return (Doc = 0);
}
else
{
return (Doc = NO_MORE_DOCS);
}
}
public override int Advance(int target)
{
return SlowAdvance(target);
}
public void Reset(Bits liveDocs, int[] positions, int[] startOffsets, int[] endOffsets, int[] payloadLengths, byte[] payloadBytes)
{
this.LiveDocs = liveDocs;
this.Positions = positions;
this.StartOffsets = startOffsets;
this.EndOffsets = endOffsets;
this.PayloadOffsets = payloadLengths;
this.PayloadBytes = payloadBytes;
this.Doc = -1;
DidNext = false;
NextPos = 0;
}
public override BytesRef Payload
{
get
{
if (PayloadOffsets == null)
{
return null;
}
else
{
int off = PayloadOffsets[NextPos - 1];
int end = NextPos == PayloadOffsets.Length ? PayloadBytes.Length : PayloadOffsets[NextPos];
if (end - off == 0)
{
return null;
}
Payload_Renamed.Bytes = PayloadBytes;
Payload_Renamed.Offset = off;
Payload_Renamed.Length = end - off;
return Payload_Renamed;
}
}
}
public override int NextPosition()
{
Debug.Assert((Positions != null && NextPos < Positions.Length) || StartOffsets != null && NextPos < StartOffsets.Length);
if (Positions != null)
{
return Positions[NextPos++];
}
else
{
NextPos++;
return -1;
}
}
public override int StartOffset()
{
if (StartOffsets == null)
{
return -1;
}
else
{
return StartOffsets[NextPos - 1];
}
}
public override int EndOffset()
{
if (EndOffsets == null)
{
return -1;
}
else
{
return EndOffsets[NextPos - 1];
}
}
public override long Cost()
{
return 1;
}
}
public override Fields Get(int docID)
{
if (Tvx != null)
{
Fields fields = new TVFields(this, docID);
if (fields.Size == 0)
{
// TODO: we can improve writer here, eg write 0 into
// tvx file, so we know on first read from tvx that
// this doc has no TVs
return null;
}
else
{
return fields;
}
}
else
{
return null;
}
}
public override object Clone()
{
IndexInput cloneTvx = null;
IndexInput cloneTvd = null;
IndexInput cloneTvf = null;
// These are null when a TermVectorsReader was created
// on a segment that did not have term vectors saved
if (Tvx != null && Tvd != null && Tvf != null)
{
cloneTvx = (IndexInput)Tvx.Clone();
cloneTvd = (IndexInput)Tvd.Clone();
cloneTvf = (IndexInput)Tvf.Clone();
}
return new Lucene40TermVectorsReader(FieldInfos, cloneTvx, cloneTvd, cloneTvf, Size_Renamed, NumTotalDocs);
}
public override long RamBytesUsed()
{
return 0;
}
public override void CheckIntegrity()
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
internal partial class Interop
{
//
// These structures define the layout of CNG key blobs passed to NCryptImportKey
//
internal partial class BCrypt
{
/// <summary>
/// Append "value" to the data already in blob.
/// </summary>
internal static void Emit(byte[] blob, ref int offset, byte[] value)
{
Debug.Assert(blob != null);
Debug.Assert(offset >= 0);
Buffer.BlockCopy(value, 0, blob, offset, value.Length);
offset += value.Length;
}
/// <summary>
/// Append "value" to the data already in blob.
/// </summary>
internal static void EmitByte(byte[] blob, ref int offset, byte value, int count = 1)
{
Debug.Assert(blob != null);
Debug.Assert(offset >= 0);
Debug.Assert(count > 0);
int finalOffset = offset + count;
for (int i = offset; i < finalOffset; i++)
{
blob[i] = value;
}
offset = finalOffset;
}
/// <summary>
/// Append "value" in big Endian format to the data already in blob.
/// </summary>
internal static void EmitBigEndian(byte[] blob, ref int offset, int value)
{
Debug.Assert(blob != null);
Debug.Assert(offset >= 0);
blob[offset++] = ((byte)(value >> 24));
blob[offset++] = ((byte)(value >> 16));
blob[offset++] = ((byte)(value >> 8));
blob[offset++] = ((byte)(value));
}
/// <summary>
/// Peel off the next "count" bytes in blob and return them in a byte array.
/// </summary>
internal static byte[] Consume(byte[] blob, ref int offset, int count)
{
byte[] value = new byte[count];
Buffer.BlockCopy(blob, offset, value, 0, count);
offset += count;
return value;
}
/// <summary>
/// Magic numbers identifying blob types
/// </summary>
internal enum KeyBlobMagicNumber : int
{
BCRYPT_DSA_PUBLIC_MAGIC = 0x42505344,
BCRYPT_DSA_PRIVATE_MAGIC = 0x56505344,
BCRYPT_DSA_PUBLIC_MAGIC_V2 = 0x32425044,
BCRYPT_DSA_PRIVATE_MAGIC_V2 = 0x32565044,
BCRYPT_ECDH_PUBLIC_P256_MAGIC = 0x314B4345,
BCRYPT_ECDH_PRIVATE_P256_MAGIC = 0x324B4345,
BCRYPT_ECDH_PUBLIC_P384_MAGIC = 0x334B4345,
BCRYPT_ECDH_PRIVATE_P384_MAGIC = 0x344B4345,
BCRYPT_ECDH_PUBLIC_P521_MAGIC = 0x354B4345,
BCRYPT_ECDH_PRIVATE_P521_MAGIC = 0x364B4345,
BCRYPT_ECDH_PUBLIC_GENERIC_MAGIC = 0x504B4345,
BCRYPT_ECDH_PRIVATE_GENERIC_MAGIC = 0x564B4345,
BCRYPT_ECDSA_PUBLIC_P256_MAGIC = 0x31534345,
BCRYPT_ECDSA_PRIVATE_P256_MAGIC = 0x32534345,
BCRYPT_ECDSA_PUBLIC_P384_MAGIC = 0x33534345,
BCRYPT_ECDSA_PRIVATE_P384_MAGIC = 0x34534345,
BCRYPT_ECDSA_PUBLIC_P521_MAGIC = 0x35534345,
BCRYPT_ECDSA_PRIVATE_P521_MAGIC = 0x36534345,
BCRYPT_ECDSA_PUBLIC_GENERIC_MAGIC = 0x50444345,
BCRYPT_ECDSA_PRIVATE_GENERIC_MAGIC = 0x56444345,
BCRYPT_RSAPUBLIC_MAGIC = 0x31415352,
BCRYPT_RSAPRIVATE_MAGIC = 0x32415352,
BCRYPT_RSAFULLPRIVATE_MAGIC = 0x33415352,
BCRYPT_KEY_DATA_BLOB_MAGIC = 0x4d42444b,
}
/// <summary>
/// Well known key blob types
/// </summary>
internal static class KeyBlobType
{
internal const string BCRYPT_PUBLIC_KEY_BLOB = "PUBLICBLOB";
internal const string BCRYPT_PRIVATE_KEY_BLOB = "PRIVATEBLOB";
internal const string BCRYPT_RSAFULLPRIVATE_BLOB = "RSAFULLPRIVATEBLOB";
internal const string BCRYPT_RSAPRIVATE_BLOB = "RSAPRIVATEBLOB";
internal const string BCRYPT_RSAPUBLIC_KEY_BLOB = "RSAPUBLICBLOB";
internal const string BCRYPT_DSA_PUBLIC_BLOB = "DSAPUBLICBLOB";
internal const string BCRYPT_DSA_PRIVATE_BLOB = "DSAPRIVATEBLOB";
internal const string LEGACY_DSA_V2_PUBLIC_BLOB = "V2CAPIDSAPUBLICBLOB";
internal const string LEGACY_DSA_V2_PRIVATE_BLOB = "V2CAPIDSAPRIVATEBLOB";
internal const string BCRYPT_ECCPUBLIC_BLOB = "ECCPUBLICBLOB";
internal const string BCRYPT_ECCPRIVATE_BLOB = "ECCPRIVATEBLOB";
internal const string BCRYPT_ECCFULLPUBLIC_BLOB = "ECCFULLPUBLICBLOB";
internal const string BCRYPT_ECCFULLPRIVATE_BLOB = "ECCFULLPRIVATEBLOB";
}
/// <summary>
/// The BCRYPT_RSAKEY_BLOB structure is used as a header for an RSA public key or private key BLOB in memory.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct BCRYPT_RSAKEY_BLOB
{
internal KeyBlobMagicNumber Magic;
internal int BitLength;
internal int cbPublicExp;
internal int cbModulus;
internal int cbPrime1;
internal int cbPrime2;
}
/// <summary>
/// The BCRYPT_DSA_KEY_BLOB structure is used as a v1 header for a DSA public key or private key BLOB in memory.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
unsafe internal struct BCRYPT_DSA_KEY_BLOB
{
internal KeyBlobMagicNumber Magic;
internal int cbKey;
internal fixed byte Count[4];
internal fixed byte Seed[20];
internal fixed byte q[20];
}
/// <summary>
/// The BCRYPT_DSA_KEY_BLOB structure is used as a v2 header for a DSA public key or private key BLOB in memory.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
unsafe internal struct BCRYPT_DSA_KEY_BLOB_V2
{
internal KeyBlobMagicNumber Magic;
internal int cbKey;
internal HASHALGORITHM_ENUM hashAlgorithm;
internal DSAFIPSVERSION_ENUM standardVersion;
internal int cbSeedLength;
internal int cbGroupSize;
internal fixed byte Count[4];
}
public enum HASHALGORITHM_ENUM
{
DSA_HASH_ALGORITHM_SHA1 = 0,
DSA_HASH_ALGORITHM_SHA256 = 1,
DSA_HASH_ALGORITHM_SHA512 = 2,
}
public enum DSAFIPSVERSION_ENUM
{
DSA_FIPS186_2 = 0,
DSA_FIPS186_3 = 1,
}
/// <summary>
/// The BCRYPT_ECCKEY_BLOB structure is used as a header for an ECC public key or private key BLOB in memory.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct BCRYPT_ECCKEY_BLOB
{
internal KeyBlobMagicNumber Magic;
internal int cbKey;
}
/// <summary>
/// Represents the type of curve.
/// </summary>
internal enum ECC_CURVE_TYPE_ENUM : int
{
BCRYPT_ECC_PRIME_SHORT_WEIERSTRASS_CURVE = 0x1,
BCRYPT_ECC_PRIME_TWISTED_EDWARDS_CURVE = 0x2,
BCRYPT_ECC_PRIME_MONTGOMERY_CURVE = 0x3,
}
/// <summary>
/// Represents the algorithm that was used with Seed to generate A and B.
/// </summary>
internal enum ECC_CURVE_ALG_ID_ENUM : int
{
BCRYPT_NO_CURVE_GENERATION_ALG_ID = 0x0,
}
/// <summary>
/// Used as a header to curve parameters including the public and potentially private key.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct BCRYPT_ECCFULLKEY_BLOB
{
internal KeyBlobMagicNumber Magic;
internal int Version; //Version of the structure
internal ECC_CURVE_TYPE_ENUM CurveType; //Supported curve types.
internal ECC_CURVE_ALG_ID_ENUM CurveGenerationAlgId; //For X.592 verification purposes, if we include Seed we will need to include the algorithm ID.
internal int cbFieldLength; //Byte length of the fields P, A, B, X, Y.
internal int cbSubgroupOrder; //Byte length of the subgroup.
internal int cbCofactor; //Byte length of cofactor of G in E.
internal int cbSeed; //Byte length of the seed used to generate the curve.
// The rest of the buffer contains the domain parameters
}
/// <summary>
/// NCrypt buffer descriptors
/// </summary>
internal enum NCryptBufferDescriptors : int
{
NCRYPTBUFFER_ECC_CURVE_NAME = 60,
}
/// <summary>
/// BCrypt buffer
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct BCryptBuffer
{
internal int cbBuffer; // Length of buffer, in bytes
internal NCryptBufferDescriptors BufferType; // Buffer type
internal IntPtr pvBuffer; // Pointer to buffer
}
/// <summary>
/// The version of BCryptBuffer
/// </summary>
internal const int BCRYPTBUFFER_VERSION = 0;
/// <summary>
/// Contains a set of generic CNG buffers.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct BCryptBufferDesc
{
internal int ulVersion; // Version number
internal int cBuffers; // Number of buffers
internal IntPtr pBuffers; // Pointer to array of BCryptBuffers
}
/// <summary>
/// The version of BCRYPT_ECC_PARAMETER_HEADER
/// </summary>
internal const int BCRYPT_ECC_PARAMETER_HEADER_V1 = 1;
/// <summary>
/// Used as a header to curve parameters.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct BCRYPT_ECC_PARAMETER_HEADER
{
internal int Version; //Version of the structure
internal ECC_CURVE_TYPE_ENUM CurveType; //Supported curve types.
internal ECC_CURVE_ALG_ID_ENUM CurveGenerationAlgId; //For X.592 verification purposes, if we include Seed we will need to include the algorithm ID.
internal int cbFieldLength; //Byte length of the fields P, A, B, X, Y.
internal int cbSubgroupOrder; //Byte length of the subgroup.
internal int cbCofactor; //Byte length of cofactor of G in E.
internal int cbSeed; //Byte length of the seed used to generate the curve.
// The rest of the buffer contains the domain parameters
}
}
}
| |
//
// Manager.cs
//
// Author:
// Alex Launi <[email protected]>
//
// Copyright (c) 2010 Alex Launi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if ENABLE_GIO_HARDWARE
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using GLib;
using GUdev;
using System.Runtime.InteropServices;
using Banshee.Hardware;
namespace Banshee.Hardware.Gio
{
public class Manager : IEnumerable<IDevice>, IDisposable
{
private readonly string[] subsystems = new string[] {"block", "usb"};
private Client client;
private VolumeMonitor monitor;
private Dictionary<string, string> device_uuids;
public event EventHandler<MountArgs> DeviceAdded;
public event EventHandler<MountArgs> DeviceRemoved;
public Manager ()
{
device_uuids = new Dictionary<string, string> ();
client = new Client (subsystems);
monitor = VolumeMonitor.Default;
monitor.MountAdded += HandleMonitorMountAdded;
monitor.MountRemoved += HandleMonitorMountRemoved;
monitor.VolumeRemoved += HandleMonitorVolumeRemoved;
}
#region IDisposable
public void Dispose ()
{
client.Dispose ();
monitor.Dispose ();
}
#endregion
void HandleMonitorMountAdded (object o, MountAddedArgs args)
{
// Manually get the mount as gio-sharp translates it to the wrong managed object
var mount = GLib.MountAdapter.GetObject ((GLib.Object) args.Args [0]);
if (mount.Volume == null)
return;
var device = GudevDeviceFromGioMount (mount);
var h = DeviceAdded;
if (h != null) {
var v = new RawVolume (mount.Volume,
this,
new GioVolumeMetadataSource (mount.Volume),
new UdevMetadataSource (device));
h (this, new MountArgs (HardwareManager.Resolve (new Device (v))));
device_uuids [mount.Volume.Name] = v.Uuid;
}
}
void HandleMonitorMountRemoved (object o, MountRemovedArgs args)
{
// Manually get the mount as gio-sharp translates it to the wrong managed object
var mount = GLib.MountAdapter.GetObject ((GLib.Object) args.Args [0]);
if (mount.Volume == null || mount.Root == null || mount.Root.Path == null) {
return;
}
VolumeRemoved (mount.Volume);
}
void HandleMonitorVolumeRemoved (object o, VolumeRemovedArgs args)
{
var volume = GLib.VolumeAdapter.GetObject ((GLib.Object) args.Args [0]);
if (volume == null) {
return;
}
VolumeRemoved (volume);
}
void VolumeRemoved (GLib.Volume volume)
{
var h = DeviceRemoved;
if (h != null) {
var device = GudevDeviceFromGioVolume (volume);
var v = new RawVolume (volume,
this,
new GioVolumeMetadataSource (volume),
new UdevMetadataSource (device));
if (device_uuids.ContainsKey (volume.Name)) {
v.Uuid = device_uuids [volume.Name];
device_uuids.Remove (volume.Name);
}
h (this, new MountArgs (new Device (v)));
}
}
public IEnumerable<IDevice> GetAllDevices ()
{
foreach (GLib.Volume vol in monitor.Volumes) {
var device = GudevDeviceFromGioVolume (vol);
if (device == null) {
continue;
}
var raw = new RawVolume (vol,
this,
new GioVolumeMetadataSource (vol),
new UdevMetadataSource (device));
yield return HardwareManager.Resolve (new Device (raw));
}
}
public GUdev.Device GudevDeviceFromSubsystemPropertyValue (string sub, string prop, string val)
{
foreach (GUdev.Device dev in client.QueryBySubsystem (sub)) {
if (dev.HasProperty (prop) && dev.GetProperty (prop) == val)
return dev;
}
return null;
}
public GUdev.Device GudevDeviceFromGioDrive (GLib.Drive drive)
{
GUdev.Device device = null;
if (drive == null) {
return null;
}
string devFile = drive.GetIdentifier ("unix-device");
if (!String.IsNullOrEmpty (devFile)) {
device = client.QueryByDeviceFile (devFile);
}
return device;
}
public GUdev.Device GudevDeviceFromGioVolume (GLib.Volume volume)
{
GUdev.Device device = null;
if (volume == null) {
return null;
}
var s = volume.GetIdentifier ("unix-device");
if (!String.IsNullOrEmpty (s)) {
device = client.QueryByDeviceFile (s);
}
if (device == null) {
s = volume.Uuid;
foreach (GUdev.Device d in client.QueryBySubsystem ("usb")) {
if (s == d.GetSysfsAttr ("serial")) {
device = d;
break;
}
}
}
return device;
}
public GUdev.Device GudevDeviceFromGioMount (GLib.Mount mount)
{
if (mount == null) {
return null;
}
return GudevDeviceFromGioVolume (mount.Volume);
}
#region IEnumerable
public IEnumerator<IDevice> GetEnumerator ()
{
foreach (var device in GetAllDevices ())
yield return device;
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
#endregion
}
public class MountArgs : EventArgs
{
public IDevice Device {
get; private set;
}
public MountArgs (IDevice device)
{
Device = device;
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Xml;
using System.Security;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Runtime.Serialization.DataContract>;
#if !NET_NATIVE
using ExtensionDataObject = System.Object;
#endif
namespace System.Runtime.Serialization.Json
{
#if NET_NATIVE
public class XmlObjectSerializerReadContextComplexJson : XmlObjectSerializerReadContextComplex
#else
internal class XmlObjectSerializerReadContextComplexJson : XmlObjectSerializerReadContextComplex
#endif
{
private DataContractJsonSerializer _jsonSerializer;
private DateTimeFormat _dateTimeFormat;
private bool _useSimpleDictionaryFormat;
public XmlObjectSerializerReadContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract)
: base(null, int.MaxValue, new StreamingContext(), true)
{
this.rootTypeDataContract = rootTypeDataContract;
this.serializerKnownTypeList = serializer.KnownTypes;
_jsonSerializer = serializer;
}
internal XmlObjectSerializerReadContextComplexJson(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract)
: base(serializer, serializer.MaxItemsInObjectGraph, new StreamingContext(), false)
{
this.rootTypeDataContract = rootTypeDataContract;
this.serializerKnownTypeList = serializer.knownTypeList;
_dateTimeFormat = serializer.DateTimeFormat;
_useSimpleDictionaryFormat = serializer.UseSimpleDictionaryFormat;
}
internal static XmlObjectSerializerReadContextComplexJson CreateContext(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract)
{
return new XmlObjectSerializerReadContextComplexJson(serializer, rootTypeDataContract);
}
protected override object ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
{
return DataContractJsonSerializerImpl.ReadJsonValue(dataContract, reader, this);
}
public int GetJsonMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, int memberIndex, ExtensionDataObject extensionData)
{
int length = memberNames.Length;
if (length != 0)
{
for (int i = 0, index = (memberIndex + 1) % length; i < length; i++, index = (index + 1) % length)
{
if (xmlReader.IsStartElement(memberNames[index], XmlDictionaryString.Empty))
{
return index;
}
}
string name;
if (TryGetJsonLocalName(xmlReader, out name))
{
for (int i = 0, index = (memberIndex + 1) % length; i < length; i++, index = (index + 1) % length)
{
if (memberNames[index].Value == name)
{
return index;
}
}
}
}
HandleMemberNotFound(xmlReader, extensionData, memberIndex);
return length;
}
internal IList<Type> SerializerKnownTypeList
{
get
{
return this.serializerKnownTypeList;
}
}
public bool UseSimpleDictionaryFormat
{
get
{
return _useSimpleDictionaryFormat;
}
}
internal override void ReadAttributes(XmlReaderDelegator xmlReader)
{
if (attributes == null)
attributes = new Attributes();
attributes.Reset();
if (xmlReader.MoveToAttribute(JsonGlobals.typeString) && xmlReader.Value == JsonGlobals.nullString)
{
attributes.XsiNil = true;
}
else if (xmlReader.MoveToAttribute(JsonGlobals.serverTypeString))
{
XmlQualifiedName qualifiedTypeName = JsonReaderDelegator.ParseQualifiedName(xmlReader.Value);
attributes.XsiTypeName = qualifiedTypeName.Name;
string serverTypeNamespace = qualifiedTypeName.Namespace;
if (!string.IsNullOrEmpty(serverTypeNamespace))
{
switch (serverTypeNamespace[0])
{
case '#':
serverTypeNamespace = string.Concat(Globals.DataContractXsdBaseNamespace, serverTypeNamespace.Substring(1));
break;
case '\\':
if (serverTypeNamespace.Length >= 2)
{
switch (serverTypeNamespace[1])
{
case '#':
case '\\':
serverTypeNamespace = serverTypeNamespace.Substring(1);
break;
default:
break;
}
}
break;
default:
break;
}
}
attributes.XsiTypeNamespace = serverTypeNamespace;
}
xmlReader.MoveToElement();
}
internal DataContract ResolveDataContractFromType(string typeName, string typeNs, DataContract memberTypeContract)
{
this.PushKnownTypes(this.rootTypeDataContract);
this.PushKnownTypes(memberTypeContract);
XmlQualifiedName qname = ParseQualifiedName(typeName);
DataContract contract = ResolveDataContractFromKnownTypes(qname.Name, TrimNamespace(qname.Namespace), memberTypeContract);
this.PopKnownTypes(this.rootTypeDataContract);
this.PopKnownTypes(memberTypeContract);
return contract;
}
internal void CheckIfTypeNeedsVerifcation(DataContract declaredContract, DataContract runtimeContract)
{
bool verifyType = true;
CollectionDataContract collectionContract = declaredContract as CollectionDataContract;
if (collectionContract != null && collectionContract.UnderlyingType.GetTypeInfo().IsInterface)
{
switch (collectionContract.Kind)
{
case CollectionKind.Dictionary:
case CollectionKind.GenericDictionary:
verifyType = declaredContract.Name == runtimeContract.Name;
break;
default:
Type t = collectionContract.ItemType.MakeArrayType();
verifyType = (t != runtimeContract.UnderlyingType);
break;
}
}
if (verifyType)
{
this.PushKnownTypes(declaredContract);
VerifyType(runtimeContract);
this.PopKnownTypes(declaredContract);
}
}
internal void VerifyType(DataContract dataContract)
{
DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/);
if (knownContract == null || knownContract.UnderlyingType != dataContract.UnderlyingType)
{
throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace)));
}
}
internal string TrimNamespace(string serverTypeNamespace)
{
if (!string.IsNullOrEmpty(serverTypeNamespace))
{
switch (serverTypeNamespace[0])
{
case '#':
serverTypeNamespace = string.Concat(Globals.DataContractXsdBaseNamespace, serverTypeNamespace.Substring(1));
break;
case '\\':
if (serverTypeNamespace.Length >= 2)
{
switch (serverTypeNamespace[1])
{
case '#':
case '\\':
serverTypeNamespace = serverTypeNamespace.Substring(1);
break;
default:
break;
}
}
break;
default:
break;
}
}
return serverTypeNamespace;
}
internal static XmlQualifiedName ParseQualifiedName(string qname)
{
string name, ns;
if (string.IsNullOrEmpty(qname))
{
name = ns = String.Empty;
}
else
{
qname = qname.Trim();
int colon = qname.IndexOf(':');
if (colon >= 0)
{
name = qname.Substring(0, colon);
ns = qname.Substring(colon + 1);
}
else
{
name = qname;
ns = string.Empty;
}
}
return new XmlQualifiedName(name, ns);
}
internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type)
{
DataContract dataContract = base.GetDataContract(typeHandle, type);
DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
return dataContract;
}
internal override DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type)
{
DataContract dataContract = base.GetDataContractSkipValidation(typeId, typeHandle, type);
DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
return dataContract;
}
internal override DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle)
{
DataContract dataContract = base.GetDataContract(id, typeHandle);
DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
return dataContract;
}
internal static bool TryGetJsonLocalName(XmlReaderDelegator xmlReader, out string name)
{
if (xmlReader.IsStartElement(JsonGlobals.itemDictionaryString, JsonGlobals.itemDictionaryString))
{
if (xmlReader.MoveToAttribute(JsonGlobals.itemString))
{
name = xmlReader.Value;
return true;
}
}
name = null;
return false;
}
public static string GetJsonMemberName(XmlReaderDelegator xmlReader)
{
string name;
if (!TryGetJsonLocalName(xmlReader, out name))
{
name = xmlReader.LocalName;
}
return name;
}
#if !NET_NATIVE
public static void ThrowDuplicateMemberException(object obj, XmlDictionaryString[] memberNames, int memberIndex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(
SR.Format(SR.JsonDuplicateMemberInInput, DataContract.GetClrTypeFullName(obj.GetType()), memberNames[memberIndex])));
}
public static void ThrowMissingRequiredMembers(object obj, XmlDictionaryString[] memberNames, byte[] expectedElements, byte[] requiredElements)
{
StringBuilder stringBuilder = new StringBuilder();
int missingMembersCount = 0;
for (int i = 0; i < memberNames.Length; i++)
{
if (IsBitSet(expectedElements, i) && IsBitSet(requiredElements, i))
{
if (stringBuilder.Length != 0)
stringBuilder.Append(", ");
stringBuilder.Append(memberNames[i]);
missingMembersCount++;
}
}
if (missingMembersCount == 1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(
SR.JsonOneRequiredMemberNotFound, DataContract.GetClrTypeFullName(obj.GetType()), stringBuilder.ToString())));
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(
SR.JsonRequiredMembersNotFound, DataContract.GetClrTypeFullName(obj.GetType()), stringBuilder.ToString())));
}
}
[SecuritySafeCritical]
private static bool IsBitSet(byte[] bytes, int bitIndex)
{
return BitFlagsGenerator.IsBitSet(bytes, bitIndex);
}
#endif
}
}
| |
// This software code is made available "AS IS" without warranties of any
// kind. You may copy, display, modify and redistribute the software
// code either by itself or as incorporated into your code; provided that
// you do not remove any proprietary notices. Your use of this software
// code is at your own risk and you waive any claim against Amazon
// Digital Services, Inc. or its affiliates with respect to your use of
// this software code. (c) 2006 Amazon Digital Services, Inc. or its
// affiliates.
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
namespace com.CastRoller.AmazonS3DA
{
class Utils
{
public static readonly string METADATA_PREFIX = "x-amz-meta-";
public static readonly string AMAZON_HEADER_PREFIX = "x-amz-";
public static readonly string ALTERNATIVE_DATE_HEADER = "x-amz-date";
private static string host = "s3.amazonaws.com";
public static string Host {
get {
return host;
}
set {
host = value;
}
}
private static int securePort = 443;
public static int SecurePort {
get {
return securePort;
}
set {
securePort = value;
}
}
private static int insecurePort = 80;
public static int InsecurePort {
get {
return insecurePort;
}
set {
insecurePort = value;
}
}
public static string makeCanonicalString( string resource, WebRequest request )
{
SortedList headers = new SortedList();
foreach ( string key in request.Headers )
{
headers.Add( key, request.Headers[ key ] );
}
if (headers["Content-Type"] == null)
{
headers.Add("Content-Type", request.ContentType);
}
return makeCanonicalString(request.Method, resource, headers, null);
}
public static string makeCanonicalString( string verb, string resource,
SortedList headers, string expires )
{
StringBuilder buf = new StringBuilder();
buf.Append( verb );
buf.Append( "\n" );
SortedList interestingHeaders = new SortedList();
if (headers != null)
{
foreach (string key in headers.Keys)
{
string lk = key.ToLower();
if (lk.Equals("content-type") ||
lk.Equals("content-md5") ||
lk.Equals("date") ||
lk.StartsWith(AMAZON_HEADER_PREFIX))
{
interestingHeaders.Add(lk, headers[key]);
}
}
}
if ( interestingHeaders[ ALTERNATIVE_DATE_HEADER ] != null )
{
interestingHeaders.Add( "date", "" );
}
// if the expires is non-null, use that for the date field. this
// trumps the x-amz-date behavior.
if ( expires != null )
{
interestingHeaders.Add( "date", expires );
}
// these headers require that we still put a new line after them,
// even if they don't exist.
{
string [] newlineHeaders = { "content-type", "content-md5" };
foreach ( string header in newlineHeaders )
{
if ( interestingHeaders.IndexOfKey( header ) == -1 )
{
interestingHeaders.Add( header, "" );
}
}
}
// Finally, add all the interesting headers (i.e.: all that startwith x-amz- ;-))
foreach ( string key in interestingHeaders.Keys )
{
if ( key.StartsWith( AMAZON_HEADER_PREFIX ) )
{
buf.Append( key ).Append( ":" ).Append( ( interestingHeaders[ key ] as string ).Trim() );
}
else
{
buf.Append( interestingHeaders[ key ] );
}
buf.Append( "\n" );
}
// Do not include the query string parameters
int queryIndex = resource.IndexOf( '?' );
if ( queryIndex == -1 )
{
buf.Append( "/" + resource );
}
else
{
buf.Append( "/" + resource.Substring( 0, queryIndex ) );
}
Regex aclQueryStringRegEx = new Regex( ".*[&?]acl($|=|&).*" );
Regex torrentQueryStringRegEx = new Regex( ".*[&?]torrent($|=|&).*" );
Regex loggingQueryStringRegEx = new Regex(".*[&?]logging($|=|&).*");
if (aclQueryStringRegEx.IsMatch(resource))
{
buf.Append( "?acl" );
}
else if ( torrentQueryStringRegEx.IsMatch( resource ) )
{
buf.Append( "?torrent" );
}
else if (loggingQueryStringRegEx.IsMatch(resource))
{
buf.Append("?logging");
}
return buf.ToString();
}
public static string encode( string awsSecretAccessKey, string canonicalString, bool urlEncode )
{
Encoding ae = new UTF8Encoding();
HMACSHA1 signature = new HMACSHA1( ae.GetBytes( awsSecretAccessKey ) );
string b64 = Convert.ToBase64String(
signature.ComputeHash( ae.GetBytes(
canonicalString.ToCharArray() ) )
);
if ( urlEncode )
{
return HttpUtility.UrlEncode(b64);
}
else
{
return b64;
}
}
public static byte[] slurpInputStream(Stream stream)
{
using (MemoryStream ms = new MemoryStream())
{
byte[] buffer = new byte[32 * 1024];
while (true)
{
int nRead = stream.Read(buffer, 0, buffer.Length);
if (nRead <= 0)
{
return ms.ToArray();
}
ms.Write(buffer, 0, nRead);
}
}
}
public static string slurpInputStreamAsString(Stream stream)
{
ASCIIEncoding encoding = new ASCIIEncoding();
return encoding.GetString( slurpInputStream( stream ) );
}
public static string getXmlChildText(XmlNode data)
{
StringBuilder builder = new StringBuilder();
foreach (XmlNode node in data.ChildNodes)
{
if (node.NodeType == XmlNodeType.Text ||
node.NodeType == XmlNodeType.CDATA)
{
builder.Append(node.Value);
}
}
return builder.ToString();
}
public static DateTime parseDate(string dateStr)
{
return DateTime.Parse(dateStr);
}
public static string getHttpDate()
{
// Setting the Culture will ensure we get a proper HTTP Date.
string date = System.DateTime.UtcNow.ToString( "ddd, dd MMM yyyy HH:mm:ss ", System.Globalization.CultureInfo.InvariantCulture ) + "GMT";
return date;
}
public static long currentTimeMillis()
{
return (long)( DateTime.UtcNow - new DateTime( 1970, 1, 1 ) ).TotalMilliseconds;
}
}
}
| |
/**
The new controller will go through a basic round robin
free-inject&throttle test to obtain each application's sensitivity to
throttling. The number of this test can be specified through
config.TWOTESTPHASES.
If the application is not sensitive(small ipc differnece),
it will be put into an always-throttled cluster. The old mechanism that
divides applications into low and high cluster is still intact. The
additional cluster is just the always throttled cluster. The
controller tests the application sensitivity every several sampling
periods(config.sampling_period_freq).
**/
//#define DEBUG_NETUTIL
//#define DEBUG
#define DEBUG_CLUSTER
#define DEBUG_NET
#define DEBUG_CLUSTER2
using System;
using System.Collections.Generic;
namespace ICSimulator
{
public class Controller_NetGain_Three_Level_Cluster: Controller_Adaptive_Cluster
{
public static int num_throttle_periods;
public static int num_test_phases;
public static bool isTestPhase;
//nodes in these clusters are always throttled without given it a free injection slot!
public static Cluster throttled_cluster;
public static Cluster low_intensity_cluster;
/* Stats for applications' sensitivity to throttling test */
public static double[] ipc_accum_diff=new double[Config.N];
//total ipc retired during every free injection slot
public static double[] ipc_free=new double[Config.N];
public static double[] ipc_throttled=new double[Config.N];
public static ulong[] ins_free=new ulong[Config.N];
public static ulong[] ins_throttled=new ulong[Config.N];
public static int[] last_free_nodes=new int[Config.N];
//override the cluster_pool defined in Batch Controller!
public static new UniformBatchClusterPool cluster_pool;
//Current app within test phase2 that measure how much an app
//hurt others
public static int hurt_app_idx;
public static bool free_for_all;
public static int HURT_MEASURE=2;
public static ulong[] last_ins_count=new ulong[Config.N];
public static double[,] ipc_hurt=new double[Config.N,Config.N];
public static int TWOTESTPHASES=2;
string getName(int ID)
{
return Simulator.network.workload.getName(ID);
}
void writeNode(int ID)
{
Console.Write("{0} ({1}) ", ID, getName(ID));
}
public Controller_NetGain_Three_Level_Cluster()
{
isThrottling = false;
for (int i = 0; i < Config.N; i++)
{
//initialization on stats for the test
ipc_accum_diff[i]=0.0;
ipc_free[i]=0.0;
ipc_throttled[i]=0.0;
ins_free[i]=0;
ins_throttled[i]=0;
last_free_nodes[i]=0;
//test phase timing
num_throttle_periods=0;
num_test_phases=0;
isTestPhase=false;
//test phase2
hurt_app_idx=0;
free_for_all=true;
MPKI[i]=0.0;
num_ins_last_epoch[i]=0;
m_isThrottled[i]=false;
L1misses[i]=0;
lastNetUtil = 0;
}
throttled_cluster=new Cluster();
low_intensity_cluster=new Cluster();
cluster_pool=new UniformBatchClusterPool(Config.cluster_MPKI_threshold);
}
//0:low, 1:RR, 2:always throttled
//TODO: use ipc_hurt_sum? this is only for %
public int netGainDecision(double ipc_hurt_sum,double app_gain,double net_gain)
{
if(app_gain>=0&&ipc_hurt_sum>=0)//gain & no hurt
return 0;
else if(app_gain<0&&ipc_hurt_sum<0)//no gain & hurt
return 2;
else if(app_gain>=0&&ipc_hurt_sum<0)//gain & hurt
{
if(Config.gain_hurt_rr_only)
return 1;
else
{
if(net_gain>0)
return 1;
else
return 2;
}
}
//no gain and no hurt
return 0;
}
public override void doThrottling()
{
//All nodes in the low intensity can alway freely inject.
int [] low_nodes=low_intensity_cluster.allNodes();
if(low_nodes.Length>0 && isTestPhase==true)
{
low_intensity_cluster.printCluster();
throw new Exception("ERROR: Low nodes exist during sensitivity test phase.");
}
if(low_nodes.Length>0)
{
#if DEBUG_CLUSTER2
Console.WriteLine("\n:: cycle {0} ::", Simulator.CurrentRound);
Console.Write("\nLow nodes *NOT* throttled: ");
double mpki_low=0.0;
#endif
foreach (int node in low_nodes)
{
#if DEBUG_CLUSTER2
writeNode(node);
mpki_low+=MPKI[node];
#endif
setThrottleRate(node,false);
m_nodeStates[node] = NodeState.Low;
}
#if DEBUG_CLUSTER2
Console.Write(" TOTAL MPKI: {0}",mpki_low);
#endif
}
//Throttle all the high other nodes
int [] high_nodes=cluster_pool.allNodes();
#if DEBUG_CLUSTER2
Console.Write("\nAll high other nodes: ");
#endif
foreach (int node in high_nodes)
{
#if DEBUG_CLUSTER2
writeNode(node);
#endif
setThrottleRate(node,true);
m_nodeStates[node] = NodeState.HighOther;
}
//Unthrottle all the nodes in the free-injecting cluster
if(cluster_pool.count()>0)
{
int [] nodes=cluster_pool.nodesInNextCluster();
#if DEBUG_CLUSTER2
Console.Write("\nUnthrottling cluster nodes: ");
double mpki=0.0;
#endif
if(nodes.Length>0)
{
//Clear the vector for last free nodes
Array.Clear(last_free_nodes,0,last_free_nodes.Length);
foreach (int node in nodes)
{
ins_free[node]=(ulong)Simulator.stats.insns_persrc[node].Count;
last_free_nodes[node]=1;
setThrottleRate(node,false);
m_nodeStates[node] = NodeState.HighGolden;
Simulator.stats.throttle_time_bysrc[node].Add();
#if DEBUG_CLUSTER2
mpki+=MPKI[node];
writeNode(node);
#endif
}
#if DEBUG_CLUSTER2
Console.Write(" TOTAL MPKI: {0}",mpki);
#endif
}
}
/* Throttle nodes in always throttled mode. */
int [] throttled_nodes=throttled_cluster.allNodes();
if(throttled_nodes.Length>0 && isTestPhase==true)
{
throttled_cluster.printCluster();
throw new Exception("ERROR: Throttled nodes exist during sensitivity test phase.");
}
if(throttled_nodes.Length>0)
{
#if DEBUG_CLUSTER2
Console.Write("\nAlways Throttled nodes: ");
#endif
foreach (int node in throttled_nodes)
{
setThrottleRate(node,true);
//TODO: need another state for throttled throttled_nodes
m_nodeStates[node] = NodeState.AlwaysThrottled;
Simulator.stats.always_throttle_time_bysrc[node].Add();
#if DEBUG_CLUSTER2
writeNode(node);
#endif
}
}
#if DEBUG_CLUSTER2
double mpki_all=0.0;
Console.Write("\n*NOT* Throttled nodes: ");
for(int i=0;i<Config.N;i++)
if(!m_isThrottled[i])
{
writeNode(i);
mpki_all+=MPKI[i];
}
Console.Write(" TOTAL MPKI: {0}",mpki_all);
Console.Write("\n");
#endif
}
public void collectIPCDiff()
{
#if DEBUG_CLUSTER
Console.WriteLine("\n***COLLECT IPC DIFF*** CYCLE{0}",Simulator.CurrentRound);
#endif
int free_inj_count=Config.throttle_sampling_period/Config.interval_length/Config.N;
int throttled_inj_count=(Config.throttle_sampling_period/Config.interval_length)-free_inj_count;
for(int i=0;i<Config.N;i++)
{
ipc_free[i]/=free_inj_count;
ipc_throttled[i]/=throttled_inj_count;
double temp_ipc_diff;
if(ipc_free[i]==0)
temp_ipc_diff=0;
else
{
if(Config.use_absolute)
temp_ipc_diff=ipc_free[i]-ipc_throttled[i];
else
temp_ipc_diff=(ipc_free[i]-ipc_throttled[i])/ipc_throttled[i];
}
//record the % difference
ipc_accum_diff[i]+=temp_ipc_diff;
Simulator.stats.ipc_diff_bysrc[i].Add(temp_ipc_diff);
#if DEBUG_CLUSTER
Console.Write("id:");
writeNode(i);
if(Config.use_absolute)
Console.WriteLine("ipc_free:{0} ipc_th:{1} ipc free gain:{2}",ipc_free[i],ipc_throttled[i],temp_ipc_diff);
else
Console.WriteLine("ipc_free:{0} ipc_th:{1} ipc free gain:{2}%",ipc_free[i],ipc_throttled[i],(int)(temp_ipc_diff*100));
#endif
//Reset
//ipc_accum_diff[i]=0.0;
ipc_free[i]=0.0;
ipc_throttled[i]=0.0;
ins_free[i]=0;
ins_throttled[i]=0;
last_free_nodes[i]=0;
}
}
public void updateInsCount()
{
#if DEBUG_CLUSTER
Console.WriteLine("***Update instructions count*** CYCLE{0}",Simulator.CurrentRound);
#endif
for(int node=0;node<Config.N;node++)
{
/* Calculate IPC during the last free-inject and throtttled interval */
if(ins_throttled[node]==0)
ins_throttled[node]=(ulong)Simulator.stats.insns_persrc[node].Count;
if(last_free_nodes[node]==1)
{
ulong ins_retired=(ulong)Simulator.stats.insns_persrc[node].Count-ins_free[node];
ipc_free[node]+=(double)ins_retired/Config.interval_length;
#if DEBUG_CLUSTER
Console.Write("Free calc: Node ");
writeNode(node);
Console.WriteLine(" w/ ins {0}->{2} retired {1}::IPC accum:{3}",
ins_free[node],ins_retired,Simulator.stats.insns_persrc[node].Count,
ipc_free[node]);
#endif
}
else
{
ulong ins_retired=(ulong)Simulator.stats.insns_persrc[node].Count-ins_throttled[node];
ipc_throttled[node]+=(double)ins_retired/Config.interval_length;
}
ins_throttled[node]=(ulong)Simulator.stats.insns_persrc[node].Count;
}
}
public void unthrottleAll()
{
for(int i=0;i<Config.N;i++)
setThrottleRate(i,false);
}
//Calculate the IPC when all the applications are freely running
public void collectFreeIPC()
{
#if DEBUG_NET
Console.WriteLine("\n::cycle {0} ::", Simulator.CurrentRound);
Console.Write("--Control Node: ");
writeNode(hurt_app_idx);
Console.WriteLine("--");
#endif
for(int i=0;i<Config.N;i++)
{
if(i==hurt_app_idx) continue;
double ins_retired=Simulator.stats.insns_persrc[i].Count-last_ins_count[i];
//temporarily store the free for all ipc in ipc_hurt array
ipc_hurt[hurt_app_idx,i]=ins_retired/(Config.interval_length/2);
#if DEBUG_NET
writeNode(i);
Console.WriteLine("->Free-For-All ipc {0} ins {1}",ipc_hurt[hurt_app_idx,i],ins_retired);
#endif
}
}
public void collectIPCHurt()
{
#if DEBUG_NET
Console.WriteLine("\n::cycle {0} ::", Simulator.CurrentRound);
Console.Write("--Control Node: ");
writeNode(hurt_app_idx);
Console.WriteLine("--");
#endif
for(int i=0;i<Config.N;i++)
{
if(i==hurt_app_idx) continue;
double ins_retired=Simulator.stats.insns_persrc[i].Count-last_ins_count[i];
double ipc=ins_retired/(Config.interval_length/2);
//collect the actual ipc difference when the app becomes unthrottled
if(Config.use_absolute)
ipc_hurt[hurt_app_idx,i]-=ipc;
else //calculate the percentage of hurt w.r.t one app being throttled
ipc_hurt[hurt_app_idx,i]=(ipc_hurt[hurt_app_idx,i]-ipc)/ipc;
#if DEBUG_NET
writeNode(i);
if(Config.use_absolute)
Console.WriteLine("->ipc hurt {0} ins {1}",ipc_hurt[hurt_app_idx,i],ins_retired);
else
Console.WriteLine("->ipc hurt {0}% ins {1}",ipc_hurt[hurt_app_idx,i]*100,ins_retired);
#endif
}
}
public override void doStep()
{
//Gather stats at the beginning of next sampling period.
if(isTestPhase==true)
{
if(num_test_phases!=HURT_MEASURE)
{
if (isThrottling && Simulator.CurrentRound > (ulong)Config.warmup_cyc &&
(Simulator.CurrentRound % (ulong)Config.interval_length) == 0)
updateInsCount();
//Obtain the ipc difference between free injection and throttled.
if (isThrottling && Simulator.CurrentRound > (ulong)Config.warmup_cyc &&
(Simulator.CurrentRound % (ulong)Config.throttle_sampling_period) == 0)
collectIPCDiff();
}
else
{
if (isThrottling && Simulator.CurrentRound > (ulong)Config.warmup_cyc &&
(Simulator.CurrentRound % (ulong)(Config.interval_length/2)) == 0)
{
if(free_for_all)//the beginning of the next ffa
{
collectIPCHurt();
hurt_app_idx++;
hurt_app_idx%=Config.N;
}
else
collectFreeIPC();
}
}
}
//sampling period: Examine the network state and determine whether to throttle or not
if (Simulator.CurrentRound > (ulong)Config.warmup_cyc &&
(Simulator.CurrentRound % (ulong)Config.throttle_sampling_period) == 0)
{
setThrottling();
lastNetUtil = Simulator.stats.netutil.Total;
resetStat();
}
//once throttle mode is turned on. Let each cluster run for a certain time interval
//to ensure fairness. Otherwise it's throttled most of the time.
if (isThrottling && Simulator.CurrentRound > (ulong)Config.warmup_cyc &&
(Simulator.CurrentRound % (ulong)Config.interval_length) == 0)
{
Console.WriteLine("\n:: do throttle cycle {0} ::", Simulator.CurrentRound);
doThrottling();
}
//Second test phase: trying to measure how much an app hurt others
if (isTestPhase==true && isThrottling &&
Simulator.CurrentRound > (ulong)Config.warmup_cyc &&
num_test_phases==HURT_MEASURE &&
(Simulator.CurrentRound % (ulong)(Config.interval_length/2)) == 0)
{
//update Instructions Count
for(int i=0;i<Config.N;i++)
last_ins_count[i]=(ulong)Simulator.stats.insns_persrc[i].Count;
//TODO: change the throttle rate to 100%?
if(free_for_all)
unthrottleAll();
else
setThrottleRate(hurt_app_idx,true);
#if DEBUG_NET
Console.WriteLine("\n:: test phase 2 do throttle cycle {0} ::", Simulator.CurrentRound);
for(int i=0;i<Config.N;i++)
{
writeNode(i);
Console.WriteLine("throttled:{0}",m_isThrottled[i]);
}
#endif
free_for_all=!free_for_all;
}
}
public override void setThrottling()
{
#if DEBUG_NETUTIL
Console.Write("\n:: cycle {0} ::",
Simulator.CurrentRound);
#endif
//get the MPKI value
for (int i = 0; i < Config.N; i++)
{
prev_MPKI[i]=MPKI[i];
if(num_ins_last_epoch[i]==0)
MPKI[i]=((double)(L1misses[i]*1000))/(Simulator.stats.insns_persrc[i].Count);
else
{
if(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]>0)
MPKI[i]=((double)(L1misses[i]*1000))/(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]);
else if(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]==0)
MPKI[i]=0;
else
throw new Exception("MPKI error!");
}
}
recordStats();
if(isThrottling)
{
double netutil=((double)(Simulator.stats.netutil.Total-lastNetUtil)/(double)Config.throttle_sampling_period);
#if DEBUG_NETUTIL
Console.WriteLine("In throttle mode: avg netUtil = {0} thres at {1}",
netutil,Config.netutil_throttling_threshold);
#endif
/* TODO:
* 1.If the netutil remains high, lower the threshold value for each cluster
* to reduce the netutil further more and create a new pool/schedule for
* all the clusters. How to raise it back?
* Worst case: 1 app per cluster.
*
* 2.Find the difference b/w the current netutil and the threshold.
* Then increase the throttle rate for each cluster based on that difference.
*
* 3.maybe add stalling clusters?
* */
isThrottling=false;
//un-throttle the network
for(int i=0;i<Config.N;i++)
setThrottleRate(i,false);
//Clear all the clusters
#if DEBUG_CLUSTER
Console.WriteLine("cycle {0} ___Clear clusters___",Simulator.CurrentRound);
#endif
cluster_pool.removeAllClusters();
throttled_cluster.removeAllNodes();
low_intensity_cluster.removeAllNodes();
double diff=netutil-Config.netutil_throttling_threshold;
//Option1: adjust the mpki thresh for each cluster
//if netutil within range of 10% increase MPKI boundary for each cluster
if(Config.adaptive_cluster_mpki)
{
double new_MPKI_thresh=cluster_pool.clusterThreshold();
if(diff<0.10)
new_MPKI_thresh+=10;
else if(diff>0.2)
new_MPKI_thresh-=20;
cluster_pool.changeThresh(new_MPKI_thresh);
}
//Option2: adjust the throttle rate
//
//
//Use alpha*total_MPKI+base to find the optimal netutil for performance
//0.5 is the baseline netutil threshold
//0.03 is calculated empricically using some base cases to find this number b/w total_mpki and target netutil
double total_mpki=0.0;
for(int i=0;i<Config.N;i++)
total_mpki+=MPKI[i];
double target_netutil=(0.03*total_mpki+50)/100;
//50% baseline
if(Config.alpha)
{
//within 2% range
if(netutil<(0.98*target_netutil))
Config.RR_throttle_rate-=0.02;
else if(netutil>(1.02*target_netutil))
if(Config.RR_throttle_rate<0.95)//max is 95%
Config.RR_throttle_rate+=0.01;
//if target is too high, only throttle max to 95% inj rate
if(target_netutil>0.9)
Config.RR_throttle_rate=0.95;
}
//Trying to force 60-70% netutil
if(Config.adaptive_rate)
{
if(diff<0.1)
Config.RR_throttle_rate-=0.02;
else if(diff>0.2)
if(Config.RR_throttle_rate<0.95)
Config.RR_throttle_rate+=0.01;
}
#if DEBUG_NETUTIL
Console.WriteLine("Netutil diff: {2}-{3}={1} New th rate:{0} New MPKI thresh: {6} Target netutil:{4} Total MPKI:{5}",
Config.RR_throttle_rate,diff,
netutil,Config.netutil_throttling_threshold,target_netutil,total_mpki,cluster_pool.clusterThreshold());
#endif
Simulator.stats.total_th_rate.Add(Config.RR_throttle_rate);
}
#if DEBUG_CLUSTER
Console.WriteLine("***SET THROTTLING Thresh trigger point*** CYCLE{0}",Simulator.CurrentRound);
#endif
//TODO: test phase can also reduce the mpki,so...might not have consecutive test phases
if (thresholdTrigger()) // an abstract fn() that trigger whether to start throttling or not
{
#if DEBUG_CLUSTER
Console.WriteLine("Congested!! Trigger throttling! isTest {0}, num th {1}, num samp {2}",
isTestPhase,num_test_phases,num_throttle_periods);
#endif
#if DEBUG_CLUSTER
Console.WriteLine("cycle {0} ___Clear clusters___",Simulator.CurrentRound);
#endif
cluster_pool.removeAllClusters();
throttled_cluster.removeAllNodes();
low_intensity_cluster.removeAllNodes();
///////State Trasition
//Initial state
if(num_throttle_periods==0&&num_test_phases==0)
isTestPhase=true;
//From test->cluster throttling
if(isTestPhase && num_test_phases==TWOTESTPHASES)
{
isTestPhase=false;
num_test_phases=0;
}
//From cluster throttling->test
if(num_throttle_periods==Config.sampling_period_freq)
{
//reset ipc_accum_diff
for(int node_id=0;node_id<Config.N;node_id++)
ipc_accum_diff[node_id]=0.0;
isTestPhase=true;
num_throttle_periods=0;
}
///////Cluster Distribution
if(isTestPhase==true)
{
num_test_phases++;
//Add every node to high cluster
int total_high = 0;
double total_mpki=0.0;
for (int i = 0; i < Config.N; i++)
{
total_mpki+=MPKI[i];
cluster_pool.addNewNodeUniform(i,MPKI[i]);
total_high++;
#if DEBUG
Console.Write("#ON#:Node {0} with MPKI {1} ",i,MPKI[i]);
#endif
}
Simulator.stats.total_sum_mpki.Add(total_mpki);
#if DEBUG
Console.WriteLine(")");
#endif
//if no node needs to be throttled, set throttling to false
isThrottling = (total_high>0)?true:false;
#if DEBUG_CLUSTER
cluster_pool.printClusterPool();
#endif
}
else
{
//Increment the number of throttle periods so that the test phase can kick back
//in after certain number of throttle periods.
num_throttle_periods++;
List<int> sortedList = new List<int>();
double total_mpki=0.0;
double small_mpki=0.0;
double current_allow=0.0;
int total_high=0;
for(int i=0;i<Config.N;i++)
{
sortedList.Add(i);
total_mpki+=MPKI[i];
//stats recording-see what's the total mpki composed by low/med apps
if(MPKI[i]<=30)
small_mpki+=MPKI[i];
}
//sort by mpki
sortedList.Sort(CompareByMpki);
#if DEBUG_CLUSTER
for(int i=0;i<Config.N;i++)
Console.WriteLine("ID:{0} MPKI:{1}",sortedList[i],MPKI[sortedList[i]]);
Console.WriteLine("*****total MPKI: {0}",total_mpki);
Console.WriteLine("*****total MPKIs of apps with MPKI<30: {0}\n",small_mpki);
#endif
//find the first few apps that will be allowed to run freely without being throttled
for(int list_index=0;list_index<Config.N;list_index++)
{
int node_id=sortedList[list_index];
//add the node that has no performance gain from free injection slot to
//always throttled cluster.
double ipc_avg_diff=ipc_accum_diff[node_id];
//Net gain = coefficient*sum(ipc_hurt)+app_gain
double sum=0.0;
for(int i=0;i<Config.N;i++)
{
if(i==node_id && ipc_hurt[node_id,i]!=0)
throw new Exception("Non-zero ipc hurt for own node.");
// ONLY collects negative valuse. Omit all the positive values.
if(Config.ipc_hurt_neg_only)
sum+=(ipc_hurt[node_id,i]<0)?ipc_hurt[node_id,i]:0;
else
sum+=ipc_hurt[node_id,i];
}
double net_gain=Config.ipc_hurt_co*sum+ipc_avg_diff;
#if DEBUG_CLUSTER
writeNode(node_id);
if(Config.use_absolute)
Console.WriteLine("with ipc diff {1} ipc hurt {4} netgain {2} mpki {3}",node_id,ipc_avg_diff,net_gain,MPKI[node_id],sum);
else
Console.WriteLine("with ipc diff {1}% ipc hurt {4}% netgain {2}% mpki {3}",node_id,ipc_avg_diff*100,net_gain*100,MPKI[node_id],sum);
#endif
//If an application doesn't fit into one cluster, it will always be throttled
/*if(ipc_avg_diff<Config.sensitivity_threshold || (Config.use_cluster_threshold && MPKI[node_id]>Config.cluster_MPKI_threshold))
{
#if DEBUG_CLUSTER
Console.WriteLine("->Throttled node: {0}",node_id);
#endif
throttled_cluster.addNode(node_id,MPKI[node_id]);
}
else
{
if(withInRange(current_allow+MPKI[node_id],Config.free_total_MPKI))
{
#if DEBUG_CLUSTER
Console.WriteLine("->Low node: {0}",node_id);
#endif
low_intensity_cluster.addNode(node_id,MPKI[node_id]);
current_allow+=MPKI[node_id];
continue;
}
else
{
#if DEBUG_CLUSTER
Console.WriteLine("->High node: {0}",node_id);
#endif
cluster_pool.addNewNode(node_id,MPKI[node_id]);
total_high++;
}
}*/
//0:low, 1:RR, 2:always throttled
int decision=netGainDecision(sum,ipc_avg_diff,net_gain);
if(decision==0)
{
#if DEBUG_CLUSTER
Console.WriteLine("->Low node: {0}",node_id);
#endif
low_intensity_cluster.addNode(node_id,MPKI[node_id]);
}
else if(decision==1)
{
#if DEBUG_CLUSTER
Console.WriteLine("->High node: {0}",node_id);
#endif
cluster_pool.addNewNode(node_id,MPKI[node_id]);
total_high++;
}
else if(decision==2)
{
#if DEBUG_CLUSTER
Console.WriteLine("->Throttled node: {0}",node_id);
#endif
throttled_cluster.addNode(node_id,MPKI[node_id]);
total_high++;
}
else
throw new Exception("Unknown decision!");
}
#if DEBUG_CLUSTER
Console.WriteLine("total high: {0}\n",total_high);
#endif
//STATS
Simulator.stats.allowed_sum_mpki.Add(current_allow);
Simulator.stats.total_sum_mpki.Add(total_mpki);
sortedList.Clear();
isThrottling = (total_high>0)?true:false;
#if DEBUG_CLUSTER
cluster_pool.printClusterPool();
#endif
}
}
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Linq;
using FluentAssertions;
using Microsoft.DotNet.Tools.Test.Utilities;
using Xunit;
using Microsoft.DotNet.ProjectJsonMigration;
using System;
using System.IO;
using Microsoft.Build.Construction;
using Microsoft.DotNet.Internal.ProjectModel;
using NuGet.Frameworks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using Microsoft.DotNet.ProjectJsonMigration.Rules;
namespace Microsoft.DotNet.ProjectJsonMigration.Tests
{
public class GivenThatIWantToMigrateRuntimeOptions : TestBase
{
private static readonly string s_runtimeConfigFileName = "runtimeconfig.template.json";
[Fact]
public void RuntimeOptionsAreCopiedFromProjectJsonToRuntimeConfigTemplateJsonFile()
{
var testInstance = TestAssetsManager.CreateTestInstance("TestAppWithRuntimeOptions");
var projectDir = testInstance.Path;
var projectPath = Path.Combine(testInstance.Path, "project.json");
var project = JObject.Parse(File.ReadAllText(projectPath));
var rawRuntimeOptions = (JObject)project.GetValue("runtimeOptions");
var projectContext = ProjectContext.Create(projectDir, FrameworkConstants.CommonFrameworks.NetCoreApp10);
var testSettings = MigrationSettings.CreateMigrationSettingsTestHook(projectDir, projectDir, default(ProjectRootElement));
var testInputs = new MigrationRuleInputs(new[] { projectContext }, null, null, null);
new MigrateRuntimeOptionsRule().Apply(testSettings, testInputs);
var migratedRuntimeOptionsPath = Path.Combine(projectDir, s_runtimeConfigFileName);
File.Exists(migratedRuntimeOptionsPath).Should().BeTrue();
var migratedRuntimeOptionsContent = JObject.Parse(File.ReadAllText(migratedRuntimeOptionsPath));
JToken.DeepEquals(rawRuntimeOptions, migratedRuntimeOptionsContent).Should().BeTrue();
}
[Fact]
public void MigratingProjectJsonWithNoRuntimeOptionsProducesNoRuntimeConfigTemplateJsonFile()
{
var testInstance = TestAssetsManager.CreateTestInstance("PJTestAppSimple");
var projectDir = testInstance.Path;
var projectContext = ProjectContext.Create(projectDir, FrameworkConstants.CommonFrameworks.NetCoreApp10);
var testSettings = MigrationSettings.CreateMigrationSettingsTestHook(projectDir, projectDir, default(ProjectRootElement));
var testInputs = new MigrationRuleInputs(new[] { projectContext }, null, null, null);
new MigrateRuntimeOptionsRule().Apply(testSettings, testInputs);
var migratedRuntimeOptionsPath = Path.Combine(projectDir, s_runtimeConfigFileName);
File.Exists(migratedRuntimeOptionsPath).Should().BeFalse();
}
[Fact]
public void MigratingProjectJsonWithOnlyServerGCRuntimeOptionsProducesNoRuntimeConfigTemplateJsonFile()
{
var testDirectory = Temp.CreateDirectory().Path;
var pj = @"
{
""runtimeOptions"": {
""configProperties"": {
""System.GC.Server"": true
}
}
}";
RunMigrateRuntimeOptionsRulePj(pj, testDirectory);
var migratedRuntimeOptionsPath = Path.Combine(testDirectory, s_runtimeConfigFileName);
File.Exists(migratedRuntimeOptionsPath).Should().BeFalse();
}
[Fact]
public void MigratingProjectJsonWithServerGCAndOtherConfigPropertiesProducesRuntimeConfigTemplateJsonFile()
{
var testDirectory = Temp.CreateDirectory().Path;
var pj = @"
{
""runtimeOptions"": {
""configProperties"": {
""System.GC.Server"": false,
""Other"": false
}
}
}";
RunMigrateRuntimeOptionsRulePj(pj, testDirectory);
var migratedRuntimeOptionsPath = Path.Combine(testDirectory, s_runtimeConfigFileName);
File.Exists(migratedRuntimeOptionsPath).Should().BeTrue();
var root = JObject.Parse(File.ReadAllText(migratedRuntimeOptionsPath));
var configProperties = root.Value<JObject>("configProperties");
configProperties.Should().NotBeNull();
configProperties["System.GC.Server"].Should().BeNull();
configProperties["Other"].Should().NotBeNull();
}
[Fact]
public void MigratingProjectJsonWithServerGCAndOtherRuntimeOptionsProducesRuntimeConfigTemplateJsonFile()
{
var testDirectory = Temp.CreateDirectory().Path;
var pj = @"
{
""runtimeOptions"": {
""configProperties"": {
""System.GC.Server"": false
},
""Other"": false
}
}";
RunMigrateRuntimeOptionsRulePj(pj, testDirectory);
var migratedRuntimeOptionsPath = Path.Combine(testDirectory, s_runtimeConfigFileName);
File.Exists(migratedRuntimeOptionsPath).Should().BeTrue();
var root = JObject.Parse(File.ReadAllText(migratedRuntimeOptionsPath));
root.Value<JObject>("configProperties").Should().BeNull();
}
[Fact]
public void MigratingProjectJsonWithServerGCTrueProducesServerGarbageCollectionProperty()
{
var testDirectory = Temp.CreateDirectory().Path;
var pj = @"
{
""runtimeOptions"": {
""configProperties"": {
""System.GC.Server"": true
}
}
}";
var mockProj = RunMigrateRuntimeOptionsRulePj(pj, testDirectory);
var props = mockProj.Properties.Where(p => p.Name.Equals("ServerGarbageCollection", StringComparison.Ordinal));
props.Count().Should().Be(1);
props.First().Value.Should().Be("true");
}
[Fact]
public void MigratingProjectJsonWithServerGCFalseProducesServerGarbageCollectionProperty()
{
var testDirectory = Temp.CreateDirectory().Path;
var pj = @"
{
""runtimeOptions"": {
""configProperties"": {
""System.GC.Server"": false
}
}
}";
var mockProj = RunMigrateRuntimeOptionsRulePj(pj, testDirectory);
var props = mockProj.Properties.Where(p => p.Name.Equals("ServerGarbageCollection", StringComparison.Ordinal));
props.Count().Should().Be(1);
props.First().Value.Should().Be("false");
}
[Fact]
public void MigratingWebProjectJsonWithServerGCTrueDoesNotProduceServerGarbageCollectionProperty()
{
var testDirectory = Temp.CreateDirectory().Path;
var pj = @"
{
""buildOptions"": {
""emitEntryPoint"": true
},
""dependencies"": {
""Microsoft.AspNetCore.Mvc"": ""1.0.0""
},
""runtimeOptions"": {
""configProperties"": {
""System.GC.Server"": true
}
}
}";
var mockProj = RunMigrateRuntimeOptionsRulePj(pj, testDirectory);
var props = mockProj.Properties.Where(p => p.Name.Equals("ServerGarbageCollection", StringComparison.Ordinal));
props.Count().Should().Be(0);
}
[Fact]
public void MigratingWebProjectJsonWithServerGCFalseProducesServerGarbageCollectionProperty()
{
var testDirectory = Temp.CreateDirectory().Path;
var pj = @"
{
""buildOptions"": {
""emitEntryPoint"": true
},
""dependencies"": {
""Microsoft.AspNetCore.Mvc"": ""1.0.0""
},
""runtimeOptions"": {
""configProperties"": {
""System.GC.Server"": false
}
}
}";
var mockProj = RunMigrateRuntimeOptionsRulePj(pj, testDirectory);
var props = mockProj.Properties.Where(p => p.Name.Equals("ServerGarbageCollection", StringComparison.Ordinal));
props.Count().Should().Be(1);
props.First().Value.Should().Be("false");
}
private ProjectRootElement RunMigrateRuntimeOptionsRulePj(string s, string testDirectory = null)
{
testDirectory = testDirectory ?? Temp.CreateDirectory().Path;
return TemporaryProjectFileRuleRunner.RunRules(new IMigrationRule[]
{
new MigrateRuntimeOptionsRule()
}, s, testDirectory);
}
}
}
| |
// Copyright (c) 2009 Bohumir Zamecnik <[email protected]>
// License: The MIT License, see the LICENSE file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HalftoneLab
{
/// <summary>
/// Spot functions define screening dot growth depending on intensity.
/// </summary>
/// <remarks>
/// <para>
/// Spot functions define continuous periodic 2-D functions with values
/// in range (0.0-1.0). They are parametrized by angle and period
/// (distance).
/// </para>
/// <para>
/// Technically, spot functions are defined as prototypes using lambda
/// functions. When parameters are known, they are 'instantiated' to
/// other lambda functions as normal real valued 2-D functions.
/// </para>
/// <para>
/// To use a spot function you have to set the SpotFuncPrototype property
/// and optionally set Angle and Distance properties. Then the spot
/// function is available in SpotFunc property.
/// </para>
/// </remarks>
[Serializable]
[Module(TypeName = "Spot function")]
public class SpotFunction : Module
{
/// <summary>
///
/// </summary>
/// <param name="angle"></param>
/// <param name="distance"></param>
/// <returns></returns>
public delegate SpotFuncDelegate SpotFuncPrototypeDelegate(double angle, double distance);
/// <summary>
///
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public delegate int SpotFuncDelegate(int x, int y);
private double _angle = Math.PI * 0.25;
/// <summary>
/// Angle of rotation of the screen.
/// </summary>
/// <value>
/// In radians. Default: 0.
/// </value>
public double Angle {
get { return _angle; }
set {
_angle = value;
initSpotFunction();
}
}
private double _distance = 10;
/// <summary>
/// Distance between screen elements (inverse of frequency)
/// </summary>
/// <remarks>
/// Distance = PPI (pixels per inch) / LPI (lines per inch).
/// </remarks>
/// <value>
/// In 2-D plane units corresponding to pixels.
/// </value>
public double Distance {
get { return _distance; }
set {
_distance = value;
initSpotFunction();
}
}
private SpotFuncPrototypeDelegate _spotFuncPrototype;
/// <summary>
/// Spot function prototype. There you set the prototype and the
/// finished spot function will be available in SpotFunc property.
/// </summary>
public SpotFuncPrototypeDelegate SpotFuncPrototype {
get { return _spotFuncPrototype; }
set {
_spotFuncPrototype = value;
initSpotFunction();
}
}
[NonSerialized]
private SpotFuncDelegate _spotFunc;
/// <summary>
/// Spot function made of a prototype which has been set to
/// SpotFuncPrototype property.
/// </summary>
public SpotFuncDelegate SpotFunc {
get {
if (_spotFunc == null) {
initSpotFunction();
}
return _spotFunc;
}
private set { _spotFunc = value; }
}
/// <summary>
/// Create a new spot function with default prototype and parameters.
/// </summary>
public SpotFunction()
: this(SpotFunction.Samples.euclidDot.SpotFuncPrototype) {}
/// <summary>
/// Create a new spot function using a prototype and default
/// parameters.
/// </summary>
/// <param name="spotFuncPrototype">Spot function prototype</param>
public SpotFunction(SpotFuncPrototypeDelegate spotFuncPrototype) {
SpotFuncPrototype = spotFuncPrototype;
}
/// <summary>
/// Create a spot function with given prototype and parameters.
/// </summary>
/// <param name="spotFuncPrototype">Spot function prototype</param>
/// <param name="angle">Screen angle in radians (usually 0-2*PI but
/// any real value will do the job)</param>
/// <param name="distance">Distance between screen elements</param>
public SpotFunction(SpotFuncPrototypeDelegate spotFuncPrototype,
double angle, double distance)
{
Angle = angle;
Distance = distance;
SpotFuncPrototype = spotFuncPrototype;
}
/// <summary>
/// Initialize the spot function from its prototype.
/// </summary>
private void initSpotFunction() {
if (SpotFuncPrototype != null) {
SpotFunc = SpotFuncPrototype(Angle, Distance);
}
}
public override void init(Image.ImageRunInfo imageRunInfo) {
base.init(imageRunInfo);
initSpotFunction();
}
/// <summary>
/// Utility functions for SpotFunction.
/// </summary>
[Serializable]
protected class Util
{
/// <summary>
/// Rotate coordinates (inX, inY) by given angle to (outX, outY).
/// </summary>
/// <param name="inX">Input X coordinate</param>
/// <param name="inY">Input Y coordinate</param>
/// <param name="angle">Rotation angle in radians.</param>
/// <param name="outX">Output X coordinate</param>
/// <param name="outY">Output Y coordinate</param>
public static void rotate(
double inX, double inY,
double angle,
out double outX, out double outY)
{
double sin = Math.Sin(angle);
double cos = Math.Cos(angle);
outX = inX * sin + inY * cos;
outY = -inX * cos + inY * sin;
}
}
/// <summary>
/// Samples of commonly used spot functions.
/// </summary>
[Serializable]
public class Samples
{
public static SpotFunction nullSpot;
public static SpotFunction euclidDot;
public static SpotFunction perturbedEuclidDot;
public static SpotFunction squareDot;
public static SpotFunction line;
public static SpotFunction triangle;
public static SpotFunction circleDot;
private static List<SpotFunction> _list;
/// <summary>
/// Iterate over the list of the samples.
/// </summary>
/// <returns>Enumerable of sample spot functions.</returns>
public static IEnumerable<SpotFunction> list() {
return _list;
}
static Samples() {
_list = new List<SpotFunction>();
nullSpot = new SpotFunction((double angle, double distance) =>
{
return (int x, int y) => 128;
})
{
Name = "Null spot function"
}
;
euclidDot = new SpotFunction((double angle, double distance) =>
{
double pixelDivisor = 2.0 / distance;
return (int x, int y) =>
{
double rotatedX, rotatedY;
Util.rotate(
x * pixelDivisor, y * pixelDivisor,
angle, out rotatedX, out rotatedY);
return (int)(
255 * (0.5 - (0.25 * (
// to make an elipse multiply sin/cos
// arguments with different multipliers
Math.Sin(Math.PI * (rotatedX + 0.5)) +
Math.Cos(Math.PI * rotatedY)))));
};
})
{
Name = "Euclid dot",
Description = "circular dot changing to square at 50% grey"
};
_list.Add(euclidDot);
perturbedEuclidDot = new SpotFunction(
(double angle, double distance) =>
{
Random random = new Random();
double noiseAmplitude = 0.01;
double pixelDivisor = 2.0 / distance;
return (int x, int y) =>
{
double rotatedX, rotatedY;
SpotFunction.Util.rotate(
x * pixelDivisor, y * pixelDivisor,
angle, out rotatedX, out rotatedY);
return (int)(
255 * (
((random.NextDouble() - 0.5) * 2 * noiseAmplitude) +
(0.5 - (0.25 * (
// to make an elipse multiply sin/cos
// arguments with different multipliers
Math.Sin(Math.PI * (rotatedX + 0.5)) +
Math.Cos(Math.PI * rotatedY))))));
};
})
{
Name = "Euclid dot, perturbed",
Description = "Euclid dot with some noise"
};
_list.Add(perturbedEuclidDot);
squareDot = new SpotFunction((double angle, double distance) =>
{
return (int x, int y) =>
{
double rotatedX, rotatedY;
SpotFunction.Util.rotate(x, y, angle, out rotatedX, out rotatedY);
return (int)(255 *
(1 - (0.5 * (
Math.Abs(((Math.Abs(rotatedX) / (distance * 0.5)) % 2) - 1) +
Math.Abs(((Math.Abs(rotatedY) / (distance * 0.5)) % 2) - 1)
))));
};
})
{
Name = "Square dot"
};
_list.Add(squareDot);
line = new SpotFunction((double angle, double distance) =>
{
angle %= Math.PI * 0.5;
double invDistance = 1 / distance;
double sinInvDistance = Math.Sin(angle) * invDistance;
double cosInvDistance = Math.Cos(angle) * invDistance;
return (int x, int y) =>
{
double value = (sinInvDistance * x) + (cosInvDistance * y);
return (int)(255 * (Math.Abs(
Math.Sign(value) * value % Math.Sign(value))));
};
})
{
Name = "Line"
};
_list.Add(line);
triangle = new SpotFunction((double angle, double distance) =>
{
double invDistance = 1 / distance;
return (int x, int y) =>
{
// TODO: it does not rotate
return (int)(255 * 0.5 * (
((invDistance * x) % 1) +
((invDistance * y) % 1)
));
};
})
{
Name = "Triangle"
};
_list.Add(triangle);
circleDot = new SpotFunction((double angle, double distance) =>
{
double invDistance = 1 / distance;
return (int x, int y) =>
{
// TODO: fix this
double xSq = x - distance * 0.5;
xSq = (xSq * xSq) % distance;
double ySq = y - distance * 0.5;
ySq = (ySq * ySq) % distance;
return (int)(255 *
//((1 - Math.Sqrt(
//(invDistance * (x*x) % 1) +
//(invDistance * (y*y) % 1)
//) * 0.5)));
((1 - invDistance * Math.Sqrt(2*(xSq + ySq)))));
};
})
{
Name = "Circle dot"
};
// TODO: uncomment this when circle dot will work
//_list.Add(circleDot);
}
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using SDKTemplate;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Devices.Midi;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace MIDI
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Scenario1_MIDIDeviceEnumeration : Page
{
/// <summary>
/// Main Page
/// </summary>
private MainPage rootPage;
/// <summary>
/// Device watchers for MIDI in and out ports
/// </summary>
MidiDeviceWatcher midiInDeviceWatcher;
MidiDeviceWatcher midiOutDeviceWatcher;
/// <summary>
/// Set the rootpage context when entering the scenario
/// </summary>
/// <param name="e">Event arguments</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
this.rootPage = MainPage.Current;
}
/// <summary>
/// Stop the device watchers when leaving the scenario
/// </summary>
/// <param name="e">Event arguments</param>
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
// Stop the input and output device watchers
this.midiInDeviceWatcher.Stop();
this.midiOutDeviceWatcher.Stop();
}
/// <summary>
/// Constructor: Empty device lists, start the device watchers and
/// set initial states for buttons
/// </summary>
public Scenario1_MIDIDeviceEnumeration()
{
this.InitializeComponent();
// Start with a clean slate
ClearAllDeviceValues();
// Ensure Auto-detect devices toggle is on
this.deviceAutoDetectToggle.IsOn = true;
// Set up the MIDI input and output device watchers
this.midiInDeviceWatcher = new MidiDeviceWatcher(MidiInPort.GetDeviceSelector(), Dispatcher, this.inputDevices);
this.midiOutDeviceWatcher = new MidiDeviceWatcher(MidiOutPort.GetDeviceSelector(), Dispatcher, this.outputDevices);
// Start watching for devices
this.midiInDeviceWatcher.Start();
this.midiOutDeviceWatcher.Start();
// Disable manual enumeration buttons
this.listInputDevicesButton.IsEnabled = false;
this.listOutputDevicesButton.IsEnabled = false;
}
/// <summary>
/// Clear all input and output MIDI device lists and properties
/// </summary>
private void ClearAllDeviceValues()
{
// Clear input devices
this.inputDevices.Items.Clear();
this.inputDevices.Items.Add("Click button to list input MIDI devices");
this.inputDevices.IsEnabled = false;
// Clear output devices
this.outputDevices.Items.Clear();
this.outputDevices.Items.Add("Click button to list output MIDI devices");
this.outputDevices.IsEnabled = false;
// Clear input device properties
this.inputDeviceProperties.Items.Clear();
this.inputDeviceProperties.Items.Add("Select a MIDI input device to view its properties");
this.inputDeviceProperties.IsEnabled = false;
// Clear output device properties
this.outputDeviceProperties.Items.Clear();
this.outputDeviceProperties.Items.Add("Select a MIDI output device to view its properties");
this.outputDeviceProperties.IsEnabled = false;
}
/// <summary>
/// Input button click handler
/// </summary>
/// <param name="sender">Element that fired the event</param>
/// <param name="e">Event arguments</param>
private async void listInputDevicesButton_Click(object sender, RoutedEventArgs e)
{
// Enumerate input devices
await EnumerateMidiInputDevices();
}
/// <summary>
/// Query DeviceInformation class for Midi Input devices
/// </summary>
private async Task EnumerateMidiInputDevices()
{
// Clear input devices
this.inputDevices.Items.Clear();
this.inputDeviceProperties.Items.Clear();
this.inputDeviceProperties.IsEnabled = false;
// Find all input MIDI devices
string midiInputQueryString = MidiInPort.GetDeviceSelector();
DeviceInformationCollection midiInputDevices = await DeviceInformation.FindAllAsync(midiInputQueryString);
// Return if no external devices are connected
if (midiInputDevices.Count == 0)
{
this.inputDevices.Items.Add("No MIDI input devices found!");
this.inputDevices.IsEnabled = false;
this.rootPage.NotifyUser("Please connect at least one external MIDI device for this demo to work correctly", NotifyType.ErrorMessage);
return;
}
// Else, add each connected input device to the list
foreach (DeviceInformation deviceInfo in midiInputDevices)
{
this.inputDevices.Items.Add(deviceInfo.Name);
this.inputDevices.IsEnabled = true;
}
this.rootPage.NotifyUser("MIDI Input devices found!", NotifyType.StatusMessage);
}
/// <summary>
/// Output button click handler
/// </summary>
/// <param name="sender">Element that fired the event</param>
/// <param name="e">Event arguments</param>
private async void listOutputDevicesButton_Click(object sender, RoutedEventArgs e)
{
// Enumerate output devices
await EnumerateMidiOutputDevices();
}
/// <summary>
/// Query DeviceInformation class for Midi Output devices
/// </summary>
private async Task EnumerateMidiOutputDevices()
{
// Clear output devices
this.outputDevices.Items.Clear();
this.outputDeviceProperties.Items.Clear();
this.outputDeviceProperties.IsEnabled = false;
// Find all output MIDI devices
string midiOutputQueryString = MidiOutPort.GetDeviceSelector();
DeviceInformationCollection midiOutputDevices = await DeviceInformation.FindAllAsync(midiOutputQueryString);
// Return if no external devices are connected, and GS synth is not detected
if (midiOutputDevices.Count == 0)
{
this.outputDevices.Items.Add("No MIDI output devices found!");
this.outputDevices.IsEnabled = false;
this.rootPage.NotifyUser("Please connect at least one external MIDI device for this demo to work correctly", NotifyType.ErrorMessage);
return;
}
// List specific device information for each output device
foreach (DeviceInformation deviceInfo in midiOutputDevices)
{
this.outputDevices.Items.Add(deviceInfo.Name);
this.outputDevices.IsEnabled = true;
}
this.rootPage.NotifyUser("MIDI Output devices found!", NotifyType.StatusMessage);
}
/// <summary>
/// Detect the toggle state of the Devicewatcher button.
/// If auto-detect is on, disable manual enumeration buttons and start device watchers
/// If auto-detect is off, enable manual enumeration buttons and stop device watchers
/// </summary>
/// <param name="sender">Element that fired the event</param>
/// <param name="e">Event arguments</param>
private void DeviceAutoDetectToggle_Toggled(object sender, RoutedEventArgs e)
{
if (this.deviceAutoDetectToggle.IsOn)
{
this.listInputDevicesButton.IsEnabled = false;
this.listOutputDevicesButton.IsEnabled = false;
if (this.midiInDeviceWatcher != null)
{
this.midiInDeviceWatcher.Start();
}
if (this.midiOutDeviceWatcher != null)
{
this.midiOutDeviceWatcher.Start();
}
}
else
{
this.listInputDevicesButton.IsEnabled = true;
this.listOutputDevicesButton.IsEnabled = true;
if (this.midiInDeviceWatcher != null)
{
this.midiInDeviceWatcher.Stop();
}
if (this.midiOutDeviceWatcher != null)
{
this.midiOutDeviceWatcher.Stop();
}
}
}
/// <summary>
/// Change the active input MIDI device
/// </summary>
/// <param name="sender">Element that fired the event</param>
/// <param name="e">Event arguments</param>
private void inputDevices_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Get the selected input MIDI device
int selectedInputDeviceIndex = this.inputDevices.SelectedIndex;
// Try to display the appropriate device properties
if (selectedInputDeviceIndex < 0)
{
// Clear input device properties
this.inputDeviceProperties.Items.Clear();
this.inputDeviceProperties.Items.Add("Select a MIDI input device to view its properties");
this.inputDeviceProperties.IsEnabled = false;
this.rootPage.NotifyUser("Select a MIDI input device to view its properties", NotifyType.StatusMessage);
return;
}
DeviceInformationCollection devInfoCollection = this.midiInDeviceWatcher.GetDeviceInformationCollection();
if (devInfoCollection == null)
{
this.inputDeviceProperties.Items.Clear();
this.inputDeviceProperties.Items.Add("Device not found!");
this.inputDeviceProperties.IsEnabled = false;
this.rootPage.NotifyUser("Device not found!", NotifyType.ErrorMessage);
return;
}
DeviceInformation devInfo = devInfoCollection[selectedInputDeviceIndex];
if (devInfo == null)
{
this.inputDeviceProperties.Items.Clear();
this.inputDeviceProperties.Items.Add("Device not found!");
this.inputDeviceProperties.IsEnabled = false;
this.rootPage.NotifyUser("Device not found!", NotifyType.ErrorMessage);
return;
}
// Display the found properties
DisplayDeviceProperties(devInfo, this.inputDeviceProperties);
this.rootPage.NotifyUser("Device information found!", NotifyType.StatusMessage);
}
/// <summary>
/// Change the active output MIDI device
/// </summary>
/// <param name="sender">Element that fired the event</param>
/// <param name="e">Event arguments</param>
private void outputDevices_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Get the selected output MIDI device
int selectedOutputDeviceIndex = this.outputDevices.SelectedIndex;
// Try to display the appropriate device properties
if (selectedOutputDeviceIndex < 0)
{
// Clear output device properties
this.outputDeviceProperties.Items.Clear();
this.outputDeviceProperties.Items.Add("Select a MIDI output device to view its properties");
this.outputDeviceProperties.IsEnabled = false;
this.rootPage.NotifyUser("Select a MIDI output device to view its properties", NotifyType.StatusMessage);
return;
}
DeviceInformationCollection devInfoCollection = this.midiOutDeviceWatcher.GetDeviceInformationCollection();
if (devInfoCollection == null)
{
this.outputDeviceProperties.Items.Clear();
this.outputDeviceProperties.Items.Add("Device not found!");
this.outputDeviceProperties.IsEnabled = false;
this.rootPage.NotifyUser("Device not found!", NotifyType.ErrorMessage);
return;
}
DeviceInformation devInfo = devInfoCollection[selectedOutputDeviceIndex];
if (devInfo == null)
{
this.outputDeviceProperties.Items.Clear();
this.outputDeviceProperties.Items.Add("Device not found!");
this.outputDeviceProperties.IsEnabled = false;
this.rootPage.NotifyUser("Device not found!", NotifyType.ErrorMessage);
return;
}
// Display the found properties
DisplayDeviceProperties(devInfo, this.outputDeviceProperties);
this.rootPage.NotifyUser("Device information found!", NotifyType.StatusMessage);
}
/// <summary>
/// Display the properties of the MIDI device to the user
/// </summary>
/// <param name="devInfo"></param>
/// <param name="propertiesList"></param>
private void DisplayDeviceProperties(DeviceInformation devInfo, ListBox propertiesList)
{
propertiesList.Items.Clear();
propertiesList.Items.Add("Id: " + devInfo.Id);
propertiesList.Items.Add("Name: " + devInfo.Name);
propertiesList.Items.Add("IsDefault: " + devInfo.IsDefault);
propertiesList.Items.Add("IsEnabled: " + devInfo.IsEnabled);
propertiesList.Items.Add("EnclosureLocation: " + devInfo.EnclosureLocation);
// Add device interface information
propertiesList.Items.Add("----Device Interface----");
foreach (var deviceProperty in devInfo.Properties)
{
propertiesList.Items.Add(deviceProperty.Key + ": " + deviceProperty.Value);
}
propertiesList.IsEnabled = true;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Hyak.Common;
using Microsoft.Azure.Management.Internal.Resources.Models;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Azure.Management.Internal.Resources
{
/// <summary>
/// Operations for managing deployment operations.
/// </summary>
internal partial class DeploymentOperationOperations : IServiceOperations<ResourceManagementClient>, IDeploymentOperationOperations
{
/// <summary>
/// Initializes a new instance of the DeploymentOperationOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DeploymentOperationOperations(ResourceManagementClient client)
{
this._client = client;
}
private ResourceManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Internal.Resources.ResourceManagementClient.
/// </summary>
public ResourceManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Get a list of deployments operations.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group. The name is case
/// insensitive.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='operationId'>
/// Required. Operation Id.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Deployment operation.
/// </returns>
public async Task<DeploymentOperationsGetResult> GetAsync(string resourceGroupName, string deploymentName, string operationId, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
if (operationId == null)
{
throw new ArgumentNullException("operationId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("operationId", operationId);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourcegroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/operations/";
url = url + Uri.EscapeDataString(operationId);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DeploymentOperationsGetResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DeploymentOperationsGetResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DeploymentOperation operationInstance = new DeploymentOperation();
result.Operation = operationInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
operationInstance.Id = idInstance;
}
JToken operationIdValue = responseDoc["operationId"];
if (operationIdValue != null && operationIdValue.Type != JTokenType.Null)
{
string operationIdInstance = ((string)operationIdValue);
operationInstance.OperationId = operationIdInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
DeploymentOperationProperties propertiesInstance = new DeploymentOperationProperties();
operationInstance.Properties = propertiesInstance;
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
propertiesInstance.ProvisioningState = provisioningStateInstance;
}
JToken timestampValue = propertiesValue["timestamp"];
if (timestampValue != null && timestampValue.Type != JTokenType.Null)
{
DateTime timestampInstance = ((DateTime)timestampValue);
propertiesInstance.Timestamp = timestampInstance;
}
JToken statusCodeValue = propertiesValue["statusCode"];
if (statusCodeValue != null && statusCodeValue.Type != JTokenType.Null)
{
string statusCodeInstance = ((string)statusCodeValue);
propertiesInstance.StatusCode = statusCodeInstance;
}
JToken statusMessageValue = propertiesValue["statusMessage"];
if (statusMessageValue != null && statusMessageValue.Type != JTokenType.Null)
{
string statusMessageInstance = statusMessageValue.ToString(Newtonsoft.Json.Formatting.Indented);
propertiesInstance.StatusMessage = statusMessageInstance;
}
JToken targetResourceValue = propertiesValue["targetResource"];
if (targetResourceValue != null && targetResourceValue.Type != JTokenType.Null)
{
TargetResource targetResourceInstance = new TargetResource();
propertiesInstance.TargetResource = targetResourceInstance;
JToken idValue2 = targetResourceValue["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
targetResourceInstance.Id = idInstance2;
}
JToken resourceNameValue = targetResourceValue["resourceName"];
if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null)
{
string resourceNameInstance = ((string)resourceNameValue);
targetResourceInstance.ResourceName = resourceNameInstance;
}
JToken resourceTypeValue = targetResourceValue["resourceType"];
if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
{
string resourceTypeInstance = ((string)resourceTypeValue);
targetResourceInstance.ResourceType = resourceTypeInstance;
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets a list of deployments operations.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group. The name is case
/// insensitive.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of deployment operations.
/// </returns>
public async Task<DeploymentOperationsListResult> ListAsync(string resourceGroupName, string deploymentName, DeploymentOperationsListParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceGroupName != null && resourceGroupName.Length > 1000)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false)
{
throw new ArgumentOutOfRangeException("resourceGroupName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourcegroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/operations";
List<string> queryParameters = new List<string>();
if (parameters != null && parameters.Top != null)
{
queryParameters.Add("$top=" + Uri.EscapeDataString(parameters.Top.Value.ToString()));
}
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DeploymentOperationsListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DeploymentOperationsListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
DeploymentOperation deploymentOperationInstance = new DeploymentOperation();
result.Operations.Add(deploymentOperationInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
deploymentOperationInstance.Id = idInstance;
}
JToken operationIdValue = valueValue["operationId"];
if (operationIdValue != null && operationIdValue.Type != JTokenType.Null)
{
string operationIdInstance = ((string)operationIdValue);
deploymentOperationInstance.OperationId = operationIdInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
DeploymentOperationProperties propertiesInstance = new DeploymentOperationProperties();
deploymentOperationInstance.Properties = propertiesInstance;
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
propertiesInstance.ProvisioningState = provisioningStateInstance;
}
JToken timestampValue = propertiesValue["timestamp"];
if (timestampValue != null && timestampValue.Type != JTokenType.Null)
{
DateTime timestampInstance = ((DateTime)timestampValue);
propertiesInstance.Timestamp = timestampInstance;
}
JToken statusCodeValue = propertiesValue["statusCode"];
if (statusCodeValue != null && statusCodeValue.Type != JTokenType.Null)
{
string statusCodeInstance = ((string)statusCodeValue);
propertiesInstance.StatusCode = statusCodeInstance;
}
JToken statusMessageValue = propertiesValue["statusMessage"];
if (statusMessageValue != null && statusMessageValue.Type != JTokenType.Null)
{
string statusMessageInstance = statusMessageValue.ToString(Newtonsoft.Json.Formatting.Indented);
propertiesInstance.StatusMessage = statusMessageInstance;
}
JToken targetResourceValue = propertiesValue["targetResource"];
if (targetResourceValue != null && targetResourceValue.Type != JTokenType.Null)
{
TargetResource targetResourceInstance = new TargetResource();
propertiesInstance.TargetResource = targetResourceInstance;
JToken idValue2 = targetResourceValue["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
targetResourceInstance.Id = idInstance2;
}
JToken resourceNameValue = targetResourceValue["resourceName"];
if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null)
{
string resourceNameInstance = ((string)resourceNameValue);
targetResourceInstance.ResourceName = resourceNameInstance;
}
JToken resourceTypeValue = targetResourceValue["resourceType"];
if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
{
string resourceTypeInstance = ((string)resourceTypeValue);
targetResourceInstance.ResourceType = resourceTypeInstance;
}
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets a next list of deployments operations.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of deployment operations.
/// </returns>
public async Task<DeploymentOperationsListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DeploymentOperationsListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DeploymentOperationsListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
DeploymentOperation deploymentOperationInstance = new DeploymentOperation();
result.Operations.Add(deploymentOperationInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
deploymentOperationInstance.Id = idInstance;
}
JToken operationIdValue = valueValue["operationId"];
if (operationIdValue != null && operationIdValue.Type != JTokenType.Null)
{
string operationIdInstance = ((string)operationIdValue);
deploymentOperationInstance.OperationId = operationIdInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
DeploymentOperationProperties propertiesInstance = new DeploymentOperationProperties();
deploymentOperationInstance.Properties = propertiesInstance;
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
propertiesInstance.ProvisioningState = provisioningStateInstance;
}
JToken timestampValue = propertiesValue["timestamp"];
if (timestampValue != null && timestampValue.Type != JTokenType.Null)
{
DateTime timestampInstance = ((DateTime)timestampValue);
propertiesInstance.Timestamp = timestampInstance;
}
JToken statusCodeValue = propertiesValue["statusCode"];
if (statusCodeValue != null && statusCodeValue.Type != JTokenType.Null)
{
string statusCodeInstance = ((string)statusCodeValue);
propertiesInstance.StatusCode = statusCodeInstance;
}
JToken statusMessageValue = propertiesValue["statusMessage"];
if (statusMessageValue != null && statusMessageValue.Type != JTokenType.Null)
{
string statusMessageInstance = statusMessageValue.ToString(Newtonsoft.Json.Formatting.Indented);
propertiesInstance.StatusMessage = statusMessageInstance;
}
JToken targetResourceValue = propertiesValue["targetResource"];
if (targetResourceValue != null && targetResourceValue.Type != JTokenType.Null)
{
TargetResource targetResourceInstance = new TargetResource();
propertiesInstance.TargetResource = targetResourceInstance;
JToken idValue2 = targetResourceValue["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
targetResourceInstance.Id = idInstance2;
}
JToken resourceNameValue = targetResourceValue["resourceName"];
if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null)
{
string resourceNameInstance = ((string)resourceNameValue);
targetResourceInstance.ResourceName = resourceNameInstance;
}
JToken resourceTypeValue = targetResourceValue["resourceType"];
if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
{
string resourceTypeInstance = ((string)resourceTypeValue);
targetResourceInstance.ResourceType = resourceTypeInstance;
}
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class DynamicTests : ExpressionCompilerTestBase
{
[Fact]
public void Local_Simple()
{
var source =
@"class C
{
static void M()
{
dynamic d = 1;
}
static dynamic ForceDynamicAttribute()
{
return null;
}
}";
var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
var method = testData.Methods.Single().Value.Method;
Assert.NotNull(GetDynamicAttributeIfAny(method));
Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind);
VerifyCustomTypeInfo(locals[0], "d", 0x01);
VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt:
@"{
// Code size 2 (0x2)
.maxstack 1
.locals init (dynamic V_0) //d
IL_0000: ldloc.0
IL_0001: ret
}");
locals.Free();
});
}
[Fact]
public void Local_Array()
{
var source =
@"class C
{
static void M()
{
dynamic[] d = new dynamic[1];
}
static dynamic ForceDynamicAttribute()
{
return null;
}
}";
var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
var method = testData.Methods.Single().Value.Method;
Assert.NotNull(GetDynamicAttributeIfAny(method));
Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind);
VerifyCustomTypeInfo(locals[0], "d", 0x02);
VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt:
@"{
// Code size 2 (0x2)
.maxstack 1
.locals init (dynamic[] V_0) //d
IL_0000: ldloc.0
IL_0001: ret
}");
locals.Free();
});
}
[Fact]
public void Local_Generic()
{
var source =
@"class C
{
static void M()
{
System.Collections.Generic.List<dynamic> d = null;
}
static dynamic ForceDynamicAttribute()
{
return null;
}
}";
var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
var method = testData.Methods.Single().Value.Method;
Assert.NotNull(GetDynamicAttributeIfAny(method));
Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments.Single().TypeKind);
VerifyCustomTypeInfo(locals[0], "d", 0x02);
VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt:
@"{
// Code size 2 (0x2)
.maxstack 1
.locals init (System.Collections.Generic.List<dynamic> V_0) //d
IL_0000: ldloc.0
IL_0001: ret
}");
locals.Free();
});
}
[Fact]
public void LocalConstant_Simple()
{
var source =
@"class C
{
static void M()
{
const dynamic d = null;
}
static dynamic ForceDynamicAttribute()
{
return null;
}
}";
var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
var method = testData.Methods.Single().Value.Method;
Assert.NotNull(GetDynamicAttributeIfAny(method));
Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind);
VerifyCustomTypeInfo(locals[0], "d", 0x01);
VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldnull
IL_0001: ret
}");
locals.Free();
});
}
[Fact]
public void LocalConstant_Array()
{
var source =
@"class C
{
static void M()
{
const dynamic[] d = null;
}
static dynamic ForceDynamicAttribute()
{
return null;
}
}";
var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
var method = testData.Methods.Single().Value.Method;
Assert.NotNull(GetDynamicAttributeIfAny(method));
Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind);
VerifyCustomTypeInfo(locals[0], "d", 0x02);
VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @"
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldnull
IL_0001: ret
}");
locals.Free();
});
}
[Fact]
public void LocalConstant_Generic()
{
var source =
@"class C
{
static void M()
{
const Generic<dynamic> d = null;
}
static dynamic ForceDynamicAttribute()
{
return null;
}
}
class Generic<T>
{
}
";
var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
var method = testData.Methods.Single().Value.Method;
Assert.NotNull(GetDynamicAttributeIfAny(method));
Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments.Single().TypeKind);
VerifyCustomTypeInfo(locals[0], "d", 0x02);
VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @"
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldnull
IL_0001: ret
}");
locals.Free();
});
}
[WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")]
[Fact]
public void LocalDuplicateConstantAndNonConstantDynamic()
{
var source =
@"class C
{
static void M()
{
{
#line 799
dynamic a = null;
const dynamic b = null;
}
{
const dynamic[] a = null;
#line 899
dynamic[] b = null;
}
}
static dynamic ForceDynamicAttribute()
{
return null;
}
}";
var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799);
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(2, locals.Count);
if (runtime.DebugFormat == DebugInformationFormat.PortablePdb)
{
VerifyCustomTypeInfo(locals[0], "a", 0x01);
}
else
{
VerifyCustomTypeInfo(locals[0], "a", null); // Dynamic info ignored because ambiguous.
}
VerifyCustomTypeInfo(locals[1], "b", 0x01);
locals.Free();
context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899);
testData = new CompilationTestData();
locals = ArrayBuilder<LocalAndMethod>.GetInstance();
context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(2, locals.Count);
VerifyCustomTypeInfo(locals[0], "b", 0x02);
if (runtime.DebugFormat == DebugInformationFormat.PortablePdb)
{
VerifyCustomTypeInfo(locals[1], "a", 0x02);
}
else
{
VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous.
}
locals.Free();
});
}
[WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")]
[Fact]
public void LocalDuplicateConstantAndNonConstantNonDynamic()
{
var source =
@"class C
{
static void M()
{
{
#line 799
object a = null;
const dynamic b = null;
}
{
const dynamic[] a = null;
#line 899
object[] b = null;
}
}
static dynamic ForceDynamicAttribute()
{
return null;
}
}";
var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799);
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(2, locals.Count);
VerifyCustomTypeInfo(locals[0], "a", null);
VerifyCustomTypeInfo(locals[1], "b", 0x01);
locals.Free();
context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899);
testData = new CompilationTestData();
locals = ArrayBuilder<LocalAndMethod>.GetInstance();
context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(2, locals.Count);
VerifyCustomTypeInfo(locals[0], "b", null);
if (runtime.DebugFormat == DebugInformationFormat.PortablePdb)
{
VerifyCustomTypeInfo(locals[1], "a", 0x02);
}
else
{
VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous.
}
locals.Free();
});
}
[WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")]
[Fact]
public void LocalDuplicateConstantAndConstantDynamic()
{
var source =
@"class C
{
static void M()
{
{
const dynamic a = null;
const dynamic b = null;
#line 799
object e = null;
}
{
const dynamic[] a = null;
const dynamic[] c = null;
#line 899
object[] e = null;
}
{
#line 999
object e = null;
const dynamic a = null;
const dynamic c = null;
}
}
static dynamic ForceDynamicAttribute()
{
return null;
}
}";
var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799);
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(3, locals.Count);
VerifyCustomTypeInfo(locals[0], "e", null);
if (runtime.DebugFormat == DebugInformationFormat.PortablePdb)
{
VerifyCustomTypeInfo(locals[1], "a", 0x01);
}
else
{
VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous.
}
VerifyCustomTypeInfo(locals[2], "b", 0x01);
locals.Free();
context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899);
testData = new CompilationTestData();
locals = ArrayBuilder<LocalAndMethod>.GetInstance();
context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(3, locals.Count);
VerifyCustomTypeInfo(locals[0], "e", null);
if (runtime.DebugFormat == DebugInformationFormat.PortablePdb)
{
VerifyCustomTypeInfo(locals[1], "a", 0x02);
VerifyCustomTypeInfo(locals[2], "c", 0x02);
}
else
{
VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous.
VerifyCustomTypeInfo(locals[2], "c", null); // Dynamic info ignored because ambiguous.
}
locals.Free();
context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 999);
testData = new CompilationTestData();
locals = ArrayBuilder<LocalAndMethod>.GetInstance();
context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(3, locals.Count);
VerifyCustomTypeInfo(locals[0], "e", null);
if (runtime.DebugFormat == DebugInformationFormat.PortablePdb)
{
VerifyCustomTypeInfo(locals[1], "a", 0x01);
VerifyCustomTypeInfo(locals[2], "c", 0x01);
}
else
{
VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous.
VerifyCustomTypeInfo(locals[2], "c", null); // Dynamic info ignored because ambiguous.
}
locals.Free();
});
}
[WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")]
[Fact]
public void LocalDuplicateConstantAndConstantNonDynamic()
{
var source =
@"class C
{
static void M()
{
{
const dynamic a = null;
const object c = null;
#line 799
object e = null;
}
{
const dynamic[] b = null;
#line 899
object[] e = null;
}
{
const object[] a = null;
#line 999
object e = null;
const dynamic[] c = null;
}
}
static dynamic ForceDynamicAttribute()
{
return null;
}
}";
var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799);
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(3, locals.Count);
VerifyCustomTypeInfo(locals[0], "e", null);
if (runtime.DebugFormat == DebugInformationFormat.PortablePdb)
{
VerifyCustomTypeInfo(locals[1], "a", 0x01);
}
else
{
VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous.
}
VerifyCustomTypeInfo(locals[2], "c", null);
locals.Free();
context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899);
testData = new CompilationTestData();
locals = ArrayBuilder<LocalAndMethod>.GetInstance();
context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(2, locals.Count);
VerifyCustomTypeInfo(locals[0], "e", null);
VerifyCustomTypeInfo(locals[1], "b", 0x02);
locals.Free();
context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 999);
testData = new CompilationTestData();
locals = ArrayBuilder<LocalAndMethod>.GetInstance();
context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(3, locals.Count);
VerifyCustomTypeInfo(locals[0], "e", null);
VerifyCustomTypeInfo(locals[1], "a", null);
if (runtime.DebugFormat == DebugInformationFormat.PortablePdb)
{
VerifyCustomTypeInfo(locals[2], "c", 0x02);
}
else
{
VerifyCustomTypeInfo(locals[2], "c", null); // Dynamic info ignored because ambiguous.
}
locals.Free();
});
}
[Fact]
public void LocalsWithLongAndShortNames()
{
var source =
@"class C
{
static void M()
{
const dynamic a123456789012345678901234567890123456789012345678901234567890123 = null; // 64 chars
const dynamic b = null;
dynamic c123456789012345678901234567890123456789012345678901234567890123 = null; // 64 chars
dynamic d = null;
}
static dynamic ForceDynamicAttribute()
{
return null;
}
}";
var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, methodName: "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(4, locals.Count);
if (runtime.DebugFormat == DebugInformationFormat.PortablePdb)
{
VerifyCustomTypeInfo(locals[0], "c123456789012345678901234567890123456789012345678901234567890123", 0x01);
VerifyCustomTypeInfo(locals[2], "a123456789012345678901234567890123456789012345678901234567890123", 0x01);
}
else
{
VerifyCustomTypeInfo(locals[0], "c123456789012345678901234567890123456789012345678901234567890123", null); // dynamic info dropped
VerifyCustomTypeInfo(locals[2], "a123456789012345678901234567890123456789012345678901234567890123", null); // dynamic info dropped
}
VerifyCustomTypeInfo(locals[1], "d", 0x01);
VerifyCustomTypeInfo(locals[3], "b", 0x01);
locals.Free();
});
}
[Fact]
public void Parameter_Simple()
{
var source =
@"class C
{
static void M(dynamic d)
{
}
static dynamic ForceDynamicAttribute()
{
return null;
}
}";
var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
var method = testData.Methods.Single().Value.Method;
Assert.NotNull(GetDynamicAttributeIfAny(method));
Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind);
VerifyCustomTypeInfo(locals[0], "d", 0x01);
VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt:
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}");
locals.Free();
});
}
[Fact]
public void Parameter_Array()
{
var source =
@"class C
{
static void M(dynamic[] d)
{
}
static dynamic ForceDynamicAttribute()
{
return null;
}
}";
var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
var method = testData.Methods.Single().Value.Method;
Assert.NotNull(GetDynamicAttributeIfAny(method));
Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind);
VerifyCustomTypeInfo(locals[0], "d", 0x02);
VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt:
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}");
locals.Free();
});
}
[Fact]
public void Parameter_Generic()
{
var source =
@"class C
{
static void M(System.Collections.Generic.List<dynamic> d)
{
}
static dynamic ForceDynamicAttribute()
{
return null;
}
}";
var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
var method = testData.Methods.Single().Value.Method;
Assert.NotNull(GetDynamicAttributeIfAny(method));
Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments.Single().TypeKind);
VerifyCustomTypeInfo(locals[0], "d", 0x02);
VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt:
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}");
locals.Free();
});
}
[WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")]
[Fact]
public void ComplexDynamicType()
{
var source =
@"class C
{
static void M(Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic> d)
{
}
static dynamic ForceDynamicAttribute()
{
return null;
}
}
public class Outer<T, U>
{
public class Inner<V, W>
{
}
}
";
var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
var method = testData.Methods.Single().Value.Method;
Assert.NotNull(GetDynamicAttributeIfAny(method));
VerifyCustomTypeInfo(locals[0], "d", 0x04, 0x03);
VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt:
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}");
string error;
var result = context.CompileExpression("d", out error);
Assert.Null(error);
VerifyCustomTypeInfo(result, 0x04, 0x03);
// Note that the method produced by CompileAssignment returns void
// so there is never custom type info.
result = context.CompileAssignment("d", "d", out error);
Assert.Null(error);
VerifyCustomTypeInfo(result, null);
ResultProperties resultProperties;
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
testData = new CompilationTestData();
result = context.CompileExpression(
"var dd = d;",
DkmEvaluationFlags.None,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Null(error);
VerifyCustomTypeInfo(result, null);
Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 60 (0x3c)
.maxstack 6
IL_0000: ldtoken ""Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic>""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""dd""
IL_000f: ldstr ""108766ce-df68-46ee-b761-0dcb7ac805f1""
IL_0014: newobj ""System.Guid..ctor(string)""
IL_0019: ldc.i4.3
IL_001a: newarr ""byte""
IL_001f: dup
IL_0020: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=3 <PrivateImplementationDetails>.A4E591DA7617172655FE45FC3878ECC8CC0D44B3""
IL_0025: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_002a: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_002f: ldstr ""dd""
IL_0034: call ""Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic> Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic>>(string)""
IL_0039: ldarg.0
IL_003a: stind.ref
IL_003b: ret
}");
locals.Free();
});
}
[Fact]
public void DynamicAliases()
{
var source =
@"class C
{
static void M()
{
}
static dynamic ForceDynamicAttribute()
{
return null;
}
}";
var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(
runtime,
"C.M");
var aliases = ImmutableArray.Create(
Alias(
DkmClrAliasKind.Variable,
"d1",
"d1",
typeof(object).AssemblyQualifiedName,
MakeCustomTypeInfo(true)),
Alias(
DkmClrAliasKind.Variable,
"d2",
"d2",
typeof(Dictionary<Dictionary<dynamic, Dictionary<object[], dynamic[]>>, object>).AssemblyQualifiedName,
MakeCustomTypeInfo(false, false, true, false, false, false, false, true, false)));
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var diagnostics = DiagnosticBag.GetInstance();
var testData = new CompilationTestData();
context.CompileGetLocals(
locals,
argumentsOnly: false,
aliases: aliases,
diagnostics: diagnostics,
typeName: out typeName,
testData: testData);
diagnostics.Free();
Assert.Equal(locals.Count, 2);
VerifyCustomTypeInfo(locals[0], "d1", 0x01);
VerifyLocal(testData, typeName, locals[0], "<>m0", "d1", expectedILOpt:
@"{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr ""d1""
IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_000a: ret
}");
VerifyCustomTypeInfo(locals[1], "d2", 0x84, 0x00); // Note: read flags right-to-left in each byte: 0010 0001 0(000 0000)
VerifyLocal(testData, typeName, locals[1], "<>m1", "d2", expectedILOpt:
@"{
// Code size 16 (0x10)
.maxstack 1
IL_0000: ldstr ""d2""
IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_000a: castclass ""System.Collections.Generic.Dictionary<System.Collections.Generic.Dictionary<dynamic, System.Collections.Generic.Dictionary<object[], dynamic[]>>, object>""
IL_000f: ret
}");
locals.Free();
});
}
private static ReadOnlyCollection<byte> MakeCustomTypeInfo(params bool[] flags)
{
Assert.NotNull(flags);
var builder = ArrayBuilder<bool>.GetInstance();
builder.AddRange(flags);
var bytes = DynamicFlagsCustomTypeInfo.ToBytes(builder);
builder.Free();
return CustomTypeInfo.Encode(bytes, null);
}
[Fact]
public void DynamicAttribute_NotAvailable()
{
var source =
@"class C
{
static void M()
{
dynamic d = 1;
}
}";
var comp = CreateStandardCompilation(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
var method = testData.Methods.Single().Value.Method;
Assert.Null(GetDynamicAttributeIfAny(method));
VerifyCustomTypeInfo(locals[0], "d", null);
VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt:
@"{
// Code size 2 (0x2)
.maxstack 1
.locals init (dynamic V_0) //d
IL_0000: ldloc.0
IL_0001: ret
}");
locals.Free();
});
}
[Fact]
public void DynamicCall()
{
var source = @"
class C
{
void M()
{
dynamic d = this;
d.M();
}
}
";
var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
var result = context.CompileExpression("d.M()", out error, testData);
Assert.Null(error);
VerifyCustomTypeInfo(result, 0x01);
var methodData = testData.GetMethodData("<>x.<>m0");
Assert.Equal(TypeKind.Dynamic, methodData.Method.ReturnType.TypeKind);
methodData.VerifyIL(@"
{
// Code size 77 (0x4d)
.maxstack 9
.locals init (dynamic V_0) //d
IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0""
IL_0005: brtrue.s IL_0037
IL_0007: ldc.i4.0
IL_0008: ldstr ""M""
IL_000d: ldnull
IL_000e: ldtoken ""C""
IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0018: ldc.i4.1
IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_001e: dup
IL_001f: ldc.i4.0
IL_0020: ldc.i4.0
IL_0021: ldnull
IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0027: stelem.ref
IL_0028: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_002d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0032: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0""
IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0""
IL_003c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target""
IL_0041: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0""
IL_0046: ldloc.0
IL_0047: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_004c: ret
}
");
});
}
[WorkItem(1160855, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1160855")]
[Fact]
public void AwaitDynamic()
{
var source = @"
using System;
using System.Threading;
using System.Threading.Tasks;
class C
{
dynamic d;
void M(int p)
{
d.Test(); // Force reference to runtime binder.
}
static void G(Func<Task<object>> f)
{
}
}
";
var comp = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
var result = context.CompileExpression("G(async () => await d())", out error, testData);
Assert.Null(error);
VerifyCustomTypeInfo(result, null);
var methodData = testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()");
methodData.VerifyIL(@"
{
// Code size 544 (0x220)
.maxstack 10
.locals init (int V_0,
<>x.<>c__DisplayClass0_0 V_1,
object V_2,
object V_3,
System.Runtime.CompilerServices.ICriticalNotifyCompletion V_4,
System.Runtime.CompilerServices.INotifyCompletion V_5,
System.Exception V_6)
IL_0000: ldarg.0
IL_0001: ldfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state""
IL_0006: stloc.0
IL_0007: ldarg.0
IL_0008: ldfld ""<>x.<>c__DisplayClass0_0 <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>4__this""
IL_000d: stloc.1
.try
{
IL_000e: ldloc.0
IL_000f: brfalse IL_018a
IL_0014: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0""
IL_0019: brtrue.s IL_004b
IL_001b: ldc.i4.0
IL_001c: ldstr ""GetAwaiter""
IL_0021: ldnull
IL_0022: ldtoken ""C""
IL_0027: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_002c: ldc.i4.1
IL_002d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0032: dup
IL_0033: ldc.i4.0
IL_0034: ldc.i4.0
IL_0035: ldnull
IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_003b: stelem.ref
IL_003c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0041: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0046: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0""
IL_004b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0""
IL_0050: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target""
IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0""
IL_005a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0""
IL_005f: brtrue.s IL_008b
IL_0061: ldc.i4.0
IL_0062: ldtoken ""C""
IL_0067: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_006c: ldc.i4.1
IL_006d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0072: dup
IL_0073: ldc.i4.0
IL_0074: ldc.i4.0
IL_0075: ldnull
IL_0076: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_007b: stelem.ref
IL_007c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0081: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0086: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0""
IL_008b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0""
IL_0090: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target""
IL_0095: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0""
IL_009a: ldloc.1
IL_009b: ldfld ""C <>x.<>c__DisplayClass0_0.<>4__this""
IL_00a0: ldfld ""dynamic C.d""
IL_00a5: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_00aa: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_00af: stloc.3
IL_00b0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2""
IL_00b5: brtrue.s IL_00dc
IL_00b7: ldc.i4.s 16
IL_00b9: ldtoken ""bool""
IL_00be: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_00c3: ldtoken ""C""
IL_00c8: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_00cd: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_00d2: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_00d7: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2""
IL_00dc: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2""
IL_00e1: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Target""
IL_00e6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2""
IL_00eb: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1""
IL_00f0: brtrue.s IL_0121
IL_00f2: ldc.i4.0
IL_00f3: ldstr ""IsCompleted""
IL_00f8: ldtoken ""C""
IL_00fd: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0102: ldc.i4.1
IL_0103: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0108: dup
IL_0109: ldc.i4.0
IL_010a: ldc.i4.0
IL_010b: ldnull
IL_010c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0111: stelem.ref
IL_0112: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0117: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_011c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1""
IL_0121: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1""
IL_0126: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target""
IL_012b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1""
IL_0130: ldloc.3
IL_0131: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_0136: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_013b: brtrue.s IL_01a1
IL_013d: ldarg.0
IL_013e: ldc.i4.0
IL_013f: dup
IL_0140: stloc.0
IL_0141: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state""
IL_0146: ldarg.0
IL_0147: ldloc.3
IL_0148: stfld ""object <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>u__1""
IL_014d: ldloc.3
IL_014e: isinst ""System.Runtime.CompilerServices.ICriticalNotifyCompletion""
IL_0153: stloc.s V_4
IL_0155: ldloc.s V_4
IL_0157: brtrue.s IL_0174
IL_0159: ldloc.3
IL_015a: castclass ""System.Runtime.CompilerServices.INotifyCompletion""
IL_015f: stloc.s V_5
IL_0161: ldarg.0
IL_0162: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder""
IL_0167: ldloca.s V_5
IL_0169: ldarg.0
IL_016a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.AwaitOnCompleted<System.Runtime.CompilerServices.INotifyCompletion, <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d>(ref System.Runtime.CompilerServices.INotifyCompletion, ref <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d)""
IL_016f: ldnull
IL_0170: stloc.s V_5
IL_0172: br.s IL_0182
IL_0174: ldarg.0
IL_0175: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder""
IL_017a: ldloca.s V_4
IL_017c: ldarg.0
IL_017d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ICriticalNotifyCompletion, <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d>(ref System.Runtime.CompilerServices.ICriticalNotifyCompletion, ref <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d)""
IL_0182: ldnull
IL_0183: stloc.s V_4
IL_0185: leave IL_021f
IL_018a: ldarg.0
IL_018b: ldfld ""object <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>u__1""
IL_0190: stloc.3
IL_0191: ldarg.0
IL_0192: ldnull
IL_0193: stfld ""object <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>u__1""
IL_0198: ldarg.0
IL_0199: ldc.i4.m1
IL_019a: dup
IL_019b: stloc.0
IL_019c: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state""
IL_01a1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3""
IL_01a6: brtrue.s IL_01d8
IL_01a8: ldc.i4.0
IL_01a9: ldstr ""GetResult""
IL_01ae: ldnull
IL_01af: ldtoken ""C""
IL_01b4: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_01b9: ldc.i4.1
IL_01ba: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_01bf: dup
IL_01c0: ldc.i4.0
IL_01c1: ldc.i4.0
IL_01c2: ldnull
IL_01c3: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_01c8: stelem.ref
IL_01c9: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_01ce: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_01d3: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3""
IL_01d8: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3""
IL_01dd: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target""
IL_01e2: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3""
IL_01e7: ldloc.3
IL_01e8: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_01ed: ldnull
IL_01ee: stloc.3
IL_01ef: stloc.2
IL_01f0: leave.s IL_020b
}
catch System.Exception
{
IL_01f2: stloc.s V_6
IL_01f4: ldarg.0
IL_01f5: ldc.i4.s -2
IL_01f7: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state""
IL_01fc: ldarg.0
IL_01fd: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder""
IL_0202: ldloc.s V_6
IL_0204: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)""
IL_0209: leave.s IL_021f
}
IL_020b: ldarg.0
IL_020c: ldc.i4.s -2
IL_020e: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state""
IL_0213: ldarg.0
IL_0214: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder""
IL_0219: ldloc.2
IL_021a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)""
IL_021f: ret
}
");
});
}
[WorkItem(1072296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072296")]
[Fact]
public void InvokeStaticMemberInLambda()
{
var source = @"
class C
{
static dynamic x;
static void Foo(dynamic y)
{
System.Action a = () => Foo(x);
}
}
";
var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.Foo");
var testData = new CompilationTestData();
string error;
var result = context.CompileAssignment("a", "() => Foo(x)", out error, testData);
Assert.Null(error);
VerifyCustomTypeInfo(result, null);
testData.GetMethodData("<>x.<>c.<<>m0>b__0_0").VerifyIL(@"
{
// Code size 106 (0x6a)
.maxstack 9
IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0""
IL_0005: brtrue.s IL_0046
IL_0007: ldc.i4 0x100
IL_000c: ldstr ""Foo""
IL_0011: ldnull
IL_0012: ldtoken ""C""
IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001c: ldc.i4.2
IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0022: dup
IL_0023: ldc.i4.0
IL_0024: ldc.i4.s 33
IL_0026: ldnull
IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002c: stelem.ref
IL_002d: dup
IL_002e: ldc.i4.1
IL_002f: ldc.i4.0
IL_0030: ldnull
IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0036: stelem.ref
IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0""
IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0""
IL_004b: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Target""
IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0""
IL_0055: ldtoken ""<>x""
IL_005a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_005f: ldsfld ""dynamic C.x""
IL_0064: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)""
IL_0069: ret
}");
context = CreateMethodContext(runtime, "C.<>c.<Foo>b__1_0");
testData = new CompilationTestData();
result = context.CompileExpression("Foo(x)", out error, testData);
Assert.Null(error);
VerifyCustomTypeInfo(result, 0x01);
var methodData = testData.GetMethodData("<>x.<>m0");
methodData.VerifyIL(@"
{
// Code size 102 (0x66)
.maxstack 9
IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0""
IL_0005: brtrue.s IL_0042
IL_0007: ldc.i4.0
IL_0008: ldstr ""Foo""
IL_000d: ldnull
IL_000e: ldtoken ""C""
IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0018: ldc.i4.2
IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_001e: dup
IL_001f: ldc.i4.0
IL_0020: ldc.i4.s 33
IL_0022: ldnull
IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0028: stelem.ref
IL_0029: dup
IL_002a: ldc.i4.1
IL_002b: ldc.i4.0
IL_002c: ldnull
IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0032: stelem.ref
IL_0033: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0038: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_003d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0""
IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0""
IL_0047: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target""
IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0""
IL_0051: ldtoken ""<>x""
IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_005b: ldsfld ""dynamic C.x""
IL_0060: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)""
IL_0065: ret
}");
});
}
[WorkItem(1095613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1095613")]
[Fact]
public void HoistedLocalsLoseDynamicAttribute()
{
var source = @"
class C
{
static void M(dynamic x)
{
dynamic y = 3;
System.Func<dynamic> a = () => x + y;
}
static void Foo(int x)
{
M(x);
}
}
";
var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
var result = context.CompileExpression("Foo(x)", out error, testData);
Assert.Null(error);
VerifyCustomTypeInfo(result, 0x01);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 103 (0x67)
.maxstack 9
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
System.Func<dynamic> V_1) //a
IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0""
IL_0005: brtrue.s IL_0042
IL_0007: ldc.i4.0
IL_0008: ldstr ""Foo""
IL_000d: ldnull
IL_000e: ldtoken ""C""
IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0018: ldc.i4.2
IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_001e: dup
IL_001f: ldc.i4.0
IL_0020: ldc.i4.s 33
IL_0022: ldnull
IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0028: stelem.ref
IL_0029: dup
IL_002a: ldc.i4.1
IL_002b: ldc.i4.0
IL_002c: ldnull
IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0032: stelem.ref
IL_0033: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0038: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_003d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0""
IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0""
IL_0047: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target""
IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0""
IL_0051: ldtoken ""<>x""
IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_005b: ldloc.0
IL_005c: ldfld ""dynamic C.<>c__DisplayClass0_0.x""
IL_0061: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)""
IL_0066: ret
}");
testData = new CompilationTestData();
result = context.CompileExpression("Foo(y)", out error, testData);
Assert.Null(error);
VerifyCustomTypeInfo(result, 0x01);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 103 (0x67)
.maxstack 9
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
System.Func<dynamic> V_1) //a
IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0""
IL_0005: brtrue.s IL_0042
IL_0007: ldc.i4.0
IL_0008: ldstr ""Foo""
IL_000d: ldnull
IL_000e: ldtoken ""C""
IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0018: ldc.i4.2
IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_001e: dup
IL_001f: ldc.i4.0
IL_0020: ldc.i4.s 33
IL_0022: ldnull
IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0028: stelem.ref
IL_0029: dup
IL_002a: ldc.i4.1
IL_002b: ldc.i4.0
IL_002c: ldnull
IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0032: stelem.ref
IL_0033: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0038: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_003d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0""
IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0""
IL_0047: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target""
IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0""
IL_0051: ldtoken ""<>x""
IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_005b: ldloc.0
IL_005c: ldfld ""dynamic C.<>c__DisplayClass0_0.y""
IL_0061: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)""
IL_0066: ret
}");
});
}
private static void VerifyCustomTypeInfo(LocalAndMethod localAndMethod, string expectedName, params byte[] expectedBytes)
{
Assert.Equal(localAndMethod.LocalName, expectedName);
ReadOnlyCollection<byte> customTypeInfo;
Guid customTypeInfoId = localAndMethod.GetCustomTypeInfo(out customTypeInfo);
VerifyCustomTypeInfo(customTypeInfoId, customTypeInfo, expectedBytes);
}
private static void VerifyCustomTypeInfo(CompileResult compileResult, params byte[] expectedBytes)
{
ReadOnlyCollection<byte> customTypeInfo;
Guid customTypeInfoId = compileResult.GetCustomTypeInfo(out customTypeInfo);
VerifyCustomTypeInfo(customTypeInfoId, customTypeInfo, expectedBytes);
}
private static void VerifyCustomTypeInfo(Guid customTypeInfoId, ReadOnlyCollection<byte> customTypeInfo, params byte[] expectedBytes)
{
if (expectedBytes == null)
{
Assert.Equal(Guid.Empty, customTypeInfoId);
Assert.Null(customTypeInfo);
}
else
{
Assert.Equal(CustomTypeInfo.PayloadTypeId, customTypeInfoId);
// Include leading count byte.
var builder = ArrayBuilder<byte>.GetInstance();
builder.Add((byte)expectedBytes.Length);
builder.AddRange(expectedBytes);
expectedBytes = builder.ToArrayAndFree();
Assert.Equal(expectedBytes, customTypeInfo);
}
}
}
}
| |
using System.Collections.Generic;
using Android.Content;
using Android.Content.Res;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Support.V4.View;
using Android.Util;
using Android.Views;
using Com.Flyco.PageIndicator.Indicator.Base;
using Java.Lang;
namespace Com.Flyco.PageIndicator.Indicator
{
/** A pratice demo use GradientDrawable to realize the effect of JakeWharton's CirclePageIndicator */
public class RoundCornerIndicator : View, IPageIndicator
{
private Context context;
private ViewPager vp;
private List<GradientDrawable> unselectDrawables = new List<GradientDrawable>();
private List<Rect> unselectRects = new List<Rect>();
private GradientDrawable selectDrawable = new GradientDrawable();
private Rect selectRect = new Rect();
private int count;
private int currentItem;
private float positionOffset;
private int indicatorWidth;
private int indicatorHeight;
private int indicatorGap;
private int cornerRadius;
private int selectColor;
private int unselectColor;
private int strokeWidth;
private int strokeColor;
private bool isSnap;
public RoundCornerIndicator(Context context) : this(context, null)
{
}
public RoundCornerIndicator(Context context, IAttributeSet attrs) : this(context, attrs, 0)
{
}
public RoundCornerIndicator(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr)
{
this.context = context;
TypedArray ta = context.ObtainStyledAttributes(attrs, Resource.Styleable.RoundCornerIndicaor);
indicatorWidth = ta.GetDimensionPixelSize(Resource.Styleable.RoundCornerIndicaor_rci_width, Dp2px(6));
indicatorHeight = ta.GetDimensionPixelSize(Resource.Styleable.RoundCornerIndicaor_rci_height, Dp2px(6));
indicatorGap = ta.GetDimensionPixelSize(Resource.Styleable.RoundCornerIndicaor_rci_gap, Dp2px(8));
cornerRadius = ta.GetDimensionPixelSize(Resource.Styleable.RoundCornerIndicaor_rci_cornerRadius, Dp2px(3));
strokeWidth = ta.GetDimensionPixelSize(Resource.Styleable.RoundCornerIndicaor_rci_strokeWidth, Dp2px(0));
selectColor = ta.GetColor(Resource.Styleable.RoundCornerIndicaor_rci_selectColor, Color.ParseColor("#ffffff"));
unselectColor = ta.GetColor(Resource.Styleable.RoundCornerIndicaor_rci_unselectColor, Color.ParseColor("#88ffffff"));
strokeColor = ta.GetColor(Resource.Styleable.RoundCornerIndicaor_rci_strokeColor, Color.ParseColor("#ffffff"));
isSnap = ta.GetBoolean(Resource.Styleable.RoundCornerIndicaor_rci_isSnap, false);
ta.Recycle();
}
public void SetViewPager(ViewPager vp)
{
if (IsValid(vp))
{
this.vp = vp;
this.count = vp.Adapter.Count;
vp.RemoveOnPageChangeListener(this);
vp.AddOnPageChangeListener(this);
unselectDrawables.Clear();
unselectRects.Clear();
for (int i = 0; i < count; i++)
{
unselectDrawables.Add(new GradientDrawable());
unselectRects.Add(new Rect());
}
Invalidate();
}
}
public void SetViewPager(ViewPager vp, int realCount)
{
if (IsValid(vp))
{
this.vp = vp;
this.count = realCount;
vp.RemoveOnPageChangeListener(this);
vp.AddOnPageChangeListener(this);
unselectDrawables.Clear();
unselectRects.Clear();
for (int i = 0; i < count; i++)
{
unselectDrawables.Add(new GradientDrawable());
unselectRects.Add(new Rect());
}
Invalidate();
}
}
public void SetCurrentItem(int item)
{
if (IsValid(vp))
{
vp.CurrentItem = item;
}
}
public int IndicatorWidth
{
set
{
this.indicatorWidth = value;
Invalidate();
}
get
{
return indicatorWidth;
}
}
public int IndicatorHeight
{
set
{
this.indicatorHeight = value;
Invalidate();
}
get
{
return indicatorHeight;
}
}
public int IndicatorGap
{
set
{
this.indicatorGap = value;
Invalidate();
}
get
{
return indicatorGap;
}
}
public int CornerRadius
{
set
{
this.cornerRadius = value;
Invalidate();
}
get
{
return cornerRadius;
}
}
public int SelectColor
{
set
{
this.selectColor = value;
Invalidate();
}
get
{
return selectColor;
}
}
public int UnselectColor
{
set
{
this.unselectColor = value;
Invalidate();
}
get
{
return unselectColor;
}
}
public int StrokeWidth
{
set
{
this.strokeWidth = value;
Invalidate();
}
get
{
return strokeWidth;
}
}
public int StrokeColor
{
set
{
this.strokeColor = value;
Invalidate();
}
get
{
return strokeColor;
}
}
public bool IsSnap
{
set
{
this.isSnap = value;
Invalidate();
}
get
{
return isSnap;
}
}
private bool IsValid(ViewPager vp)
{
if (vp == null)
{
throw new IllegalStateException("ViewPager can not be NULL!");
}
if (vp.Adapter == null)
{
throw new IllegalStateException("ViewPager adapter can not be NULL!");
}
return true;
}
public void OnPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
if (!isSnap)
{
currentItem = position;
this.positionOffset = positionOffset;
Invalidate();
}
}
public void OnPageSelected(int position)
{
if (isSnap)
{
currentItem = position;
Invalidate();
}
}
public void OnPageScrollStateChanged(int state)
{
}
protected override void OnDraw(Canvas canvas)
{
base.OnDraw(canvas);
if (count <= 0)
{
return;
}
int verticalOffset = PaddingTop + (Height - PaddingTop - PaddingBottom) / 2 - indicatorHeight / 2;
int indicatorLayoutWidth = indicatorWidth * count + indicatorGap * (count - 1);
int horizontalOffset = PaddingLeft + (Width - PaddingLeft - PaddingRight) / 2 - indicatorLayoutWidth / 2;
DrawUnselect(canvas, count, verticalOffset, horizontalOffset);
DrawSelect(canvas, verticalOffset, horizontalOffset);
}
private void DrawUnselect(Canvas canvas, int count, int verticalOffset, int horizontalOffset)
{
for (int i = 0; i < count; i++)
{
Rect rect = unselectRects[i];
rect.Left = horizontalOffset + (indicatorWidth + indicatorGap) * i;
rect.Top = verticalOffset;
rect.Right = rect.Left + indicatorWidth;
rect.Bottom = rect.Top + indicatorHeight;
GradientDrawable unselectDrawable = unselectDrawables[i];
unselectDrawable.SetCornerRadius(cornerRadius);
unselectDrawable.SetColor(unselectColor);
unselectDrawable.SetStroke(strokeWidth, new Color(strokeColor));
unselectDrawable.Bounds = rect;
unselectDrawable.Draw(canvas);
}
}
private void DrawSelect(Canvas canvas, int verticalOffset, int horizontalOffset)
{
int delta = (int)((indicatorGap + indicatorWidth) * (isSnap ? 0 : positionOffset));
selectRect.Left = horizontalOffset + (indicatorWidth + indicatorGap) * currentItem + delta;
selectRect.Top = verticalOffset;
selectRect.Right = selectRect.Left + indicatorWidth;
selectRect.Bottom = selectRect.Top + indicatorHeight;
selectDrawable.SetCornerRadius(cornerRadius);
selectDrawable.SetColor(selectColor);
selectDrawable.Bounds = selectRect;
selectDrawable.Draw(canvas);
}
protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
SetMeasuredDimension(MeasureWidth(widthMeasureSpec), MeasureHeight(heightMeasureSpec));
}
private int MeasureWidth(int widthMeasureSpec)
{
int result;
MeasureSpecMode specMode = MeasureSpec.GetMode(widthMeasureSpec);
int specSize = MeasureSpec.GetSize(widthMeasureSpec);
if (specMode == MeasureSpecMode.Exactly || count == 0)
{
result = specSize;
}
else {
int padding = PaddingLeft + PaddingRight;
result = padding + indicatorWidth * count + indicatorGap * (count - 1);
if (specMode == MeasureSpecMode.AtMost)
{
result = Math.Min(result, specSize);
}
}
return result;
}
private int MeasureHeight(int heightMeasureSpec)
{
int result;
MeasureSpecMode specMode = MeasureSpec.GetMode(heightMeasureSpec);
int specSize = MeasureSpec.GetSize(heightMeasureSpec);
if (specMode == MeasureSpecMode.Exactly)
{
result = specSize;
}
else {
int padding = PaddingTop + PaddingBottom;
result = padding + indicatorHeight;
if (specMode == MeasureSpecMode.AtMost)
{
result = Math.Min(result, specSize);
}
}
return result;
}
protected override IParcelable OnSaveInstanceState()
{
Bundle bundle = new Bundle();
bundle.PutParcelable("instanceState", base.OnSaveInstanceState());
bundle.PutInt("currentItem", currentItem);
return bundle;
}
protected override void OnRestoreInstanceState(IParcelable state)
{
if (state is Bundle)
{
Bundle bundle = (Bundle)state;
currentItem = bundle.GetInt("currentItem");
state = bundle.GetParcelable("instanceState") as IParcelable;
}
base.OnRestoreInstanceState(state);
}
protected int Dp2px(float dp)
{
float scale = context.Resources.DisplayMetrics.Density;
return (int)(dp * scale + 0.5f);
}
}
}
| |
/*
* Copyright (C) 2011 Keijiro Takahashi
* Copyright (C) 2012 GREE, Inc.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
#if UNITY_2018_4_OR_NEWER
using UnityEngine.Networking;
#endif
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
using System.IO;
using System.Text.RegularExpressions;
using UnityEngine.Rendering;
#endif
using Callback = System.Action<string>;
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
public class UnitySendMessageDispatcher
{
public static void Dispatch(string name, string method, string message)
{
GameObject obj = GameObject.Find(name);
if (obj != null)
obj.SendMessage(method, message);
}
}
#endif
public class WebViewObject : MonoBehaviour
{
Callback onJS;
Callback onError;
Callback onHttpError;
Callback onStarted;
Callback onLoaded;
Callback onHooked;
bool visibility;
bool alertDialogEnabled = true;
bool scrollBounceEnabled = true;
int mMarginLeft;
int mMarginTop;
int mMarginRight;
int mMarginBottom;
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
IntPtr webView;
Rect rect;
Texture2D texture;
string inputString = "";
// string keyChars0 = "";
// ushort keyCode0 = 0;
bool hasFocus;
#elif UNITY_IPHONE
IntPtr webView;
#elif UNITY_ANDROID
AndroidJavaObject webView;
bool mVisibility;
bool mIsKeyboardVisible0;
bool mIsKeyboardVisible;
float mResumedTimestamp;
void OnApplicationPause(bool paused)
{
if (webView == null)
return;
if (!paused)
{
webView.Call("SetVisibility", false);
mResumedTimestamp = Time.realtimeSinceStartup;
}
webView.Call("OnApplicationPause", paused);
}
void Update()
{
if (webView == null)
return;
if (mResumedTimestamp != 0.0f && Time.realtimeSinceStartup - mResumedTimestamp > 0.5f)
{
mResumedTimestamp = 0.0f;
webView.Call("SetVisibility", mVisibility);
}
}
/// Called from Java native plugin to set when the keyboard is opened
public void SetKeyboardVisible(string pIsVisible)
{
mIsKeyboardVisible = (pIsVisible == "true");
if (mIsKeyboardVisible != mIsKeyboardVisible0)
{
mIsKeyboardVisible0 = mIsKeyboardVisible;
SetMargins(mMarginLeft, mMarginTop, mMarginRight, mMarginBottom);
} else if (mIsKeyboardVisible) {
SetMargins(mMarginLeft, mMarginTop, mMarginRight, mMarginBottom);
}
}
public int AdjustBottomMargin(int bottom)
{
if (!mIsKeyboardVisible)
{
return bottom;
}
else
{
int keyboardHeight = 0;
using(AndroidJavaClass UnityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
AndroidJavaObject View = UnityClass.GetStatic<AndroidJavaObject>("currentActivity").Get<AndroidJavaObject>("mUnityPlayer").Call<AndroidJavaObject>("getView");
using(AndroidJavaObject Rct = new AndroidJavaObject("android.graphics.Rect"))
{
View.Call("getWindowVisibleDisplayFrame", Rct);
keyboardHeight = View.Call<int>("getHeight") - Rct.Call<int>("height");
}
}
return (bottom > keyboardHeight) ? bottom : keyboardHeight;
}
}
#else
IntPtr webView;
#endif
public bool IsKeyboardVisible
{
get
{
#if !UNITY_EDITOR && UNITY_ANDROID
return mIsKeyboardVisible;
#elif !UNITY_EDITOR && UNITY_IPHONE
return TouchScreenKeyboard.visible;
#else
return false;
#endif
}
}
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
[DllImport("WebView")]
private static extern string _CWebViewPlugin_GetAppPath();
[DllImport("WebView")]
private static extern IntPtr _CWebViewPlugin_InitStatic(
bool inEditor, bool useMetal);
[DllImport("WebView")]
private static extern IntPtr _CWebViewPlugin_Init(
string gameObject, bool transparent, int width, int height, string ua, bool separated);
[DllImport("WebView")]
private static extern int _CWebViewPlugin_Destroy(IntPtr instance);
[DllImport("WebView")]
private static extern void _CWebViewPlugin_SetRect(
IntPtr instance, int width, int height);
[DllImport("WebView")]
private static extern void _CWebViewPlugin_SetVisibility(
IntPtr instance, bool visibility);
[DllImport("WebView")]
private static extern bool _CWebViewPlugin_SetURLPattern(
IntPtr instance, string allowPattern, string denyPattern, string hookPattern);
[DllImport("WebView")]
private static extern void _CWebViewPlugin_LoadURL(
IntPtr instance, string url);
[DllImport("WebView")]
private static extern void _CWebViewPlugin_LoadHTML(
IntPtr instance, string html, string baseUrl);
[DllImport("WebView")]
private static extern void _CWebViewPlugin_EvaluateJS(
IntPtr instance, string url);
[DllImport("WebView")]
private static extern int _CWebViewPlugin_Progress(
IntPtr instance);
[DllImport("WebView")]
private static extern bool _CWebViewPlugin_CanGoBack(
IntPtr instance);
[DllImport("WebView")]
private static extern bool _CWebViewPlugin_CanGoForward(
IntPtr instance);
[DllImport("WebView")]
private static extern void _CWebViewPlugin_GoBack(
IntPtr instance);
[DllImport("WebView")]
private static extern void _CWebViewPlugin_GoForward(
IntPtr instance);
[DllImport("WebView")]
private static extern void _CWebViewPlugin_SendMouseEvent(IntPtr instance, int x, int y, float deltaY, int mouseState);
[DllImport("WebView")]
private static extern void _CWebViewPlugin_SendKeyEvent(IntPtr instance, int x, int y, string keyChars, ushort keyCode, int keyState);
[DllImport("WebView")]
private static extern void _CWebViewPlugin_Update(IntPtr instance, bool refreshBitmap);
[DllImport("WebView")]
private static extern int _CWebViewPlugin_BitmapWidth(IntPtr instance);
[DllImport("WebView")]
private static extern int _CWebViewPlugin_BitmapHeight(IntPtr instance);
[DllImport("WebView")]
private static extern void _CWebViewPlugin_SetTextureId(IntPtr instance, IntPtr textureId);
[DllImport("WebView")]
private static extern void _CWebViewPlugin_SetCurrentInstance(IntPtr instance);
[DllImport("WebView")]
private static extern IntPtr GetRenderEventFunc();
[DllImport("WebView")]
private static extern void _CWebViewPlugin_AddCustomHeader(IntPtr instance, string headerKey, string headerValue);
[DllImport("WebView")]
private static extern string _CWebViewPlugin_GetCustomHeaderValue(IntPtr instance, string headerKey);
[DllImport("WebView")]
private static extern void _CWebViewPlugin_RemoveCustomHeader(IntPtr instance, string headerKey);
[DllImport("WebView")]
private static extern void _CWebViewPlugin_ClearCustomHeader(IntPtr instance);
[DllImport("WebView")]
private static extern string _CWebViewPlugin_GetMessage(IntPtr instance);
#elif UNITY_IPHONE
[DllImport("__Internal")]
private static extern IntPtr _CWebViewPlugin_Init(string gameObject, bool transparent, string ua, bool enableWKWebView);
[DllImport("__Internal")]
private static extern int _CWebViewPlugin_Destroy(IntPtr instance);
[DllImport("__Internal")]
private static extern void _CWebViewPlugin_SetMargins(
IntPtr instance, float left, float top, float right, float bottom, bool relative);
[DllImport("__Internal")]
private static extern void _CWebViewPlugin_SetVisibility(
IntPtr instance, bool visibility);
[DllImport("__Internal")]
private static extern void _CWebViewPlugin_SetAlertDialogEnabled(
IntPtr instance, bool enabled);
[DllImport("__Internal")]
private static extern void _CWebViewPlugin_SetScrollBounceEnabled(
IntPtr instance, bool enabled);
[DllImport("__Internal")]
private static extern bool _CWebViewPlugin_SetURLPattern(
IntPtr instance, string allowPattern, string denyPattern, string hookPattern);
[DllImport("__Internal")]
private static extern void _CWebViewPlugin_LoadURL(
IntPtr instance, string url);
[DllImport("__Internal")]
private static extern void _CWebViewPlugin_LoadHTML(
IntPtr instance, string html, string baseUrl);
[DllImport("__Internal")]
private static extern void _CWebViewPlugin_EvaluateJS(
IntPtr instance, string url);
[DllImport("__Internal")]
private static extern int _CWebViewPlugin_Progress(
IntPtr instance);
[DllImport("__Internal")]
private static extern bool _CWebViewPlugin_CanGoBack(
IntPtr instance);
[DllImport("__Internal")]
private static extern bool _CWebViewPlugin_CanGoForward(
IntPtr instance);
[DllImport("__Internal")]
private static extern void _CWebViewPlugin_GoBack(
IntPtr instance);
[DllImport("__Internal")]
private static extern void _CWebViewPlugin_GoForward(
IntPtr instance);
[DllImport("__Internal")]
private static extern void _CWebViewPlugin_AddCustomHeader(IntPtr instance, string headerKey, string headerValue);
[DllImport("__Internal")]
private static extern string _CWebViewPlugin_GetCustomHeaderValue(IntPtr instance, string headerKey);
[DllImport("__Internal")]
private static extern void _CWebViewPlugin_RemoveCustomHeader(IntPtr instance, string headerKey);
[DllImport("__Internal")]
private static extern void _CWebViewPlugin_ClearCustomHeader(IntPtr instance);
[DllImport("__Internal")]
private static extern void _CWebViewPlugin_ClearCookies();
[DllImport("__Internal")]
private static extern void _CWebViewPlugin_SaveCookies();
[DllImport("__Internal")]
private static extern string _CWebViewPlugin_GetCookies(string url);
[DllImport("__Internal")]
private static extern void _CWebViewPlugin_SetBasicAuthInfo(IntPtr instance, string userName, string password);
#elif UNITY_WEBGL
[DllImport("__Internal")]
private static extern void _gree_unity_webview_init(string name);
[DllImport("__Internal")]
private static extern void _gree_unity_webview_setMargins(string name, int left, int top, int right, int bottom);
[DllImport("__Internal")]
private static extern void _gree_unity_webview_setVisibility(string name, bool visible);
[DllImport("__Internal")]
private static extern void _gree_unity_webview_loadURL(string name, string url);
[DllImport("__Internal")]
private static extern void _gree_unity_webview_evaluateJS(string name, string js);
[DllImport("__Internal")]
private static extern void _gree_unity_webview_destroy(string name);
#endif
public static bool IsWebViewAvailable()
{
#if !UNITY_EDITOR && UNITY_ANDROID
return (new AndroidJavaObject("net.gree.unitywebview.CWebViewPlugin")).CallStatic<bool>("IsWebViewAvailable");
#else
return true;
#endif
}
public void Init(
Callback cb = null,
bool transparent = false,
string ua = "",
Callback err = null,
Callback httpErr = null,
Callback ld = null,
bool enableWKWebView = false,
Callback started = null,
Callback hooked = null
#if UNITY_EDITOR
, bool separated = false
#endif
)
{
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
_CWebViewPlugin_InitStatic(
Application.platform == RuntimePlatform.OSXEditor,
SystemInfo.graphicsDeviceType == GraphicsDeviceType.Metal);
#endif
onJS = cb;
onError = err;
onHttpError = httpErr;
onStarted = started;
onLoaded = ld;
onHooked = hooked;
#if UNITY_WEBGL
#if !UNITY_EDITOR
_gree_unity_webview_init(name);
#endif
#elif UNITY_WEBPLAYER
Application.ExternalCall("unityWebView.init", name);
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
Debug.LogError("Webview is not supported on this platform.");
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
{
var uri = new Uri(_CWebViewPlugin_GetAppPath());
var info = File.ReadAllText(uri.LocalPath + "Contents/Info.plist");
if (Regex.IsMatch(info, @"<key>CFBundleGetInfoString</key>\s*<string>Unity version [5-9]\.[3-9]")
&& !Regex.IsMatch(info, @"<key>NSAppTransportSecurity</key>\s*<dict>\s*<key>NSAllowsArbitraryLoads</key>\s*<true/>\s*</dict>")) {
Debug.LogWarning("<color=yellow>WebViewObject: NSAppTransportSecurity isn't configured to allow HTTP. If you need to allow any HTTP access, please shutdown Unity and invoke:</color>\n/usr/libexec/PlistBuddy -c \"Add NSAppTransportSecurity:NSAllowsArbitraryLoads bool true\" /Applications/Unity/Unity.app/Contents/Info.plist");
}
}
#if UNITY_EDITOR_OSX
// if (string.IsNullOrEmpty(ua)) {
// ua = @"Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53";
// }
#endif
webView = _CWebViewPlugin_Init(
name,
transparent,
Screen.width,
Screen.height,
ua
#if UNITY_EDITOR
, separated
#else
, false
#endif
);
// define pseudo requestAnimationFrame.
EvaluateJS(@"(function() {
var vsync = 1000 / 60;
var t0 = window.performance.now();
window.requestAnimationFrame = function(callback, element) {
var t1 = window.performance.now();
var duration = t1 - t0;
var d = vsync - ((duration > vsync) ? duration % vsync : duration);
var id = window.setTimeout(function() {t0 = window.performance.now(); callback(t1 + d);}, d);
return id;
};
})()");
rect = new Rect(0, 0, Screen.width, Screen.height);
OnApplicationFocus(true);
#elif UNITY_IPHONE
webView = _CWebViewPlugin_Init(name, transparent, ua, enableWKWebView);
#elif UNITY_ANDROID
webView = new AndroidJavaObject("net.gree.unitywebview.CWebViewPlugin");
webView.Call("Init", name, transparent, ua);
#else
Debug.LogError("Webview is not supported on this platform.");
#endif
}
protected virtual void OnDestroy()
{
#if UNITY_WEBGL
#if !UNITY_EDITOR
_gree_unity_webview_destroy(name);
#endif
#elif UNITY_WEBPLAYER
Application.ExternalCall("unityWebView.destroy", name);
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_Destroy(webView);
webView = IntPtr.Zero;
Destroy(texture);
#elif UNITY_IPHONE
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_Destroy(webView);
webView = IntPtr.Zero;
#elif UNITY_ANDROID
if (webView == null)
return;
webView.Call("Destroy");
webView = null;
#endif
}
// Use this function instead of SetMargins to easily set up a centered window
// NOTE: for historical reasons, `center` means the lower left corner and positive y values extend up.
public void SetCenterPositionWithScale(Vector2 center, Vector2 scale)
{
#if UNITY_WEBPLAYER || UNITY_WEBGL
//TODO: UNSUPPORTED
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
#else
float left = (Screen.width - scale.x) / 2.0f + center.x;
float right = Screen.width - (left + scale.x);
float bottom = (Screen.height - scale.y) / 2.0f + center.y;
float top = Screen.height - (bottom + scale.y);
SetMargins((int)left, (int)top, (int)right, (int)bottom);
#endif
}
public void SetMargins(int left, int top, int right, int bottom, bool relative = false)
{
#if UNITY_WEBPLAYER || UNITY_WEBGL
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
if (webView == IntPtr.Zero)
return;
#elif UNITY_IPHONE
if (webView == IntPtr.Zero)
return;
#elif UNITY_ANDROID
if (webView == null)
return;
#endif
mMarginLeft = left;
mMarginTop = top;
mMarginRight = right;
mMarginBottom = bottom;
#if UNITY_WEBGL
#if !UNITY_EDITOR
_gree_unity_webview_setMargins(name, left, top, right, bottom);
#endif
#elif UNITY_WEBPLAYER
Application.ExternalCall("unityWebView.setMargins", name, left, top, right, bottom);
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
int width = Screen.width - (left + right);
int height = Screen.height - (bottom + top);
_CWebViewPlugin_SetRect(webView, width, height);
rect = new Rect(left, bottom, width, height);
#elif UNITY_IPHONE
if (relative) {
float w = (float)Screen.width;
float h = (float)Screen.height;
_CWebViewPlugin_SetMargins(webView, left / w, top / h, right / w, bottom / h, true);
} else {
_CWebViewPlugin_SetMargins(webView, (float)left, (float)top, (float)right, (float)bottom, false);
}
#elif UNITY_ANDROID
if (relative) {
float w = (float)Screen.width;
float h = (float)Screen.height;
int iw = Screen.currentResolution.width;
int ih = Screen.currentResolution.height;
webView.Call("SetMargins", (int)(left / w * iw), (int)(top / h * ih), (int)(right / w * iw), AdjustBottomMargin((int)(bottom / h * ih)));
} else {
webView.Call("SetMargins", left, top, right, AdjustBottomMargin(bottom));
}
#endif
}
public void SetVisibility(bool v)
{
#if UNITY_WEBGL
#if !UNITY_EDITOR
_gree_unity_webview_setVisibility(name, v);
#endif
#elif UNITY_WEBPLAYER
Application.ExternalCall("unityWebView.setVisibility", name, v);
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_SetVisibility(webView, v);
#elif UNITY_IPHONE
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_SetVisibility(webView, v);
#elif UNITY_ANDROID
if (webView == null)
return;
mVisibility = v;
webView.Call("SetVisibility", v);
#endif
visibility = v;
}
public bool GetVisibility()
{
return visibility;
}
public void SetAlertDialogEnabled(bool e)
{
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
// TODO: UNSUPPORTED
#elif UNITY_IPHONE
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_SetAlertDialogEnabled(webView, e);
#elif UNITY_ANDROID
if (webView == null)
return;
webView.Call("SetAlertDialogEnabled", e);
#else
// TODO: UNSUPPORTED
#endif
alertDialogEnabled = e;
}
public bool GetAlertDialogEnabled()
{
return alertDialogEnabled;
}
public void SetScrollBounceEnabled(bool e)
{
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
// TODO: UNSUPPORTED
#elif UNITY_IPHONE
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_SetScrollBounceEnabled(webView, e);
#elif UNITY_ANDROID
// TODO: UNSUPPORTED
#else
// TODO: UNSUPPORTED
#endif
scrollBounceEnabled = e;
}
public bool GetScrollBounceEnabled()
{
return scrollBounceEnabled;
}
public bool SetURLPattern(string allowPattern, string denyPattern, string hookPattern)
{
#if UNITY_WEBPLAYER || UNITY_WEBGL
//TODO: UNSUPPORTED
return false;
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
return false;
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IPHONE
if (webView == IntPtr.Zero)
return false;
return _CWebViewPlugin_SetURLPattern(webView, allowPattern, denyPattern, hookPattern);
#elif UNITY_ANDROID
if (webView == null)
return false;
return webView.Call<bool>("SetURLPattern", allowPattern, denyPattern, hookPattern);
#endif
}
public void LoadURL(string url)
{
if (string.IsNullOrEmpty(url))
return;
#if UNITY_WEBGL
#if !UNITY_EDITOR
_gree_unity_webview_loadURL(name, url);
#endif
#elif UNITY_WEBPLAYER
Application.ExternalCall("unityWebView.loadURL", name, url);
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IPHONE
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_LoadURL(webView, url);
#elif UNITY_ANDROID
if (webView == null)
return;
webView.Call("LoadURL", url);
#endif
}
public void LoadHTML(string html, string baseUrl)
{
if (string.IsNullOrEmpty(html))
return;
if (string.IsNullOrEmpty(baseUrl))
baseUrl = "";
#if UNITY_WEBPLAYER || UNITY_WEBGL
//TODO: UNSUPPORTED
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IPHONE
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_LoadHTML(webView, html, baseUrl);
#elif UNITY_ANDROID
if (webView == null)
return;
webView.Call("LoadHTML", html, baseUrl);
#endif
}
public void EvaluateJS(string js)
{
#if UNITY_WEBGL
#if !UNITY_EDITOR
_gree_unity_webview_evaluateJS(name, js);
#endif
#elif UNITY_WEBPLAYER
Application.ExternalCall("unityWebView.evaluateJS", name, js);
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IPHONE
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_EvaluateJS(webView, js);
#elif UNITY_ANDROID
if (webView == null)
return;
webView.Call("EvaluateJS", js);
#endif
}
public int Progress()
{
#if UNITY_WEBPLAYER || UNITY_WEBGL
//TODO: UNSUPPORTED
return 0;
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
return 0;
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IPHONE
if (webView == IntPtr.Zero)
return 0;
return _CWebViewPlugin_Progress(webView);
#elif UNITY_ANDROID
if (webView == null)
return 0;
return webView.Get<int>("progress");
#endif
}
public bool CanGoBack()
{
#if UNITY_WEBPLAYER || UNITY_WEBGL
//TODO: UNSUPPORTED
return false;
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
return false;
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IPHONE
if (webView == IntPtr.Zero)
return false;
return _CWebViewPlugin_CanGoBack(webView);
#elif UNITY_ANDROID
if (webView == null)
return false;
return webView.Get<bool>("canGoBack");
#endif
}
public bool CanGoForward()
{
#if UNITY_WEBPLAYER || UNITY_WEBGL
//TODO: UNSUPPORTED
return false;
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
return false;
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IPHONE
if (webView == IntPtr.Zero)
return false;
return _CWebViewPlugin_CanGoForward(webView);
#elif UNITY_ANDROID
if (webView == null)
return false;
return webView.Get<bool>("canGoForward");
#endif
}
public void GoBack()
{
#if UNITY_WEBPLAYER || UNITY_WEBGL
//TODO: UNSUPPORTED
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IPHONE
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_GoBack(webView);
#elif UNITY_ANDROID
if (webView == null)
return;
webView.Call("GoBack");
#endif
}
public void GoForward()
{
#if UNITY_WEBPLAYER || UNITY_WEBGL
//TODO: UNSUPPORTED
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IPHONE
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_GoForward(webView);
#elif UNITY_ANDROID
if (webView == null)
return;
webView.Call("GoForward");
#endif
}
public void CallOnError(string error)
{
if (onError != null)
{
onError(error);
}
}
public void CallOnHttpError(string error)
{
if (onHttpError != null)
{
onHttpError(error);
}
}
public void CallOnStarted(string url)
{
if (onStarted != null)
{
onStarted(url);
}
}
public void CallOnLoaded(string url)
{
if (onLoaded != null)
{
onLoaded(url);
}
}
public void CallFromJS(string message)
{
if (onJS != null)
{
#if !UNITY_ANDROID
#if UNITY_2018_4_OR_NEWER
message = UnityWebRequest.UnEscapeURL(message);
#else // UNITY_2018_4_OR_NEWER
message = WWW.UnEscapeURL(message);
#endif // UNITY_2018_4_OR_NEWER
#endif // !UNITY_ANDROID
onJS(message);
}
}
public void CallOnHooked(string message)
{
if (onHooked != null)
{
#if !UNITY_ANDROID
#if UNITY_2018_4_OR_NEWER
message = UnityWebRequest.UnEscapeURL(message);
#else // UNITY_2018_4_OR_NEWER
message = WWW.UnEscapeURL(message);
#endif // UNITY_2018_4_OR_NEWER
#endif // !UNITY_ANDROID
onHooked(message);
}
}
public void AddCustomHeader(string headerKey, string headerValue)
{
#if UNITY_WEBPLAYER || UNITY_WEBGL
//TODO: UNSUPPORTED
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IPHONE
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_AddCustomHeader(webView, headerKey, headerValue);
#elif UNITY_ANDROID
if (webView == null)
return;
webView.Call("AddCustomHeader", headerKey, headerValue);
#endif
}
public string GetCustomHeaderValue(string headerKey)
{
#if UNITY_WEBPLAYER || UNITY_WEBGL
//TODO: UNSUPPORTED
return null;
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
return null;
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IPHONE
if (webView == IntPtr.Zero)
return null;
return _CWebViewPlugin_GetCustomHeaderValue(webView, headerKey);
#elif UNITY_ANDROID
if (webView == null)
return null;
return webView.Call<string>("GetCustomHeaderValue", headerKey);
#endif
}
public void RemoveCustomHeader(string headerKey)
{
#if UNITY_WEBPLAYER || UNITY_WEBGL
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IPHONE
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_RemoveCustomHeader(webView, headerKey);
#elif UNITY_ANDROID
if (webView == null)
return;
webView.Call("RemoveCustomHeader", headerKey);
#endif
}
public void ClearCustomHeader()
{
#if UNITY_WEBPLAYER || UNITY_WEBGL
//TODO: UNSUPPORTED
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IPHONE
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_ClearCustomHeader(webView);
#elif UNITY_ANDROID
if (webView == null)
return;
webView.Call("ClearCustomHeader");
#endif
}
public void ClearCookies()
{
#if UNITY_WEBPLAYER || UNITY_WEBGL
//TODO: UNSUPPORTED
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
#elif UNITY_IPHONE && !UNITY_EDITOR
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_ClearCookies();
#elif UNITY_ANDROID && !UNITY_EDITOR
if (webView == null)
return;
webView.Call("ClearCookies");
#endif
}
public void SaveCookies()
{
#if UNITY_WEBPLAYER || UNITY_WEBGL
//TODO: UNSUPPORTED
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
#elif UNITY_IPHONE && !UNITY_EDITOR
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_SaveCookies();
#elif UNITY_ANDROID && !UNITY_EDITOR
if (webView == null)
return;
webView.Call("SaveCookies");
#endif
}
public string GetCookies(string url)
{
#if UNITY_WEBPLAYER || UNITY_WEBGL
//TODO: UNSUPPORTED
return "";
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
return "";
#elif UNITY_IPHONE && !UNITY_EDITOR
if (webView == IntPtr.Zero)
return "";
return _CWebViewPlugin_GetCookies(url);
#elif UNITY_ANDROID && !UNITY_EDITOR
if (webView == null)
return "";
return webView.Call<string>("GetCookies", url);
#else
//TODO: UNSUPPORTED
return "";
#endif
}
public void SetBasicAuthInfo(string userName, string password)
{
#if UNITY_WEBPLAYER || UNITY_WEBGL
//TODO: UNSUPPORTED
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
//TODO: UNSUPPORTED
#elif UNITY_IPHONE
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_SetBasicAuthInfo(webView, userName, password);
#elif UNITY_ANDROID
if (webView == null)
return;
webView.Call("SetBasicAuthInfo", userName, password);
#endif
}
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
void OnApplicationFocus(bool focus)
{
hasFocus = focus;
}
void Update()
{
if (hasFocus) {
inputString += Input.inputString;
}
for (;;) {
if (webView == IntPtr.Zero)
break;
string s = _CWebViewPlugin_GetMessage(webView);
if (s == null)
break;
switch (s[0]) {
case 'E':
CallOnError(s.Substring(1));
break;
case 'S':
CallOnStarted(s.Substring(1));
break;
case 'L':
CallOnLoaded(s.Substring(1));
break;
case 'J':
CallFromJS(s.Substring(1));
break;
case 'H':
CallOnHooked(s.Substring(1));
break;
}
}
}
public int bitmapRefreshCycle = 1;
void OnGUI()
{
if (webView == IntPtr.Zero || !visibility)
return;
Vector3 p;
p.x = Input.mousePosition.x - rect.x;
p.y = Input.mousePosition.y - rect.y;
{
int mouseState = 0;
if (Input.GetButtonDown("Fire1")) {
mouseState = 1;
} else if (Input.GetButtonUp("Fire1")) {
mouseState = 3;
} else if (Input.GetButton("Fire1")) {
mouseState = 2;
}
_CWebViewPlugin_SendMouseEvent(webView, (int)p.x, (int)p.y, Input.GetAxis("Mouse ScrollWheel"), mouseState);
}
{
string keyChars = "";
ushort keyCode = 0;
if (!string.IsNullOrEmpty(inputString)) {
keyChars = inputString.Substring(0, 1);
keyCode = (ushort)inputString[0];
inputString = inputString.Substring(1);
}
if (!string.IsNullOrEmpty(keyChars) || keyCode != 0) {
_CWebViewPlugin_SendKeyEvent(webView, (int)p.x, (int)p.y, keyChars, keyCode, 1);
}
// if (keyChars != keyChars0) {
// if (!string.IsNullOrEmpty(keyChars0)) {
// Debug.Log("XX1 " + (short)keyChars0[0]);
// _CWebViewPlugin_SendKeyEvent(webView, (int)p.x, (int)p.y, keyChars0, keyCode0, 3);
// }
// if (!string.IsNullOrEmpty(keyChars)) {
// Debug.Log("XX2 " + (short)keyChars[0]);
// _CWebViewPlugin_SendKeyEvent(webView, (int)p.x, (int)p.y, keyChars, keyCode, 1);
// }
// } else {
// if (!string.IsNullOrEmpty(keyChars)) {
// Debug.Log("XX3");
// _CWebViewPlugin_SendKeyEvent(webView, (int)p.x, (int)p.y, keyChars, keyCode, 2);
// }
// }
// keyChars0 = keyChars;
// keyCode0 = keyCode;
}
bool refreshBitmap = (Time.frameCount % bitmapRefreshCycle == 0);
_CWebViewPlugin_Update(webView, refreshBitmap);
if (refreshBitmap) {
{
var w = _CWebViewPlugin_BitmapWidth(webView);
var h = _CWebViewPlugin_BitmapHeight(webView);
if (texture == null || texture.width != w || texture.height != h) {
texture = new Texture2D(w, h, TextureFormat.RGBA32, false, true);
texture.filterMode = FilterMode.Bilinear;
texture.wrapMode = TextureWrapMode.Clamp;
}
}
_CWebViewPlugin_SetTextureId(webView, texture.GetNativeTexturePtr());
_CWebViewPlugin_SetCurrentInstance(webView);
#if UNITY_4_6 || UNITY_5_0 || UNITY_5_1
GL.IssuePluginEvent(-1);
#else
GL.IssuePluginEvent(GetRenderEventFunc(), -1);
#endif
}
if (texture != null) {
Matrix4x4 m = GUI.matrix;
GUI.matrix
= Matrix4x4.TRS(
new Vector3(0, Screen.height, 0),
Quaternion.identity,
new Vector3(1, -1, 1));
GUI.DrawTexture(rect, texture);
GUI.matrix = m;
}
}
#endif
}
| |
//
// WebView.cs
//
// Author:
// Cody Russell <[email protected]>
// Vsevolod Kukol <[email protected]>
//
// Copyright (c) 2014 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Drawing;
using Xwt.Backends;
using System.ComponentModel;
namespace Xwt
{
[BackendType (typeof(IWebViewBackend))]
public class WebView : Widget
{
EventHandler loading;
EventHandler loaded;
EventHandler<NavigateToUrlEventArgs> navigateToUrl;
EventHandler titleChanged;
string url = String.Empty;
protected new class WidgetBackendHost : Widget.WidgetBackendHost, IWebViewEventSink
{
public bool OnNavigateToUrl (string url)
{
var args = new NavigateToUrlEventArgs (new Uri(url, UriKind.RelativeOrAbsolute));
((WebView)Parent).OnNavigateToUrl (args);
return args.Handled;
}
[MappedEvent(WebViewEvent.Loading)]
public void OnLoading ()
{
((WebView)Parent).OnLoading (EventArgs.Empty);
}
public void OnLoaded ()
{
((WebView)Parent).OnLoaded (EventArgs.Empty);
}
public void OnTitleChanged ()
{
((WebView)Parent).OnTitleChanged (EventArgs.Empty);
}
}
public WebView ()
{
ContextMenuEnabled = true;
ScrollBarsEnabled = true;
}
public WebView (string url)
{
Url = url;
}
protected override Xwt.Backends.BackendHost CreateBackendHost ()
{
return new WidgetBackendHost ();
}
IWebViewBackend Backend {
get { return (IWebViewBackend) BackendHost.Backend; }
}
[DefaultValue("")]
public string Url {
get {
if (!String.IsNullOrEmpty (Backend.Url))
url = Backend.Url;
return url;
}
set {
url = value;
Backend.Url = url;
}
}
[DefaultValue("")]
public string Title {
get { return Backend.Title ?? ""; }
}
[DefaultValue(0.0)]
public double LoadProgress {
get { return Backend.LoadProgress; }
}
[DefaultValue(false)]
public bool CanGoBack {
get { return Backend.CanGoBack; }
}
[DefaultValue(false)]
public bool CanGoForward {
get { return Backend.CanGoForward; }
}
[DefaultValue (true)]
public bool ContextMenuEnabled {
get { return Backend.ContextMenuEnabled; }
set { Backend.ContextMenuEnabled = value; }
}
[DefaultValue (true)]
public bool DrawsBackground {
get { return Backend.DrawsBackground; }
set { Backend.DrawsBackground = value; }
}
[DefaultValue (null)]
public string CustomCss {
get { return Backend.CustomCss; }
set { Backend.CustomCss = value; }
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="T:Xwt.WebView"/> has own scroll bars.
/// </summary>
/// <value><c>true</c> if the scroll bars are enabled; otherwise, <c>false</c>.</value>
/// <remarks>
/// By default all WebView backends support scrolling and don't need to be packed into a
/// ScrollView. Setting this to <c>false</c> will disable the internal scrolling feature.
/// </remarks>
[DefaultValue (true)]
public bool ScrollBarsEnabled {
get { return Backend.ScrollBarsEnabled; }
set { Backend.ScrollBarsEnabled = value; }
}
public void GoBack ()
{
Backend.GoBack ();
}
public void GoForward ()
{
Backend.GoForward ();
}
public void Reload ()
{
Backend.Reload ();
}
public void StopLoading ()
{
Backend.StopLoading ();
}
public void LoadHtml (string content, string base_uri)
{
Backend.LoadHtml (content, base_uri);
}
protected virtual void OnLoading (EventArgs e)
{
if (loading != null)
loading (this, e);
}
public event EventHandler Loading {
add {
BackendHost.OnBeforeEventAdd (WebViewEvent.Loading, loading);
loading += value;
}
remove {
loading -= value;
BackendHost.OnAfterEventRemove (WebViewEvent.Loading, loading);
}
}
[MappedEvent(WebViewEvent.Loaded)]
protected virtual void OnLoaded (EventArgs e)
{
if (loaded != null)
loaded (this, e);
}
public event EventHandler Loaded {
add {
BackendHost.OnBeforeEventAdd (WebViewEvent.Loaded, loaded);
loaded += value;
}
remove {
loaded -= value;
BackendHost.OnAfterEventRemove (WebViewEvent.Loaded, loaded);
}
}
[MappedEvent(WebViewEvent.NavigateToUrl)]
protected virtual void OnNavigateToUrl (NavigateToUrlEventArgs e)
{
if (navigateToUrl != null)
navigateToUrl (this, e);
}
public event EventHandler<NavigateToUrlEventArgs> NavigateToUrl {
add {
BackendHost.OnBeforeEventAdd (WebViewEvent.NavigateToUrl, navigateToUrl);
navigateToUrl += value;
}
remove {
navigateToUrl -= value;
BackendHost.OnAfterEventRemove (WebViewEvent.NavigateToUrl, navigateToUrl);
}
}
[MappedEvent(WebViewEvent.TitleChanged)]
protected virtual void OnTitleChanged (EventArgs e)
{
if (titleChanged != null)
titleChanged (this, e);
}
public event EventHandler TitleChanged {
add {
BackendHost.OnBeforeEventAdd (WebViewEvent.TitleChanged, titleChanged);
titleChanged += value;
}
remove {
titleChanged -= value;
BackendHost.OnAfterEventRemove (WebViewEvent.TitleChanged, titleChanged);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Razor.Parser.SyntaxTree;
using Codex.ObjectModel;
using Codex.Storage;
using Codex.Storage.ElasticProviders;
using Codex.Utilities;
using Codex.Web.Monaco.Models;
using Codex.Web.Monaco.Util;
using WebUI.Rendering;
using Span = Codex.Web.Monaco.Models.Span;
namespace WebUI.Controllers
{
public class SourceController : Controller
{
private readonly IStorage Storage;
private readonly ElasticsearchStorage EsStorage;
private readonly static IEqualityComparer<SymbolReferenceEntry> m_referenceEquator = new EqualityComparerBuilder<SymbolReferenceEntry>()
.CompareByAfter(rs => rs.Span.Reference.Id)
.CompareByAfter(rs => rs.Span.Reference.ProjectId)
.CompareByAfter(rs => rs.Span.Reference.ReferenceKind)
.CompareByAfter(rs => rs.ReferringProjectId)
.CompareByAfter(rs => rs.ReferringFilePath);
public struct LinkEdit
{
public string Inserted;
public int Offset;
public int TruncateLength;
public bool ReplacePrefix;
}
public Dictionary<string, LinkEdit> m_edits = new Dictionary<string, LinkEdit>(StringComparer.OrdinalIgnoreCase)
{
//{ "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/VS?path=",
// new LinkEdit() { Inserted = "/src", Offset = 3 } },
//{ "https://mseng.visualstudio.com/DefaultCollection/VSIDEProj/_git/VSIDEProj.Threading#path=/src/",
// new LinkEdit() { TruncateLength = 11, Inserted = "?path=" } },
//{ "https://mseng.visualstudio.com/DefaultCollection/VSIDEProj/_git/VSIDEProj.MEF#path=/src/",
// new LinkEdit() { ReplacePrefix = true, Inserted = "https://devdiv.visualstudio.com/DevDiv/_git/VSMEF?path=" } }
};
public SourceController(IStorage storage)
{
Storage = storage;
EsStorage = (ElasticsearchStorage) storage;
}
[Route("repos/{repoName}/sourcecontent/{projectId}")]
[Route("sourcecontent/{projectId}")]
public async Task<ActionResult> Contents(string projectId, string filename)
{
try
{
Requests.LogRequest(this);
if (string.IsNullOrEmpty(filename))
{
return this.HttpNotFound();
}
return WrapTheModel(await GetSourceFileAsync(projectId, filename));
}
catch (Exception ex)
{
return Responses.Exception(ex);
}
}
private JsonResult WrapTheModel(object model)
{
if (model == null)
{
return new JsonResult();
}
return new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = model,
};
}
private async Task<SourceFileContentsModel> GetSourceFileAsync(string projectId, string filename)
{
var boundSourceFile = await Storage.GetBoundSourceFileAsync(
this.GetSearchRepos(),
projectId,
filename,
includeDefinitions: true);
if (boundSourceFile == null)
{
return null;
}
Responses.PrepareResponse(Response);
var sourceFile = new SourceFileContentsModel()
{
projectId = projectId,
filePath = filename,
};
await sourceFile.Populate(boundSourceFile);
return sourceFile;
}
[Route("repos/{repoName}/source/{projectId}")]
[Route("source/{projectId}")]
public async Task<ActionResult> Index(string projectId, string filename, bool partial = false)
{
try
{
Requests.LogRequest(this);
if (string.IsNullOrEmpty(filename))
{
return this.HttpNotFound();
}
var boundSourceFile = await Storage.GetBoundSourceFileAsync(this.GetSearchRepos(), projectId, filename);
if (boundSourceFile == null)
{
return PartialView("~/Views/Source/Index.cshtml", new EditorModel { Error = $"Bound source file for {filename} in {projectId} not found." });
}
var renderer = new SourceFileRenderer(boundSourceFile, projectId);
Responses.PrepareResponse(Response);
var model = await renderer.RenderAsync();
foreach (var editEntry in m_edits)
{
if (model.WebLink?.StartsWith(editEntry.Key, StringComparison.OrdinalIgnoreCase) == true)
{
var truncateLength = editEntry.Value.TruncateLength;
if (editEntry.Value.ReplacePrefix)
{
truncateLength = editEntry.Key.Length;
}
var start = model.WebLink.Substring(0, editEntry.Key.Length - truncateLength);
var end = model.WebLink.Substring(editEntry.Key.Length + editEntry.Value.Offset);
model.WebLink = start + editEntry.Value.Inserted + end;
}
}
if (partial)
{
return PartialView("~/Views/Source/Index.cshtml", (object)model);
}
return View((object)model);
}
catch (Exception ex)
{
return Responses.Exception(ex);
}
}
[Route("repos/{repoName}/definitions/{projectId}")]
[Route("definitions/{projectId}")]
public async Task<ActionResult> GoToDefinitionAsync(string projectId, string symbolId)
{
try
{
Requests.LogRequest(this);
var definitions = await Storage.GetReferencesToSymbolAsync(
this.GetSearchRepos(),
new Symbol()
{
ProjectId = projectId,
Id = SymbolId.UnsafeCreateWithValue(symbolId),
Kind = nameof(ReferenceKind.Definition)
});
definitions.Entries = definitions.Entries.Distinct(m_referenceEquator).ToList();
if (definitions.Entries.Count == 1)
{
var definitionReference = definitions.Entries[0];
return await Index(definitionReference.ReferringProjectId, definitionReference.File, partial: true);
}
else
{
var definitionResult = await Storage.GetDefinitionsAsync(this.GetSearchRepos(), projectId, symbolId);
var symbolName = definitionResult?.FirstOrDefault()?.Span.Definition.DisplayName ?? symbolId;
definitions.SymbolName = symbolName ?? definitions.SymbolName;
if (definitions.Entries.Count == 0)
{
definitions = await Storage.GetReferencesToSymbolAsync(
this.GetSearchRepos(),
new Symbol()
{
ProjectId = projectId,
Id = SymbolId.UnsafeCreateWithValue(symbolId)
});
}
var referencesText = ReferencesController.GenerateReferencesHtml(definitions);
if (string.IsNullOrEmpty(referencesText))
{
referencesText = "No definitions found.";
}
else
{
referencesText = "<!--Definitions-->" + referencesText;
}
Responses.PrepareResponse(Response);
return PartialView("~/Views/References/References.cshtml", referencesText);
}
}
catch (Exception ex)
{
return Responses.Exception(ex);
}
}
[Route("definitionscontents/{projectId}")]
public async Task<ActionResult> GoToDefinitionGetContentAsync(string projectId, string symbolId)
{
try
{
Requests.LogRequest(this);
var definitions = await Storage.GetReferencesToSymbolAsync(
this.GetSearchRepos(),
new Symbol()
{
ProjectId = projectId,
Id = SymbolId.UnsafeCreateWithValue(symbolId),
Kind = nameof(ReferenceKind.Definition)
});
definitions.Entries = definitions.Entries.Distinct(m_referenceEquator).ToList();
if (definitions.Entries.Count == 1)
{
var definitionReference = definitions.Entries[0];
var sourceFile = await GetSourceFileAsync(definitionReference.ReferringProjectId, definitionReference.File);
if (sourceFile != null)
{
var referringSpan = definitions.Entries[0].ReferringSpan;
var position = new Codex.Web.Monaco.Models.LineSpan()
{
position = referringSpan.Start,
length = referringSpan.Length,
line = definitionReference.ReferringSpan.LineNumber + 1,
column = definitionReference.ReferringSpan.LineSpanStart + 1
};
sourceFile.span = position;
}
return WrapTheModel(sourceFile);
}
else
{
var definitionResult = await Storage.GetDefinitionsAsync(this.GetSearchRepos(), projectId, symbolId);
var symbolName = definitionResult?.FirstOrDefault()?.Span.Definition.DisplayName ?? symbolId;
definitions.SymbolName = symbolName ?? definitions.SymbolName;
if (definitions.Entries.Count == 0)
{
definitions = await Storage.GetReferencesToSymbolAsync(
this.GetSearchRepos(),
new Symbol()
{
ProjectId = projectId,
Id = SymbolId.UnsafeCreateWithValue(symbolId)
});
}
var referencesText = ReferencesController.GenerateReferencesHtml(definitions);
if (string.IsNullOrEmpty(referencesText))
{
referencesText = "No definitions found.";
}
else
{
referencesText = "<!--Definitions-->" + referencesText;
}
Responses.PrepareResponse(Response);
return PartialView("~/Views/References/References.cshtml", referencesText);
}
}
catch (Exception ex)
{
return Responses.Exception(ex);
}
}
[Route("definitionlocation/{projectId}")]
public async Task<ActionResult> GoToDefinitionLocationAsync(string projectId, string symbolId)
{
try
{
Requests.LogRequest(this);
var definitions = await Storage.GetReferencesToSymbolAsync(
this.GetSearchRepos(),
new Symbol()
{
ProjectId = projectId,
Id = SymbolId.UnsafeCreateWithValue(symbolId),
Kind = nameof(ReferenceKind.Definition)
});
definitions.Entries = definitions.Entries.Distinct(m_referenceEquator).ToList();
if (definitions.Entries.Count == 1)
{
var definitionReference = definitions.Entries[0];
var referringSpan = definitionReference.ReferringSpan;
var model = new SourceFileLocationModel()
{
projectId = definitionReference.ReferringProjectId,
filename = definitionReference.File,
span = new Codex.Web.Monaco.Models.LineSpan()
{
position = referringSpan.Start,
length = referringSpan.Length,
line = definitionReference.ReferringSpan.LineNumber + 1,
column = definitionReference.ReferringSpan.LineSpanStart + 1
}
};
return WrapTheModel(model);
}
else
{
var definitionResult = await Storage.GetDefinitionsAsync(this.GetSearchRepos(), projectId, symbolId);
var symbolName = definitionResult?.FirstOrDefault()?.Span.Definition.DisplayName ?? symbolId;
definitions.SymbolName = symbolName ?? definitions.SymbolName;
if (definitions.Entries.Count == 0)
{
definitions = await Storage.GetReferencesToSymbolAsync(
this.GetSearchRepos(),
new Symbol()
{
ProjectId = projectId,
Id = SymbolId.UnsafeCreateWithValue(symbolId)
});
}
var referencesText = ReferencesController.GenerateReferencesHtml(definitions);
if (string.IsNullOrEmpty(referencesText))
{
referencesText = "No definitions found.";
}
else
{
referencesText = "<!--Definitions-->" + referencesText;
}
Responses.PrepareResponse(Response);
return PartialView("~/Views/References/References.cshtml", referencesText);
}
}
catch (Exception ex)
{
return Responses.Exception(ex);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.IO.Pipes;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
namespace System.Data.SqlClient.SNI
{
/// <summary>
/// Named Pipe connection handle
/// </summary>
internal class SNINpHandle : SNIHandle
{
internal const string DefaultPipePath = @"sql\query"; // e.g. \\HOSTNAME\pipe\sql\query
private const int MAX_PIPE_INSTANCES = 255;
private readonly string _targetServer;
private readonly object _callbackObject;
private readonly TaskScheduler _writeScheduler;
private readonly TaskFactory _writeTaskFactory;
private Stream _stream;
private NamedPipeClientStream _pipeStream;
private SslOverTdsStream _sslOverTdsStream;
private SslStream _sslStream;
private SNIAsyncCallback _receiveCallback;
private SNIAsyncCallback _sendCallback;
private bool _validateCert = true;
private readonly uint _status = TdsEnums.SNI_UNINITIALIZED;
private int _bufferSize = TdsEnums.DEFAULT_LOGIN_PACKET_SIZE;
private readonly Guid _connectionId = Guid.NewGuid();
public SNINpHandle(string serverName, string pipeName, long timerExpire, object callbackObject)
{
_targetServer = serverName;
_callbackObject = callbackObject;
_writeScheduler = new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler;
_writeTaskFactory = new TaskFactory(_writeScheduler);
try
{
_pipeStream = new NamedPipeClientStream(
serverName,
pipeName,
PipeDirection.InOut,
PipeOptions.Asynchronous | PipeOptions.WriteThrough);
bool isInfiniteTimeOut = long.MaxValue == timerExpire;
if (isInfiniteTimeOut)
{
_pipeStream.Connect(Threading.Timeout.Infinite);
}
else
{
TimeSpan ts = DateTime.FromFileTime(timerExpire) - DateTime.Now;
ts = ts.Ticks < 0 ? TimeSpan.FromTicks(0) : ts;
_pipeStream.Connect((int)ts.TotalMilliseconds);
}
}
catch(TimeoutException te)
{
SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnTimeoutError, te);
_status = TdsEnums.SNI_WAIT_TIMEOUT;
return;
}
catch(IOException ioe)
{
SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnOpenFailedError, ioe);
_status = TdsEnums.SNI_ERROR;
return;
}
if (!_pipeStream.IsConnected || !_pipeStream.CanWrite || !_pipeStream.CanRead)
{
SNICommon.ReportSNIError(SNIProviders.NP_PROV, 0, SNICommon.ConnOpenFailedError, string.Empty);
_status = TdsEnums.SNI_ERROR;
return;
}
_sslOverTdsStream = new SslOverTdsStream(_pipeStream);
_sslStream = new SslStream(_sslOverTdsStream, true, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
_stream = _pipeStream;
_status = TdsEnums.SNI_SUCCESS;
}
public override Guid ConnectionId
{
get
{
return _connectionId;
}
}
public override uint Status
{
get
{
return _status;
}
}
public override uint CheckConnection()
{
if (!_stream.CanWrite || !_stream.CanRead)
{
return TdsEnums.SNI_ERROR;
}
else
{
return TdsEnums.SNI_SUCCESS;
}
}
public override void Dispose()
{
lock (this)
{
if (_sslOverTdsStream != null)
{
_sslOverTdsStream.Dispose();
_sslOverTdsStream = null;
}
if (_sslStream != null)
{
_sslStream.Dispose();
_sslStream = null;
}
if (_pipeStream != null)
{
_pipeStream.Dispose();
_pipeStream = null;
}
}
}
public override uint Receive(out SNIPacket packet, int timeout)
{
lock (this)
{
packet = null;
try
{
packet = new SNIPacket(null);
packet.Allocate(_bufferSize);
packet.ReadFromStream(_stream);
if (packet.Length == 0)
{
return ReportErrorAndReleasePacket(packet, 0, SNICommon.ConnTerminatedError, string.Empty);
}
}
catch (ObjectDisposedException ode)
{
return ReportErrorAndReleasePacket(packet, ode);
}
catch (IOException ioe)
{
return ReportErrorAndReleasePacket(packet, ioe);
}
return TdsEnums.SNI_SUCCESS;
}
}
public override uint ReceiveAsync(ref SNIPacket packet)
{
lock (this)
{
packet = new SNIPacket(null);
packet.Allocate(_bufferSize);
try
{
packet.ReadFromStreamAsync(_stream, _receiveCallback);
return TdsEnums.SNI_SUCCESS_IO_PENDING;
}
catch (ObjectDisposedException ode)
{
return ReportErrorAndReleasePacket(packet, ode);
}
catch (IOException ioe)
{
return ReportErrorAndReleasePacket(packet, ioe);
}
}
}
public override uint Send(SNIPacket packet)
{
lock (this)
{
try
{
packet.WriteToStream(_stream);
return TdsEnums.SNI_SUCCESS;
}
catch (ObjectDisposedException ode)
{
return ReportErrorAndReleasePacket(packet, ode);
}
catch (IOException ioe)
{
return ReportErrorAndReleasePacket(packet, ioe);
}
}
}
public override uint SendAsync(SNIPacket packet, SNIAsyncCallback callback = null)
{
SNIPacket newPacket = packet;
_writeTaskFactory.StartNew(() =>
{
try
{
lock (this)
{
packet.WriteToStream(_stream);
}
}
catch (Exception e)
{
SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.InternalExceptionError, e);
if (callback != null)
{
callback(packet, TdsEnums.SNI_ERROR);
}
else
{
_sendCallback(packet, TdsEnums.SNI_ERROR);
}
return;
}
if (callback != null)
{
callback(packet, TdsEnums.SNI_SUCCESS);
}
else
{
_sendCallback(packet, TdsEnums.SNI_SUCCESS);
}
});
return TdsEnums.SNI_SUCCESS_IO_PENDING;
}
public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyncCallback sendCallback)
{
_receiveCallback = receiveCallback;
_sendCallback = sendCallback;
}
public override uint EnableSsl(uint options)
{
_validateCert = (options & TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE) != 0;
try
{
_sslStream.AuthenticateAsClientAsync(_targetServer).GetAwaiter().GetResult();
_sslOverTdsStream.FinishHandshake();
}
catch (AuthenticationException aue)
{
return SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.InternalExceptionError, aue);
}
catch (InvalidOperationException ioe)
{
return SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.InternalExceptionError, ioe);
}
_stream = _sslStream;
return TdsEnums.SNI_SUCCESS;
}
public override void DisableSsl()
{
_sslStream.Dispose();
_sslStream = null;
_sslOverTdsStream.Dispose();
_sslOverTdsStream = null;
_stream = _pipeStream;
}
/// <summary>
/// Validate server certificate
/// </summary>
/// <param name="sender">Sender object</param>
/// <param name="cert">X.509 certificate</param>
/// <param name="chain">X.509 chain</param>
/// <param name="policyErrors">Policy errors</param>
/// <returns>true if valid</returns>
private bool ValidateServerCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors)
{
if (!_validateCert)
{
return true;
}
return SNICommon.ValidateSslServerCertificate(_targetServer, sender, cert, chain, policyErrors);
}
/// <summary>
/// Set buffer size
/// </summary>
/// <param name="bufferSize">Buffer size</param>
public override void SetBufferSize(int bufferSize)
{
_bufferSize = bufferSize;
}
private uint ReportErrorAndReleasePacket(SNIPacket packet, Exception sniException)
{
if (packet != null)
{
packet.Release();
}
return SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.InternalExceptionError, sniException);
}
private uint ReportErrorAndReleasePacket(SNIPacket packet, uint nativeError, uint sniError, string errorMessage)
{
if (packet != null)
{
packet.Release();
}
return SNICommon.ReportSNIError(SNIProviders.NP_PROV, nativeError, sniError, errorMessage);
}
#if DEBUG
/// <summary>
/// Test handle for killing underlying connection
/// </summary>
public override void KillConnection()
{
_pipeStream.Dispose();
_pipeStream = null;
}
#endif
}
}
| |
//------------------------------------------------------------------
// <summary>
// A P/Invoke wrapper for TaskDialog. Usability was given preference to perf and size.
// </summary>
//
// <remarks/>
//------------------------------------------------------------------
namespace PSTaskDialog
{
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// Class to hold native code interop declarations.
/// </summary>
internal static partial class VistaUnsafeNativeMethods
{
/// <summary>
/// WM_USER taken from WinUser.h
/// </summary>
internal const uint WM_USER = 0x0400;
/// <summary>
/// The signature of the callback that receives messages from the Task Dialog when various events occur.
/// </summary>
/// <param name="hwnd">The window handle of the </param>
/// <param name="msg">The message being passed.</param>
/// <param name="wParam">wParam which is interpreted differently depending on the message.</param>
/// <param name="lParam">wParam which is interpreted differently depending on the message.</param>
/// <param name="refData">The refrence data that was set to TaskDialog.CallbackData.</param>
/// <returns>A HRESULT value. The return value is specific to the message being processed. </returns>
internal delegate int VistaTaskDialogCallback([In] IntPtr hwnd, [In] uint msg, [In] UIntPtr wParam, [In] IntPtr lParam, [In] IntPtr refData);
/// <summary>
/// TASKDIALOG_FLAGS taken from CommCtrl.h.
/// </summary>
[Flags]
internal enum TASKDIALOG_FLAGS
{
/// <summary>
/// Enable hyperlinks.
/// </summary>
TDF_ENABLE_HYPERLINKS = 0x0001,
/// <summary>
/// Use icon handle for main icon.
/// </summary>
TDF_USE_HICON_MAIN = 0x0002,
/// <summary>
/// Use icon handle for footer icon.
/// </summary>
TDF_USE_HICON_FOOTER = 0x0004,
/// <summary>
/// Allow dialog to be cancelled, even if there is no cancel button.
/// </summary>
TDF_ALLOW_DIALOG_CANCELLATION = 0x0008,
/// <summary>
/// Use command links rather than buttons.
/// </summary>
TDF_USE_COMMAND_LINKS = 0x0010,
/// <summary>
/// Use command links with no icons rather than buttons.
/// </summary>
TDF_USE_COMMAND_LINKS_NO_ICON = 0x0020,
/// <summary>
/// Show expanded info in the footer area.
/// </summary>
TDF_EXPAND_FOOTER_AREA = 0x0040,
/// <summary>
/// Expand by default.
/// </summary>
TDF_EXPANDED_BY_DEFAULT = 0x0080,
/// <summary>
/// Start with verification flag already checked.
/// </summary>
TDF_VERIFICATION_FLAG_CHECKED = 0x0100,
/// <summary>
/// Show a progress bar.
/// </summary>
TDF_SHOW_PROGRESS_BAR = 0x0200,
/// <summary>
/// Show a marquee progress bar.
/// </summary>
TDF_SHOW_MARQUEE_PROGRESS_BAR = 0x0400,
/// <summary>
/// Callback every 200 milliseconds.
/// </summary>
TDF_CALLBACK_TIMER = 0x0800,
/// <summary>
/// Center the dialog on the owner window rather than the monitor.
/// </summary>
TDF_POSITION_RELATIVE_TO_WINDOW = 0x1000,
/// <summary>
/// Right to Left Layout.
/// </summary>
TDF_RTL_LAYOUT = 0x2000,
/// <summary>
/// No default radio button.
/// </summary>
TDF_NO_DEFAULT_RADIO_BUTTON = 0x4000,
/// <summary>
/// Task Dialog can be minimized.
/// </summary>
TDF_CAN_BE_MINIMIZED = 0x8000
}
/// <summary>
/// TASKDIALOG_ELEMENTS taken from CommCtrl.h
/// </summary>
internal enum TASKDIALOG_ELEMENTS
{
/// <summary>
/// The content element.
/// </summary>
TDE_CONTENT,
/// <summary>
/// Expanded Information.
/// </summary>
TDE_EXPANDED_INFORMATION,
/// <summary>
/// Footer.
/// </summary>
TDE_FOOTER,
/// <summary>
/// Main Instructions
/// </summary>
TDE_MAIN_INSTRUCTION
}
/// <summary>
/// TASKDIALOG_ICON_ELEMENTS taken from CommCtrl.h
/// </summary>
internal enum TASKDIALOG_ICON_ELEMENTS
{
/// <summary>
/// Main instruction icon.
/// </summary>
TDIE_ICON_MAIN,
/// <summary>
/// Footer icon.
/// </summary>
TDIE_ICON_FOOTER
}
/// <summary>
/// TASKDIALOG_MESSAGES taken from CommCtrl.h.
/// </summary>
internal enum TASKDIALOG_MESSAGES : uint
{
// Spec is not clear on what this is for.
///// <summary>
///// Navigate page.
///// </summary>
////TDM_NAVIGATE_PAGE = WM_USER + 101,
/// <summary>
/// Click button.
/// </summary>
TDM_CLICK_BUTTON = WM_USER + 102, // wParam = Button ID
/// <summary>
/// Set Progress bar to be marquee mode.
/// </summary>
TDM_SET_MARQUEE_PROGRESS_BAR = WM_USER + 103, // wParam = 0 (nonMarque) wParam != 0 (Marquee)
/// <summary>
/// Set Progress bar state.
/// </summary>
TDM_SET_PROGRESS_BAR_STATE = WM_USER + 104, // wParam = new progress state
/// <summary>
/// Set progress bar range.
/// </summary>
TDM_SET_PROGRESS_BAR_RANGE = WM_USER + 105, // lParam = MAKELPARAM(nMinRange, nMaxRange)
/// <summary>
/// Set progress bar position.
/// </summary>
TDM_SET_PROGRESS_BAR_POS = WM_USER + 106, // wParam = new position
/// <summary>
/// Set progress bar marquee (animation).
/// </summary>
TDM_SET_PROGRESS_BAR_MARQUEE = WM_USER + 107, // wParam = 0 (stop marquee), wParam != 0 (start marquee), lparam = speed (milliseconds between repaints)
/// <summary>
/// Set a text element of the Task Dialog.
/// </summary>
TDM_SET_ELEMENT_TEXT = WM_USER + 108, // wParam = element (TASKDIALOG_ELEMENTS), lParam = new element text (LPCWSTR)
/// <summary>
/// Click a radio button.
/// </summary>
TDM_CLICK_RADIO_BUTTON = WM_USER + 110, // wParam = Radio Button ID
/// <summary>
/// Enable or disable a button.
/// </summary>
TDM_ENABLE_BUTTON = WM_USER + 111, // lParam = 0 (disable), lParam != 0 (enable), wParam = Button ID
/// <summary>
/// Enable or disable a radio button.
/// </summary>
TDM_ENABLE_RADIO_BUTTON = WM_USER + 112, // lParam = 0 (disable), lParam != 0 (enable), wParam = Radio Button ID
/// <summary>
/// Check or uncheck the verfication checkbox.
/// </summary>
TDM_CLICK_VERIFICATION = WM_USER + 113, // wParam = 0 (unchecked), 1 (checked), lParam = 1 (set key focus)
/// <summary>
/// Update the text of an element (no effect if origially set as null).
/// </summary>
TDM_UPDATE_ELEMENT_TEXT = WM_USER + 114, // wParam = element (TASKDIALOG_ELEMENTS), lParam = new element text (LPCWSTR)
/// <summary>
/// Designate whether a given Task Dialog button or command link should have a User Account Control (UAC) shield icon.
/// </summary>
TDM_SET_BUTTON_ELEVATION_REQUIRED_STATE = WM_USER + 115, // wParam = Button ID, lParam = 0 (elevation not required), lParam != 0 (elevation required)
/// <summary>
/// Refreshes the icon of the task dialog.
/// </summary>
TDM_UPDATE_ICON = WM_USER + 116 // wParam = icon element (TASKDIALOG_ICON_ELEMENTS), lParam = new icon (hIcon if TDF_USE_HICON_* was set, PCWSTR otherwise)
}
///// <summary>
///// TaskDialog taken from commctrl.h.
///// </summary>
///// <param name="hwndParent">Parent window.</param>
///// <param name="hInstance">Module instance to get resources from.</param>
///// <param name="pszWindowTitle">Title of the Task Dialog window.</param>
///// <param name="pszMainInstruction">The main instructions.</param>
///// <param name="dwCommonButtons">Common push buttons to show.</param>
///// <param name="pszIcon">The main icon.</param>
///// <param name="pnButton">The push button pressed.</param>
////[DllImport("ComCtl32", CharSet = CharSet.Unicode, PreserveSig = false)]
////public static extern void TaskDialog(
//// [In] IntPtr hwndParent,
//// [In] IntPtr hInstance,
//// [In] String pszWindowTitle,
//// [In] String pszMainInstruction,
//// [In] TaskDialogCommonButtons dwCommonButtons,
//// [In] IntPtr pszIcon,
//// [Out] out int pnButton);
/// <summary>
/// TaskDialogIndirect taken from commctl.h
/// </summary>
/// <param name="pTaskConfig">All the parameters about the Task Dialog to Show.</param>
/// <param name="pnButton">The push button pressed.</param>
/// <param name="pnRadioButton">The radio button that was selected.</param>
/// <param name="pfVerificationFlagChecked">The state of the verification checkbox on dismiss of the Task Dialog.</param>
[DllImport("ComCtl32", CharSet = CharSet.Unicode, PreserveSig = false)]
internal static extern void TaskDialogIndirect(
[In] ref TASKDIALOGCONFIG pTaskConfig,
[Out] out int pnButton,
[Out] out int pnRadioButton,
[Out] out bool pfVerificationFlagChecked);
/// <summary>
/// Win32 SendMessage.
/// </summary>
/// <param name="hWnd">Window handle to send to.</param>
/// <param name="Msg">The windows message to send.</param>
/// <param name="wParam">Specifies additional message-specific information.</param>
/// <param name="lParam">Specifies additional message-specific information.</param>
/// <returns>The return value specifies the result of the message processing; it depends on the message sent.</returns>
[DllImport("user32.dll")]
internal static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
/// <summary>
/// Win32 SendMessage.
/// </summary>
/// <param name="hWnd">Window handle to send to.</param>
/// <param name="Msg">The windows message to send.</param>
/// <param name="wParam">Specifies additional message-specific information.</param>
/// <param name="lParam">Specifies additional message-specific information as a string.</param>
/// <returns>The return value specifies the result of the message processing; it depends on the message sent.</returns>
[DllImport("user32.dll", EntryPoint="SendMessage")]
internal static extern IntPtr SendMessageWithString(IntPtr hWnd, uint Msg, IntPtr wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);
/// <summary>
/// TASKDIALOGCONFIG taken from commctl.h.
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
internal struct TASKDIALOGCONFIG
{
/// <summary>
/// Size of the structure in bytes.
/// </summary>
public uint cbSize;
/// <summary>
/// Parent window handle.
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] // Managed code owns actual resource. Passed to native in syncronous call. No lifetime issues.
public IntPtr hwndParent;
/// <summary>
/// Module instance handle for resources.
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] // Managed code owns actual resource. Passed to native in syncronous call. No lifetime issues.
public IntPtr hInstance;
/// <summary>
/// Flags.
/// </summary>
public TASKDIALOG_FLAGS dwFlags; // TASKDIALOG_FLAGS (TDF_XXX) flags
/// <summary>
/// Bit flags for commonly used buttons.
/// </summary>
public VistaTaskDialogCommonButtons dwCommonButtons; // TASKDIALOG_COMMON_BUTTON (TDCBF_XXX) flags
/// <summary>
/// Window title.
/// </summary>
[MarshalAs(UnmanagedType.LPWStr)]
public string pszWindowTitle; // string or MAKEINTRESOURCE()
/// <summary>
/// The Main icon. Overloaded member. Can be string, a handle, a special value or a resource ID.
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] // Managed code owns actual resource. Passed to native in syncronous call. No lifetime issues.
public IntPtr MainIcon;
/// <summary>
/// Main Instruction.
/// </summary>
[MarshalAs(UnmanagedType.LPWStr)]
public string pszMainInstruction;
/// <summary>
/// Content.
/// </summary>
[MarshalAs(UnmanagedType.LPWStr)]
public string pszContent;
/// <summary>
/// Count of custom Buttons.
/// </summary>
public uint cButtons;
/// <summary>
/// Array of custom buttons.
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] // Managed code owns actual resource. Passed to native in syncronous call. No lifetime issues.
public IntPtr pButtons;
/// <summary>
/// ID of default button.
/// </summary>
public int nDefaultButton;
/// <summary>
/// Count of radio Buttons.
/// </summary>
public uint cRadioButtons;
/// <summary>
/// Array of radio buttons.
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] // Managed code owns actual resource. Passed to native in syncronous call. No lifetime issues.
public IntPtr pRadioButtons;
/// <summary>
/// ID of default radio button.
/// </summary>
public int nDefaultRadioButton;
/// <summary>
/// Text for verification check box. often "Don't ask be again".
/// </summary>
[MarshalAs(UnmanagedType.LPWStr)]
public string pszVerificationText;
/// <summary>
/// Expanded Information.
/// </summary>
[MarshalAs(UnmanagedType.LPWStr)]
public string pszExpandedInformation;
/// <summary>
/// Text for expanded control.
/// </summary>
[MarshalAs(UnmanagedType.LPWStr)]
public string pszExpandedControlText;
/// <summary>
/// Text for expanded control.
/// </summary>
[MarshalAs(UnmanagedType.LPWStr)]
public string pszCollapsedControlText;
/// <summary>
/// Icon for the footer. An overloaded member link MainIcon.
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] // Managed code owns actual resource. Passed to native in syncronous call. No lifetime issues.
public IntPtr FooterIcon;
/// <summary>
/// Footer Text.
/// </summary>
[MarshalAs(UnmanagedType.LPWStr)]
public string pszFooter;
/// <summary>
/// Function pointer for callback.
/// </summary>
public VistaTaskDialogCallback pfCallback;
/// <summary>
/// Data that will be passed to the call back.
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] // Managed code owns actual resource. Passed to native in syncronous call. No lifetime issues.
public IntPtr lpCallbackData;
/// <summary>
/// Width of the Task Dialog's area in DLU's.
/// </summary>
public uint cxWidth; // width of the Task Dialog's client area in DLU's. If 0, Task Dialog will calculate the ideal width.
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//
using System;
using System.Diagnostics.Contracts;
namespace System.Collections
{
// Useful base class for typed read/write collections where items derive from object
[Serializable]
public abstract class CollectionBase : IList
{
private ArrayList list;
protected CollectionBase()
{
list = new ArrayList();
}
internal ArrayList InnerList
{
get
{
if (list == null)
list = new ArrayList();
return list;
}
}
protected IList List
{
get { return (IList)this; }
}
public int Count
{
get
{
return list == null ? 0 : list.Count;
}
}
public void Clear()
{
OnClear();
InnerList.Clear();
OnClearComplete();
}
public void RemoveAt(int index)
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
Object temp = InnerList[index];
OnValidate(temp);
OnRemove(index, temp);
InnerList.RemoveAt(index);
try
{
OnRemoveComplete(index, temp);
}
catch
{
InnerList.Insert(index, temp);
throw;
}
}
bool IList.IsReadOnly
{
get { return InnerList.IsReadOnly; }
}
bool IList.IsFixedSize
{
get { return InnerList.IsFixedSize; }
}
bool ICollection.IsSynchronized
{
get { return InnerList.IsSynchronized; }
}
Object ICollection.SyncRoot
{
get { return InnerList.SyncRoot; }
}
void ICollection.CopyTo(Array array, int index)
{
InnerList.CopyTo(array, index);
}
Object IList.this[int index]
{
get
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
return InnerList[index];
}
set
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
OnValidate(value);
Object temp = InnerList[index];
OnSet(index, temp, value);
InnerList[index] = value;
try
{
OnSetComplete(index, temp, value);
}
catch
{
InnerList[index] = temp;
throw;
}
}
}
bool IList.Contains(Object value)
{
return InnerList.Contains(value);
}
int IList.Add(Object value)
{
OnValidate(value);
OnInsert(InnerList.Count, value);
int index = InnerList.Add(value);
try
{
OnInsertComplete(index, value);
}
catch
{
InnerList.RemoveAt(index);
throw;
}
return index;
}
void IList.Remove(Object value)
{
OnValidate(value);
int index = InnerList.IndexOf(value);
if (index < 0) throw new ArgumentException(Environment.GetResourceString("Arg_RemoveArgNotFound"));
OnRemove(index, value);
InnerList.RemoveAt(index);
try
{
OnRemoveComplete(index, value);
}
catch
{
InnerList.Insert(index, value);
throw;
}
}
int IList.IndexOf(Object value)
{
return InnerList.IndexOf(value);
}
void IList.Insert(int index, Object value)
{
if (index < 0 || index > Count)
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
OnValidate(value);
OnInsert(index, value);
InnerList.Insert(index, value);
try
{
OnInsertComplete(index, value);
}
catch
{
InnerList.RemoveAt(index);
throw;
}
}
public IEnumerator GetEnumerator()
{
return InnerList.GetEnumerator();
}
protected virtual void OnSet(int index, Object oldValue, Object newValue)
{
}
protected virtual void OnInsert(int index, Object value)
{
}
protected virtual void OnClear()
{
}
protected virtual void OnRemove(int index, Object value)
{
}
protected virtual void OnValidate(Object value)
{
if (value == null) throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
}
protected virtual void OnSetComplete(int index, Object oldValue, Object newValue)
{
}
protected virtual void OnInsertComplete(int index, Object value)
{
}
protected virtual void OnClearComplete()
{
}
protected virtual void OnRemoveComplete(int index, Object value)
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.ComponentModel.Tests
{
public class BindingListTest
{
[Fact]
public void BindingListDefaults()
{
BindingList<string> l = new BindingList<string>();
IBindingList ibl = (IBindingList)l;
Assert.True(l.AllowEdit, "1");
Assert.False(l.AllowNew, "2");
Assert.True(l.AllowRemove, "3");
Assert.True(l.RaiseListChangedEvents, "4");
Assert.False(ibl.IsSorted, "5");
Assert.Equal(ibl.SortDirection, ListSortDirection.Ascending);
Assert.True(ibl.SupportsChangeNotification, "7");
Assert.False(ibl.SupportsSearching, "8");
Assert.False(ibl.SupportsSorting, "9");
Assert.False(((IRaiseItemChangedEvents)l).RaisesItemChangedEvents, "10");
}
[Fact]
public void BindingListDefaults_FixedSizeList()
{
string[] arr = new string[10];
BindingList<string> l = new BindingList<string>(arr);
IBindingList ibl = (IBindingList)l;
Assert.True(l.AllowEdit, "1");
Assert.False(l.AllowNew, "2");
Assert.True(l.AllowRemove, "3");
Assert.True(l.RaiseListChangedEvents, "4");
Assert.False(ibl.IsSorted, "5");
Assert.Equal(ibl.SortDirection, ListSortDirection.Ascending);
Assert.True(ibl.SupportsChangeNotification, "7");
Assert.False(ibl.SupportsSearching, "8");
Assert.False(ibl.SupportsSorting, "9");
Assert.False(((IRaiseItemChangedEvents)l).RaisesItemChangedEvents, "10");
}
[Fact]
public void BindingListDefaults_NonFixedSizeList()
{
List<string> list = new List<string>();
BindingList<string> l = new BindingList<string>(list);
IBindingList ibl = (IBindingList)l;
Assert.True(l.AllowEdit, "1");
Assert.False(l.AllowNew, "2");
Assert.True(l.AllowRemove, "3");
Assert.True(l.RaiseListChangedEvents, "4");
Assert.False(ibl.IsSorted, "5");
Assert.Equal(ibl.SortDirection, ListSortDirection.Ascending);
Assert.True(ibl.SupportsChangeNotification, "7");
Assert.False(ibl.SupportsSearching, "8");
Assert.False(ibl.SupportsSorting, "9");
Assert.False(((IRaiseItemChangedEvents)l).RaisesItemChangedEvents, "10");
}
[Fact]
public void BindingListDefaults_ReadOnlyList()
{
List<string> list = new List<string>();
BindingList<string> l = new BindingList<string>(list);
IBindingList ibl = (IBindingList)l;
Assert.True(l.AllowEdit, "1");
Assert.False(l.AllowNew, "2");
Assert.True(l.AllowRemove, "3");
Assert.True(l.RaiseListChangedEvents, "4");
Assert.False(ibl.IsSorted, "5");
Assert.Equal(ibl.SortDirection, ListSortDirection.Ascending);
Assert.True(ibl.SupportsChangeNotification, "7");
Assert.False(ibl.SupportsSearching, "8");
Assert.False(ibl.SupportsSorting, "9");
Assert.False(((IRaiseItemChangedEvents)l).RaisesItemChangedEvents, "10");
}
[Fact]
public void TestAllowNew()
{
// Object has a default ctor
BindingList<object> l1 = new BindingList<object>();
Assert.True(l1.AllowNew, "1");
// string has no default ctor
BindingList<string> l2 = new BindingList<string>();
Assert.False(l2.AllowNew, "2");
// adding a delegate to AddingNew fixes that
l2.AddingNew += delegate (object sender, AddingNewEventArgs e) { };
Assert.True(l2.AllowNew, "3");
l1 = new BindingList<object>();
bool list_changed = false;
bool expected = false;
l1.ListChanged += delegate (object sender, ListChangedEventArgs e)
{
list_changed = true;
Assert.Equal(-1, e.NewIndex);
Assert.Equal(ListChangedType.Reset, e.ListChangedType);
Assert.Equal(expected, l1.AllowNew);
};
expected = false;
l1.AllowNew = false;
Assert.True(list_changed, "7");
//the default for T=object is true, so check
//if we enter the block for raising the event
//if we explicitly set it to the value it
//currently has.
l1 = new BindingList<object>();
list_changed = false;
l1.ListChanged += delegate (object sender, ListChangedEventArgs e)
{
list_changed = true;
Assert.Equal(-1, e.NewIndex);
Assert.Equal(ListChangedType.Reset, e.ListChangedType);
Assert.Equal(expected, l1.AllowNew);
};
expected = true;
l1.AllowNew = true;
//turns out it doesn't raise the event, so the check must only be for "allow_new == value"
Assert.False(list_changed, "11");
}
[Fact]
public void TestResetBindings()
{
BindingList<object> l = new BindingList<object>();
bool list_changed = false;
l.ListChanged += delegate (object sender, ListChangedEventArgs e)
{
list_changed = true;
Assert.Equal(-1, e.NewIndex);
Assert.Equal(ListChangedType.Reset, e.ListChangedType);
};
l.ResetBindings();
Assert.True(list_changed, "3");
}
[Fact]
public void TestResetItem()
{
List<object> list = new List<object>();
list.Add(new object());
BindingList<object> l = new BindingList<object>(list);
bool item_changed = false;
l.ListChanged += delegate (object sender, ListChangedEventArgs e)
{
item_changed = true;
Assert.Equal(0, e.NewIndex);
Assert.Equal(ListChangedType.ItemChanged, e.ListChangedType);
};
l.ResetItem(0);
Assert.True(item_changed, "3");
}
[Fact]
public void TestRemoveItem()
{
List<object> list = new List<object>();
list.Add(new object());
BindingList<object> l = new BindingList<object>(list);
bool item_deleted = false;
l.ListChanged += delegate (object sender, ListChangedEventArgs e)
{
item_deleted = true;
Assert.Equal(0, e.NewIndex);
Assert.Equal(ListChangedType.ItemDeleted, e.ListChangedType);
Assert.Equal(0, l.Count); // to show the event is raised after the removal
};
l.RemoveAt(0);
Assert.True(item_deleted, "4");
}
[Fact]
public void TestRemoveItem_AllowRemoveFalse()
{
List<object> list = new List<object>();
list.Add(new object());
BindingList<object> l = new BindingList<object>(list);
l.AllowRemove = false;
Assert.Throws<NotSupportedException>(() => l.RemoveAt(0));
}
[Fact]
public void TestAllowEditEvent()
{
BindingList<object> l = new BindingList<object>();
bool event_raised = false;
bool expected = false;
l.ListChanged += delegate (object sender, ListChangedEventArgs e)
{
event_raised = true;
Assert.Equal(-1, e.NewIndex);
Assert.Equal(ListChangedType.Reset, e.ListChangedType);
Assert.Equal(expected, l.AllowEdit);
};
expected = false;
l.AllowEdit = false;
Assert.True(event_raised, "4");
// check to see if RaiseListChangedEvents affects AllowEdit's event.
l.RaiseListChangedEvents = false;
event_raised = false;
expected = true;
l.AllowEdit = true;
Assert.False(event_raised, "5");
}
[Fact]
public void TestAllowRemove()
{
BindingList<object> l = new BindingList<object>();
bool event_raised = false;
bool expected = false;
l.ListChanged += delegate (object sender, ListChangedEventArgs e)
{
event_raised = true;
Assert.Equal(-1, e.NewIndex);
Assert.Equal(ListChangedType.Reset, e.ListChangedType);
Assert.Equal(expected, l.AllowRemove);
};
expected = false;
l.AllowRemove = false;
Assert.True(event_raised, "4");
// check to see if RaiseListChangedEvents affects AllowRemove's event.
l.RaiseListChangedEvents = false;
event_raised = false;
expected = true;
l.AllowRemove = true;
Assert.False(event_raised, "5");
}
[Fact]
public void TestAddNew_SettingArgsNewObject()
{
BindingList<object> l = new BindingList<object>();
bool adding_event_raised = false;
object o = new object();
l.AddingNew += delegate (object sender, AddingNewEventArgs e)
{
adding_event_raised = true;
Assert.Null(e.NewObject);
e.NewObject = o;
};
object rv = l.AddNew();
Assert.True(adding_event_raised, "2");
Assert.Same(o, rv);
}
[Fact]
public void TestAddNew()
{
BindingList<object> l = new BindingList<object>();
bool adding_event_raised = false;
object o = new object();
l.AddingNew += delegate (object sender, AddingNewEventArgs e)
{
adding_event_raised = true;
Assert.Null(e.NewObject);
};
object rv = l.AddNew();
Assert.True(adding_event_raised, "2");
Assert.NotNull(rv);
}
[Fact]
public void TestAddNew_Cancel()
{
BindingList<object> l = new BindingList<object>();
bool adding_event_raised = false;
object o = new object();
bool list_changed = false;
ListChangedType change_type = ListChangedType.Reset;
int list_changed_index = -1;
l.AddingNew += delegate (object sender, AddingNewEventArgs e)
{
adding_event_raised = true;
Assert.Null(e.NewObject);
};
l.ListChanged += delegate (object sender, ListChangedEventArgs e)
{
list_changed = true;
change_type = e.ListChangedType;
list_changed_index = e.NewIndex;
};
object rv = l.AddNew();
Assert.True(adding_event_raised, "2");
Assert.NotNull(rv);
Assert.Equal(1, l.Count);
Assert.Equal(0, l.IndexOf(rv));
Assert.True(list_changed, "6");
Assert.Equal(ListChangedType.ItemAdded, change_type);
Assert.Equal(0, list_changed_index);
list_changed = false;
l.CancelNew(0);
Assert.Equal(0, l.Count);
Assert.True(list_changed, "10");
Assert.Equal(ListChangedType.ItemDeleted, change_type);
Assert.Equal(0, list_changed_index);
}
[Fact]
public void TestAddNew_CancelDifferentIndex()
{
List<object> list = new List<object>();
list.Add(new object());
list.Add(new object());
BindingList<object> l = new BindingList<object>(list);
bool adding_event_raised = false;
object o = new object();
bool list_changed = false;
ListChangedType change_type = ListChangedType.Reset;
int list_changed_index = -1;
l.AddingNew += delegate (object sender, AddingNewEventArgs e)
{
adding_event_raised = true;
Assert.Null(e.NewObject);
};
l.ListChanged += delegate (object sender, ListChangedEventArgs e)
{
list_changed = true;
change_type = e.ListChangedType;
list_changed_index = e.NewIndex;
};
object rv = l.AddNew();
Assert.True(adding_event_raised, "2");
Assert.NotNull(rv);
Assert.Equal(3, l.Count);
Assert.Equal(2, l.IndexOf(rv));
Assert.True(list_changed, "6");
Assert.Equal(ListChangedType.ItemAdded, change_type);
Assert.Equal(2, list_changed_index);
list_changed = false;
l.CancelNew(0);
Assert.False(list_changed, "9");
Assert.Equal(3, l.Count);
l.CancelNew(2);
Assert.True(list_changed, "11");
Assert.Equal(ListChangedType.ItemDeleted, change_type);
Assert.Equal(2, list_changed_index);
Assert.Equal(2, l.Count);
}
[Fact]
public void TestAddNew_End()
{
BindingList<object> l = new BindingList<object>();
bool adding_event_raised = false;
object o = new object();
bool list_changed = false;
ListChangedType change_type = ListChangedType.Reset;
int list_changed_index = -1;
l.AddingNew += delegate (object sender, AddingNewEventArgs e)
{
adding_event_raised = true;
Assert.Null(e.NewObject);
};
l.ListChanged += delegate (object sender, ListChangedEventArgs e)
{
list_changed = true;
change_type = e.ListChangedType;
list_changed_index = e.NewIndex;
};
object rv = l.AddNew();
Assert.True(adding_event_raised, "2");
Assert.NotNull(rv);
Assert.Equal(1, l.Count);
Assert.Equal(0, l.IndexOf(rv));
Assert.True(list_changed, "6");
Assert.Equal(ListChangedType.ItemAdded, change_type);
Assert.Equal(0, list_changed_index);
list_changed = false;
l.EndNew(0);
Assert.Equal(1, l.Count);
Assert.False(list_changed, "10");
}
[Fact]
public void TestAddNew_CancelDifferentIndexThenEnd()
{
BindingList<object> l = new BindingList<object>();
bool adding_event_raised = false;
object o = new object();
bool list_changed = false;
ListChangedType change_type = ListChangedType.Reset;
int list_changed_index = -1;
l.AddingNew += delegate (object sender, AddingNewEventArgs e)
{
adding_event_raised = true;
Assert.Null(e.NewObject);
};
l.ListChanged += delegate (object sender, ListChangedEventArgs e)
{
list_changed = true;
change_type = e.ListChangedType;
list_changed_index = e.NewIndex;
};
object rv = l.AddNew();
Assert.True(adding_event_raised, "2");
Assert.NotNull(rv);
Assert.Equal(1, l.Count);
Assert.Equal(0, l.IndexOf(rv));
Assert.True(list_changed, "6");
Assert.Equal(ListChangedType.ItemAdded, change_type);
Assert.Equal(0, list_changed_index);
list_changed = false;
l.CancelNew(2);
Assert.Equal(1, l.Count);
Assert.False(list_changed, "10");
l.EndNew(0);
Assert.Equal(1, l.Count);
Assert.False(list_changed, "12");
}
[Fact]
public void TestAddNew_EndDifferentIndexThenCancel()
{
BindingList<object> l = new BindingList<object>();
bool adding_event_raised = false;
object o = new object();
bool list_changed = false;
ListChangedType change_type = ListChangedType.Reset;
int list_changed_index = -1;
l.AddingNew += delegate (object sender, AddingNewEventArgs e)
{
adding_event_raised = true;
Assert.Null(e.NewObject);
};
l.ListChanged += delegate (object sender, ListChangedEventArgs e)
{
list_changed = true;
change_type = e.ListChangedType;
list_changed_index = e.NewIndex;
};
object rv = l.AddNew();
Assert.True(adding_event_raised, "2");
Assert.NotNull(rv);
Assert.Equal(1, l.Count);
Assert.Equal(0, l.IndexOf(rv));
Assert.True(list_changed, "6");
Assert.Equal(ListChangedType.ItemAdded, change_type);
Assert.Equal(0, list_changed_index);
list_changed = false;
l.EndNew(2);
Assert.Equal(1, l.Count);
Assert.False(list_changed, "10");
l.CancelNew(0);
Assert.True(list_changed, "11");
Assert.Equal(ListChangedType.ItemDeleted, change_type);
Assert.Equal(0, list_changed_index);
}
class BindingListPoker : BindingList<object>
{
public object DoAddNewCore()
{
return base.AddNewCore();
}
}
// test to make sure that the events are raised in AddNewCore and not in AddNew
[Fact]
public void TestAddNewCore_Insert()
{
BindingListPoker poker = new BindingListPoker();
bool adding_event_raised = false;
bool list_changed = false;
ListChangedType change_type = ListChangedType.Reset;
int list_changed_index = -1;
poker.AddingNew += delegate (object sender, AddingNewEventArgs e)
{
adding_event_raised = true;
};
poker.ListChanged += delegate (object sender, ListChangedEventArgs e)
{
list_changed = true;
change_type = e.ListChangedType;
list_changed_index = e.NewIndex;
};
object o = poker.DoAddNewCore();
Assert.True(adding_event_raised, "1");
Assert.True(list_changed, "2");
Assert.Equal(ListChangedType.ItemAdded, change_type);
Assert.Equal(0, list_changed_index);
Assert.Equal(1, poker.Count);
}
private class Item : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
string _name;
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
OnPropertyChanged("Name");
}
}
}
void OnPropertyChanged(string name)
{
var fn = PropertyChanged;
if (fn != null)
fn(this, new PropertyChangedEventArgs(name));
}
}
[Fact]
public void Test_InsertNull()
{
var list = new BindingList<Item>();
list.Insert(0, null);
var count = list.Count;
Assert.Equal(1, count);
}
private class Person : INotifyPropertyChanged
{
private string _lastName;
private string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
OnPropertyChanged("FirstName"); // string matches property name
}
}
public string LastName
{
get { return _lastName; }
set
{
_lastName = value;
OnPropertyChanged("NotTheName"); // string doesn't match property name
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Xml;
namespace Microsoft.Zing
{
#region Types related to getting information from a Zing state
/// <summary>
/// This enumeration denotes the type of a Zing state.
/// </summary>
/// <remarks>
/// Of the five state types here, three are terminal states from which no
/// transitions are possible (Error, NormalTermination, FailedAssumption)
/// and two are non-terminal state types (Execution and Choice).
/// </remarks>
public enum StateType
{
/// <summary>
/// A non-terminal node in which forward progress is possible by executing one of
/// the runnable processes.
/// </summary>
Execution,
/// <summary>
/// A non-terminal node in which forward progress is possible by
/// selecting from a set of available non-deterministic choices.
/// </summary>
Choice,
/// <summary>
/// A terminal node in which some error has occurred. Use the
/// <see cref="Error"/> property to retrieve specific information
/// about the error.
/// </summary>
Error,
/// <summary>
/// A terminal node in which all processes have either terminated
/// normally or are in a valid end-state.
/// </summary>
NormalTermination,
/// <summary>
/// A terminal node in which an "assume" statement has failed. This
/// condition halts further execution from the state, but is not
/// considered an error - it simply prunes the search tree.
/// </summary>
FailedAssumption
}
/// <summary>
/// This class denotes a contiguous fragment of Zing source code.
/// </summary>
/// <remarks>
/// The Zing object model exposes the source code from which it was compiled. As
/// a Zing model is executed, the current source context for each process may be
/// obtained in the form of a ZingSourceContext. The readonly properties return
/// the index of the source file and an offset range within it.
/// </remarks>
public class ZingSourceContext
{
public ZingSourceContext()
: this(0, 0, 0)
{
}
/// <summary>
/// Construct a ZingSourceContext for the given docIndex, startColumn, and endColumn.
/// </summary>
/// <param name="docIndex">The zero-based index of the source file referenced.</param>
/// <param name="startColumn">The starting column number.</param>
/// <param name="endColumn">The ending column number (not inclusive)</param>
public ZingSourceContext(int docIndex, int startColumn, int endColumn)
{
this.docIndex = docIndex;
this.startColumn = startColumn;
this.endColumn = endColumn;
}
/// <summary>
/// Returns the index of the source file referenced.
/// </summary>
public int DocIndex { get { return docIndex; } }
private int docIndex;
/// <summary>
/// Returns the starting column number of the source fragment.
/// </summary>
public int StartColumn { get { return startColumn; } }
private int startColumn;
/// <summary>
/// Returns the ending column number of the source fragment.
/// </summary>
public int EndColumn { get { return endColumn; } }
private int endColumn;
public void CopyTo(ZingSourceContext other)
{
other.docIndex = this.docIndex;
other.endColumn = this.endColumn;
other.startColumn = this.startColumn;
}
}
/// <summary>
/// This enumeration provides the status of a Zing process
/// </summary>
public enum ProcessStatus
{
/// <summary>
/// The process is currently runnable.
/// </summary>
Runnable,
/// <summary>
/// The process is blocked in a select statement which is *not* marked with the
/// "end" keyword and thus is not a suitable endstate for the process.
/// </summary>
Blocked,
/// <summary>
/// The process is blocked in a select statement marked with the "end" keyword.
/// If no other processes are runnable, the model is in a valid end state.
/// </summary>
BlockedInEndState,
/// <summary>
/// The process completed normally through a return out of it's entry point.
/// </summary>
Completed
}
/// <summary>
/// This structure returns information about a Zing process. It is obtained by calling
/// State.GetProcessInfo().
/// </summary>
public struct ProcessInfo
{
/// <summary>
/// Returns the current status of the process
/// </summary>
public ProcessStatus Status { get { return status; } }
private ProcessStatus status;
/// <summary>
/// Returns the name of the process (i.e. its entry point)
/// </summary>
public string Name { get { return name; } }
private string name;
/// <summary>
/// Returns the name of the method on the top of the stack.
/// </summary>
public string MethodName
{
get
{
return topOfStack.MethodName;
}
}
/// <summary>
/// Returns the source context of the active method.
/// </summary>
public ZingSourceContext Context { get { return context; } }
private ZingSourceContext context;
/// <summary>
/// Returns the context attribute found on the current statement of
/// the active method, or null if no attribute was present.
/// </summary>
public ZingAttribute ContextAttribute { get { return contextAttribute; } }
private ZingAttribute contextAttribute;
/// <summary>
/// Returns a string representation of the logical program counter for the active method.
/// </summary>
public string ProgramCounter
{
get
{
return topOfStack.ProgramCounter;
}
}
/// <summary>
/// Returns true if a "backward" transition was encountered in the last execution.
/// </summary>
public bool BackTransitionEncountered
{
get
{
return this.backTransitionEncountered;
}
}
private bool backTransitionEncountered;
// We keep the top of stack around so we can lazily compute the ProgramCounter and
// MethodName later. This is a big win since these operations use reflection and are
// not required in performance-critical paths.
private ZingMethod topOfStack;
internal ProcessInfo(Process p)
{
topOfStack = p.TopOfStack;
backTransitionEncountered = p.BackTransitionEncountered;
status = p.CurrentStatus;
name = Utils.Unmangle(p.Name);
context = p.Context;
contextAttribute = p.ContextAttribute;
}
public override bool Equals(object obj)
{
ProcessInfo other = (ProcessInfo)obj;
return
this.backTransitionEncountered == other.backTransitionEncountered &&
this.context == other.context &&
this.contextAttribute == other.contextAttribute &&
this.name == other.name &&
this.status == other.status &&
this.topOfStack == other.topOfStack;
}
public override int GetHashCode()
{
throw new NotImplementedException("The method or operation is not implemented.");
}
public static bool operator ==(ProcessInfo p1, ProcessInfo p2)
{
return p1.Equals(p2);
}
public static bool operator !=(ProcessInfo p1, ProcessInfo p2)
{
return p1.Equals(p2);
}
}
#endregion Types related to getting information from a Zing state
#region Execution traces & related types
/// <summary>
/// This enum lists the possible results of running the model-checker or
/// refinement checker.
/// </summary>
public enum ZingerResult
{
/// <summary>
/// No errors were found within the specified limits of the search (if any).
/// </summary>
Success = 0,
/// <summary>
/// The state-space search was cancelled.
/// </summary>
Canceled = 1,
/// <summary>
/// A state was found in which one or more processes were stuck, but not at
/// valid "end" states.
/// </summary>
Deadlock = 2,
/// <summary>
/// An assertion failure was encountered in the Zing model.
/// </summary>
Assertion = 3,
/// <summary>
/// This code is returned for a number of different runtime errors in the user's
/// Zing model (null reference, divide by zero, integer overflow, unhandled
/// Zing exception, and index out of range, invalid blocking select, invalid
/// choose).
/// </summary>
ProgramRuntimeError = 4,
/// <summary>
/// This error is returned when an unexpected runtime error is encountered. This
/// typically indicates a bug in the Zing compiler or runtime.
/// </summary>
ZingRuntimeError = 5,
/// <summary>
/// Liveness Acceptance Cycle
/// </summary>
AcceptanceCyleFound = 6,
/// <summary>
/// Invalid Parameters Passed
/// </summary>
InvalidParameters = 7,
/// <summary>
/// DFS search stack size exceeded the maximum size.
/// </summary>
DFSStackOverFlowError = 8,
/// <summary>
/// Zinger Time Out
/// </summary>
ZingerTimeOut = 9,
/// <summary>
/// Zinger is terminating on a call to the motion planner
/// </summary>
ZingerMotionPlanningInvocation = 10
}
/// <summary>
/// A step structure represents one edge in a Zing state-transition graph.
/// </summary>
/// <remarks>
/// A step is normally part of an execution trace. It represents
/// either the execution of a particular process or the selection of a
/// particular non-deterministic choice.
/// </remarks>
[Serializable]
public struct TraceStep
{
[CLSCompliant(false)]
public TraceStep(uint data)
{
stepData = (ushort)data;
}
#if UNUSED
internal TraceStep(bool isExecutionStep, uint selection)
{
stepData = (selection << 1) | (isExecutionStep ? 0u : 1u);
}
#endif
public TraceStep(bool isExecutionStep, int selection)
{
stepData = (ushort)selection;
stepData <<= 1;
stepData |= isExecutionStep ? (ushort)0 : (ushort)1;
}
private ushort stepData;
[CLSCompliant(false)]
public UInt32 StepData { get { return stepData; } }
public override bool Equals(object obj)
{
TraceStep other = (TraceStep)obj;
return (other.stepData == this.stepData);
}
public override int GetHashCode()
{
return stepData.GetHashCode();
}
public static bool operator ==(TraceStep step1, TraceStep step2)
{
return step1.Equals(step2);
}
public static bool operator !=(TraceStep step1, TraceStep step2)
{
return !step1.Equals(step2);
}
/// <summary>
/// Does the Step represent a process execution?
/// </summary>
public bool IsExecution
{
get
{
return (stepData & 1) == 0;
}
}
/// <summary>
/// Does the Step represent a non-deterministic choice?
/// </summary>
public bool IsChoice
{
get
{
return !this.IsExecution;
}
}
/// <summary>
/// Return the process or choice number associated with the Step.
/// </summary>
public int Selection
{
get
{
return (int)(stepData >> 1);
}
}
}
/// <summary>
/// A trace object contains an array of Step structures representing some
/// execution of a Zing model.
/// </summary>
/// <remarks>
/// A trace object represents a series of transitions from the initial state
/// of a Zing model to some ending state (terminal or non-terminal). Traces
/// may represent any execution of a Zing model and do not necessarily end
/// in a terminal state or an error state. Because we implement IEnumerable,
/// it's possible to use "foreach" to iterate over the steps in a trace. An
/// indexer is also provided for accessing the Steps with a numeric index.
/// </remarks>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[Serializable]
public class Trace : IEnumerable, IEnumerable<TraceStep>
{
/// <summary>
/// Construct an empty trace object.
/// </summary>
public Trace()
{
this.steps = new List<TraceStep>();
}
/// <summary>
/// Construct a trace object and populate it with the given step array.
/// </summary>
/// <param name="steps">An array of Step structs containing the trace data</param>
public Trace(TraceStep[] steps)
{
this.steps = new List<TraceStep>(steps.Length);
this.steps.AddRange(steps);
}
//
// This constructor is only needed for the distributed checker
//
[CLSCompliant(false)]
public Trace(uint[] stepList)
{
this.steps = new List<TraceStep>(stepList.Length);
for (int i = 0; i < stepList.Length; ++i)
{
steps.Add(new TraceStep(stepList[i]));
}
}
private List<TraceStep> steps;
/// <summary>
/// Add a Step to the end of the current trace.
/// </summary>
/// <param name="traceStep">The step to be added to the trace.</param>
public void AddStep(TraceStep traceStep)
{
steps.Add(traceStep);
}
/// <summary>
/// Insert a Step at the beginning of the current trace.
/// </summary>
/// <param name="traceStep">The step to be inserted in the trace.</param>
public void InsertStep(TraceStep traceStep)
{
steps.Insert(0, traceStep);
}
/// <summary>
/// Return the number of steps in the trace.
/// </summary>
public int Count
{
get
{
return this.steps.Count;
}
}
/// <summary>
/// This indexer allows the steps to be set or retrieved by their index.
/// </summary>
/// <param name="stepNumber">Index of the step to be retrieved.</param>
public TraceStep this[int stepNumber]
{
get
{
return this.steps[stepNumber];
}
set
{
this.steps[stepNumber] = value;
}
}
/// <summary>
/// Return an enumerator for the trace.
/// </summary>
/// <returns>Returns an enumerator over the steps in the trace.</returns>
public IEnumerator GetEnumerator()
{
return this.steps.GetEnumerator();
}
IEnumerator<TraceStep> IEnumerable<TraceStep>.GetEnumerator()
{
return this.steps.GetEnumerator();
}
/// <summary>
/// Replays the execution trace against the given initial state returning the
/// resulting array of State objects.
/// </summary>
/// <param name="initialState">The initial state of the model.</param>
/// <returns>An array of State objects corresponding to the trace.</returns>
public State[] GetStates(State initialState)
{
//during trace generation don't canonicalize symbolic ids
State[] stateList = new State[this.Count + 1];
stateList[0] = initialState;
State currentState = initialState;
bool isDeadLock = currentState.SI.IsInvalidEndState();
for (int i = 0; i < this.Count; i++)
{
/*
if (i == 0)
Console.Write ("#### State {0} : \r\n {1}", i, currentState);
else
{
if (this[i-1].IsExecution)
Console.Write("#### State {0} (ran process {1}) :\r\n{2}", i, this[i-1].Selection, currentState);
else
Console.Write("#### State {0} (took choice {1}) :\r\n{2}", i, this[i-1].Selection, currentState);
}
if (currentState != null)
Console.Write ("\r\nError in state:\r\n{0}\r\n", currentState.Error);
*/
currentState = currentState.Run(this[i]);
stateList[i + 1] = currentState;
}
return stateList;
}
public State GetLastState(State initialState)
{
StateImpl stateImpl = initialState.SI;
for (int i = 0; i < this.Count; i++)
{
TraceStep step = this[i];
if (step.IsChoice)
stateImpl.RunChoice((int)step.Selection);
else
stateImpl.RunProcess((int)step.Selection);
}
return initialState;
}
public override string ToString()
{
string retval = "";
for (int i = 0; i < this.Count; i++)
{
if (i > 0)
{
retval += ",";
}
TraceStep step = this[i];
if (step.IsChoice)
{
retval += "C" + step.Selection;
}
else
{
retval += "E" + step.Selection;
}
}
return retval;
}
}
#endregion Execution traces & related types
/// <summary>
/// This class represents one state in the state-space of a Zing model.
/// </summary>
/// <remarks>
/// A Zing state is created by referencing a Zing assembly (either as an
/// Assembly object or by a pathname). From an initial state, successor
/// states can be obtained by calling RunProcess, RunChoice, or Run.
/// </remarks>
public class State
{
public bool IsAcceptanceState
{
get
{
return si.IsAcceptingState;
}
set
{
si.IsAcceptingState = value;
}
}
#region Constructors
// Users never get State objects by construction, so the constructor is private.
public State(StateImpl si)
{
this.si = si;
}
private State(StateImpl si, State lastState)
{
this.si = si;
this.lastState = lastState;
}
#endregion Constructors
#region Fields
// A reference to our associated state detail.
private StateImpl si;
public StateImpl SI
{
get { return si; }
}
// A reference to our predecessor state or null for the initial state.
private State lastState;
// The step by which the current State was reached.
private TraceStep lastStep;
#endregion Fields
#region State creation (for end users)
/// <summary>
/// Creates an initial Zing state from the given assembly reference.
/// </summary>
/// <param name="zingAssembly">An assembly object referencing a valid Zing assembly.</param>
/// <returns>Returns the initial state of the referenced Zing model.</returns>
public static State Load(Assembly zingAssembly)
{
return new State(StateImpl.Load(zingAssembly));
}
/// <summary>
/// Creates an initial Zing state from the given assembly reference.
/// </summary>
/// <param name="zingAssemblyPath">A pathname pointing to a valid Zing assembly.</param>
/// <returns>Returns the initial state of the referenced Zing model.</returns>
public static State Load(string zingAssemblyPath)
{
return new State(StateImpl.Load(zingAssemblyPath));
}
#endregion State creation (for end users)
#region Helpful overrides
/// <summary>
/// Checks the equality of this state with another by comparing their fingerprints.
/// This is correct with high probability.
/// </summary>
/// <param name="obj">The state object to be compared.</param>
/// <returns>Returns true if the states are (very likely) equal, false otherwise.</returns>
public override bool Equals(object obj)
{
return this.si.Equals(((State)obj).si);
}
/// <summary>
/// Returns a hash code based on the fingerprint of our underlying state implementation.
/// The hash codes of "equivalent" states are guaranteed to be equal.
/// </summary>
/// <returns>Returns a hash code for the State object.</returns>
public override int GetHashCode()
{
return this.si.GetHashCode();
}
/// <summary>
/// Compares two states using their fingerprints. This is correct with high
/// probability.
/// </summary>
/// <param name="obj1">The first state to be compared.</param>
/// <param name="obj2">The second state to be compared.</param>
/// <returns>True, if the states are equal, false otherwise.</returns>
static public new bool Equals(object obj1, object obj2)
{
Debug.Assert(obj1 is State && obj2 is State);
return obj1.Equals(obj2);
}
/// <summary>
/// Returns a string containing all of the state details in a reasonably readable format.
/// </summary>
/// <returns>Returns a string containing our state details.</returns>
public override string ToString()
{
return si.ToString();
}
#endregion Helpful overrides
#region Basic queries
/// <summary>
/// Returns a <see cref="Fingerprint"/> object which uniquely (with high probablity)
/// this state. If two states have the same fingerprint, then they are equivalent
/// although their details may differ in unimportant respects.
/// </summary>
public Fingerprint Fingerprint
{
get
{
return si.Fingerprint;
}
}
/// <summary>
/// Returns the <see cref="StateType"/> enumeration value which describes the current state.
/// </summary>
public StateType Type
{
get
{
return si.Type;
}
}
/// <summary>
/// Returns true on the initial state of the model, false otherwise.
/// </summary>
public bool IsInitial
{
get
{
return this.lastState == null;
}
}
/// <summary>
/// Returns true if no transitions may be made from the current state.
/// </summary>
public bool IsTerminal
{
get
{
switch (this.Type)
{
case StateType.Execution:
case StateType.Choice:
return false;
default:
return true;
}
}
}
/// <summary>
/// Returns the <see cref="TraceStep"/> by which the current state was reached. Throws
/// InvalidOperationException if referenced from the initial state.
/// I
/// </summary>
public TraceStep LastStep
{
get
{
if (this.lastState == null)
throw new InvalidOperationException("Invalid reference to LastStep on the initial state");
return this.lastStep;
}
}
/// <summary>
/// Returns a reference to the predecessor state, or null on the initial state.
/// </summary>
public State LastState
{
get
{
return this.lastState;
}
}
/// <summary>
/// Returns the number of processes present in the current state.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public int NumProcesses
{
get
{
return si.NumProcesses;
}
}
/// <summary>
/// Returns the number of non-deterministic choices available in the current state or zero
/// if the current state is not of type StateType.Choice.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public int NumChoices
{
get
{
return si.NumChoices;
}
}
/// <summary>
/// In a Choice state, this property returns the number of the process currently executing.
/// </summary>
public int ChoiceProcess
{
get
{
return si.choiceProcessNumber;
}
}
/// <summary>
/// Returns an array of strings containing the pathnames of the files used to compile
/// the Zing model.
/// </summary>
/// <returns>Array of source code pathnames</returns>
public string[] GetSourceFiles()
{
return si.GetSourceFiles();
}
/// <summary>
/// Returns an array of strings containing the Zing source code which corresponds to
/// the pathnames in the <see cref="GetSourceFiles"/> method.
/// </summary>
/// <returns>Array of source code strings</returns>
public string[] GetSourceText()
{
return si.GetSources();
}
/// <summary>
/// For states of type StateType.Error or StateType.FailedAssumption, this property returns
/// a reference to an exception describing the state's failure. Otherwise, the property
/// returns null.
/// </summary>
public Exception Error
{
get
{
return si.Error;
}
}
/// <summary>
/// Returns an array (possibly empty) of event objects describing the actions of the model
/// during the transition from the prior state to the current one. Event objects all derive
/// from <see cref="ZingEvent"/> and contain relevant information about process creation,
/// process termination, messaging, and "trace" statements that were encountered.
/// </summary>
/// <returns>Array of event objects</returns>
public ZingEvent[] GetEvents()
{
return si.GetEvents();
}
public ZingEvent[] GetTraceLog()
{
return si.GetTraceLog();
}
#endregion Basic queries
#region Basic execution model
/// <summary>
/// This method is designed for use with execution traces. The caller can
/// simply enumerate the Steps of the Trace and call Run() to generate the
/// successor State.
/// </summary>
/// <param name="step">A step object describing the transition to be made</param>
/// <returns>Returns a <see cref="State"/> object representing the new state.</returns>
public State Run(TraceStep step)
{
if (step.IsChoice)
return this.RunChoice((int)step.Selection);
else
return this.RunProcess((int)step.Selection);
}
/// <summary>
/// Returns a new state representing the execution of process <c>p</c> in the current state.
/// </summary>
/// <param name="processNumber">The number of the process to be executed.</param>
/// <returns>Returns a <see cref="State"/> object representing the new state.</returns>
/// <exception cref="InvalidOperationException">Thrown if the current state is not of type <c>StateType.Execution</c>.</exception>
public State RunProcess(int processNumber)
{
if (this.Type != StateType.Execution)
throw new InvalidOperationException("RunProcess must be called on an execution state.");
StateImpl siNew = (StateImpl)si.Clone();
siNew.RunProcess(processNumber);
State sNew = new State(siNew, this);
sNew.lastStep = new TraceStep(true, processNumber);
return sNew;
}
/// <summary>
/// Returns a new state representing the selection of choice <c>c</c> in the current state.
/// </summary>
/// <param name="choice">The number of the choice to be selected.</param>
/// <returns>Returns a <see cref="State"/> object representing the new state.</returns>
/// <exception cref="InvalidOperationException">Thrown if the current state is not of type <c>StateType.Choice</c>.</exception>
public State RunChoice(int choice)
{
if (this.Type != StateType.Choice)
throw new InvalidOperationException("RunChoice must be called on a choice state.");
StateImpl siNew = (StateImpl)si.Clone();
siNew.RunChoice(choice);
State sNew = new State(siNew, this);
sNew.lastStep = new TraceStep(false, choice);
return sNew;
}
/// <summary>
/// Returns a new state representing the execution of process <c>processNumber</c> in the current state.
/// </summary>
/// <param name="processNumber">The number of the process to be executed.</param>
/// <param name="steps">The number of steps for which the process should be executed.</param>
/// <returns>Returns a <see cref="State"/> object representing the new state.</returns>
/// <exception cref="InvalidOperationException">Thrown if the current state is not of type <c>StateType.Execution</c>.</exception>
public State RunProcess(int processNumber, int steps)
{
if (this.Type != StateType.Execution)
throw new InvalidOperationException("RunProcess must be called on an execution state.");
StateImpl siNew = (StateImpl)si.Clone();
for (int i = 0; i < steps; i++)
siNew.RunProcess(processNumber);
State sNew = new State(siNew, this);
sNew.lastStep = new TraceStep(true, processNumber);
return sNew;
}
/// <summary>
/// Returns a <see cref="Trace"/> object representing the execution path to the current state.
/// </summary>
/// <returns>A Trace object for the current state.</returns>
public Trace BuildTrace()
{
if (this.IsInitial)
{
return new Trace();
}
else
{
Trace t = this.lastState.BuildTrace();
t.AddStep(this.lastStep);
return t;
}
}
#endregion Basic execution model
#region Advanced queries
/// <summary>
/// Retrieve the ProcessInfo for a given process id.
/// </summary>
/// <param name="processId">The process of interest.</param>
/// <returns>Returns a populated ProcessInfo struct.</returns>
public ProcessInfo GetProcessInfo(int processId)
{
return si.GetProcessInfo(processId);
}
/// <summary>
/// Returns true if there exists a global variable of the given name.
/// </summary>
/// <param name="name">The name of the variable of interest.</param>
/// <returns>Returns true if the variable exists.</returns>
public bool ContainsGlobalVariable(string name)
{
return si.ContainsGlobalVariable(name);
}
/// <summary>
/// Returns the value of a given global variable.
/// </summary>
/// <param name="name">The name of the variable of interest.</param>
/// <returns>Returns the value of the variable, or null if it doesn't exist.</returns>
public object LookupGlobalVariableByName(string name)
{
return si.LookupGlobalVarByName(name);
}
/// <summary>
/// Returns true if there exists a local variable of the given name.
/// </summary>
/// <param name="processId">The process whose current method should be checked.</param>
/// <param name="name">The name of the variable of interest.</param>
/// <returns>Returns true if the variable exists in the current stack frame of the given process.</returns>
public bool ContainsLocalVariable(int processId, string name)
{
return si.ContainsLocalVariable(processId, name);
}
/// <summary>
/// Returns the value of a given local variable.
/// </summary>
/// <param name="processId">The process whose current method should be checked.</param>
/// <param name="name">The name of the variable of interest.</param>
/// <returns>Returns the value of the variable, or null if it doesn't exist.</returns>
public object LookupLocalVariableByName(int processId, string name)
{
return si.LookupLocalVarByName(processId, name);
}
/// <summary>
/// Returns an XML representation of the complete state including processes and their
/// stacks, global variables, events, and the heap.
/// </summary>
/// <returns>An XmlDocument object containing a dump of the state details.</returns>
public XmlDocument ToXml()
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<?xml version='1.0'?><ZingState/>");
//TODO: doc.ReadXmlSchema(...);
si.ToXml(doc.DocumentElement);
return doc;
}
#endregion Advanced queries
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------
// <copyright file="ImportCollection_Tests.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>Baseline Regression Tests for v9 OM Public Interface Compatibility: ImportCollection Class</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using NUnit.Framework;
using Microsoft.Build;
using Microsoft.Build.BuildEngine;
using Microsoft.Build.Framework;
using Microsoft.Build.UnitTests;
namespace Microsoft.Build.UnitTests.OM.OrcasCompatibility
{
/// <summary>
/// Fixture Class for the v9 OM Public Interface Compatibility Tests. Import Class.
/// Also see Toolset tests in the Project test class.
/// </summary>
[TestFixture]
public class ImportCollection_Tests : AddNewImportTests
{
/// <summary>
/// Set the indirection for AddNewImport Tests
/// </summary>
public ImportCollection_Tests()
{
InvokeAddNewImportMethod = new AddNewImportDelegate(AddNewImportOverload);
}
/// <summary>
/// Count Test. Increment Count on Import Add
/// </summary>
[Test]
public void Count_IncrementOnAdd()
{
string importPath = String.Empty;
try
{
importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.Content3SimpleTargetsDefaultSpecified);
Project p = new Project();
Assertion.AssertEquals(0, p.Imports.Count);
p.Imports.AddNewImport(importPath, "true");
Assertion.AssertEquals(0, p.Imports.Count);
object o = p.EvaluatedItems;
Assertion.AssertEquals(1, p.Imports.Count);
}
finally
{
CompatibilityTestHelpers.RemoveFile(importPath);
}
}
/// <summary>
/// Count Test. Decrement\Reset Count to 0 on clear import list.
/// </summary>
[Test]
public void Count_DecrementOnRemove()
{
string importPath = String.Empty;
try
{
importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.Content3SimpleTargetsDefaultSpecified);
Project p = new Project();
p.Imports.AddNewImport(importPath, "true");
object o = p.EvaluatedItems;
Assertion.AssertEquals(1, p.Imports.Count);
p.Imports.RemoveImport(CompatibilityTestHelpers.FindFirstMatchingImportByPath(p.Imports, importPath));
Assertion.AssertEquals(0, p.Imports.Count);
}
finally
{
CompatibilityTestHelpers.RemoveFile(importPath);
}
}
/// <summary>
/// CopyTo Test, copy into array at index zero
/// </summary>
[Test]
public void CopyToStrong_IndexZero()
{
string importPath = String.Empty;
try
{
importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.Content3SimpleTargetsDefaultSpecified);
Project p = new Project();
p.Imports.AddNewImport(importPath, "true");
object o = p.EvaluatedItems;
Import import = CompatibilityTestHelpers.FindFirstMatchingImportByPath(p.Imports, importPath);
Import[] importArray = new Import[p.Imports.Count];
p.Imports.CopyTo(importArray, 0);
Assertion.AssertEquals(p.Imports.Count, importArray.Length);
Assertion.AssertEquals(0, Array.IndexOf(importArray, import));
Assertion.AssertEquals(true, object.ReferenceEquals(importArray[Array.IndexOf(importArray, import)], import));
}
finally
{
CompatibilityTestHelpers.RemoveFile(importPath);
}
}
/// <summary>
/// CopyTo Test, copy into array at an offset Index
/// </summary>
[Test]
public void CopyToStrong_OffsetIndex()
{
string importPath = String.Empty;
try
{
const int OffsetIndex = 2;
importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.Content3SimpleTargetsDefaultSpecified);
Project p = new Project();
p.Imports.AddNewImport(importPath, "true");
object o = p.EvaluatedItems;
Import import = CompatibilityTestHelpers.FindFirstMatchingImportByPath(p.Imports, importPath);
Import[] importArray = new Import[p.Imports.Count + OffsetIndex];
p.Imports.CopyTo(importArray, OffsetIndex);
Assertion.AssertEquals(p.Imports.Count, importArray.Length - OffsetIndex);
Assertion.AssertNull(importArray[OffsetIndex - 1]);
Assertion.AssertEquals(true, 0 < Array.IndexOf(importArray, import));
}
finally
{
CompatibilityTestHelpers.RemoveFile(importPath);
}
}
/// <summary>
/// CopyTo Test, copy into array that is initialized too small to contain all imports
/// </summary>
[Test]
[ExpectedException(typeof(OverflowException))]
public void CopyToStrong_ArrayTooSmallImportsNotEvaludated()
{
string importPath = String.Empty;
try
{
importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.Content3SimpleTargetsDefaultSpecified);
Project p = new Project();
p.Imports.AddNewImport(importPath, "true");
p.Imports.CopyTo(new Toolset[p.Imports.Count - 1], 0);
}
finally
{
CompatibilityTestHelpers.RemoveFile(importPath);
}
}
/// <summary>
/// CopyTo Test, copy into array that is initialized too small to contain all imports
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void CopyToStrong_ArrayTooSmall()
{
string importPath = String.Empty;
try
{
importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.Content3SimpleTargetsDefaultSpecified);
Project p = new Project();
p.Imports.AddNewImport(importPath, "true");
object o = p.EvaluatedItems;
p.Imports.CopyTo(new Toolset[p.Imports.Count - 1], 0);
}
finally
{
CompatibilityTestHelpers.RemoveFile(importPath);
}
}
/// <summary>
/// CopyTo Test, weak array, cast and narrow the return to import type
/// </summary>
[Test]
public void CopyToWeak_CastNarrowReturns()
{
string importPath = String.Empty;
try
{
importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.Content3SimpleTargetsDefaultSpecified);
Project p = new Project();
p.Imports.AddNewImport(importPath, "true");
object o = p.EvaluatedItems;
Import import = CompatibilityTestHelpers.FindFirstMatchingImportByPath(p.Imports, importPath);
Import[] importArray = new Import[p.Imports.Count];
p.Imports.CopyTo(importArray, 0);
Assertion.AssertEquals(p.Imports.Count, importArray.Length);
Assertion.AssertEquals(0, Array.IndexOf(importArray, import));
Assertion.AssertEquals(true, object.ReferenceEquals(importArray[Array.IndexOf(importArray, import)], import));
}
finally
{
CompatibilityTestHelpers.RemoveFile(importPath);
}
}
/// <summary>
/// CopyTo Test, store the return in weakly typed array
/// </summary>
[Test]
public void CopyToWeak_Simple()
{
string importPath = String.Empty;
try
{
importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.Content3SimpleTargetsDefaultSpecified);
Project p = new Project(new Engine());
p.Imports.AddNewImport(importPath, "true");
object o = p.EvaluatedItems;
Import import = CompatibilityTestHelpers.FindFirstMatchingImportByPath(p.Imports, importPath);
Array importArray = Array.CreateInstance(typeof(Import), p.Imports.Count);
p.Imports.CopyTo(importArray, 0);
Assertion.AssertEquals(p.Imports.Count, importArray.Length);
Assertion.AssertEquals(0, Array.IndexOf(importArray, import));
}
finally
{
CompatibilityTestHelpers.RemoveFile(importPath);
}
}
/// <summary>
/// RemoveImport Test, null
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void RemoveImport_Null()
{
Project p = new Project(new Engine());
p.Imports.RemoveImport(null);
}
/// <summary>
/// RemoveImport Test, remove a import that belongs to a differnet project
/// </summary>
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void RemoveImport_Empty()
{
string importPath = String.Empty;
try
{
importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.Content3SimpleTargetsDefaultSpecified);
Project p = new Project();
Project p2 = new Project();
p.Imports.AddNewImport(importPath, "true");
p2.Imports.AddNewImport(importPath, "true");
object o = p.EvaluatedItems;
o = p2.EvaluatedItems;
Import import2 = CompatibilityTestHelpers.FindFirstMatchingImportByPath(p2.Imports, importPath);
p.Imports.RemoveImport(import2); // does not exist in this project
}
finally
{
CompatibilityTestHelpers.RemoveFile(importPath);
}
}
/// <summary>
/// RemoveImport Test, remove a import and check dirty
/// </summary>
[Test]
public void RemoveImport_SimpleDirtyAfterRemove()
{
string importPath = String.Empty;
string projectPath = String.Empty;
try
{
importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.Content3SimpleTargetsDefaultSpecified);
projectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("project.proj", TestData.Content3SimpleTargetsDefaultSpecified);
Project p = new Project();
p.Imports.AddNewImport(importPath, "true");
object o = p.EvaluatedItems;
Import import = CompatibilityTestHelpers.FindFirstMatchingImportByPath(p.Imports, importPath);
p.Save(projectPath);
Assertion.AssertEquals(false, p.IsDirty);
p.Imports.RemoveImport(import);
Assertion.AssertNull(CompatibilityTestHelpers.FindFirstMatchingImportByPath(p.Imports, importPath));
Assertion.AssertEquals(true, p.IsDirty);
}
finally
{
CompatibilityTestHelpers.RemoveFile(importPath);
CompatibilityTestHelpers.RemoveFile(projectPath);
}
}
/// <summary>
/// RemoveImport Test, try to remove an import that is not first order
/// </summary>
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void RemoveImport_ImportOfImport()
{
string project1 = String.Empty;
string importPathA = String.Empty;
string importPathB = String.Empty;
string importPathBFull = String.Empty;
try
{
project1 = ObjectModelHelpers.CreateFileInTempProjectDirectory("project.proj", TestData.ContentImportA);
importPathA = ObjectModelHelpers.CreateFileInTempProjectDirectory("importA.proj", TestData.ContentImportB);
importPathB = "importB.proj"; // as specified in TestData.ContentImportB xml
importPathBFull = ObjectModelHelpers.CreateFileInTempProjectDirectory(importPathB, TestData.ContentA);
Project p = new Project();
p.Load(project1);
object o = p.EvaluatedProperties;
Import import = CompatibilityTestHelpers.FindFirstMatchingImportByPath(p.Imports, importPathB);
p.Imports.RemoveImport(import);
}
finally
{
CompatibilityTestHelpers.RemoveFile(project1);
CompatibilityTestHelpers.RemoveFile(importPathA);
CompatibilityTestHelpers.RemoveFile(importPathBFull);
}
}
/// <summary>
/// Enumeration Test, manual iteration over ImportCollection using GetEnumerator();
/// </summary>
[Test]
public void GetEnumerator()
{
string importPath = String.Empty;
string importPath2 = String.Empty;
try
{
importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.Content3SimpleTargetsDefaultSpecified);
importPath2 = ObjectModelHelpers.CreateFileInTempProjectDirectory("import2.proj", TestData.Content3SimpleTargetsDefaultSpecified);
Project p = new Project();
p.Imports.AddNewImport(importPath, "true");
p.Imports.AddNewImport(importPath2, "true");
object o = p.EvaluatedItems;
Import[] importArray = new Import[p.Imports.Count];
p.Imports.CopyTo(importArray, 0);
System.Collections.IEnumerator importEnum = p.Imports.GetEnumerator();
int enumerationCounter = 0;
while (importEnum.MoveNext())
{
Assertion.AssertEquals(true, object.ReferenceEquals(importArray[enumerationCounter], importEnum.Current));
Assertion.AssertEquals(importArray[enumerationCounter].ProjectPath, ((Import)importEnum.Current).ProjectPath);
enumerationCounter++;
}
}
finally
{
CompatibilityTestHelpers.RemoveFile(importPath);
CompatibilityTestHelpers.RemoveFile(importPath2);
}
}
/// <summary>
/// SyncRoot Test, Take a lock on SyncRoot then iterate over it.
/// </summary>
[Test]
public void SyncRoot()
{
string importPath = String.Empty;
string importPath2 = String.Empty;
try
{
importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.Content3SimpleTargetsDefaultSpecified);
importPath2 = ObjectModelHelpers.CreateFileInTempProjectDirectory("import2.proj", TestData.Content3SimpleTargetsDefaultSpecified);
Project p = new Project();
p.Imports.AddNewImport(importPath, "true");
p.Imports.AddNewImport(importPath2, "true");
object o = p.EvaluatedItems;
Import[] importArray = new Import[p.Imports.Count];
p.Imports.CopyTo(importArray, 0);
lock (p.Imports.SyncRoot)
{
int i = 0;
foreach (Import import in p.Imports)
{
Assertion.AssertEquals(importArray[i].ProjectPath, import.ProjectPath);
i++;
}
}
}
finally
{
CompatibilityTestHelpers.RemoveFile(importPath);
CompatibilityTestHelpers.RemoveFile(importPath2);
}
}
/// <summary>
/// isSynchronized, is false : returned collection is not threadsafe.
/// </summary>
[Test]
public void IsSynchronized()
{
string importPath = String.Empty;
try
{
importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.Content3SimpleTargetsDefaultSpecified);
Project p = new Project();
p.Imports.AddNewImport(importPath, "true");
object o = p.EvaluatedItems;
Assertion.AssertEquals(false, p.Imports.IsSynchronized);
}
finally
{
CompatibilityTestHelpers.RemoveFile(importPath);
}
}
/// <summary>
/// Indirection for common tests to p.AddNewImport
/// </summary>
private void AddNewImportOverload(Project p, string path, string condition)
{
p.Imports.AddNewImport(path, condition);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Spark.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using Avalonia.Data;
using Xunit;
namespace Avalonia.Base.UnitTests
{
public class AvaloniaObjectTests_SetValue
{
[Fact]
public void ClearValue_Clears_Value()
{
Class1 target = new Class1();
target.SetValue(Class1.FooProperty, "newvalue");
target.ClearValue(Class1.FooProperty);
Assert.Equal("foodefault", target.GetValue(Class1.FooProperty));
}
[Fact]
public void ClearValue_Raises_PropertyChanged()
{
Class1 target = new Class1();
var raised = 0;
target.SetValue(Class1.FooProperty, "newvalue");
target.PropertyChanged += (s, e) =>
{
Assert.Same(target, s);
Assert.Equal(BindingPriority.Unset, e.Priority);
Assert.Equal(Class1.FooProperty, e.Property);
Assert.Equal("newvalue", (string)e.OldValue);
Assert.Equal("foodefault", (string)e.NewValue);
++raised;
};
target.ClearValue(Class1.FooProperty);
Assert.Equal(1, raised);
}
[Fact]
public void IsSet_Returns_False_For_Unset_Property()
{
var target = new Class1();
Assert.False(target.IsSet(Class1.FooProperty));
}
[Fact]
public void IsSet_Returns_False_For_Set_Property()
{
var target = new Class1();
target.SetValue(Class1.FooProperty, "foo");
Assert.True(target.IsSet(Class1.FooProperty));
}
[Fact]
public void IsSet_Returns_False_For_Cleared_Property()
{
var target = new Class1();
target.SetValue(Class1.FooProperty, "foo");
target.SetValue(Class1.FooProperty, AvaloniaProperty.UnsetValue);
Assert.False(target.IsSet(Class1.FooProperty));
}
[Fact]
public void SetValue_Sets_Value()
{
Class1 target = new Class1();
target.SetValue(Class1.FooProperty, "newvalue");
Assert.Equal("newvalue", target.GetValue(Class1.FooProperty));
}
[Fact]
public void SetValue_Sets_Attached_Value()
{
Class2 target = new Class2();
target.SetValue(AttachedOwner.AttachedProperty, "newvalue");
Assert.Equal("newvalue", target.GetValue(AttachedOwner.AttachedProperty));
}
[Fact]
public void SetValue_Raises_PropertyChanged()
{
Class1 target = new Class1();
bool raised = false;
target.PropertyChanged += (s, e) =>
{
raised = s == target &&
e.Property == Class1.FooProperty &&
(string)e.OldValue == "foodefault" &&
(string)e.NewValue == "newvalue";
};
target.SetValue(Class1.FooProperty, "newvalue");
Assert.True(raised);
}
[Fact]
public void SetValue_Style_Priority_Raises_PropertyChanged()
{
Class1 target = new Class1();
bool raised = false;
target.PropertyChanged += (s, e) =>
{
raised = s == target &&
e.Property == Class1.FooProperty &&
(string)e.OldValue == "foodefault" &&
(string)e.NewValue == "newvalue";
};
target.SetValue(Class1.FooProperty, "newvalue", BindingPriority.Style);
Assert.True(raised);
}
[Fact]
public void SetValue_Doesnt_Raise_PropertyChanged_If_Value_Not_Changed()
{
Class1 target = new Class1();
bool raised = false;
target.SetValue(Class1.FooProperty, "bar");
target.PropertyChanged += (s, e) =>
{
raised = true;
};
target.SetValue(Class1.FooProperty, "bar");
Assert.False(raised);
}
[Fact]
public void SetValue_Doesnt_Raise_PropertyChanged_If_Value_Not_Changed_From_Default()
{
Class1 target = new Class1();
bool raised = false;
target.PropertyChanged += (s, e) =>
{
raised = true;
};
target.SetValue(Class1.FooProperty, "foodefault");
Assert.False(raised);
}
[Fact]
public void SetValue_Allows_Setting_Unregistered_Property()
{
Class1 target = new Class1();
Assert.False(AvaloniaPropertyRegistry.Instance.IsRegistered(target, Class2.BarProperty));
target.SetValue(Class2.BarProperty, "bar");
Assert.Equal("bar", target.GetValue(Class2.BarProperty));
}
[Fact]
public void SetValue_Allows_Setting_Unregistered_Attached_Property()
{
Class1 target = new Class1();
Assert.False(AvaloniaPropertyRegistry.Instance.IsRegistered(target, AttachedOwner.AttachedProperty));
target.SetValue(AttachedOwner.AttachedProperty, "bar");
Assert.Equal("bar", target.GetValue(AttachedOwner.AttachedProperty));
}
[Fact]
public void SetValue_Throws_Exception_For_Invalid_Value_Type()
{
Class1 target = new Class1();
Assert.Throws<ArgumentException>(() =>
{
target.SetValue(Class1.FooProperty, 123);
});
}
[Fact]
public void SetValue_Of_Integer_On_Double_Property_Works()
{
Class2 target = new Class2();
target.SetValue((AvaloniaProperty)Class2.FlobProperty, 4);
var value = target.GetValue(Class2.FlobProperty);
Assert.IsType<double>(value);
Assert.Equal(4, value);
}
[Fact]
public void SetValue_Respects_Implicit_Conversions()
{
Class2 target = new Class2();
target.SetValue((AvaloniaProperty)Class2.FlobProperty, new ImplictDouble(4));
var value = target.GetValue(Class2.FlobProperty);
Assert.IsType<double>(value);
Assert.Equal(4, value);
}
[Fact]
public void SetValue_Can_Convert_To_Nullable()
{
Class2 target = new Class2();
target.SetValue((AvaloniaProperty)Class2.FredProperty, 4.0);
var value = target.GetValue(Class2.FredProperty);
Assert.IsType<double>(value);
Assert.Equal(4, value);
}
[Fact]
public void SetValue_Respects_Priority()
{
Class1 target = new Class1();
target.SetValue(Class1.FooProperty, "one", BindingPriority.TemplatedParent);
Assert.Equal("one", target.GetValue(Class1.FooProperty));
target.SetValue(Class1.FooProperty, "two", BindingPriority.Style);
Assert.Equal("one", target.GetValue(Class1.FooProperty));
target.SetValue(Class1.FooProperty, "three", BindingPriority.StyleTrigger);
Assert.Equal("three", target.GetValue(Class1.FooProperty));
}
[Fact]
public void SetValue_Style_Doesnt_Override_LocalValue()
{
Class1 target = new Class1();
target.SetValue(Class1.FooProperty, "one", BindingPriority.LocalValue);
Assert.Equal("one", target.GetValue(Class1.FooProperty));
target.SetValue(Class1.FooProperty, "two", BindingPriority.Style);
Assert.Equal("one", target.GetValue(Class1.FooProperty));
}
[Fact]
public void SetValue_LocalValue_Overrides_Style()
{
Class1 target = new Class1();
target.SetValue(Class1.FooProperty, "one", BindingPriority.Style);
Assert.Equal("one", target.GetValue(Class1.FooProperty));
target.SetValue(Class1.FooProperty, "two", BindingPriority.LocalValue);
Assert.Equal("two", target.GetValue(Class1.FooProperty));
}
[Fact]
public void SetValue_Animation_Overrides_LocalValue()
{
Class1 target = new Class1();
target.SetValue(Class1.FooProperty, "one", BindingPriority.LocalValue);
Assert.Equal("one", target.GetValue(Class1.FooProperty));
target.SetValue(Class1.FooProperty, "two", BindingPriority.Animation);
Assert.Equal("two", target.GetValue(Class1.FooProperty));
}
[Fact]
public void Setting_UnsetValue_Reverts_To_Default_Value()
{
Class1 target = new Class1();
target.SetValue(Class1.FooProperty, "newvalue");
target.SetValue(Class1.FooProperty, AvaloniaProperty.UnsetValue);
Assert.Equal("foodefault", target.GetValue(Class1.FooProperty));
}
[Fact]
public void Setting_Object_Property_To_UnsetValue_Reverts_To_Default_Value()
{
Class1 target = new Class1();
target.SetValue(Class1.FrankProperty, "newvalue");
target.SetValue(Class1.FrankProperty, AvaloniaProperty.UnsetValue);
Assert.Equal("Kups", target.GetValue(Class1.FrankProperty));
}
[Fact]
public void Setting_Object_Property_To_DoNothing_Does_Nothing()
{
Class1 target = new Class1();
target.SetValue(Class1.FrankProperty, "newvalue");
target.SetValue(Class1.FrankProperty, BindingOperations.DoNothing);
Assert.Equal("newvalue", target.GetValue(Class1.FrankProperty));
}
[Fact]
public void Disposing_Style_SetValue_Reverts_To_DefaultValue()
{
Class1 target = new Class1();
var d = target.SetValue(Class1.FooProperty, "foo", BindingPriority.Style);
d.Dispose();
Assert.Equal("foodefault", target.GetValue(Class1.FooProperty));
}
[Fact]
public void Disposing_Style_SetValue_Reverts_To_Previous_Style_Value()
{
Class1 target = new Class1();
target.SetValue(Class1.FooProperty, "foo", BindingPriority.Style);
var d = target.SetValue(Class1.FooProperty, "bar", BindingPriority.Style);
d.Dispose();
Assert.Equal("foo", target.GetValue(Class1.FooProperty));
}
[Fact]
public void Disposing_Animation_SetValue_Reverts_To_Previous_Local_Value()
{
Class1 target = new Class1();
target.SetValue(Class1.FooProperty, "foo", BindingPriority.LocalValue);
var d = target.SetValue(Class1.FooProperty, "bar", BindingPriority.Animation);
d.Dispose();
Assert.Equal("foo", target.GetValue(Class1.FooProperty));
}
private class Class1 : AvaloniaObject
{
public static readonly StyledProperty<string> FooProperty =
AvaloniaProperty.Register<Class1, string>("Foo", "foodefault");
public static readonly StyledProperty<object> FrankProperty =
AvaloniaProperty.Register<Class1, object>("Frank", "Kups");
}
private class Class2 : Class1
{
public static readonly StyledProperty<string> BarProperty =
AvaloniaProperty.Register<Class2, string>("Bar", "bardefault");
public static readonly StyledProperty<double> FlobProperty =
AvaloniaProperty.Register<Class2, double>("Flob");
public static readonly StyledProperty<double?> FredProperty =
AvaloniaProperty.Register<Class2, double?>("Fred");
public Class1 Parent
{
get { return (Class1)InheritanceParent; }
set { InheritanceParent = value; }
}
}
private class AttachedOwner
{
public static readonly AttachedProperty<string> AttachedProperty =
AvaloniaProperty.RegisterAttached<AttachedOwner, Class2, string>("Attached");
}
private class ImplictDouble
{
public ImplictDouble(double value)
{
Value = value;
}
public double Value { get; }
public static implicit operator double (ImplictDouble v)
{
return v.Value;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Insights
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Composite Swagger for Insights Management Client
/// </summary>
public partial class InsightsManagementClient : Microsoft.Rest.ServiceClient<InsightsManagementClient>, IInsightsManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// The Azure subscription Id.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IAutoscaleSettingsOperations.
/// </summary>
public virtual IAutoscaleSettingsOperations AutoscaleSettings { get; private set; }
/// <summary>
/// Gets the IServiceDiagnosticSettingsOperations.
/// </summary>
public virtual IServiceDiagnosticSettingsOperations ServiceDiagnosticSettings { get; private set; }
/// <summary>
/// Gets the IAlertRulesOperations.
/// </summary>
public virtual IAlertRulesOperations AlertRules { get; private set; }
/// <summary>
/// Gets the IAlertRuleIncidentsOperations.
/// </summary>
public virtual IAlertRuleIncidentsOperations AlertRuleIncidents { get; private set; }
/// <summary>
/// Gets the ILogProfilesOperations.
/// </summary>
public virtual ILogProfilesOperations LogProfiles { get; private set; }
/// <summary>
/// Initializes a new instance of the InsightsManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected InsightsManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the InsightsManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected InsightsManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the InsightsManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected InsightsManagementClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the InsightsManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected InsightsManagementClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the InsightsManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public InsightsManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the InsightsManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public InsightsManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the InsightsManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public InsightsManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the InsightsManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public InsightsManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.AutoscaleSettings = new AutoscaleSettingsOperations(this);
this.ServiceDiagnosticSettings = new ServiceDiagnosticSettingsOperations(this);
this.AlertRules = new AlertRulesOperations(this);
this.AlertRuleIncidents = new AlertRuleIncidentsOperations(this);
this.LogProfiles = new LogProfilesOperations(this);
this.BaseUri = new System.Uri("https://management.azure.com");
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter());
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new Microsoft.Rest.Serialization.PolymorphicSerializeJsonConverter<RuleCondition>("odata.type"));
DeserializationSettings.Converters.Add(new Microsoft.Rest.Serialization.PolymorphicDeserializeJsonConverter<RuleCondition>("odata.type"));
SerializationSettings.Converters.Add(new Microsoft.Rest.Serialization.PolymorphicSerializeJsonConverter<RuleDataSource>("odata.type"));
DeserializationSettings.Converters.Add(new Microsoft.Rest.Serialization.PolymorphicDeserializeJsonConverter<RuleDataSource>("odata.type"));
SerializationSettings.Converters.Add(new Microsoft.Rest.Serialization.PolymorphicSerializeJsonConverter<RuleAction>("odata.type"));
DeserializationSettings.Converters.Add(new Microsoft.Rest.Serialization.PolymorphicDeserializeJsonConverter<RuleAction>("odata.type"));
CustomInitialize();
DeserializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter());
DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter());
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Testing.Algo
File: EmulationMessageAdapter.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.Testing
{
using System;
using System.Collections.Generic;
using System.Linq;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;
using StockSharp.Algo.Positions;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
using StockSharp.Algo.Storages;
/// <summary>
/// The interface of the real time market data adapter.
/// </summary>
public interface IEmulationMessageAdapter : IMessageAdapterWrapper
{
}
/// <summary>
/// Emulation message adapter.
/// </summary>
public class EmulationMessageAdapter : MessageAdapterWrapper, IEmulationMessageAdapter
{
private readonly SynchronizedSet<long> _subscriptionIds = new();
private readonly SynchronizedSet<long> _emuOrderIds = new();
private readonly IMessageAdapter _inAdapter;
private readonly bool _isEmulationOnly;
/// <summary>
/// Initialize <see cref="EmulationMessageAdapter"/>.
/// </summary>
/// <param name="innerAdapter">Underlying adapter.</param>
/// <param name="inChannel">Incoming messages channel.</param>
/// <param name="isEmulationOnly">Send <see cref="TimeMessage"/> to emulator.</param>
/// <param name="securityProvider">The provider of information about instruments.</param>
/// <param name="portfolioProvider">The portfolio to be used to register orders. If value is not given, the portfolio with default name Simulator will be created.</param>
/// <param name="exchangeInfoProvider">Exchanges and trading boards provider.</param>
public EmulationMessageAdapter(IMessageAdapter innerAdapter, IMessageChannel inChannel, bool isEmulationOnly, ISecurityProvider securityProvider, IPortfolioProvider portfolioProvider, IExchangeInfoProvider exchangeInfoProvider)
: base(innerAdapter)
{
Emulator = new MarketEmulator(securityProvider, portfolioProvider, exchangeInfoProvider, TransactionIdGenerator)
{
Parent = this,
Settings =
{
ConvertTime = true,
InitialOrderId = DateTime.Now.Ticks,
InitialTradeId = DateTime.Now.Ticks,
}
};
InChannel = inChannel;
_inAdapter = new SubscriptionOnlineMessageAdapter(Emulator);
_inAdapter = new PositionMessageAdapter(_inAdapter, new StrategyPositionManager(Emulator.IsPositionsEmulationRequired ?? true));
_inAdapter = new ChannelMessageAdapter(_inAdapter, inChannel, new PassThroughMessageChannel());
_inAdapter.NewOutMessage += RaiseNewOutMessage;
_isEmulationOnly = isEmulationOnly;
}
/// <inheritdoc />
public override void Dispose()
{
_inAdapter.NewOutMessage -= RaiseNewOutMessage;
base.Dispose();
}
/// <summary>
/// Emulator.
/// </summary>
public IMarketEmulator Emulator { get; }
/// <summary>
/// Settings of exchange emulator.
/// </summary>
public MarketEmulatorSettings Settings => Emulator.Settings;
/// <summary>
/// Incoming messages channel.
/// </summary>
public IMessageChannel InChannel { get; }
/// <inheritdoc />
public override IEnumerable<MessageTypes> SupportedInMessages => InnerAdapter.SupportedInMessages.Concat(Emulator.SupportedInMessages).Distinct().ToArray();
/// <inheritdoc />
public override IEnumerable<MessageTypes> SupportedOutMessages => InnerAdapter.SupportedOutMessages.Concat(Emulator.SupportedOutMessages).Distinct().ToArray();
/// <inheritdoc />
public override bool? IsPositionsEmulationRequired => Emulator.IsPositionsEmulationRequired;
/// <inheritdoc />
public override bool IsSupportTransactionLog => Emulator.IsSupportTransactionLog;
private void SendToEmulator(Message message)
{
_inAdapter.SendInMessage(message);
}
/// <inheritdoc />
protected override bool OnSendInMessage(Message message)
{
switch (message.Type)
{
case MessageTypes.OrderRegister:
{
var regMsg = (OrderRegisterMessage)message;
ProcessOrderMessage(regMsg.PortfolioName, regMsg);
return true;
}
case MessageTypes.OrderReplace:
case MessageTypes.OrderCancel:
{
ProcessOrderMessage(((OrderMessage)message).OriginalTransactionId, message);
return true;
}
case MessageTypes.OrderPairReplace:
{
var ordMsg = (OrderPairReplaceMessage)message;
ProcessOrderMessage(ordMsg.Message1.OriginalTransactionId, message);
return true;
}
case MessageTypes.OrderGroupCancel:
{
SendToEmulator(message);
return true;
}
case MessageTypes.Reset:
case MessageTypes.Connect:
case MessageTypes.Disconnect:
{
SendToEmulator(message);
if (message.Type == MessageTypes.Reset)
{
_subscriptionIds.Clear();
_emuOrderIds.Clear();
}
if (OwnInnerAdapter)
return base.OnSendInMessage(message);
else
return true;
}
case MessageTypes.PortfolioLookup:
case MessageTypes.Portfolio:
case MessageTypes.OrderStatus:
{
if (OwnInnerAdapter)
base.OnSendInMessage(message);
SendToEmulator(message);
return true;
}
case MessageTypes.SecurityLookup:
case MessageTypes.TimeFrameLookup:
case MessageTypes.BoardLookup:
case MessageTypes.MarketData:
{
_subscriptionIds.Add(((ISubscriptionMessage)message).TransactionId);
// sends to emu for init subscription ids
SendToEmulator(message);
return base.OnSendInMessage(message);
}
case MessageTypes.Level1Change:
case ExtendedMessageTypes.CommissionRule:
{
SendToEmulator(message);
return true;
}
default:
{
if (OwnInnerAdapter)
return base.OnSendInMessage(message);
return true;
}
}
}
/// <inheritdoc />
protected override void InnerAdapterNewOutMessage(Message message)
{
if (OwnInnerAdapter || !message.IsBack())
base.InnerAdapterNewOutMessage(message);
}
/// <inheritdoc />
protected override void OnInnerAdapterNewOutMessage(Message message)
{
if (message.IsBack())
{
if (OwnInnerAdapter)
base.OnInnerAdapterNewOutMessage(message);
return;
}
switch (message.Type)
{
case MessageTypes.Connect:
case MessageTypes.Disconnect:
case MessageTypes.Reset:
break;
case MessageTypes.SubscriptionResponse:
case MessageTypes.SubscriptionFinished:
case MessageTypes.SubscriptionOnline:
{
if (_subscriptionIds.Contains(((IOriginalTransactionIdMessage)message).OriginalTransactionId))
SendToEmulator(message);
break;
}
//case MessageTypes.BoardState:
case MessageTypes.Portfolio:
case MessageTypes.PositionChange:
{
if (OwnInnerAdapter)
base.OnInnerAdapterNewOutMessage(message);
break;
}
case MessageTypes.Execution:
{
var execMsg = (ExecutionMessage)message;
if (execMsg.IsMarketData())
TrySendToEmulator((ISubscriptionIdMessage)message);
else
{
if (OwnInnerAdapter)
base.OnInnerAdapterNewOutMessage(message);
}
break;
}
case MessageTypes.Security:
case MessageTypes.Board:
{
if (OwnInnerAdapter)
base.OnInnerAdapterNewOutMessage(message);
SendToEmulator(message);
//TrySendToEmulator((ISubscriptionIdMessage)message);
break;
}
case ExtendedMessageTypes.EmulationState:
SendToEmulator(message);
break;
case MessageTypes.Time:
{
if (OwnInnerAdapter)
{
if (_isEmulationOnly)
SendToEmulator(message);
else
base.OnInnerAdapterNewOutMessage(message);
}
break;
}
default:
{
if (message is ISubscriptionIdMessage subscrMsg)
TrySendToEmulator(subscrMsg);
else
{
if (OwnInnerAdapter)
base.OnInnerAdapterNewOutMessage(message);
}
break;
}
}
}
private void TrySendToEmulator(ISubscriptionIdMessage message)
{
foreach (var id in message.GetSubscriptionIds())
{
if (_subscriptionIds.Contains(id))
{
SendToEmulator((Message)message);
break;
}
}
}
private void ProcessOrderMessage(string portfolioName, OrderMessage message)
{
if (OwnInnerAdapter)
{
if (_isEmulationOnly || portfolioName.EqualsIgnoreCase(Extensions.SimulatorPortfolioName))
{
if (!_isEmulationOnly)
_emuOrderIds.Add(message.TransactionId);
SendToEmulator(message);
}
else
base.OnSendInMessage(message);
}
else
{
_emuOrderIds.Add(message.TransactionId);
SendToEmulator(message);
}
}
private void ProcessOrderMessage(long transId, Message message)
{
if (_isEmulationOnly || _emuOrderIds.Contains(transId))
SendToEmulator(message);
else
base.OnSendInMessage(message);
}
/// <inheritdoc />
public override void Save(SettingsStorage storage)
{
base.Save(storage);
storage.SetValue(nameof(MarketEmulator), Settings.Save());
}
/// <inheritdoc />
public override void Load(SettingsStorage storage)
{
base.Load(storage);
Settings.Load(storage.GetValue<SettingsStorage>(nameof(MarketEmulator)));
}
/// <summary>
/// Create a copy of <see cref="EmulationMessageAdapter"/>.
/// </summary>
/// <returns>Copy.</returns>
public override IMessageChannel Clone()
=> new EmulationMessageAdapter(InnerAdapter.TypedClone(), InChannel, _isEmulationOnly, Emulator.SecurityProvider, Emulator.PortfolioProvider, Emulator.ExchangeInfoProvider);
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Backend.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Logic
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <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="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.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="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.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="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.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="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.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="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.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="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.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>
/// Gets the integration account callback URL.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='parameters'>
/// The callback URL parameters.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<CallbackUrl>> GetCallbackUrlWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, GetCallbackUrlParameters parameters, 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="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.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="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.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));
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Asn1;
namespace X500 {
/*
* A DNPart instance encodes an X.500 name element: it has a type (an
* OID) and a value. The value is an ASN.1 object. If the name type is
* one of a list of standard types, then the value is a character
* string, and there is a "friendly type" which is a character string
* (such as "CN" for the "common name", of OID 2.5.4.3).
*/
public class DNPart {
/*
* These are the known "friendly types". The values decode as
* strings.
*/
public const string COMMON_NAME = "CN";
public const string LOCALITY = "L";
public const string STATE = "ST";
public const string ORGANIZATION = "O";
public const string ORGANIZATIONAL_UNIT = "OU";
public const string COUNTRY = "C";
public const string STREET = "STREET";
public const string DOMAIN_COMPONENT = "DC";
public const string USER_ID = "UID";
public const string EMAIL_ADDRESS = "EMAILADDRESS";
/*
* Get the type OID (decimal-dotted string representation).
*/
public string OID {
get {
return OID_;
}
}
string OID_;
/*
* Get the string value for this element. If the element value
* could not be decoded as a string, then this method returns
* null.
*
* (Decoding error for name elements of a standard type trigger
* exceptions upon instance creation. Thus, a null value is
* possible only for a name element that uses an unknown type.)
*/
public string Value {
get {
return Value_;
}
}
string Value_;
/*
* Tell whether this element is string based. This property
* returns true if and only if Value returns a non-null value.
*/
public bool IsString {
get {
return Value_ != null;
}
}
/*
* Get the element value as an ASN.1 structure.
*/
public AsnElt AsnValue {
get {
return AsnValue_;
}
}
AsnElt AsnValue_;
/*
* Get the "friendly type" for this element. This is the
* string mnemonic such as "CN" for "common name". If no
* friendly type is known for that element, then the OID
* is returned (decimal-dotted representation).
*/
public string FriendlyType {
get {
return GetFriendlyType(OID);
}
}
/*
* "Normalized" string value (converted to uppercase then
* lowercase, leading and trailing whitespace trimmed, adjacent
* spaces coalesced). This should allow for efficient comparison
* while still supporting most corner cases.
*
* This does not implement full RFC 4518 rules, but it should
* be good enough for an analysis tool.
*/
string normValue;
byte[] encodedValue;
int hashCode;
internal DNPart(string oid, AsnElt val)
{
OID_ = oid;
AsnValue_ = val;
encodedValue = val.Encode();
uint hc = (uint)oid.GetHashCode();
try {
string s = val.GetString();
Value_ = s;
s = s.ToUpperInvariant().ToLowerInvariant();
StringBuilder sb = new StringBuilder();
bool lwws = true;
foreach (char c in s.Trim()) {
if (IsControl(c)) {
continue;
}
if (IsWS(c)) {
if (lwws) {
continue;
}
lwws = true;
sb.Append(' ');
} else {
sb.Append(c);
}
}
int n = sb.Length;
if (n > 0 && sb[n - 1] == ' ') {
sb.Length = n - 1;
}
normValue = sb.ToString();
hc += (uint)normValue.GetHashCode();
} catch {
if (OID_TO_FT.ContainsKey(oid)) {
throw;
}
Value_ = null;
foreach (byte b in encodedValue) {
hc = ((hc << 7) | (hc >> 25)) ^ (uint)b;
}
}
hashCode = (int)hc;
}
static bool MustEscape(int x)
{
if (x < 0x20 || x >= 0x7F) {
return true;
}
switch (x) {
case '"':
case '+':
case ',':
case ';':
case '<':
case '>':
case '\\':
return true;
default:
return false;
}
}
/*
* Convert this element to a string. This uses RFC 4514 rules.
*/
public override string ToString()
{
StringBuilder sb = new StringBuilder();
string ft;
if (OID_TO_FT.TryGetValue(OID, out ft) && IsString) {
sb.Append(ft);
sb.Append("=");
byte[] buf = Encoding.UTF8.GetBytes(Value);
for (int i = 0; i < buf.Length; i ++) {
byte b = buf[i];
if ((i == 0 && (b == ' ' || b == '#'))
|| (i == buf.Length - 1 && b == ' ')
|| MustEscape(b))
{
switch ((char)b) {
case ' ':
case '"':
case '#':
case '+':
case ',':
case ';':
case '<':
case '=':
case '>':
case '\\':
sb.Append('\\');
sb.Append((char)b);
break;
default:
sb.AppendFormat("\\{0:X2}", b);
break;
}
} else {
sb.Append((char)b);
}
}
} else {
sb.Append(OID);
sb.Append("=#");
foreach (byte b in AsnValue.Encode()) {
sb.AppendFormat("{0:X2}", b);
}
}
return sb.ToString();
}
/*
* Get the friendly type corresponding to the given OID
* (decimal-dotted representation). If no such type is known,
* then the OID string is returned.
*/
public static string GetFriendlyType(string oid)
{
string ft;
if (OID_TO_FT.TryGetValue(oid, out ft)) {
return ft;
}
return oid;
}
static int HexVal(char c)
{
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'A' && c <= 'F') {
return c - ('A' - 10);
} else if (c >= 'a' && c <= 'f') {
return c - ('a' - 10);
} else {
return -1;
}
}
static int HexValCheck(char c)
{
int x = HexVal(c);
if (x < 0) {
throw new AsnException(String.Format(
"Not an hex digit: U+{0:X4}", c));
}
return x;
}
static int HexVal2(string str, int k)
{
if (k >= str.Length) {
throw new AsnException("Missing hex digits");
}
int x = HexVal(str[k]);
if ((k + 1) >= str.Length) {
throw new AsnException("Odd number of hex digits");
}
return (x << 4) + HexVal(str[k + 1]);
}
static int ReadHexEscape(string str, ref int off)
{
if (off >= str.Length || str[off] != '\\') {
return -1;
}
if ((off + 1) >= str.Length) {
throw new AsnException("Truncated escape");
}
int x = HexVal(str[off + 1]);
if (x < 0) {
return -1;
}
if ((off + 2) >= str.Length) {
throw new AsnException("Truncated escape");
}
int y = HexValCheck(str[off + 2]);
off += 3;
return (x << 4) + y;
}
static int ReadHexUTF(string str, ref int off)
{
int x = ReadHexEscape(str, ref off);
if (x < 0x80 || x >= 0xC0) {
throw new AsnException(
"Invalid hex escape: not UTF-8");
}
return x;
}
static string UnEscapeUTF8(string str)
{
StringBuilder sb = new StringBuilder();
int n = str.Length;
int k = 0;
while (k < n) {
char c = str[k];
if (c != '\\') {
sb.Append(c);
k ++;
continue;
}
int x = ReadHexEscape(str, ref k);
if (x < 0) {
sb.Append(str[k + 1]);
k += 2;
continue;
}
if (x < 0x80) {
// nothing
} else if (x < 0xC0) {
throw new AsnException(
"Invalid hex escape: not UTF-8");
} else if (x < 0xE0) {
x &= 0x1F;
x = (x << 6) | ReadHexUTF(str, ref k) & 0x3F;
} else if (x < 0xF0) {
x &= 0x0F;
x = (x << 6) | ReadHexUTF(str, ref k) & 0x3F;
x = (x << 6) | ReadHexUTF(str, ref k) & 0x3F;
} else if (x < 0xF8) {
x &= 0x07;
x = (x << 6) | ReadHexUTF(str, ref k) & 0x3F;
x = (x << 6) | ReadHexUTF(str, ref k) & 0x3F;
x = (x << 6) | ReadHexUTF(str, ref k) & 0x3F;
if (x > 0x10FFFF) {
throw new AsnException("Invalid"
+ " hex escape: out of range");
}
} else {
throw new AsnException(
"Invalid hex escape: not UTF-8");
}
if (x < 0x10000) {
sb.Append((char)x);
} else {
x -= 0x10000;
sb.Append((char)(0xD800 + (x >> 10)));
sb.Append((char)(0xDC00 + (x & 0x3FF)));
}
}
return sb.ToString();
}
internal static DNPart Parse(string str)
{
int j = str.IndexOf('=');
if (j < 0) {
throw new AsnException("Invalid DN: no '=' sign");
}
string a = str.Substring(0, j).Trim();
string b = str.Substring(j + 1).Trim();
string oid;
if (!FT_TO_OID.TryGetValue(a, out oid)) {
oid = AsnElt.MakeOID(oid).GetOID();
}
AsnElt aVal;
if (b.StartsWith("#")) {
MemoryStream ms = new MemoryStream();
int n = b.Length;
for (int k = 1; k < n; k += 2) {
int x = HexValCheck(b[k]);
if (k + 1 >= n) {
throw new AsnException(
"Odd number of hex digits");
}
x = (x << 4) + HexValCheck(b[k + 1]);
ms.WriteByte((byte)x);
}
try {
aVal = AsnElt.Decode(ms.ToArray());
} catch (Exception e) {
throw new AsnException("Bad DN value: "
+ e.Message);
}
} else {
b = UnEscapeUTF8(b);
int type = AsnElt.PrintableString;
foreach (char c in b) {
if (!AsnElt.IsPrintable(c)) {
type = AsnElt.UTF8String;
break;
}
}
aVal = AsnElt.MakeString(type, b);
}
return new DNPart(oid, aVal);
}
static Dictionary<string, string> OID_TO_FT;
static Dictionary<string, string> FT_TO_OID;
static void AddFT(string oid, string ft)
{
OID_TO_FT[oid] = ft;
FT_TO_OID[ft] = oid;
}
static DNPart()
{
OID_TO_FT = new Dictionary<string, string>();
FT_TO_OID = new Dictionary<string, string>(
StringComparer.OrdinalIgnoreCase);
AddFT("2.5.4.3", COMMON_NAME);
AddFT("2.5.4.7", LOCALITY);
AddFT("2.5.4.8", STATE);
AddFT("2.5.4.10", ORGANIZATION);
AddFT("2.5.4.11", ORGANIZATIONAL_UNIT);
AddFT("2.5.4.6", COUNTRY);
AddFT("2.5.4.9", STREET);
AddFT("0.9.2342.19200300.100.1.25", DOMAIN_COMPONENT);
AddFT("0.9.2342.19200300.100.1.1", USER_ID);
AddFT("1.2.840.113549.1.9.1", EMAIL_ADDRESS);
/*
* We also accept 'S' as an alias for 'ST' because some
* Microsoft software uses it.
*/
FT_TO_OID["S"] = FT_TO_OID["ST"];
}
/*
* Tell whether a given character is a "control character" (to
* be ignored for DN comparison purposes). This follows RFC 4518
* but only for code points in the first plane.
*/
static bool IsControl(char c)
{
if (c <= 0x0008
|| (c >= 0x000E && c <= 0x001F)
|| (c >= 0x007F && c <= 0x0084)
|| (c >= 0x0086 && c <= 0x009F)
|| c == 0x06DD
|| c == 0x070F
|| c == 0x180E
|| (c >= 0x200C && c <= 0x200F)
|| (c >= 0x202A && c <= 0x202E)
|| (c >= 0x2060 && c <= 0x2063)
|| (c >= 0x206A && c <= 0x206F)
|| c == 0xFEFF
|| (c >= 0xFFF9 && c <= 0xFFFB))
{
return true;
}
return false;
}
/*
* Tell whether a character is whitespace. This follows
* rules of RFC 4518.
*/
static bool IsWS(char c)
{
if (c == 0x0020
|| c == 0x00A0
|| c == 0x1680
|| (c >= 0x2000 && c <= 0x200A)
|| c == 0x2028
|| c == 0x2029
|| c == 0x202F
|| c == 0x205F
|| c == 0x3000)
{
return true;
}
return false;
}
public override bool Equals(object obj)
{
return Equals(obj as DNPart);
}
public bool Equals(DNPart dnp)
{
if (dnp == null) {
return false;
}
if (OID != dnp.OID) {
return false;
}
if (IsString) {
return dnp.IsString
&& normValue == dnp.normValue;
} else if (dnp.IsString) {
return false;
} else {
return Eq(encodedValue, dnp.encodedValue);
}
}
public override int GetHashCode()
{
return hashCode;
}
static bool Eq(byte[] a, byte[] b)
{
if (a == b) {
return true;
}
if (a == null || b == null) {
return false;
}
int n = a.Length;
if (n != b.Length) {
return false;
}
for (int i = 0; i < n; i ++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
}
}
| |
#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: SccStamp.cs 618 2009-05-30 00:18:30Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using Mannex;
#endregion
/// <summary>
/// Represents a source code control (SCC) stamp and its components.
/// </summary>
[ Serializable ]
public sealed class SccStamp
{
private readonly string _id;
private readonly string _author;
private readonly string _fileName;
private readonly int _revision;
private readonly DateTime _lastChanged;
private static readonly Regex _regex;
static SccStamp()
{
//
// Expression to help parse:
//
// STAMP := "$Id:" FILENAME REVISION DATE TIME "Z" USERNAME "$"
// DATE := 4-DIGIT-YEAR "-" 2-DIGIT-MONTH "-" 2-DIGIT-DAY
// TIME := HH ":" MM ":" SS
//
string escapedNonFileNameChars = Regex.Escape(new string(Path.GetInvalidFileNameChars()));
_regex = new Regex(
@"\$ id: \s*
(?<f>[^" + escapedNonFileNameChars + @"]+) \s+ # FILENAME
(?<r>[0-9]+) \s+ # REVISION
((?<y>[0-9]{4})-(?<mo>[0-9]{2})-(?<d>[0-9]{2})) \s+ # DATE
((?<h>[0-9]{2})\:(?<mi>[0-9]{2})\:(?<s>[0-9]{2})Z) \s+ # TIME (UTC)
(?<a>\w+) # AUTHOR",
RegexOptions.CultureInvariant
| RegexOptions.IgnoreCase
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Singleline
| RegexOptions.ExplicitCapture
| RegexOptions.Compiled);
}
/// <summary>
/// Initializes an <see cref="SccStamp"/> instance given a SCC stamp
/// ID. The ID is expected to be in the format popularized by CVS
/// and SVN.
/// </summary>
public SccStamp(string id)
{
if (id == null)
throw new ArgumentNullException("id");
if (id.Length == 0)
throw new ArgumentException(null, "id");
Match match = _regex.Match(id);
if (!match.Success)
throw new ArgumentException(null, "id");
_id = id;
GroupCollection groups = match.Groups;
_fileName = groups["f"].Value;
_revision = int.Parse(groups["r"].Value);
_author = groups["a"].Value;
int year = int.Parse(groups["y"].Value);
int month = int.Parse(groups["mo"].Value);
int day = int.Parse(groups["d"].Value);
int hour = int.Parse(groups["h"].Value);
int minute = int.Parse(groups["mi"].Value);
int second = int.Parse(groups["s"].Value);
_lastChanged = new DateTime(year, month, day, hour, minute, second).ToLocalTime();
}
/// <summary>
/// Gets the original SCC stamp ID.
/// </summary>
public string Id
{
get { return _id; }
}
/// <summary>
/// Gets the author component of the SCC stamp ID.
/// </summary>
public string Author
{
get { return _author; }
}
/// <summary>
/// Gets the file name component of the SCC stamp ID.
/// </summary>
public string FileName
{
get { return _fileName; }
}
/// <summary>
/// Gets the revision number component of the SCC stamp ID.
/// </summary>
public int Revision
{
get { return _revision; }
}
/// <summary>
/// Gets the last modification time component of the SCC stamp ID.
/// </summary>
public DateTime LastChanged
{
get { return _lastChanged; }
}
/// <summary>
/// Gets the last modification time, in coordinated universal time
/// (UTC), component of the SCC stamp ID in local time.
/// </summary>
public DateTime LastChangedUtc
{
get { return _lastChanged.ToUniversalTime(); }
}
public override string ToString()
{
return Id;
}
/// <summary>
/// Finds and builds an array of <see cref="SccStamp"/> instances
/// from all the <see cref="SccAttribute"/> attributes applied to
/// the given assembly.
/// </summary>
public static SccStamp[] FindAll(Assembly assembly)
{
if (assembly == null)
throw new ArgumentNullException("assembly");
SccAttribute[] attributes = (SccAttribute[]) Attribute.GetCustomAttributes(assembly, typeof(SccAttribute), false);
if (attributes.Length == 0)
return new SccStamp[0];
List<SccStamp> list = new List<SccStamp>(attributes.Length);
foreach (SccAttribute attribute in attributes)
{
string id = attribute.Id.Trim();
if (id.Length > 0 && string.Compare("$Id" + /* IMPORTANT! */ "$", id, true, CultureInfo.InvariantCulture) != 0)
list.Add(new SccStamp(id));
}
return list.ToArray();
}
/// <summary>
/// Finds the latest SCC stamp for an assembly. The latest stamp is
/// the one with the highest revision number.
/// </summary>
public static SccStamp FindLatest(Assembly assembly)
{
return FindLatest(FindAll(assembly));
}
/// <summary>
/// Finds the latest stamp among an array of <see cref="SccStamp"/>
/// objects. The latest stamp is the one with the highest revision
/// number.
/// </summary>
public static SccStamp FindLatest(SccStamp[] stamps)
{
if (stamps == null)
throw new ArgumentNullException("stamps");
if (stamps.Length == 0)
return null;
stamps = stamps.CloneObject();
SortByRevision(stamps, /* descending */ true);
return stamps[0];
}
/// <summary>
/// Sorts an array of <see cref="SccStamp"/> objects by their
/// revision numbers in ascending order.
/// </summary>
public static void SortByRevision(SccStamp[] stamps)
{
SortByRevision(stamps, false);
}
/// <summary>
/// Sorts an array of <see cref="SccStamp"/> objects by their
/// revision numbers in ascending or descending order.
/// </summary>
public static void SortByRevision(SccStamp[] stamps, bool descending)
{
Comparison<SccStamp> comparer = (lhs, rhs) => lhs.Revision.CompareTo(rhs.Revision);
Array.Sort(stamps, descending
? ((lhs, rhs) => -comparer(lhs, rhs))
: comparer);
}
}
}
| |
using System;
namespace EasyNetQ.Logging;
/// <summary>
/// Extension methods for the <see cref="ILogger"/> interface.
/// </summary>
public static class LoggerExtensions
{
private static readonly object[] EmptyParams = Array.Empty<object>();
/// <summary>
/// Check if the <see cref="LogLevel.Debug"/> log level is enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to check with.</param>
/// <returns>True if the log level is enabled; false otherwise.</returns>
public static bool IsDebugEnabled(this ILogger logger)
{
return logger.Log(LogLevel.Debug, null, null, EmptyParams);
}
/// <summary>
/// Check if the <see cref="LogLevel.Error"/> log level is enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to check with.</param>
/// <returns>True if the log level is enabled; false otherwise.</returns>
public static bool IsErrorEnabled(this ILogger logger)
{
return logger.Log(LogLevel.Error, null, null, EmptyParams);
}
/// <summary>
/// Check if the <see cref="LogLevel.Fatal"/> log level is enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to check with.</param>
/// <returns>True if the log level is enabled; false otherwise.</returns>
public static bool IsFatalEnabled(this ILogger logger)
{
return logger.Log(LogLevel.Fatal, null, null, EmptyParams);
}
/// <summary>
/// Check if the <see cref="LogLevel.Info"/> log level is enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to check with.</param>
/// <returns>True if the log level is enabled; false otherwise.</returns>
public static bool IsInfoEnabled(this ILogger logger)
{
return logger.Log(LogLevel.Info, null, null, EmptyParams);
}
/// <summary>
/// Check if the <see cref="LogLevel.Trace"/> log level is enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to check with.</param>
/// <returns>True if the log level is enabled; false otherwise.</returns>
public static bool IsTraceEnabled(this ILogger logger)
{
return logger.Log(LogLevel.Trace, null, null, EmptyParams);
}
/// <summary>
/// Check if the <see cref="LogLevel.Warn"/> log level is enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to check with.</param>
/// <returns>True if the log level is enabled; false otherwise.</returns>
public static bool IsWarnEnabled(this ILogger logger)
{
return logger.Log(LogLevel.Warn, null, null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Debug"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="messageFunc">The message function.</param>
public static void Debug(this ILogger logger, Func<string> messageFunc)
{
if (logger.IsDebugEnabled()) logger.Log(LogLevel.Debug, messageFunc, null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Debug"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
public static void Debug(this ILogger logger, string message)
{
if (logger.IsDebugEnabled()) logger.Log(LogLevel.Debug, message.AsFunc(), null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Debug"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Debug(this ILogger logger, string message, params object[] args)
{
logger.DebugFormat(message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Debug"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="exception">The exception.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Debug(this ILogger logger, Exception exception, string message, params object[] args)
{
logger.DebugException(message, exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Debug"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void DebugFormat(this ILogger logger, string message, params object[] args)
{
if (logger.IsDebugEnabled()) logger.LogFormat(LogLevel.Debug, message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Debug"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public static void DebugException(this ILogger logger, string message, Exception exception)
{
if (logger.IsDebugEnabled()) logger.Log(LogLevel.Debug, message.AsFunc(), exception, EmptyParams);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Debug"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void DebugException(
this ILogger logger, string message, Exception exception, params object[] args
)
{
if (logger.IsDebugEnabled()) logger.Log(LogLevel.Debug, message.AsFunc(), exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Error"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="messageFunc">The message function.</param>
public static void Error(this ILogger logger, Func<string> messageFunc)
{
if (logger.IsErrorEnabled()) logger.Log(LogLevel.Error, messageFunc, null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Error"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
public static void Error(this ILogger logger, string message)
{
if (logger.IsErrorEnabled()) logger.Log(LogLevel.Error, message.AsFunc(), null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Error"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Error(this ILogger logger, string message, params object[] args)
{
logger.ErrorFormat(message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Error"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="exception">The exception.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Error(this ILogger logger, Exception exception, string message, params object[] args)
{
logger.ErrorException(message, exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Error"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void ErrorFormat(this ILogger logger, string message, params object[] args)
{
if (logger.IsErrorEnabled()) logger.LogFormat(LogLevel.Error, message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Error"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void ErrorException(
this ILogger logger, string message, Exception exception, params object[] args
)
{
if (logger.IsErrorEnabled()) logger.Log(LogLevel.Error, message.AsFunc(), exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Fatal"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="messageFunc">The message function.</param>
public static void Fatal(this ILogger logger, Func<string> messageFunc)
{
if (logger.IsFatalEnabled()) logger.Log(LogLevel.Fatal, messageFunc, null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Fatal"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
public static void Fatal(this ILogger logger, string message)
{
if (logger.IsFatalEnabled()) logger.Log(LogLevel.Fatal, message.AsFunc(), null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Fatal"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Fatal(this ILogger logger, string message, params object[] args)
{
logger.FatalFormat(message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Fatal"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="exception">The exception.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Fatal(this ILogger logger, Exception exception, string message, params object[] args)
{
logger.FatalException(message, exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Fatal"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void FatalFormat(this ILogger logger, string message, params object[] args)
{
if (logger.IsFatalEnabled()) logger.LogFormat(LogLevel.Fatal, message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Fatal"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void FatalException(
this ILogger logger, string message, Exception exception, params object[] args
)
{
if (logger.IsFatalEnabled()) logger.Log(LogLevel.Fatal, message.AsFunc(), exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Info"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="messageFunc">The message function.</param>
public static void Info(this ILogger logger, Func<string> messageFunc)
{
if (logger.IsInfoEnabled()) logger.Log(LogLevel.Info, messageFunc, null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Info"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
public static void Info(this ILogger logger, string message)
{
if (logger.IsInfoEnabled()) logger.Log(LogLevel.Info, message.AsFunc(), null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Info"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Info(this ILogger logger, string message, params object[] args)
{
logger.InfoFormat(message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Info"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="exception">The exception.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Info(this ILogger logger, Exception exception, string message, params object[] args)
{
logger.InfoException(message, exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Info"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void InfoFormat(this ILogger logger, string message, params object[] args)
{
if (logger.IsInfoEnabled()) logger.LogFormat(LogLevel.Info, message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Info"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void InfoException(
this ILogger logger, string message, Exception exception, params object[] args
)
{
if (logger.IsInfoEnabled()) logger.Log(LogLevel.Info, message.AsFunc(), exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Trace"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="messageFunc">The message function.</param>
public static void Trace(this ILogger logger, Func<string> messageFunc)
{
if (logger.IsTraceEnabled()) logger.Log(LogLevel.Trace, messageFunc, null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Trace"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
public static void Trace(this ILogger logger, string message)
{
if (logger.IsTraceEnabled()) logger.Log(LogLevel.Trace, message.AsFunc(), null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Trace"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Trace(this ILogger logger, string message, params object[] args)
{
logger.TraceFormat(message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Trace"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="exception">The exception.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Trace(this ILogger logger, Exception exception, string message, params object[] args)
{
logger.TraceException(message, exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Trace"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void TraceFormat(this ILogger logger, string message, params object[] args)
{
if (logger.IsTraceEnabled()) logger.LogFormat(LogLevel.Trace, message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Trace"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void TraceException(
this ILogger logger, string message, Exception exception, params object[] args
)
{
if (logger.IsTraceEnabled()) logger.Log(LogLevel.Trace, message.AsFunc(), exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Warn"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="messageFunc">The message function.</param>
public static void Warn(this ILogger logger, Func<string> messageFunc)
{
if (logger.IsWarnEnabled()) logger.Log(LogLevel.Warn, messageFunc, null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Warn"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
public static void Warn(this ILogger logger, string message)
{
if (logger.IsWarnEnabled()) logger.Log(LogLevel.Warn, message.AsFunc(), null, EmptyParams);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Warn"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Warn(this ILogger logger, string message, params object[] args)
{
logger.WarnFormat(message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Warn"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="exception">The exception.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void Warn(this ILogger logger, Exception exception, string message, params object[] args)
{
logger.WarnException(message, exception, args);
}
/// <summary>
/// Logs a message at the <see cref="LogLevel.Warn"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void WarnFormat(this ILogger logger, string message, params object[] args)
{
if (logger.IsWarnEnabled()) logger.LogFormat(LogLevel.Warn, message, args);
}
/// <summary>
/// Logs an exception at the <see cref="LogLevel.Warn"/> log level, if enabled.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/> to use.</param>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
/// <param name="args">Optional format parameters for the message.</param>
public static void WarnException(
this ILogger logger, string message, Exception exception, params object[] args
)
{
if (logger.IsWarnEnabled()) logger.Log(LogLevel.Warn, message.AsFunc(), exception, args);
}
private static void LogFormat(this ILogger logger, LogLevel logLevel, string message, params object[] args)
{
logger.Log(logLevel, message.AsFunc(), null, args);
}
// Avoid the closure allocation, see https://gist.github.com/AArnott/d285feef75c18f6ecd2b
private static Func<T> AsFunc<T>(this T value) where T : class
{
return value.Return;
}
private static T Return<T>(this T value)
{
return value;
}
}
| |
/**
* \file NETGeographicLib\AlbersPanel.cs
* \brief Example of various projections.
*
* NETGeographicLib.AlbersEqualArea,
* NETGeographicLib.LambertConformalConic,
* NETGeographicLib.TransverseMercator,
* and NETGeographicLib.TransverseMercatorExact example
*
* NETGeographicLib is copyright (c) Scott Heiman (2013)
* GeographicLib is Copyright (c) Charles Karney (2010-2012)
* <[email protected]> and licensed under the MIT/X11 License.
* For more information, see
* http://geographiclib.sourceforge.net/
**********************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NETGeographicLib;
namespace Projections
{
public partial class AlbersPanel : UserControl
{
enum ProjectionTypes
{
AlbersEqualArea = 0,
LambertConformalConic = 1,
TransverseMercator = 2,
TransverseMercatorExact = 3
}
ProjectionTypes m_projection;
AlbersEqualArea m_albers = null;
LambertConformalConic m_lambert = null;
TransverseMercator m_trans = null;
TransverseMercatorExact m_transExact = null;
public AlbersPanel()
{
InitializeComponent();
m_projectionComboBox.SelectedIndex = 0; // this calls OnProjection and sets it to an AlbersEqualArea
m_constructorComboBox.SelectedIndex = 3; // this calls OnConstructorChanged
m_majorRadiusTextBox.Text = m_albers.MajorRadius.ToString();
m_flatteningTextBox.Text = m_albers.Flattening.ToString();
m_centralScaleTextBox.Text = m_albers.CentralScale.ToString();
m_originLatitudeTextBox.Text = m_albers.OriginLatitude.ToString();
m_functionComboBox.SelectedIndex = 0; // this calls OnFunction
}
private void OnConstructorChanged(object sender, EventArgs e)
{
try
{
if (m_projectionComboBox.SelectedIndex > 1)
{
m_originLatitudeTextBox.ReadOnly = true;
m_originLatitudeTextBox.Text = "N/A";
if (m_constructorComboBox.SelectedIndex == 0)
{
m_convertButton.Enabled = true;
m_setButton.Enabled = false;
m_majorRadiusTextBox.ReadOnly = true;
m_flatteningTextBox.ReadOnly = true;
m_scaleLabel.Hide();
m_KTextBox.Hide();
m_stdLatLabel.Hide();
m_stdLat1TextBox.Hide();
m_stdLat2Label.Hide();
m_stdLat2TextBox.Hide();
m_sinLat2Label.Hide();
m_sinLat2TextBox.Hide();
m_cosLat2Label.Hide();
m_cosLat2TextBox.Hide();
if (m_projection == ProjectionTypes.TransverseMercator)
{
m_trans = new TransverseMercator();
m_centralScaleTextBox.Text = m_trans.CentralScale.ToString();
}
else
{
m_transExact = new TransverseMercatorExact();
m_centralScaleTextBox.Text = m_transExact.CentralScale.ToString();
}
}
else
{
m_convertButton.Enabled = false;
m_setButton.Enabled = true;
m_majorRadiusTextBox.ReadOnly = false;
m_flatteningTextBox.ReadOnly = false;
m_scaleLabel.Show();
m_KTextBox.Show();
m_stdLatLabel.Hide();
m_stdLat1TextBox.Hide();
m_stdLat2Label.Hide();
m_stdLat2TextBox.Hide();
m_sinLat2Label.Hide();
m_sinLat2TextBox.Hide();
m_cosLat2Label.Hide();
m_cosLat2TextBox.Hide();
}
}
else
{
m_originLatitudeTextBox.ReadOnly = false;
switch (m_constructorComboBox.SelectedIndex)
{
case 0:
m_convertButton.Enabled = false;
m_setButton.Enabled = true;
m_majorRadiusTextBox.ReadOnly = false;
m_flatteningTextBox.ReadOnly = false;
m_scaleLabel.Show();
m_KTextBox.Show();
m_stdLatLabel.Show();
m_stdLatLabel.Text = "Standard Latitude (degrees)";
m_stdLat1TextBox.Show();
m_stdLat2Label.Hide();
m_stdLat2TextBox.Hide();
m_sinLat2Label.Hide();
m_sinLat2TextBox.Hide();
m_cosLat2Label.Hide();
m_cosLat2TextBox.Hide();
break;
case 1:
m_convertButton.Enabled = false;
m_setButton.Enabled = true;
m_majorRadiusTextBox.ReadOnly = false;
m_flatteningTextBox.ReadOnly = false;
m_scaleLabel.Show();
m_KTextBox.Show();
m_stdLatLabel.Show();
m_stdLatLabel.Text = "Standard Latitude 1 (degrees)";
m_stdLat1TextBox.Show();
m_stdLat2Label.Text = "Standard Latitude 2 (degrees)";
m_stdLat2Label.Show();
m_stdLat2TextBox.Show();
m_sinLat2Label.Hide();
m_sinLat2TextBox.Hide();
m_cosLat2Label.Hide();
m_cosLat2TextBox.Hide();
break;
case 2:
m_convertButton.Enabled = false;
m_setButton.Enabled = true;
m_majorRadiusTextBox.ReadOnly = false;
m_flatteningTextBox.ReadOnly = false;
m_scaleLabel.Show();
m_KTextBox.Show();
m_stdLatLabel.Show();
m_stdLatLabel.Text = "Sin(Lat1)";
m_stdLat1TextBox.Show();
m_stdLat2Label.Text = "Cos(Lat1)";
m_stdLat2Label.Show();
m_stdLat2TextBox.Show();
m_sinLat2Label.Show();
m_sinLat2TextBox.Show();
m_cosLat2Label.Show();
m_cosLat2TextBox.Show();
break;
default:
m_convertButton.Enabled = true;
m_setButton.Enabled = false;
m_majorRadiusTextBox.ReadOnly = true;
m_flatteningTextBox.ReadOnly = true;
m_scaleLabel.Hide();
m_KTextBox.Hide();
m_stdLatLabel.Hide();
m_stdLat1TextBox.Hide();
m_stdLat2Label.Hide();
m_stdLat2TextBox.Hide();
m_sinLat2Label.Hide();
m_sinLat2TextBox.Hide();
m_cosLat2Label.Hide();
m_cosLat2TextBox.Hide();
break;
}
if (m_projection == ProjectionTypes.AlbersEqualArea)
AlbersConstructorChanged();
}
}
catch (Exception xcpt)
{
MessageBox.Show(xcpt.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AlbersConstructorChanged()
{
switch (m_constructorComboBox.SelectedIndex)
{
case 3:
m_albers = new AlbersEqualArea(AlbersEqualArea.StandardTypes.CylindricalEqualArea);
break;
case 4:
m_albers = new AlbersEqualArea(AlbersEqualArea.StandardTypes.AzimuthalEqualAreaNorth);
break;
case 5:
m_albers = new AlbersEqualArea(AlbersEqualArea.StandardTypes.AzimuthalEqualAreaSouth);
break;
default:
break;
}
if (m_constructorComboBox.SelectedIndex > 2)
{
m_majorRadiusTextBox.Text = m_albers.MajorRadius.ToString();
m_flatteningTextBox.Text = m_albers.Flattening.ToString();
m_centralScaleTextBox.Text = m_albers.CentralScale.ToString();
m_originLatitudeTextBox.Text = m_albers.OriginLatitude.ToString();
}
}
private void OnSet(object sender, EventArgs e)
{
try
{
switch (m_projection)
{
case ProjectionTypes.AlbersEqualArea:
SetAlbers();
break;
case ProjectionTypes.LambertConformalConic:
SetLambert();
break;
case ProjectionTypes.TransverseMercator:
SetTransverse();
break;
case ProjectionTypes.TransverseMercatorExact:
SetTransverseExact();
break;
}
}
catch (Exception xcpt)
{
MessageBox.Show(xcpt.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
m_convertButton.Enabled = true;
}
private void SetAlbers()
{
double s2, s3, s4;
double a = Double.Parse(m_majorRadiusTextBox.Text);
double f = Double.Parse(m_flatteningTextBox.Text);
double k = Double.Parse(m_KTextBox.Text);
double s1 = Double.Parse(m_stdLat1TextBox.Text);
switch (m_constructorComboBox.SelectedIndex)
{
case 0:
m_albers = new AlbersEqualArea(a, f, s1, k);
break;
case 1:
s2 = Double.Parse(m_stdLat2TextBox.Text);
m_albers = new AlbersEqualArea(a, f, s1, s2, k);
break;
case 2:
s2 = Double.Parse(m_stdLat2TextBox.Text);
s3 = Double.Parse(m_sinLat2TextBox.Text);
s4 = Double.Parse(m_cosLat2TextBox.Text);
m_albers = new AlbersEqualArea(a, f, s1, s2, s3, s4, k);
break;
default:
break;
}
m_centralScaleTextBox.Text = m_albers.CentralScale.ToString();
m_originLatitudeTextBox.Text = m_albers.OriginLatitude.ToString();
}
private void SetLambert()
{
double s2, s3, s4;
double a = Double.Parse(m_majorRadiusTextBox.Text);
double f = Double.Parse(m_flatteningTextBox.Text);
double k = Double.Parse(m_KTextBox.Text);
double s1 = Double.Parse(m_stdLat1TextBox.Text);
switch (m_constructorComboBox.SelectedIndex)
{
case 0:
m_lambert = new LambertConformalConic(a, f, s1, k);
break;
case 1:
s2 = Double.Parse(m_stdLat2TextBox.Text);
m_lambert = new LambertConformalConic(a, f, s1, s2, k);
break;
case 2:
s2 = Double.Parse(m_stdLat2TextBox.Text);
s3 = Double.Parse(m_sinLat2TextBox.Text);
s4 = Double.Parse(m_cosLat2TextBox.Text);
m_lambert = new LambertConformalConic(a, f, s1, s2, s3, s4, k);
break;
default:
break;
}
m_centralScaleTextBox.Text = m_lambert.CentralScale.ToString();
m_originLatitudeTextBox.Text = m_lambert.OriginLatitude.ToString();
}
private void SetTransverse()
{
switch (m_constructorComboBox.SelectedIndex)
{
case 1:
double a = Double.Parse(m_majorRadiusTextBox.Text);
double f = Double.Parse(m_flatteningTextBox.Text);
double k = Double.Parse(m_KTextBox.Text);
m_trans = new TransverseMercator(a, f, k);
break;
default:
break;
}
m_centralScaleTextBox.Text = m_trans.CentralScale.ToString();
}
private void SetTransverseExact()
{
switch (m_constructorComboBox.SelectedIndex)
{
case 1:
double a = Double.Parse(m_majorRadiusTextBox.Text);
double f = Double.Parse(m_flatteningTextBox.Text);
double k = Double.Parse(m_KTextBox.Text);
m_transExact = new TransverseMercatorExact(a, f, k, false);
break;
default:
break;
}
m_centralScaleTextBox.Text = m_transExact.CentralScale.ToString();
}
private void OnFunction(object sender, EventArgs e)
{
switch (m_functionComboBox.SelectedIndex)
{
case 0:
m_latitudeTextBox.ReadOnly = m_longitudeTextBox.ReadOnly = false;
m_xTextBox.ReadOnly = m_yTextBox.ReadOnly = true;
break;
case 1:
m_latitudeTextBox.ReadOnly = m_longitudeTextBox.ReadOnly = true;
m_xTextBox.ReadOnly = m_yTextBox.ReadOnly = false;
break;
}
}
private void OnConvert(object sender, EventArgs e)
{
try
{
switch (m_projection)
{
case ProjectionTypes.AlbersEqualArea:
ConvertAlbers();
break;
case ProjectionTypes.LambertConformalConic:
ConvertLambert();
break;
case ProjectionTypes.TransverseMercator:
ConvertTransverse();
break;
case ProjectionTypes.TransverseMercatorExact:
ConvertTransverseExact();
break;
}
}
catch (Exception xcpt)
{
MessageBox.Show(xcpt.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ConvertAlbers()
{
double lat = 0.0, lon = 0.0, x = 0.0, y = 0.0, gamma = 0.0, k = 0.0;
double lon0 = Double.Parse(m_lon0TextBox.Text);
switch (m_functionComboBox.SelectedIndex)
{
case 0:
lat = Double.Parse(m_latitudeTextBox.Text);
lon = Double.Parse(m_longitudeTextBox.Text);
m_albers.Forward(lon0, lat, lon, out x, out y, out gamma, out k);
m_xTextBox.Text = x.ToString();
m_yTextBox.Text = y.ToString();
break;
case 1:
x = Double.Parse(m_xTextBox.Text);
y = Double.Parse(m_yTextBox.Text);
m_albers.Reverse(lon0, x, y, out lat, out lon, out gamma, out k);
m_latitudeTextBox.Text = lat.ToString();
m_longitudeTextBox.Text = lon.ToString();
break;
}
m_gammaTextBox.Text = gamma.ToString();
m_azimuthalScaleTextBox.Text = k.ToString();
}
private void ConvertLambert()
{
double lat = 0.0, lon = 0.0, x = 0.0, y = 0.0, gamma = 0.0, k = 0.0;
double lon0 = Double.Parse(m_lon0TextBox.Text);
switch (m_functionComboBox.SelectedIndex)
{
case 0:
lat = Double.Parse(m_latitudeTextBox.Text);
lon = Double.Parse(m_longitudeTextBox.Text);
m_lambert.Forward(lon0, lat, lon, out x, out y, out gamma, out k);
m_xTextBox.Text = x.ToString();
m_yTextBox.Text = y.ToString();
break;
case 1:
x = Double.Parse(m_xTextBox.Text);
y = Double.Parse(m_yTextBox.Text);
m_lambert.Reverse(lon0, x, y, out lat, out lon, out gamma, out k);
m_latitudeTextBox.Text = lat.ToString();
m_longitudeTextBox.Text = lon.ToString();
break;
}
m_gammaTextBox.Text = gamma.ToString();
m_azimuthalScaleTextBox.Text = k.ToString();
}
private void ConvertTransverse()
{
double lat = 0.0, lon = 0.0, x = 0.0, y = 0.0, gamma = 0.0, k = 0.0;
double lon0 = Double.Parse(m_lon0TextBox.Text);
switch (m_functionComboBox.SelectedIndex)
{
case 0:
lat = Double.Parse(m_latitudeTextBox.Text);
lon = Double.Parse(m_longitudeTextBox.Text);
m_trans.Forward(lon0, lat, lon, out x, out y, out gamma, out k);
m_xTextBox.Text = x.ToString();
m_yTextBox.Text = y.ToString();
break;
case 1:
x = Double.Parse(m_xTextBox.Text);
y = Double.Parse(m_yTextBox.Text);
m_trans.Reverse(lon0, x, y, out lat, out lon, out gamma, out k);
m_latitudeTextBox.Text = lat.ToString();
m_longitudeTextBox.Text = lon.ToString();
break;
}
m_gammaTextBox.Text = gamma.ToString();
m_azimuthalScaleTextBox.Text = k.ToString();
}
private void ConvertTransverseExact()
{
double lat = 0.0, lon = 0.0, x = 0.0, y = 0.0, gamma = 0.0, k = 0.0;
double lon0 = Double.Parse(m_lon0TextBox.Text);
switch (m_functionComboBox.SelectedIndex)
{
case 0:
lat = Double.Parse(m_latitudeTextBox.Text);
lon = Double.Parse(m_longitudeTextBox.Text);
m_transExact.Forward(lon0, lat, lon, out x, out y, out gamma, out k);
m_xTextBox.Text = x.ToString();
m_yTextBox.Text = y.ToString();
break;
case 1:
x = Double.Parse(m_xTextBox.Text);
y = Double.Parse(m_yTextBox.Text);
m_transExact.Reverse(lon0, x, y, out lat, out lon, out gamma, out k);
m_latitudeTextBox.Text = lat.ToString();
m_longitudeTextBox.Text = lon.ToString();
break;
}
m_gammaTextBox.Text = gamma.ToString();
m_azimuthalScaleTextBox.Text = k.ToString();
}
private void OnProjection(object sender, EventArgs e)
{
m_projection = (ProjectionTypes)m_projectionComboBox.SelectedIndex;
int save = m_constructorComboBox.SelectedIndex;
m_constructorComboBox.Items.Clear();
if (m_projectionComboBox.SelectedIndex > 1) // TransverseMercator or TransverseMercatorExact
{
m_constructorComboBox.Items.Add("Default");
m_constructorComboBox.Items.Add("Constructor #1");
}
else
{
m_constructorComboBox.Items.Add("Constructor #1");
m_constructorComboBox.Items.Add("Constructor #2");
m_constructorComboBox.Items.Add("Constructor #3");
if (m_projection == ProjectionTypes.AlbersEqualArea)
{
m_constructorComboBox.Items.Add("CylindricalEqualArea");
m_constructorComboBox.Items.Add("AzimuthalEqualAreaNorth");
m_constructorComboBox.Items.Add("AzimuthalEqualAreaSouth");
}
}
// calls OnConstructor
m_constructorComboBox.SelectedIndex = m_constructorComboBox.Items.Count > save ? save : 0;
}
private void OnValidate(object sender, EventArgs e)
{
try
{
const double DEG_TO_RAD = 3.1415926535897932384626433832795 / 180.0;
AlbersEqualArea a = new AlbersEqualArea(AlbersEqualArea.StandardTypes.AzimuthalEqualAreaNorth);
a = new AlbersEqualArea(AlbersEqualArea.StandardTypes.AzimuthalEqualAreaSouth);
double radius = a.MajorRadius;
double f = a.Flattening;
a = new AlbersEqualArea(radius, f, 60.0, 1.0);
a = new AlbersEqualArea(radius, f, 60.0, 70.0, 1.0);
a = new AlbersEqualArea(radius, f, Math.Sin(88.0 * DEG_TO_RAD), Math.Cos(88.0 * DEG_TO_RAD),
Math.Sin(89.0*DEG_TO_RAD), Math.Cos(89.0*DEG_TO_RAD), 1.0);
a = new AlbersEqualArea(AlbersEqualArea.StandardTypes.CylindricalEqualArea);
double lon0 = 0.0, lat = 32.0, lon = -86.0, x, y, gamma, k, x1, y1;
a.Forward(lon0, lat, lon, out x, out y, out gamma, out k);
a.Forward(lon0, lat, lon, out x1, out y1);
if (x != x1 || y != y1)
throw new Exception("Error in AlbersEqualArea.Forward");
a.Reverse(lon0, x, y, out lat, out lon, out gamma, out k);
a.Reverse(lon0, x, y, out x1, out y1);
if (lat != x1 || lon != y1)
throw new Exception("Error in AlbersEqualArea.Reverse");
LambertConformalConic b = new LambertConformalConic(radius, f, 60.0, 1.0);
b = new LambertConformalConic(radius, f, 60.0, 65.0, 1.0);
b = new LambertConformalConic(radius, f, Math.Sin(88.0 * DEG_TO_RAD), Math.Cos(88.0 * DEG_TO_RAD),
Math.Sin(89.0 * DEG_TO_RAD), Math.Cos(89.0 * DEG_TO_RAD), 1.0);
b = new LambertConformalConic();
b.SetScale(60.0, 1.0);
b.Forward(-87.0, 32.0, -86.0, out x, out y, out gamma, out k);
b.Forward(-87.0, 32.0, -86.0, out x1, out y1);
if (x != x1 || y != y1)
throw new Exception("Error in LambertConformalConic.Forward");
b.Reverse(-87.0, x, y, out lat, out lon, out gamma, out k);
b.Reverse(-87.0, x, y, out x1, out y1, out gamma, out k);
if (lat != x1 || lon != y1)
throw new Exception("Error in LambertConformalConic.Reverse");
TransverseMercator c = new TransverseMercator(radius, f, 1.0);
c = new TransverseMercator();
c.Forward(-87.0, 32.0, -86.0, out x, out y, out gamma, out k);
c.Forward(-87.0, 32.0, -86.0, out x1, out y1);
if (x != x1 || y != y1)
throw new Exception("Error in TransverseMercator.Forward");
c.Reverse(-87.0, x, y, out lat, out lon, out gamma, out k);
c.Reverse(-87.0, x, y, out x1, out y1);
if (lat != x1 || lon != y1)
throw new Exception("Error in TransverseMercator.Reverse");
TransverseMercatorExact d = new TransverseMercatorExact(radius, f, 1.0, false);
d = new TransverseMercatorExact();
d.Forward(-87.0, 32.0, -86.0, out x, out y, out gamma, out k);
d.Forward(-87.0, 32.0, -86.0, out x1, out y1);
if (x != x1 || y != y1)
throw new Exception("Error in TransverseMercatorExact.Forward");
d.Reverse(-87.0, x, y, out lat, out lon, out gamma, out k);
d.Reverse(-87.0, x, y, out x1, out y1);
if (lat != x1 || lon != y1)
throw new Exception("Error in TransverseMercatorExact.Reverse");
}
catch (Exception xcpt)
{
MessageBox.Show(xcpt.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
MessageBox.Show("No errors detected", "OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using Microsoft.Research.ClousotRegression;
using System.Diagnostics.Contracts;
namespace InterfaceContracts
{
[ContractClass(typeof(IFooContract))]
public interface IFoo
{
int Foo(int x);
int Value { get; }
}
[ContractClassFor(typeof(IFoo))]
abstract class IFooContract : IFoo
{
int IFoo.Foo(int x) {
Contract.Requires(x >= 0);
Contract.Ensures(Contract.Result<int>() >= 0);
return 0;
}
int IFoo.Value {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
return 0;
}
}
}
public class FooClass : IFoo
{
public int stored;
[ClousotRegressionTest("regular")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 25, MethodILOffset = 6)]
public int Foo(int x)
{
return x;
}
public int Value {
[ClousotRegressionTest("regular")]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="ensures unproven: Contract.Result<int>() >= 0. Are you missing an object invariant on field stored?",PrimaryILOffset=12,MethodILOffset=11)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 2, MethodILOffset = 0)]
get { return this.stored; }
}
}
public struct FooStruct : IFoo
{
public int stored;
[ContractInvariantMethod]
void Invariant() {
Contract.Invariant(stored >= 0);
}
[ClousotRegressionTest("regular")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 13, MethodILOffset = 13)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 25, MethodILOffset = 13)]
public int Foo(int x)
{
return x + stored;
}
public int Value {
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 12, MethodILOffset = 11)]
get { return this.stored; }
}
}
public class GenericFooUse<T> where T : IFoo
{
[ClousotRegressionTest("generics")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 8, MethodILOffset = 64)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 37, MethodILOffset = 73)]
public int Test1(T t)
{
Contract.Requires(t.Value >= 0);
Contract.Ensures(Contract.Result<int>() >= 0);
return t.Foo(t.Value);
}
[ClousotRegressionTest("generics")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 8, MethodILOffset = 61)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 36, MethodILOffset = 70)]
public int Test2(ref T t)
{
Contract.Requires(t.Value >= 0);
Contract.Ensures(Contract.Result<int>() >= 0);
return t.Foo(t.Value);
}
}
public class InstantiatedFooUse
{
public GenericFooUse<FooClass> fooClass;
public GenericFooUse<FooStruct> fooStruct;
[ClousotRegressionTest("generics")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 20, MethodILOffset = 44)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 57, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 19, MethodILOffset = 71)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 84, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 20, MethodILOffset = 97)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 110, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 19, MethodILOffset = 124)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 137, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 20, MethodILOffset = 155)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 170, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 19, MethodILOffset = 183)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 198, MethodILOffset = 0)]
public void TestMain(FooClass fc, FooStruct fs1, ref FooStruct fs2)
{
Contract.Assume(this.fooClass != null);
Contract.Assume(this.fooStruct != null);
int x1 = fooClass.Test1(fc);
Contract.Assert(x1 >= 0);
int x2 = fooClass.Test2(ref fc);
Contract.Assert(x2 >= 0);
int y1 = fooStruct.Test1(fs1);
Contract.Assert(y1 >= 0);
int y2 = fooStruct.Test2(ref fs1);
Contract.Assert(y2 >= 0);
int z1 = fooStruct.Test1(fs2);
Contract.Assert(z1 >= 0);
int z2 = fooStruct.Test2(ref fs2);
Contract.Assert(z2 >= 0);
}
}
}
namespace GenericInterfaceContracts
{
[ContractClass(typeof(ContractForJ<>))]
public interface J<T>
{
bool FooBar(T[] xs);
}
[ContractClass(typeof(ContractForK))]
public interface K
{
bool FooBar(int[] xs);
}
[ContractClassFor(typeof(J<>))]
abstract class ContractForJ<T> : J<T>
{
bool J<T>.FooBar(T[] xs)
{
Contract.Requires(xs != null);
return default(bool);
}
}
[ContractClassFor(typeof(K))]
abstract class ContractForK : K
{
bool K.FooBar(int[] xs)
{
Contract.Requires(xs != null);
return default(bool);
}
}
class B : J<int>
{
public virtual bool FooBar(int[] xs)
{
return true;
}
}
class GenericB<T> : J<T>
{
public virtual bool FooBar(T[] xs)
{
return true;
}
}
class C : K
{
public virtual bool FooBar(int[] xs)
{
return true;
}
}
class M
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.False, Message = @"requires is false: xs != null", PrimaryILOffset = 8, MethodILOffset = 9)]
public void Test1()
{
J<int> j = new B();
j.FooBar(null);
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.False, Message = @"requires is false: xs != null", PrimaryILOffset = 8, MethodILOffset = 3)]
public void Test2(K k)
{
k.FooBar(null);
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.False, Message = @"requires is false: xs != null", PrimaryILOffset = 8, MethodILOffset = 9)]
public void Test3()
{
J<int> j2 = new GenericB<int>();
j2.FooBar(null);
}
}
}
namespace AbstractClassContracts
{
[ContractClass(typeof(AContract))]
abstract class A
{
internal abstract void DoSmth(string s);
}
[ContractClassFor(typeof(A))]
abstract class AContract : A
{
internal override void DoSmth(string s)
{
Contract.Requires(s != null);
}
}
class B : A
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 3, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 8, MethodILOffset = 3)]
internal override void DoSmth(string s)
{
this.DoSmthElse(s);
}
internal void DoSmthElse(string x)
{
Contract.Requires(x != null);
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
function initializeRoadEditor()
{
echo( " - Initializing Road and Path Editor" );
exec( "./roadEditor.cs" );
exec( "./RoadEditorGui.gui" );
exec( "./RoadEditorToolbar.gui");
exec( "./roadEditorGui.cs" );
// Add ourselves to EditorGui, where all the other tools reside
RoadEditorGui.setVisible( false );
RoadEditorToolbar.setVisible( false );
RoadEditorOptionsWindow.setVisible( false );
RoadEditorTreeWindow.setVisible( false );
EditorGui.add( RoadEditorGui );
EditorGui.add( RoadEditorToolbar );
EditorGui.add( RoadEditorOptionsWindow );
EditorGui.add( RoadEditorTreeWindow );
new ScriptObject( RoadEditorPlugin )
{
superClass = "EditorPlugin";
editorGui = RoadEditorGui;
};
%map = new ActionMap();
%map.bindCmd( keyboard, "backspace", "RoadEditorGui.onDeleteKey();", "" );
%map.bindCmd( keyboard, "1", "RoadEditorGui.prepSelectionMode();", "" );
%map.bindCmd( keyboard, "2", "ToolsPaletteArray->RoadEditorMoveMode.performClick();", "" );
%map.bindCmd( keyboard, "4", "ToolsPaletteArray->RoadEditorScaleMode.performClick();", "" );
%map.bindCmd( keyboard, "5", "ToolsPaletteArray->RoadEditorAddRoadMode.performClick();", "" );
%map.bindCmd( keyboard, "=", "ToolsPaletteArray->RoadEditorInsertPointMode.performClick();", "" );
%map.bindCmd( keyboard, "numpadadd", "ToolsPaletteArray->RoadEditorInsertPointMode.performClick();", "" );
%map.bindCmd( keyboard, "-", "ToolsPaletteArray->RoadEditorRemovePointMode.performClick();", "" );
%map.bindCmd( keyboard, "numpadminus", "ToolsPaletteArray->RoadEditorRemovePointMode.performClick();", "" );
%map.bindCmd( keyboard, "z", "RoadEditorShowSplineBtn.performClick();", "" );
%map.bindCmd( keyboard, "x", "RoadEditorWireframeBtn.performClick();", "" );
%map.bindCmd( keyboard, "v", "RoadEditorShowRoadBtn.performClick();", "" );
RoadEditorPlugin.map = %map;
RoadEditorPlugin.initSettings();
}
function destroyRoadEditor()
{
}
function RoadEditorPlugin::onWorldEditorStartup( %this )
{
// Add ourselves to the window menu.
%accel = EditorGui.addToEditorsMenu( "Road and Path Editor", "", RoadEditorPlugin );
// Add ourselves to the ToolsToolbar
%tooltip = "Road Editor (" @ %accel @ ")";
EditorGui.addToToolsToolbar( "RoadEditorPlugin", "RoadEditorPalette", expandFilename("tools/worldEditor/images/toolbar/road-path-editor"), %tooltip );
//connect editor windows
GuiWindowCtrl::attach( RoadEditorOptionsWindow, RoadEditorTreeWindow);
// Add ourselves to the Editor Settings window
exec( "./RoadEditorSettingsTab.gui" );
ESettingsWindow.addTabPage( ERoadEditorSettingsPage );
}
function RoadEditorPlugin::onActivated( %this )
{
%this.readSettings();
ToolsPaletteArray->RoadEditorAddRoadMode.performClick();
EditorGui.bringToFront( RoadEditorGui );
RoadEditorGui.setVisible( true );
RoadEditorGui.makeFirstResponder( true );
RoadEditorToolbar.setVisible( true );
RoadEditorOptionsWindow.setVisible( true );
RoadEditorTreeWindow.setVisible( true );
RoadTreeView.open(ServerDecalRoadSet,true);
%this.map.push();
// Set the status bar here until all tool have been hooked up
EditorGuiStatusBar.setInfo("Road editor.");
EditorGuiStatusBar.setSelection("");
Parent::onActivated(%this);
}
function RoadEditorPlugin::onDeactivated( %this )
{
%this.writeSettings();
RoadEditorGui.setVisible( false );
RoadEditorToolbar.setVisible( false );
RoadEditorOptionsWindow.setVisible( false );
RoadEditorTreeWindow.setVisible( false );
%this.map.pop();
Parent::onDeactivated(%this);
}
function RoadEditorPlugin::onEditMenuSelect( %this, %editMenu )
{
%hasSelection = false;
if( isObject( RoadEditorGui.road ) )
%hasSelection = true;
%editMenu.enableItem( 3, false ); // Cut
%editMenu.enableItem( 4, false ); // Copy
%editMenu.enableItem( 5, false ); // Paste
%editMenu.enableItem( 6, %hasSelection ); // Delete
%editMenu.enableItem( 8, false ); // Deselect
}
function RoadEditorPlugin::handleDelete( %this )
{
RoadEditorGui.onDeleteKey();
}
function RoadEditorPlugin::handleEscape( %this )
{
return RoadEditorGui.onEscapePressed();
}
function RoadEditorPlugin::isDirty( %this )
{
return RoadEditorGui.isDirty;
}
function RoadEditorPlugin::onSaveMission( %this, %missionFile )
{
if( RoadEditorGui.isDirty )
{
getScene(0).save( %missionFile );
RoadEditorGui.isDirty = false;
}
}
function RoadEditorPlugin::setEditorFunction( %this )
{
%terrainExists = parseMissionGroup( "TerrainBlock" );
if( %terrainExists == false )
MessageBoxYesNoCancel("No Terrain","Would you like to create a New Terrain?", "Canvas.pushDialog(CreateNewTerrainGui);");
return %terrainExists;
}
//-----------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------
function RoadEditorPlugin::initSettings( %this )
{
EditorSettings.beginGroup( "RoadEditor", true );
EditorSettings.setDefaultValue( "DefaultWidth", "10" );
EditorSettings.setDefaultValue( "HoverSplineColor", "255 0 0 255" );
EditorSettings.setDefaultValue( "SelectedSplineColor", "0 255 0 255" );
EditorSettings.setDefaultValue( "HoverNodeColor", "255 255 255 255" ); //<-- Not currently used
EditorSettings.setDefaultValue( "MaterialName", "DefaultDecalRoadMaterial" );
EditorSettings.endGroup();
}
function RoadEditorPlugin::readSettings( %this )
{
EditorSettings.beginGroup( "RoadEditor", true );
RoadEditorGui.DefaultWidth = EditorSettings.value("DefaultWidth");
RoadEditorGui.HoverSplineColor = EditorSettings.value("HoverSplineColor");
RoadEditorGui.SelectedSplineColor = EditorSettings.value("SelectedSplineColor");
RoadEditorGui.HoverNodeColor = EditorSettings.value("HoverNodeColor");
RoadEditorGui.materialName = EditorSettings.value("MaterialName");
EditorSettings.endGroup();
}
function RoadEditorPlugin::writeSettings( %this )
{
EditorSettings.beginGroup( "RoadEditor", true );
EditorSettings.setValue( "DefaultWidth", RoadEditorGui.DefaultWidth );
EditorSettings.setValue( "HoverSplineColor", RoadEditorGui.HoverSplineColor );
EditorSettings.setValue( "SelectedSplineColor", RoadEditorGui.SelectedSplineColor );
EditorSettings.setValue( "HoverNodeColor", RoadEditorGui.HoverNodeColor );
EditorSettings.setValue( "MaterialName", RoadEditorGui.materialName );
EditorSettings.endGroup();
}
| |
using Lucene.Net.Documents;
using Lucene.Net.Randomized.Generators;
using Lucene.Net.Support;
using Lucene.Net.Support.Threading;
using NUnit.Framework;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Console = Lucene.Net.Support.SystemConsole;
namespace Lucene.Net.Index
{
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using Field = Field;
using FieldType = FieldType;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using TestUtil = Lucene.Net.Util.TestUtil;
/// <summary>
/// Simple test that adds numeric terms, where each term has the
/// totalTermFreq of its integer value, and checks that the totalTermFreq is correct.
/// </summary>
// TODO: somehow factor this with BagOfPostings? its almost the same
[SuppressCodecs("Direct", "Memory", "Lucene3x")] // at night this makes like 200k/300k docs and will make Direct's heart beat!
// Lucene3x doesnt have totalTermFreq, so the test isn't interesting there.
[TestFixture]
public class TestBagOfPositions : LuceneTestCase
{
[Test]
public virtual void Test()
{
IList<string> postingsList = new List<string>();
int numTerms = AtLeast(300);
int maxTermsPerDoc = TestUtil.NextInt(Random(), 10, 20);
bool isSimpleText = "SimpleText".Equals(TestUtil.GetPostingsFormat("field"));
IndexWriterConfig iwc = NewIndexWriterConfig(Random(), TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
if ((isSimpleText || iwc.MergePolicy is MockRandomMergePolicy) && (TEST_NIGHTLY || RANDOM_MULTIPLIER > 1))
{
// Otherwise test can take way too long (> 2 hours)
numTerms /= 2;
}
if (VERBOSE)
{
Console.WriteLine("maxTermsPerDoc=" + maxTermsPerDoc);
Console.WriteLine("numTerms=" + numTerms);
}
for (int i = 0; i < numTerms; i++)
{
string term = Convert.ToString(i);
for (int j = 0; j < i; j++)
{
postingsList.Add(term);
}
}
Collections.Shuffle(postingsList);
ConcurrentQueue<string> postings = new ConcurrentQueue<string>(postingsList);
Directory dir = NewFSDirectory(CreateTempDir(GetFullMethodName()));
RandomIndexWriter iw = new RandomIndexWriter(Random(), dir, iwc);
int threadCount = TestUtil.NextInt(Random(), 1, 5);
if (VERBOSE)
{
Console.WriteLine("config: " + iw.w.Config);
Console.WriteLine("threadCount=" + threadCount);
}
Field prototype = NewTextField("field", "", Field.Store.NO);
FieldType fieldType = new FieldType(prototype.FieldType);
if (Random().NextBoolean())
{
fieldType.OmitNorms = true;
}
int options = Random().Next(3);
if (options == 0)
{
fieldType.IndexOptions = IndexOptions.DOCS_AND_FREQS; // we dont actually need positions
fieldType.StoreTermVectors = true; // but enforce term vectors when we do this so we check SOMETHING
}
else if (options == 1 && !DoesntSupportOffsets.Contains(TestUtil.GetPostingsFormat("field")))
{
fieldType.IndexOptions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS;
}
// else just positions
ThreadClass[] threads = new ThreadClass[threadCount];
CountdownEvent startingGun = new CountdownEvent(1);
for (int threadID = 0; threadID < threadCount; threadID++)
{
Random threadRandom = new Random(Random().Next());
Document document = new Document();
Field field = new Field("field", "", fieldType);
document.Add(field);
threads[threadID] = new ThreadAnonymousInnerClassHelper(this, numTerms, maxTermsPerDoc, postings, iw, startingGun, threadRandom, document, field);
threads[threadID].Start();
}
startingGun.Signal();
foreach (ThreadClass t in threads)
{
t.Join();
}
iw.ForceMerge(1);
DirectoryReader ir = iw.Reader;
Assert.AreEqual(1, ir.Leaves.Count);
AtomicReader air = (AtomicReader)ir.Leaves[0].Reader;
Terms terms = air.GetTerms("field");
// numTerms-1 because there cannot be a term 0 with 0 postings:
Assert.AreEqual(numTerms - 1, terms.Count);
TermsEnum termsEnum = terms.GetIterator(null);
BytesRef termBR;
while ((termBR = termsEnum.Next()) != null)
{
int value = Convert.ToInt32(termBR.Utf8ToString());
Assert.AreEqual(value, termsEnum.TotalTermFreq);
// don't really need to check more than this, as CheckIndex
// will verify that totalTermFreq == total number of positions seen
// from a docsAndPositionsEnum.
}
ir.Dispose();
iw.Dispose();
dir.Dispose();
}
private class ThreadAnonymousInnerClassHelper : ThreadClass
{
private readonly TestBagOfPositions OuterInstance;
private int NumTerms;
private int MaxTermsPerDoc;
private ConcurrentQueue<string> Postings;
private RandomIndexWriter Iw;
private CountdownEvent StartingGun;
private Random ThreadRandom;
private Document Document;
private Field Field;
public ThreadAnonymousInnerClassHelper(TestBagOfPositions outerInstance, int numTerms, int maxTermsPerDoc, ConcurrentQueue<string> postings, RandomIndexWriter iw, CountdownEvent startingGun, Random threadRandom, Document document, Field field)
{
this.OuterInstance = outerInstance;
this.NumTerms = numTerms;
this.MaxTermsPerDoc = maxTermsPerDoc;
this.Postings = postings;
this.Iw = iw;
this.StartingGun = startingGun;
this.ThreadRandom = threadRandom;
this.Document = document;
this.Field = field;
}
public override void Run()
{
try
{
StartingGun.Wait();
while (!(Postings.Count == 0))
{
StringBuilder text = new StringBuilder();
int numTerms = ThreadRandom.Next(MaxTermsPerDoc);
for (int i = 0; i < numTerms; i++)
{
string token;
if (!Postings.TryDequeue(out token))
{
break;
}
text.Append(' ');
text.Append(token);
}
Field.SetStringValue(text.ToString());
Iw.AddDocument(Document);
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="SecurityTokenDescriptor.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace System.IdentityModel.Tokens
{
using System;
using System.Collections.Generic;
using System.IdentityModel;
using System.IdentityModel.Protocols.WSTrust;
using System.Security.Claims;
using System.Xml;
using RST = System.IdentityModel.Protocols.WSTrust.RequestSecurityToken;
using RSTR = System.IdentityModel.Protocols.WSTrust.RequestSecurityTokenResponse;
/// <summary>
/// This is a place holder for all the attributes related to the issued token.
/// </summary>
public class SecurityTokenDescriptor
{
private SecurityKeyIdentifierClause attachedReference;
private AuthenticationInformation authenticationInfo;
private string tokenIssuerName;
private ProofDescriptor proofDescriptor;
private ClaimsIdentity subject;
private SecurityToken token;
private string tokenType;
private SecurityKeyIdentifierClause unattachedReference;
private Lifetime lifetime;
private string appliesToAddress;
private string replyToAddress;
private EncryptingCredentials encryptingCredentials;
private SigningCredentials signingCredentials;
private Dictionary<string, object> properties = new Dictionary<string, object>(); // for any custom data
/// <summary>
/// Gets or sets the address for the <see cref="RequestSecurityTokenResponse"/> AppliesTo property.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if not an absolute URI.</exception>
public string AppliesToAddress
{
get
{
return this.appliesToAddress;
}
set
{
if (!string.IsNullOrEmpty(value))
{
if (!UriUtil.CanCreateValidUri(value, UriKind.Absolute))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID2002)));
}
}
this.appliesToAddress = value;
}
}
/// <summary>
/// Sets the appropriate things, such as requested security token, inside the RSTR
/// based on what is inside this token descriptor instance.
/// </summary>
/// <param name="response">The RSTR object that this security token descriptor needs to modify.</param>
/// <exception cref="ArgumentNullException">When response is null.</exception>
public virtual void ApplyTo(RSTR response)
{
if (response == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("response");
}
if (tokenType != null)
{
response.TokenType = tokenType;
}
if (token != null)
{
response.RequestedSecurityToken = new RequestedSecurityToken(token);
}
if (attachedReference != null)
{
response.RequestedAttachedReference = attachedReference;
}
if (unattachedReference != null)
{
response.RequestedUnattachedReference = unattachedReference;
}
if (lifetime != null)
{
response.Lifetime = lifetime;
}
if (proofDescriptor != null)
{
proofDescriptor.ApplyTo(response);
}
}
/// <summary>
/// Gets or sets the address for the <see cref="RequestSecurityTokenResponse"/> ReplyToAddress property.
/// </summary>
public string ReplyToAddress
{
get { return this.replyToAddress; }
set { this.replyToAddress = value; }
}
/// <summary>
/// Gets or sets the credentials used to encrypt the token.
/// </summary>
public EncryptingCredentials EncryptingCredentials
{
get { return this.encryptingCredentials; }
set { this.encryptingCredentials = value; }
}
/// <summary>
/// Gets or sets the credentials used to sign the token.
/// </summary>
public SigningCredentials SigningCredentials
{
get { return this.signingCredentials; }
set { this.signingCredentials = value; }
}
/// <summary>
/// Gets or sets the SecurityKeyIdentifierClause when the token is attached
/// to the message.
/// </summary>
public SecurityKeyIdentifierClause AttachedReference
{
get { return this.attachedReference; }
set { this.attachedReference = value; }
}
/// <summary>
/// Gets or sets the issuer name, which may be used inside the issued token as well.
/// </summary>
public string TokenIssuerName
{
get { return this.tokenIssuerName; }
set { this.tokenIssuerName = value; }
}
/// <summary>
/// Gets or sets the proof descriptor, which can be used to modify some fields inside
/// the RSTR, such as requested proof token.
/// </summary>
public ProofDescriptor Proof
{
get { return this.proofDescriptor; }
set { this.proofDescriptor = value; }
}
/// <summary>
/// Gets the properties bag to extend the object.
/// </summary>
public Dictionary<string, object> Properties
{
get { return this.properties; }
}
/// <summary>
/// Gets or sets the issued security token.
/// </summary>
public SecurityToken Token
{
get { return this.token; }
set { this.token = value; }
}
/// <summary>
/// Gets or sets the token type of the issued token.
/// </summary>
public string TokenType
{
get { return this.tokenType; }
set { this.tokenType = value; }
}
/// <summary>
/// Gets or sets the unattached token reference to refer to the issued token when it is not
/// attached to the message.
/// </summary>
public SecurityKeyIdentifierClause UnattachedReference
{
get { return this.unattachedReference; }
set { this.unattachedReference = value; }
}
/// <summary>
/// Gets or sets the lifetime information for the issued token.
/// </summary>
public Lifetime Lifetime
{
get { return this.lifetime; }
set { this.lifetime = value; }
}
/// <summary>
/// Gets or sets the OutputClaims to be included in the issued token.
/// </summary>
public ClaimsIdentity Subject
{
get { return this.subject; }
set { this.subject = value; }
}
/// <summary>
/// Gets or sets the AuthenticationInformation.
/// </summary>
public AuthenticationInformation AuthenticationInfo
{
get { return this.authenticationInfo; }
set { this.authenticationInfo = value; }
}
/// <summary>
/// Adds a <see cref="Claim"/> for the authentication type to the claim collection of
/// the <see cref="SecurityTokenDescriptor"/>
/// </summary>
/// <param name="authType">The authentication type.</param>
public void AddAuthenticationClaims(string authType)
{
this.AddAuthenticationClaims(authType, DateTime.UtcNow);
}
/// <summary>
/// Adds <see cref="Claim"/>s for the authentication type and the authentication instant
/// to the claim collection of the <see cref="SecurityTokenDescriptor"/>
/// </summary>
/// <param name="authType">Specifies the authentication type</param>
/// <param name="time">Specifies the authentication instant in UTC. If the input is not in UTC, it is converted to UTC.</param>
public void AddAuthenticationClaims(string authType, DateTime time)
{
this.Subject.AddClaim(
new Claim(ClaimTypes.AuthenticationMethod, authType, ClaimValueTypes.String));
this.Subject.AddClaim(
new Claim(ClaimTypes.AuthenticationInstant, XmlConvert.ToString(time.ToUniversalTime(), DateTimeFormats.Generated), ClaimValueTypes.DateTime));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
namespace System.Diagnostics
{
/// <devdoc>
/// <para>
/// Provides access to local and remote
/// processes. Enables you to start and stop system processes.
/// </para>
/// </devdoc>
public partial class Process : Component
{
private bool _haveProcessId;
private int _processId;
private bool _haveProcessHandle;
private SafeProcessHandle _processHandle;
private bool _isRemoteMachine;
private string _machineName;
private ProcessInfo _processInfo;
private ProcessThreadCollection _threads;
private ProcessModuleCollection _modules;
private bool _haveWorkingSetLimits;
private IntPtr _minWorkingSet;
private IntPtr _maxWorkingSet;
private bool _haveProcessorAffinity;
private IntPtr _processorAffinity;
private bool _havePriorityClass;
private ProcessPriorityClass _priorityClass;
private ProcessStartInfo _startInfo;
private bool _watchForExit;
private bool _watchingForExit;
private EventHandler _onExited;
private bool _exited;
private int _exitCode;
private DateTime? _startTime;
private DateTime _exitTime;
private bool _haveExitTime;
private bool _priorityBoostEnabled;
private bool _havePriorityBoostEnabled;
private bool _raisedOnExited;
private RegisteredWaitHandle _registeredWaitHandle;
private WaitHandle _waitHandle;
private StreamReader _standardOutput;
private StreamWriter _standardInput;
private StreamReader _standardError;
private bool _disposed;
private bool _standardInputAccessed;
private StreamReadMode _outputStreamReadMode;
private StreamReadMode _errorStreamReadMode;
// Support for asynchronously reading streams
public event DataReceivedEventHandler OutputDataReceived;
public event DataReceivedEventHandler ErrorDataReceived;
// Abstract the stream details
internal AsyncStreamReader _output;
internal AsyncStreamReader _error;
internal bool _pendingOutputRead;
internal bool _pendingErrorRead;
private static int s_cachedSerializationSwitch = 0;
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Diagnostics.Process'/> class.
/// </para>
/// </devdoc>
public Process()
{
// This class once inherited a finalizer. For backward compatibility it has one so that
// any derived class that depends on it will see the behaviour expected. Since it is
// not used by this class itself, suppress it immediately if this is not an instance
// of a derived class it doesn't suffer the GC burden of finalization.
if (GetType() == typeof(Process))
{
GC.SuppressFinalize(this);
}
_machineName = ".";
_outputStreamReadMode = StreamReadMode.Undefined;
_errorStreamReadMode = StreamReadMode.Undefined;
}
private Process(string machineName, bool isRemoteMachine, int processId, ProcessInfo processInfo)
{
GC.SuppressFinalize(this);
_processInfo = processInfo;
_machineName = machineName;
_isRemoteMachine = isRemoteMachine;
_processId = processId;
_haveProcessId = true;
_outputStreamReadMode = StreamReadMode.Undefined;
_errorStreamReadMode = StreamReadMode.Undefined;
}
public SafeProcessHandle SafeHandle
{
get
{
EnsureState(State.Associated);
return GetOrOpenProcessHandle();
}
}
public IntPtr Handle => SafeHandle.DangerousGetHandle();
/// <devdoc>
/// Returns whether this process component is associated with a real process.
/// </devdoc>
/// <internalonly/>
private bool Associated
{
get { return _haveProcessId || _haveProcessHandle; }
}
/// <devdoc>
/// <para>
/// Gets the base priority of
/// the associated process.
/// </para>
/// </devdoc>
public int BasePriority
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.BasePriority;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the
/// value that was specified by the associated process when it was terminated.
/// </para>
/// </devdoc>
public int ExitCode
{
get
{
EnsureState(State.Exited);
return _exitCode;
}
}
/// <devdoc>
/// <para>
/// Gets a
/// value indicating whether the associated process has been terminated.
/// </para>
/// </devdoc>
public bool HasExited
{
get
{
if (!_exited)
{
EnsureState(State.Associated);
UpdateHasExited();
if (_exited)
{
RaiseOnExited();
}
}
return _exited;
}
}
/// <summary>Gets the time the associated process was started.</summary>
public DateTime StartTime
{
get
{
if (!_startTime.HasValue)
{
_startTime = StartTimeCore;
}
return _startTime.Value;
}
}
/// <devdoc>
/// <para>
/// Gets the time that the associated process exited.
/// </para>
/// </devdoc>
public DateTime ExitTime
{
get
{
if (!_haveExitTime)
{
EnsureState(State.Exited);
_exitTime = ExitTimeCore;
_haveExitTime = true;
}
return _exitTime;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the unique identifier for the associated process.
/// </para>
/// </devdoc>
public int Id
{
get
{
EnsureState(State.HaveId);
return _processId;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the name of the computer on which the associated process is running.
/// </para>
/// </devdoc>
public string MachineName
{
get
{
EnsureState(State.Associated);
return _machineName;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the maximum allowable working set for the associated
/// process.
/// </para>
/// </devdoc>
public IntPtr MaxWorkingSet
{
get
{
EnsureWorkingSetLimits();
return _maxWorkingSet;
}
set
{
SetWorkingSetLimits(null, value);
}
}
/// <devdoc>
/// <para>
/// Gets or sets the minimum allowable working set for the associated
/// process.
/// </para>
/// </devdoc>
public IntPtr MinWorkingSet
{
get
{
EnsureWorkingSetLimits();
return _minWorkingSet;
}
set
{
SetWorkingSetLimits(value, null);
}
}
public ProcessModuleCollection Modules
{
get
{
if (_modules == null)
{
EnsureState(State.HaveNonExitedId | State.IsLocal);
_modules = ProcessManager.GetModules(_processId);
}
return _modules;
}
}
public long NonpagedSystemMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PoolNonPagedBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.NonpagedSystemMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int NonpagedSystemMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PoolNonPagedBytes);
}
}
public long PagedMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PageFileBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PagedMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PageFileBytes);
}
}
public long PagedSystemMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PoolPagedBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedSystemMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PagedSystemMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PoolPagedBytes);
}
}
public long PeakPagedMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PageFileBytesPeak;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakPagedMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PeakPagedMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PageFileBytesPeak);
}
}
public long PeakWorkingSet64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.WorkingSetPeak;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakWorkingSet64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PeakWorkingSet
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.WorkingSetPeak);
}
}
public long PeakVirtualMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.VirtualBytesPeak;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakVirtualMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PeakVirtualMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.VirtualBytesPeak);
}
}
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether the associated process priority
/// should be temporarily boosted by the operating system when the main window
/// has focus.
/// </para>
/// </devdoc>
public bool PriorityBoostEnabled
{
get
{
if (!_havePriorityBoostEnabled)
{
_priorityBoostEnabled = PriorityBoostEnabledCore;
_havePriorityBoostEnabled = true;
}
return _priorityBoostEnabled;
}
set
{
PriorityBoostEnabledCore = value;
_priorityBoostEnabled = value;
_havePriorityBoostEnabled = true;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the overall priority category for the
/// associated process.
/// </para>
/// </devdoc>
public ProcessPriorityClass PriorityClass
{
get
{
if (!_havePriorityClass)
{
_priorityClass = PriorityClassCore;
_havePriorityClass = true;
}
return _priorityClass;
}
set
{
if (!Enum.IsDefined(typeof(ProcessPriorityClass), value))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ProcessPriorityClass));
}
PriorityClassCore = value;
_priorityClass = value;
_havePriorityClass = true;
}
}
public long PrivateMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PrivateBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PrivateMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PrivateMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PrivateBytes);
}
}
/// <devdoc>
/// <para>
/// Gets
/// the friendly name of the process.
/// </para>
/// </devdoc>
public string ProcessName
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.ProcessName;
}
}
/// <devdoc>
/// <para>
/// Gets
/// or sets which processors the threads in this process can be scheduled to run on.
/// </para>
/// </devdoc>
public IntPtr ProcessorAffinity
{
get
{
if (!_haveProcessorAffinity)
{
_processorAffinity = ProcessorAffinityCore;
_haveProcessorAffinity = true;
}
return _processorAffinity;
}
set
{
ProcessorAffinityCore = value;
_processorAffinity = value;
_haveProcessorAffinity = true;
}
}
public int SessionId
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.SessionId;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the properties to pass into the <see cref='System.Diagnostics.Process.Start(System.Diagnostics.ProcessStartInfo)'/> method for the <see cref='System.Diagnostics.Process'/>.
/// </para>
/// </devdoc>
public ProcessStartInfo StartInfo
{
get
{
if (_startInfo == null)
{
if (Associated)
{
throw new InvalidOperationException(SR.CantGetProcessStartInfo);
}
_startInfo = new ProcessStartInfo();
}
return _startInfo;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (Associated)
{
throw new InvalidOperationException(SR.CantSetProcessStartInfo);
}
_startInfo = value;
}
}
/// <devdoc>
/// <para>
/// Gets the set of threads that are running in the associated
/// process.
/// </para>
/// </devdoc>
public ProcessThreadCollection Threads
{
get
{
if (_threads == null)
{
EnsureState(State.HaveProcessInfo);
int count = _processInfo._threadInfoList.Count;
ProcessThread[] newThreadsArray = new ProcessThread[count];
for (int i = 0; i < count; i++)
{
newThreadsArray[i] = new ProcessThread(_isRemoteMachine, _processId, (ThreadInfo)_processInfo._threadInfoList[i]);
}
ProcessThreadCollection newThreads = new ProcessThreadCollection(newThreadsArray);
_threads = newThreads;
}
return _threads;
}
}
public int HandleCount
{
get
{
EnsureState(State.HaveProcessInfo);
EnsureHandleCountPopulated();
return _processInfo.HandleCount;
}
}
partial void EnsureHandleCountPopulated();
public long VirtualMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.VirtualBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.VirtualMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int VirtualMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.VirtualBytes);
}
}
/// <devdoc>
/// <para>
/// Gets or sets whether the <see cref='System.Diagnostics.Process.Exited'/>
/// event is fired
/// when the process terminates.
/// </para>
/// </devdoc>
public bool EnableRaisingEvents
{
get
{
return _watchForExit;
}
set
{
if (value != _watchForExit)
{
if (Associated)
{
if (value)
{
EnsureWatchingForExit();
}
else
{
StopWatchingForExit();
}
}
_watchForExit = value;
}
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public StreamWriter StandardInput
{
get
{
if (_standardInput == null)
{
throw new InvalidOperationException(SR.CantGetStandardIn);
}
_standardInputAccessed = true;
return _standardInput;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public StreamReader StandardOutput
{
get
{
if (_standardOutput == null)
{
throw new InvalidOperationException(SR.CantGetStandardOut);
}
if (_outputStreamReadMode == StreamReadMode.Undefined)
{
_outputStreamReadMode = StreamReadMode.SyncMode;
}
else if (_outputStreamReadMode != StreamReadMode.SyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
return _standardOutput;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public StreamReader StandardError
{
get
{
if (_standardError == null)
{
throw new InvalidOperationException(SR.CantGetStandardError);
}
if (_errorStreamReadMode == StreamReadMode.Undefined)
{
_errorStreamReadMode = StreamReadMode.SyncMode;
}
else if (_errorStreamReadMode != StreamReadMode.SyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
return _standardError;
}
}
public long WorkingSet64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.WorkingSet;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.WorkingSet64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int WorkingSet
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.WorkingSet);
}
}
public event EventHandler Exited
{
add
{
_onExited += value;
}
remove
{
_onExited -= value;
}
}
/// <devdoc>
/// This is called from the threadpool when a process exits.
/// </devdoc>
/// <internalonly/>
private void CompletionCallback(object waitHandleContext, bool wasSignaled)
{
Debug.Assert(waitHandleContext != null, "Process.CompletionCallback called with no waitHandleContext");
lock (this)
{
// Check the exited event that we get from the threadpool
// matches the event we are waiting for.
if (waitHandleContext != _waitHandle)
{
return;
}
StopWatchingForExit();
RaiseOnExited();
}
}
/// <internalonly/>
/// <devdoc>
/// <para>
/// Free any resources associated with this component.
/// </para>
/// </devdoc>
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
//Dispose managed and unmanaged resources
Close();
}
_disposed = true;
}
}
public bool CloseMainWindow()
{
return CloseMainWindowCore();
}
public bool WaitForInputIdle()
{
return WaitForInputIdle(int.MaxValue);
}
public bool WaitForInputIdle(int milliseconds)
{
return WaitForInputIdleCore(milliseconds);
}
public ISynchronizeInvoke SynchronizingObject { get; set; }
/// <devdoc>
/// <para>
/// Frees any resources associated with this component.
/// </para>
/// </devdoc>
public void Close()
{
if (Associated)
{
// We need to lock to ensure we don't run concurrently with CompletionCallback.
// Without this lock we could reset _raisedOnExited which causes CompletionCallback to
// raise the Exited event a second time for the same process.
lock (this)
{
// This sets _waitHandle to null which causes CompletionCallback to not emit events.
StopWatchingForExit();
}
if (_haveProcessHandle)
{
_processHandle.Dispose();
_processHandle = null;
_haveProcessHandle = false;
}
_haveProcessId = false;
_isRemoteMachine = false;
_machineName = ".";
_raisedOnExited = false;
// Only call close on the streams if the user cannot have a reference on them.
// If they are referenced it is the user's responsibility to dispose of them.
try
{
if (_standardOutput != null && (_outputStreamReadMode == StreamReadMode.AsyncMode || _outputStreamReadMode == StreamReadMode.Undefined))
{
if (_outputStreamReadMode == StreamReadMode.AsyncMode)
{
_output?.CancelOperation();
_output?.Dispose();
}
_standardOutput.Close();
}
if (_standardError != null && (_errorStreamReadMode == StreamReadMode.AsyncMode || _errorStreamReadMode == StreamReadMode.Undefined))
{
if (_errorStreamReadMode == StreamReadMode.AsyncMode)
{
_error?.CancelOperation();
_error?.Dispose();
}
_standardError.Close();
}
if (_standardInput != null && !_standardInputAccessed)
{
_standardInput.Close();
}
}
finally
{
_standardOutput = null;
_standardInput = null;
_standardError = null;
_output = null;
_error = null;
CloseCore();
Refresh();
}
}
}
// Checks if the process hasn't exited on Unix systems.
// This is used to detect recycled child PIDs.
partial void ThrowIfExited(bool refresh);
/// <devdoc>
/// Helper method for checking preconditions when accessing properties.
/// </devdoc>
/// <internalonly/>
private void EnsureState(State state)
{
if ((state & State.Associated) != (State)0)
if (!Associated)
throw new InvalidOperationException(SR.NoAssociatedProcess);
if ((state & State.HaveId) != (State)0)
{
if (!_haveProcessId)
{
if (_haveProcessHandle)
{
SetProcessId(ProcessManager.GetProcessIdFromHandle(_processHandle));
}
else
{
EnsureState(State.Associated);
throw new InvalidOperationException(SR.ProcessIdRequired);
}
}
if ((state & State.HaveNonExitedId) == State.HaveNonExitedId)
{
ThrowIfExited(refresh: false);
}
}
if ((state & State.IsLocal) != (State)0 && _isRemoteMachine)
{
throw new NotSupportedException(SR.NotSupportedRemote);
}
if ((state & State.HaveProcessInfo) != (State)0)
{
if (_processInfo == null)
{
if ((state & State.HaveNonExitedId) != State.HaveNonExitedId)
{
EnsureState(State.HaveNonExitedId);
}
_processInfo = ProcessManager.GetProcessInfo(_processId, _machineName);
if (_processInfo == null)
{
throw new InvalidOperationException(SR.NoProcessInfo);
}
}
}
if ((state & State.Exited) != (State)0)
{
if (!HasExited)
{
throw new InvalidOperationException(SR.WaitTillExit);
}
if (!_haveProcessHandle)
{
throw new InvalidOperationException(SR.NoProcessHandle);
}
}
}
/// <devdoc>
/// Make sure we have obtained the min and max working set limits.
/// </devdoc>
/// <internalonly/>
private void EnsureWorkingSetLimits()
{
if (!_haveWorkingSetLimits)
{
GetWorkingSetLimits(out _minWorkingSet, out _maxWorkingSet);
_haveWorkingSetLimits = true;
}
}
/// <devdoc>
/// Helper to set minimum or maximum working set limits.
/// </devdoc>
/// <internalonly/>
private void SetWorkingSetLimits(IntPtr? min, IntPtr? max)
{
SetWorkingSetLimitsCore(min, max, out _minWorkingSet, out _maxWorkingSet);
_haveWorkingSetLimits = true;
}
/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/> component given a process identifier and
/// the name of a computer in the network.
/// </para>
/// </devdoc>
public static Process GetProcessById(int processId, string machineName)
{
if (!ProcessManager.IsProcessRunning(processId, machineName))
{
throw new ArgumentException(SR.Format(SR.MissingProccess, processId.ToString()));
}
return new Process(machineName, ProcessManager.IsRemoteMachine(machineName), processId, null);
}
/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/> component given the
/// identifier of a process on the local computer.
/// </para>
/// </devdoc>
public static Process GetProcessById(int processId)
{
return GetProcessById(processId, ".");
}
/// <devdoc>
/// <para>
/// Creates an array of <see cref='System.Diagnostics.Process'/> components that are
/// associated
/// with process resources on the
/// local computer. These process resources share the specified process name.
/// </para>
/// </devdoc>
public static Process[] GetProcessesByName(string processName)
{
return GetProcessesByName(processName, ".");
}
/// <devdoc>
/// <para>
/// Creates a new <see cref='System.Diagnostics.Process'/>
/// component for each process resource on the local computer.
/// </para>
/// </devdoc>
public static Process[] GetProcesses()
{
return GetProcesses(".");
}
/// <devdoc>
/// <para>
/// Creates a new <see cref='System.Diagnostics.Process'/>
/// component for each
/// process resource on the specified computer.
/// </para>
/// </devdoc>
public static Process[] GetProcesses(string machineName)
{
bool isRemoteMachine = ProcessManager.IsRemoteMachine(machineName);
ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName);
Process[] processes = new Process[processInfos.Length];
for (int i = 0; i < processInfos.Length; i++)
{
ProcessInfo processInfo = processInfos[i];
processes[i] = new Process(machineName, isRemoteMachine, processInfo.ProcessId, processInfo);
}
return processes;
}
/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/>
/// component and associates it with the current active process.
/// </para>
/// </devdoc>
public static Process GetCurrentProcess()
{
return new Process(".", false, GetCurrentProcessId(), null);
}
/// <devdoc>
/// <para>
/// Raises the <see cref='System.Diagnostics.Process.Exited'/> event.
/// </para>
/// </devdoc>
protected void OnExited()
{
EventHandler exited = _onExited;
if (exited != null)
{
exited(this, EventArgs.Empty);
}
}
/// <devdoc>
/// Raise the Exited event, but make sure we don't do it more than once.
/// </devdoc>
/// <internalonly/>
private void RaiseOnExited()
{
if (!_raisedOnExited)
{
lock (this)
{
if (!_raisedOnExited)
{
_raisedOnExited = true;
OnExited();
}
}
}
}
/// <devdoc>
/// <para>
/// Discards any information about the associated process
/// that has been cached inside the process component. After <see cref='System.Diagnostics.Process.Refresh'/> is called, the
/// first request for information for each property causes the process component
/// to obtain a new value from the associated process.
/// </para>
/// </devdoc>
public void Refresh()
{
_processInfo = null;
_threads = null;
_modules = null;
_exited = false;
_haveWorkingSetLimits = false;
_haveProcessorAffinity = false;
_havePriorityClass = false;
_haveExitTime = false;
_havePriorityBoostEnabled = false;
RefreshCore();
}
/// <summary>
/// Opens a long-term handle to the process, with all access. If a handle exists,
/// then it is reused. If the process has exited, it throws an exception.
/// </summary>
private SafeProcessHandle GetOrOpenProcessHandle()
{
if (!_haveProcessHandle)
{
//Cannot open a new process handle if the object has been disposed, since finalization has been suppressed.
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
SetProcessHandle(GetProcessHandle());
}
return _processHandle;
}
/// <devdoc>
/// Helper to associate a process handle with this component.
/// </devdoc>
/// <internalonly/>
private void SetProcessHandle(SafeProcessHandle processHandle)
{
_processHandle = processHandle;
_haveProcessHandle = true;
if (_watchForExit)
{
EnsureWatchingForExit();
}
}
/// <devdoc>
/// Helper to associate a process id with this component.
/// </devdoc>
/// <internalonly/>
private void SetProcessId(int processId)
{
_processId = processId;
_haveProcessId = true;
ConfigureAfterProcessIdSet();
}
/// <summary>Additional optional configuration hook after a process ID is set.</summary>
partial void ConfigureAfterProcessIdSet();
/// <devdoc>
/// <para>
/// Starts a process specified by the <see cref='System.Diagnostics.Process.StartInfo'/> property of this <see cref='System.Diagnostics.Process'/>
/// component and associates it with the
/// <see cref='System.Diagnostics.Process'/> . If a process resource is reused
/// rather than started, the reused process is associated with this <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public bool Start()
{
Close();
ProcessStartInfo startInfo = StartInfo;
if (startInfo.FileName.Length == 0)
{
throw new InvalidOperationException(SR.FileNameMissing);
}
if (startInfo.StandardInputEncoding != null && !startInfo.RedirectStandardInput)
{
throw new InvalidOperationException(SR.StandardInputEncodingNotAllowed);
}
if (startInfo.StandardOutputEncoding != null && !startInfo.RedirectStandardOutput)
{
throw new InvalidOperationException(SR.StandardOutputEncodingNotAllowed);
}
if (startInfo.StandardErrorEncoding != null && !startInfo.RedirectStandardError)
{
throw new InvalidOperationException(SR.StandardErrorEncodingNotAllowed);
}
if (!string.IsNullOrEmpty(startInfo.Arguments) && startInfo.ArgumentList.Count > 0)
{
throw new InvalidOperationException(SR.ArgumentAndArgumentListInitialized);
}
//Cannot start a new process and store its handle if the object has been disposed, since finalization has been suppressed.
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
SerializationGuard.ThrowIfDeserializationInProgress("AllowProcessCreation", ref s_cachedSerializationSwitch);
return StartCore(startInfo);
}
/// <devdoc>
/// <para>
/// Starts a process resource by specifying the name of a
/// document or application file. Associates the process resource with a new <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public static Process Start(string fileName)
{
return Start(new ProcessStartInfo(fileName));
}
/// <devdoc>
/// <para>
/// Starts a process resource by specifying the name of an
/// application and a set of command line arguments. Associates the process resource
/// with a new <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public static Process Start(string fileName, string arguments)
{
return Start(new ProcessStartInfo(fileName, arguments));
}
/// <devdoc>
/// <para>
/// Starts a process resource specified by the process start
/// information passed in, for example the file name of the process to start.
/// Associates the process resource with a new <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public static Process Start(ProcessStartInfo startInfo)
{
Process process = new Process();
if (startInfo == null)
throw new ArgumentNullException(nameof(startInfo));
process.StartInfo = startInfo;
return process.Start() ?
process :
null;
}
/// <devdoc>
/// Make sure we are not watching for process exit.
/// </devdoc>
/// <internalonly/>
private void StopWatchingForExit()
{
if (_watchingForExit)
{
RegisteredWaitHandle rwh = null;
WaitHandle wh = null;
lock (this)
{
if (_watchingForExit)
{
_watchingForExit = false;
wh = _waitHandle;
_waitHandle = null;
rwh = _registeredWaitHandle;
_registeredWaitHandle = null;
}
}
if (rwh != null)
{
rwh.Unregister(null);
}
if (wh != null)
{
wh.Dispose();
}
}
}
public override string ToString()
{
if (Associated)
{
string processName = ProcessName;
if (processName.Length != 0)
{
return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", base.ToString(), processName);
}
}
return base.ToString();
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to wait
/// indefinitely for the associated process to exit.
/// </para>
/// </devdoc>
public void WaitForExit()
{
WaitForExit(Timeout.Infinite);
}
/// <summary>
/// Instructs the Process component to wait the specified number of milliseconds for
/// the associated process to exit.
/// </summary>
public bool WaitForExit(int milliseconds)
{
bool exited = WaitForExitCore(milliseconds);
if (exited && _watchForExit)
{
RaiseOnExited();
}
return exited;
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to start
/// reading the StandardOutput stream asynchronously. The user can register a callback
/// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached
/// then the remaining information is returned. The user can add an event handler to OutputDataReceived.
/// </para>
/// </devdoc>
public void BeginOutputReadLine()
{
if (_outputStreamReadMode == StreamReadMode.Undefined)
{
_outputStreamReadMode = StreamReadMode.AsyncMode;
}
else if (_outputStreamReadMode != StreamReadMode.AsyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
if (_pendingOutputRead)
throw new InvalidOperationException(SR.PendingAsyncOperation);
_pendingOutputRead = true;
// We can't detect if there's a pending synchronous read, stream also doesn't.
if (_output == null)
{
if (_standardOutput == null)
{
throw new InvalidOperationException(SR.CantGetStandardOut);
}
Stream s = _standardOutput.BaseStream;
_output = new AsyncStreamReader(s, OutputReadNotifyUser, _standardOutput.CurrentEncoding);
}
_output.BeginReadLine();
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to start
/// reading the StandardError stream asynchronously. The user can register a callback
/// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached
/// then the remaining information is returned. The user can add an event handler to ErrorDataReceived.
/// </para>
/// </devdoc>
public void BeginErrorReadLine()
{
if (_errorStreamReadMode == StreamReadMode.Undefined)
{
_errorStreamReadMode = StreamReadMode.AsyncMode;
}
else if (_errorStreamReadMode != StreamReadMode.AsyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
if (_pendingErrorRead)
{
throw new InvalidOperationException(SR.PendingAsyncOperation);
}
_pendingErrorRead = true;
// We can't detect if there's a pending synchronous read, stream also doesn't.
if (_error == null)
{
if (_standardError == null)
{
throw new InvalidOperationException(SR.CantGetStandardError);
}
Stream s = _standardError.BaseStream;
_error = new AsyncStreamReader(s, ErrorReadNotifyUser, _standardError.CurrentEncoding);
}
_error.BeginReadLine();
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation
/// specified by BeginOutputReadLine().
/// </para>
/// </devdoc>
public void CancelOutputRead()
{
if (_output != null)
{
_output.CancelOperation();
}
else
{
throw new InvalidOperationException(SR.NoAsyncOperation);
}
_pendingOutputRead = false;
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation
/// specified by BeginErrorReadLine().
/// </para>
/// </devdoc>
public void CancelErrorRead()
{
if (_error != null)
{
_error.CancelOperation();
}
else
{
throw new InvalidOperationException(SR.NoAsyncOperation);
}
_pendingErrorRead = false;
}
internal void OutputReadNotifyUser(string data)
{
// To avoid race between remove handler and raising the event
DataReceivedEventHandler outputDataReceived = OutputDataReceived;
if (outputDataReceived != null)
{
DataReceivedEventArgs e = new DataReceivedEventArgs(data);
outputDataReceived(this, e); // Call back to user informing data is available
}
}
internal void ErrorReadNotifyUser(string data)
{
// To avoid race between remove handler and raising the event
DataReceivedEventHandler errorDataReceived = ErrorDataReceived;
if (errorDataReceived != null)
{
DataReceivedEventArgs e = new DataReceivedEventArgs(data);
errorDataReceived(this, e); // Call back to user informing data is available.
}
}
private static void AppendArguments(StringBuilder stringBuilder, Collection<string> argumentList)
{
if (argumentList.Count > 0)
{
foreach (string argument in argumentList)
{
PasteArguments.AppendArgument(stringBuilder, argument);
}
}
}
/// <summary>
/// This enum defines the operation mode for redirected process stream.
/// We don't support switching between synchronous mode and asynchronous mode.
/// </summary>
private enum StreamReadMode
{
Undefined,
SyncMode,
AsyncMode
}
/// <summary>A desired internal state.</summary>
private enum State
{
HaveId = 0x1,
IsLocal = 0x2,
HaveNonExitedId = HaveId | 0x4,
HaveProcessInfo = 0x8,
Exited = 0x10,
Associated = 0x20,
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Threading;
namespace System.Net.NetworkInformation
{
public partial class NetworkChange
{
private static readonly object s_globalLock = new object();
public static event NetworkAvailabilityChangedEventHandler NetworkAvailabilityChanged
{
add
{
AvailabilityChangeListener.Start(value);
}
remove
{
AvailabilityChangeListener.Stop(value);
}
}
public static event NetworkAddressChangedEventHandler NetworkAddressChanged
{
add
{
AddressChangeListener.Start(value);
}
remove
{
AddressChangeListener.Stop(value);
}
}
internal static class AvailabilityChangeListener
{
private static readonly NetworkAddressChangedEventHandler s_addressChange = ChangedAddress;
private static volatile bool s_isAvailable = false;
private static void ChangedAddress(object sender, EventArgs eventArgs)
{
Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext> availabilityChangedSubscribers = null;
lock (s_globalLock)
{
bool isAvailableNow = SystemNetworkInterface.InternalGetIsNetworkAvailable();
// If there is an Availability Change, need to execute user callbacks.
if (isAvailableNow != s_isAvailable)
{
s_isAvailable = isAvailableNow;
if (s_availabilityChangedSubscribers.Count > 0)
{
availabilityChangedSubscribers = new Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext>(s_availabilityChangedSubscribers);
}
}
}
// Executing user callbacks if Availability Change event occured.
if (availabilityChangedSubscribers != null)
{
bool isAvailable = s_isAvailable;
NetworkAvailabilityEventArgs args = isAvailable ? s_availableEventArgs : s_notAvailableEventArgs;
ContextCallback callbackContext = isAvailable ? s_runHandlerAvailable : s_runHandlerNotAvailable;
foreach (KeyValuePair<NetworkAvailabilityChangedEventHandler, ExecutionContext>
subscriber in availabilityChangedSubscribers)
{
NetworkAvailabilityChangedEventHandler handler = subscriber.Key;
ExecutionContext ec = subscriber.Value;
if (ec == null) // Flow supressed
{
handler(null, args);
}
else
{
ExecutionContext.Run(ec, callbackContext, handler);
}
}
}
}
internal static void Start(NetworkAvailabilityChangedEventHandler caller)
{
if (caller != null)
{
lock (s_globalLock)
{
if (s_availabilityChangedSubscribers.Count == 0)
{
s_isAvailable = NetworkInterface.GetIsNetworkAvailable();
AddressChangeListener.UnsafeStart(s_addressChange);
}
s_availabilityChangedSubscribers.TryAdd(caller, ExecutionContext.Capture());
}
}
}
internal static void Stop(NetworkAvailabilityChangedEventHandler caller)
{
if (caller != null)
{
lock (s_globalLock)
{
s_availabilityChangedSubscribers.Remove(caller);
if (s_availabilityChangedSubscribers.Count == 0)
{
AddressChangeListener.Stop(s_addressChange);
}
}
}
}
}
// Helper class for detecting address change events.
internal static unsafe class AddressChangeListener
{
// Need to keep the reference so it isn't GC'd before the native call executes.
private static bool s_isListening = false;
private static bool s_isPending = false;
private static Socket s_ipv4Socket = null;
private static Socket s_ipv6Socket = null;
private static WaitHandle s_ipv4WaitHandle = null;
private static WaitHandle s_ipv6WaitHandle = null;
// Callback fired when an address change occurs.
private static void AddressChangedCallback(object stateObject, bool signaled)
{
Dictionary<NetworkAddressChangedEventHandler, ExecutionContext> addressChangedSubscribers = null;
lock (s_globalLock)
{
// The listener was canceled, which would only happen if we aren't listening for more events.
s_isPending = false;
if (!s_isListening)
{
return;
}
s_isListening = false;
// Need to copy the array so the callback can call start and stop
if (s_addressChangedSubscribers.Count > 0)
{
addressChangedSubscribers = new Dictionary<NetworkAddressChangedEventHandler, ExecutionContext>(s_addressChangedSubscribers);
}
try
{
//wait for the next address change
StartHelper(null, false, (StartIPOptions)stateObject);
}
catch (NetworkInformationException nie)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(null, nie);
}
}
// Release the lock before calling into user callback.
if (addressChangedSubscribers != null)
{
foreach (KeyValuePair<NetworkAddressChangedEventHandler, ExecutionContext>
subscriber in addressChangedSubscribers)
{
NetworkAddressChangedEventHandler handler = subscriber.Key;
ExecutionContext ec = subscriber.Value;
if (ec == null) // Flow supressed
{
handler(null, EventArgs.Empty);
}
else
{
ExecutionContext.Run(ec, s_runAddressChangedHandler, handler);
}
}
}
}
internal static void Start(NetworkAddressChangedEventHandler caller)
{
StartHelper(caller, true, StartIPOptions.Both);
}
internal static void UnsafeStart(NetworkAddressChangedEventHandler caller)
{
StartHelper(caller, false, StartIPOptions.Both);
}
private static void StartHelper(NetworkAddressChangedEventHandler caller, bool captureContext, StartIPOptions startIPOptions)
{
lock (s_globalLock)
{
// Setup changedEvent and native overlapped struct.
if (s_ipv4Socket == null)
{
// Sockets will be initialized by the call to OSSupportsIP*.
if (Socket.OSSupportsIPv4)
{
s_ipv4Socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0) { Blocking = false };
s_ipv4WaitHandle = new AutoResetEvent(false);
}
if (Socket.OSSupportsIPv6)
{
s_ipv6Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, 0) { Blocking = false };
s_ipv6WaitHandle = new AutoResetEvent(false);
}
}
if (caller != null)
{
s_addressChangedSubscribers.TryAdd(caller, captureContext ? ExecutionContext.Capture() : null);
}
if (s_isListening || s_addressChangedSubscribers.Count == 0)
{
return;
}
if (!s_isPending)
{
if (Socket.OSSupportsIPv4 && (startIPOptions & StartIPOptions.StartIPv4) != 0)
{
ThreadPool.RegisterWaitForSingleObject(
s_ipv4WaitHandle,
new WaitOrTimerCallback(AddressChangedCallback),
StartIPOptions.StartIPv4,
-1,
true);
SocketError errorCode = Interop.Winsock.WSAIoctl_Blocking(
s_ipv4Socket.SafeHandle,
(int)IOControlCode.AddressListChange,
null, 0, null, 0,
out int length,
IntPtr.Zero, IntPtr.Zero);
if (errorCode != SocketError.Success)
{
NetworkInformationException exception = new NetworkInformationException();
if (exception.ErrorCode != (uint)SocketError.WouldBlock)
{
throw exception;
}
}
errorCode = Interop.Winsock.WSAEventSelect(
s_ipv4Socket.SafeHandle,
s_ipv4WaitHandle.GetSafeWaitHandle(),
Interop.Winsock.AsyncEventBits.FdAddressListChange);
if (errorCode != SocketError.Success)
{
throw new NetworkInformationException();
}
}
if (Socket.OSSupportsIPv6 && (startIPOptions & StartIPOptions.StartIPv6) != 0)
{
ThreadPool.RegisterWaitForSingleObject(
s_ipv6WaitHandle,
new WaitOrTimerCallback(AddressChangedCallback),
StartIPOptions.StartIPv6,
-1,
true);
SocketError errorCode = Interop.Winsock.WSAIoctl_Blocking(
s_ipv6Socket.SafeHandle,
(int)IOControlCode.AddressListChange,
null, 0, null, 0,
out int length,
IntPtr.Zero, IntPtr.Zero);
if (errorCode != SocketError.Success)
{
NetworkInformationException exception = new NetworkInformationException();
if (exception.ErrorCode != (uint)SocketError.WouldBlock)
{
throw exception;
}
}
errorCode = Interop.Winsock.WSAEventSelect(
s_ipv6Socket.SafeHandle,
s_ipv6WaitHandle.GetSafeWaitHandle(),
Interop.Winsock.AsyncEventBits.FdAddressListChange);
if (errorCode != SocketError.Success)
{
throw new NetworkInformationException();
}
}
}
s_isListening = true;
s_isPending = true;
}
}
internal static void Stop(NetworkAddressChangedEventHandler caller)
{
if (caller != null)
{
lock (s_globalLock)
{
s_addressChangedSubscribers.Remove(caller);
if (s_addressChangedSubscribers.Count == 0 && s_isListening)
{
s_isListening = false;
}
}
}
}
}
}
}
| |
//===============================================================================
// Code Associate Data Access Block for .NET
// DataAccessCore.cs
//
//===============================================================================
// Copyright (C) 2002-2014 Ravin Enterprises Ltd.
// All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
using System;
using System.Collections.Generic;
using System.Data;
using System.Collections;
using System.Data.Common;
using System.Configuration;
using CA.Blocks.DataAccess.Translator;
namespace CA.Blocks.DataAccess
{
/// <summary>
/// <para>
/// This class provides the abstract implementation for the Code Associate Data Access Block.
/// The Abstract implementation is build upon utilizing common System.Data methods and interfacing out the Specific
/// DBCommand using the IDbCommand interface. In doing this all specializations built on top of this class will behave
/// in the same manor. This class is abstract and cannot be created.
/// </para>
/// </summary>
/// <remarks>
/// <p>source code:</p>
/// <code outlining="true" source="..\CANC\Blocks\DataAccess\DataAccessCore.cs" lang="cs"/>
/// </remarks>
public abstract class DataAccessCore
{
static private bool _debugTrace = true;
private readonly string _connectionString;
#region private utility methods & constructors
/// <summary>
/// This method can be overridden to provide additional processing on the connection string
/// property. This is useful if for example you database is specified by way of a relative
/// directory which is no know at configuration time. For example accessing a Server path
/// in an http context.
///</summary>
/// <remarks>
/// <example>
/// <p>Example override method using web running in a web enviroment</p>
/// <code outlining="true" lang="cs" >
/// if (connectionString.IndexOf("%MAPPATH%") > 0)
/// {
/// string serverpath = System.Web.HttpContext.Current.Server.MapPath("");
/// connectionString = connectionString.Replace("%MAPPATH%", serverpath);
/// }
/// </code>
/// </example>
/// </remarks>
/// <param name="connectionString"> the connection string as configured in the connectionStrings element of the config file</param>
/// <returns> the default method returns the connection string as stored in the application configuration file</returns>
protected string ResolveConnectionStringValue(string connectionString)
{
return connectionString;
}
/// <summary>
/// This is a protected constructor which must be called by the inheriting class, bu default it will get the configuration
/// value stored in connectionStrings element of the configuration. This value can be overriden using the ResolveConnectionStringValue method.
/// </summary>
/// <param name="dataServiceName"></param>
protected DataAccessCore(string dataServiceName)
{
_connectionString = ConfigurationManager.ConnectionStrings[dataServiceName].ConnectionString;
_connectionString = ResolveConnectionStringValue(_connectionString);
}
/// <summary>
/// The WrapUp procedure is called when completing a database call. It will establish
/// whether or not to close the connection pending the variable closeConnection which
/// would have been passed back from the PrepCommand. The PrepCommand and WrapUp work
/// in tandem when executing commands though this common class.
/// </summary>
/// <param name="conn"></param>
/// <param name="closeConnection"></param>
protected void WrapUp(IDbConnection conn, bool closeConnection)
{
if (closeConnection)
{
if (conn != null
&& (conn.State == ConnectionState.Open
|| conn.State == ConnectionState.Executing
|| conn.State == ConnectionState.Fetching)
)
{
conn.Close();
}
}
}
//TODO make a virtual method and include a timespan on the execute time of the query
private void TraceDBStatement(IDbCommand cmd)
{
//System.Diagnostics.Debug.WriteLine(cmd.CommandText);
}
#endregion private utility methods & constructors
#region abstract methods that must me implemented
protected abstract DbDataAdapter GetDataAdapter(IDbCommand cmd);
protected abstract bool PrepCommand(IDbCommand cmd);
#endregion
protected string ConnectionString
{
get {return _connectionString;}
}
#region ExecuteNonQuery
protected int ExecuteNonQuery(IDbCommand cmd)
{
bool closeconection = PrepCommand(cmd);
int rowCount = cmd.ExecuteNonQuery();
if (_debugTrace)
TraceDBStatement(cmd);
WrapUp(cmd.Connection, closeconection);
return rowCount;
}
#endregion ExecuteNonQuery
#region ExecuteDataSet
protected DataSet ExecuteDataSet(IDbCommand cmd)
{
DataSet ds = new DataSet();
return (ExecuteDataSet(cmd, ds, "Results"));
}
protected DataSet ExecuteDataSet(IDbCommand cmd, DataSet ds, string sTableNames)
{
// full ownership of the connection
bool closeconection = PrepCommand(cmd);
string[] sTableNNameArray = sTableNames.Split(',');
using (DbDataAdapter theDataAdapter = GetDataAdapter(cmd))
{
for(int i = 1; i < sTableNNameArray.Length; i++)
{
theDataAdapter.TableMappings.Add(sTableNNameArray[0].Trim() + Convert.ToString(i), sTableNNameArray[i].Trim());
}
theDataAdapter.Fill(ds, sTableNNameArray[0].Trim());
}
WrapUp(cmd.Connection, closeconection);
if (_debugTrace)
TraceDBStatement(cmd);
return (ds);
}
#endregion ExecuteDataSet
#region ExecuteTable
protected DataTable ExecuteDataTable(IDbCommand cmd)
{
DataSet ds = ExecuteDataSet(cmd);
return(ds.Tables[0]);
}
#endregion ExecuteTable
#region ExecuteDataRow
protected DataRow ExecuteDataRow(IDbCommand cmd)
{
DataSet ds = ExecuteDataSet(cmd);
DataRow dr = null;
if (ds.Tables[0].Rows.Count > 0)
{
if (ds.Tables[0].Rows.Count == 1)
dr = ds.Tables[0].Rows[0];
else
throw new DataException("Command was asked to execute a ExecuteDataRow however more than a single data row was found, ExecuteDataRow expects one or zero rows returned");
}
return(dr);
}
#endregion ExecuteDataRow
#region ExecuteDictionary
protected IDictionary ExecuteDictionary(IDbCommand cmd)
{
Hashtable dictionary = new Hashtable();
DataTable dt = ExecuteDataTable(cmd);
if (dt.Rows.Count > 0)
{
for (int counter = 0; counter < dictionary.Count; counter++)
{
dictionary[dt.Columns[counter].ColumnName] = dt.Rows[0].ItemArray[counter];
}
}
return (dictionary);
}
#endregion ExecuteDictionary
#region ExecuteScalar
protected object ExecuteScalar(IDbCommand cmd)
{
PrepCommand(cmd);
object rv = (cmd.ExecuteScalar());
if (_debugTrace)
TraceDBStatement(cmd);
cmd.Connection.Close();
return rv;
}
protected string ExecuteScalarAsString(IDbCommand cmd, string nullDefault = null)
{
Object result = ExecuteScalar(cmd);
return result != null ? result.ToString() : nullDefault;
}
protected int ExecuteScalarAsInt(IDbCommand cmd, int nullDefault = 0)
{
Object result = ExecuteScalar(cmd);
return result != null ? int.Parse(result.ToString()) : nullDefault;
}
protected short ExecuteScalarAsShort(IDbCommand cmd, short nullDefault = 0)
{
Object result = ExecuteScalar(cmd);
return result != null ? short.Parse(result.ToString()) : nullDefault;
}
protected byte ExecuteScalarAsByte(IDbCommand cmd, byte nullDefault = 0)
{
Object result = ExecuteScalar(cmd);
return result != null ? byte.Parse(result.ToString()) : nullDefault;
}
protected long ExecuteScalarAsLong(IDbCommand cmd, long nullDefault = 0)
{
Object result = ExecuteScalar(cmd);
return result != null ? long.Parse(result.ToString()) : nullDefault;
}
protected Guid ExecuteScalarAsGuid(IDbCommand cmd, Guid nullDefault)
{
Object result = ExecuteScalar(cmd);
return result != null ? Guid.Parse(result.ToString()) : nullDefault;
}
protected Guid ExecuteScalarAsGuid(IDbCommand cmd)
{
return ExecuteScalarAsGuid(cmd, Guid.Empty);
}
#endregion ExecuteScalar
#region ExecuteReader
protected IDataReader ExecuteReader(IDbCommand cmd)
{
PrepCommand(cmd);
return(cmd.ExecuteReader(CommandBehavior.CloseConnection));
}
#endregion ExecuteReader
protected dynamic ExecuteObject(IDbCommand cmd)
{
var translator = new DynamicDbRow2ObjectTranslator();
return translator.Translate(ExecuteDataRow(cmd));
}
protected IList<dynamic> ExecuteObjectList(IDbCommand cmd)
{
var translator = new DynamicDbRow2ObjectTranslator();
return translator.Translate(ExecuteDataTable(cmd));
}
}
}
| |
#region License
/*
* All content copyright Marko Lahma, unless otherwise indicated. 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.
*
*/
#endregion
using System;
using Quartz.Spi;
namespace Quartz
{
/// <summary>
/// TriggerBuilder is used to instantiate <see cref="ITrigger" />s.
/// </summary>
/// <remarks>
/// <para>
/// The builder will always try to keep itself in a valid state, with
/// reasonable defaults set for calling build() at any point. For instance
/// if you do not invoke <i>WithSchedule(..)</i> method, a default schedule
/// of firing once immediately will be used. As another example, if you
/// do not invoked <i>WithIdentity(..)</i> a trigger name will be generated
/// for you.
/// </para>
/// <para>
/// Quartz provides a builder-style API for constructing scheduling-related
/// entities via a Domain-Specific Language (DSL). The DSL can best be
/// utilized through the usage of static imports of the methods on the classes
/// <see cref="TriggerBuilder" />, <see cref="JobBuilder" />,
/// <see cref="DateBuilder" />, <see cref="JobKey" />, <see cref="TriggerKey" />
/// and the various <see cref="IScheduleBuilder" /> implementations.
/// </para>
/// <para>
/// Client code can then use the DSL to write code such as this:
/// </para>
/// <code>
/// IJobDetail job = JobBuilder.Create<MyJob>()
/// .WithIdentity("myJob")
/// .Build();
/// ITrigger trigger = TriggerBuilder.Create()
/// .WithIdentity("myTrigger", "myTriggerGroup")
/// .WithSimpleSchedule(x => x
/// .WithIntervalInHours(1)
/// .RepeatForever())
/// .StartAt(DateBuilder.FutureDate(10, IntervalUnit.Minute))
/// .Build();
/// scheduler.scheduleJob(job, trigger);
/// </code>
/// </remarks>
/// <seealso cref="JobBuilder" />
/// <seealso cref="IScheduleBuilder" />
/// <seealso cref="DateBuilder" />
/// <seealso cref="ITrigger" />
public class TriggerBuilder
{
private TriggerKey? key;
private string? description;
private DateTimeOffset startTime = SystemTime.UtcNow();
private DateTimeOffset? endTime;
private int priority = TriggerConstants.DefaultPriority;
private string? calendarName;
private JobKey? jobKey;
private readonly JobDataMap jobDataMap = new JobDataMap();
private IScheduleBuilder? scheduleBuilder;
internal TriggerBuilder()
{
}
/// <summary>
/// Create a new TriggerBuilder with which to define a
/// specification for a Trigger.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the new TriggerBuilder</returns>
public static TriggerBuilder Create()
{
return new TriggerBuilder();
}
/// <summary>
/// Produce the <see cref="ITrigger" />.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>a Trigger that meets the specifications of the builder.</returns>
public ITrigger Build()
{
if (scheduleBuilder == null)
{
scheduleBuilder = SimpleScheduleBuilder.Create();
}
IMutableTrigger trig = scheduleBuilder.Build();
trig.CalendarName = calendarName;
trig.Description = description;
trig.StartTimeUtc = startTime;
trig.EndTimeUtc = endTime;
if (key == null)
{
key = new TriggerKey(Guid.NewGuid().ToString());
}
trig.Key = key;
if (jobKey != null)
{
trig.JobKey = jobKey;
}
trig.Priority = priority;
if (!jobDataMap.IsEmpty)
{
trig.JobDataMap = jobDataMap;
}
return trig;
}
/// <summary>
/// Use a <see cref="TriggerKey" /> with the given name and default group to
/// identify the Trigger.
/// </summary>
/// <remarks>
/// <para>If none of the 'withIdentity' methods are set on the TriggerBuilder,
/// then a random, unique TriggerKey will be generated.</para>
/// </remarks>
/// <param name="name">the name element for the Trigger's TriggerKey</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="TriggerKey" />
/// <seealso cref="ITrigger.Key" />
public TriggerBuilder WithIdentity(string name)
{
key = new TriggerKey(name);
return this;
}
/// <summary>
/// Use a TriggerKey with the given name and group to
/// identify the Trigger.
/// </summary>
/// <remarks>
/// <para>If none of the 'withIdentity' methods are set on the TriggerBuilder,
/// then a random, unique TriggerKey will be generated.</para>
/// </remarks>
/// <param name="name">the name element for the Trigger's TriggerKey</param>
/// <param name="group">the group element for the Trigger's TriggerKey</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="TriggerKey" />
/// <seealso cref="ITrigger.Key" />
public TriggerBuilder WithIdentity(string name, string group)
{
key = new TriggerKey(name, group);
return this;
}
/// <summary>
/// Use the given TriggerKey to identify the Trigger.
/// </summary>
/// <remarks>
/// <para>If none of the 'withIdentity' methods are set on the TriggerBuilder,
/// then a random, unique TriggerKey will be generated.</para>
/// </remarks>
/// <param name="key">the TriggerKey for the Trigger to be built</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="TriggerKey" />
/// <seealso cref="ITrigger.Key" />
public TriggerBuilder WithIdentity(TriggerKey key)
{
this.key = key;
return this;
}
/// <summary>
/// Set the given (human-meaningful) description of the Trigger.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="description">the description for the Trigger</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.Description" />
public TriggerBuilder WithDescription(string? description)
{
this.description = description;
return this;
}
/// <summary>
/// Set the Trigger's priority. When more than one Trigger have the same
/// fire time, the scheduler will fire the one with the highest priority
/// first.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="priority">the priority for the Trigger</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="TriggerConstants.DefaultPriority" />
/// <seealso cref="ITrigger.Priority" />
public TriggerBuilder WithPriority(int priority)
{
this.priority = priority;
return this;
}
/// <summary>
/// Set the name of the <see cref="ICalendar" /> that should be applied to this
/// Trigger's schedule.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="calendarName">the name of the Calendar to reference.</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ICalendar" />
/// <seealso cref="ITrigger.CalendarName" />
public TriggerBuilder ModifiedByCalendar(string? calendarName)
{
this.calendarName = calendarName;
return this;
}
/// <summary>
/// Set the time the Trigger should start at - the trigger may or may
/// not fire at this time - depending upon the schedule configured for
/// the Trigger. However the Trigger will NOT fire before this time,
/// regardless of the Trigger's schedule.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="startTimeUtc">the start time for the Trigger.</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.StartTimeUtc" />
/// <seealso cref="DateBuilder" />
public TriggerBuilder StartAt(DateTimeOffset startTimeUtc)
{
startTime = startTimeUtc;
return this;
}
/// <summary>
/// Set the time the Trigger should start at to the current moment -
/// the trigger may or may not fire at this time - depending upon the
/// schedule configured for the Trigger.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.StartTimeUtc" />
public TriggerBuilder StartNow()
{
startTime = SystemTime.UtcNow();
return this;
}
/// <summary>
/// Set the time at which the Trigger will no longer fire - even if it's
/// schedule has remaining repeats.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="endTimeUtc">the end time for the Trigger. If null, the end time is indefinite.</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.EndTimeUtc" />
/// <seealso cref="DateBuilder" />
public TriggerBuilder EndAt(DateTimeOffset? endTimeUtc)
{
endTime = endTimeUtc;
return this;
}
/// <summary>
/// Set the <see cref="IScheduleBuilder" /> that will be used to define the
/// Trigger's schedule.
/// </summary>
/// <remarks>
/// <para>The particular <see cref="IScheduleBuilder" /> used will dictate
/// the concrete type of Trigger that is produced by the TriggerBuilder.</para>
/// </remarks>
/// <param name="scheduleBuilder">the SchedulerBuilder to use.</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="IScheduleBuilder" />
/// <seealso cref="SimpleScheduleBuilder" />
/// <seealso cref="CronScheduleBuilder" />
/// <seealso cref="CalendarIntervalScheduleBuilder" />
public TriggerBuilder WithSchedule(IScheduleBuilder scheduleBuilder)
{
this.scheduleBuilder = scheduleBuilder;
return this;
}
/// <summary>
/// Set the identity of the Job which should be fired by the produced
/// Trigger.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="jobKey">the identity of the Job to fire.</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobKey" />
public TriggerBuilder ForJob(JobKey jobKey)
{
this.jobKey = jobKey;
return this;
}
/// <summary>
/// Set the identity of the Job which should be fired by the produced
/// Trigger - a <see cref="JobKey" /> will be produced with the given
/// name and default group.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="jobName">the name of the job (in default group) to fire.</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobKey" />
public TriggerBuilder ForJob(string jobName)
{
jobKey = new JobKey(jobName);
return this;
}
/// <summary>
/// Set the identity of the Job which should be fired by the produced
/// Trigger - a <see cref="JobKey" /> will be produced with the given
/// name and group.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="jobName">the name of the job to fire.</param>
/// <param name="jobGroup">the group of the job to fire.</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobKey" />
public TriggerBuilder ForJob(string jobName, string jobGroup)
{
jobKey = new JobKey(jobName, jobGroup);
return this;
}
/// <summary>
/// Set the identity of the Job which should be fired by the produced
/// Trigger, by extracting the JobKey from the given job.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="jobDetail">the Job to fire.</param>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobKey" />
public TriggerBuilder ForJob(IJobDetail jobDetail)
{
JobKey k = jobDetail.Key;
if (k.Name == null)
{
throw new ArgumentException("The given job has not yet had a name assigned to it.");
}
jobKey = k;
return this;
}
/// <summary>
/// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobDataMap" />
public TriggerBuilder UsingJobData(string key, string value)
{
jobDataMap.Put(key, value);
return this;
}
/// <summary>
/// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobDataMap" />
public TriggerBuilder UsingJobData(string key, int value)
{
jobDataMap.Put(key, value);
return this;
}
/// <summary>
/// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobDataMap" />
public TriggerBuilder UsingJobData(string key, long value)
{
jobDataMap.Put(key, value);
return this;
}
/// <summary>
/// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobDataMap" />
public TriggerBuilder UsingJobData(string key, float value)
{
jobDataMap.Put(key, value);
return this;
}
/// <summary>
/// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobDataMap" />
public TriggerBuilder UsingJobData(string key, double value)
{
jobDataMap.Put(key, value);
return this;
}
/// <summary>
/// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobDataMap" />
public TriggerBuilder UsingJobData(string key, decimal value)
{
jobDataMap.Put(key, value);
return this;
}
/// <summary>
/// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobDataMap" />
public TriggerBuilder UsingJobData(string key, bool value)
{
jobDataMap.Put(key, value);
return this;
}
/// <summary>
/// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobDataMap" />
public TriggerBuilder UsingJobData(string key, Guid value)
{
jobDataMap.Put(key, value);
return this;
}
/// <summary>
/// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobDataMap" />
public TriggerBuilder UsingJobData(string key, char value)
{
jobDataMap.Put(key, value);
return this;
}
/// <summary>
/// Add the given key-value pair to the Trigger's <see cref="JobDataMap" />.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>the updated TriggerBuilder</returns>
/// <seealso cref="ITrigger.JobDataMap" />
public TriggerBuilder UsingJobData(JobDataMap newJobDataMap)
{
// add data from new map to existing map (overrides old values)
foreach (string k in newJobDataMap.Keys)
{
jobDataMap.Put(k, newJobDataMap.Get(k));
}
return this;
}
internal void ClearDirty()
{
jobDataMap?.ClearDirtyFlag();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.